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
Intelligent-Systems-Phystech/2018-Project-24
https://github.com/Intelligent-Systems-Phystech/2018-Project-24
f1b34092dabb4576b0823743d48e14edd7d6f3d0
e3f363e953c233c774c5a47e66da5b28baffa102
a8c62bfca11033eb5a164fd5f4ab7bcfc3312853
refs/heads/master
2020-03-31T02:35:52.436607
2018-12-11T08:14:18
2018-12-11T08:14:18
151,831,680
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5157771706581116, "alphanum_fraction": 0.5379821062088013, "avg_line_length": 28.837209701538086, "blob_id": "550a8303d515f82ad83320ab01b082dc4e24a31b", "content_id": "4e61e312bd64edacb64b3f4d7732ee86cf1f945c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2567, "license_type": "no_license", "max_line_length": 98, "num_lines": 86, "path": "/code/Project/BasicFunctions.py", "repo_name": "Intelligent-Systems-Phystech/2018-Project-24", "src_encoding": "UTF-8", "text": "\n# coding: utf-8\n\n# In[ ]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nall_names = ['city', 'factory', 'field', 'forest', 'forest_field']\n\ndef norm1(X, y):\n \"\"\" X_norm = (X - np.mean(X)) / np.std(X) for y - the same\n \"\"\"\n X_norm = (X - np.mean(X)) / np.std(X)\n y_norm = (y - np.mean(y)) / np.std(y)\n return X_norm, y_norm\n\ndef norm2(X, y):\n \"\"\" X_norm = (X - np.mean(X, axis=0)) / np.std(X, axis=0) for y - the same\n \"\"\"\n ym = np.mean(y, axis = 0)\n ys = np.std(y, axis = 0)\n Xm = np.mean(X, axis = 0)\n Xs = np.std(X, axis = 0)\n X_norm = (X - Xm) / Xs\n y_norm = (y - ym) / ys\n return X_norm, y_norm\n\ndef norm3(X, y):\n \"\"\" X_norm = (X - np.min(X)) / np.max(X) for y - the same\n \"\"\"\n X_norm = (X - np.min(X)) / np.max(X)\n y_norm = (y - np.min(y)) / np.max(y)\n return X_norm, y_norm\n\ndef bigDataSet(dataset, names):\n \"\"\" Concatenate all dataset with names and give one big array with all pictures.\n \"\"\"\n N = dataset[names[0]].shape[0]\n w, h = dataset[names[0]].shape[1], dataset[names[0]].shape[2]\n new_dataset = np.zeros((N * len(names), w, h))\n for i, name in enumerate(names):\n new_dataset[i * N: (i + 1) * N] = dataset[name] \n return new_dataset\n \ndef whole_pic_line(X):\n \"\"\"Make one picture from array X of pictures in lines \n \"\"\"\n L = int((X.shape[0] * X.shape[1]) ** 0.5)\n picture = np.zeros((L, L))\n d = int((X.shape[1]) ** 0.5)\n k = 0\n for i in range(0, L, d):\n for j in range(0, L, d):\n picture[i: i + d, j: j + d] = np.reshape(X[k], (d, d))\n k += 1\n return picture\n\ndef whole_pic(X, overlap=0):\n \"\"\" Make one picture from array X of pictures with overlap.\n Overlap is a number of overlapping pixels from one side\n \"\"\"\n L = int(X.shape[0] ** 0.5 * (X.shape[1] - 2 * overlap))\n picture = np.zeros((L, L))\n d = int(X.shape[1] - 2 * overlap)\n k = 0\n for i in range(0, L, d):\n for j in range(0, L, d):\n picture[i: i + d, j: j + d] = X[k, overlap:d + overlap, overlap:d + overlap]\n k += 1\n return picture\n\ndef tt_plot(train_cuda_MSE, test_cuda_MSE):\n \"\"\" Plot train and test MSE.\n \"\"\"\n plt.plot(train_cuda_MSE, label='train')\n plt.plot(test_cuda_MSE, label= 'test')\n plt.legend()\n plt.show()\n \ndef pic_90x90(X, overlap=0):\n \"\"\" Show the piece 90x90 of the left angle of picture X. X is numpy.array of overlap pictures.\n \"\"\"\n plt.figure(figsize=(10,10))\n plt.imshow(whole_pic(X, overlap)[:90, :90], cmap='gray')\n plt.show()\n" }, { "alpha_fraction": 0.79347825050354, "alphanum_fraction": 0.8586956262588501, "avg_line_length": 45, "blob_id": "62d7bcc6e60a2301def5b02b2b9c38ae12b975bc", "content_id": "4ca6ec345a0cdb447b048ca32a99a3ff5af96ac7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 158, "license_type": "no_license", "max_line_length": 73, "num_lines": 2, "path": "/README.md", "repo_name": "Intelligent-Systems-Phystech/2018-Project-24", "src_encoding": "UTF-8", "text": "# 2018-Project-24\nМаксимизация энтропии при различных видах преобразований над изображением\n" }, { "alpha_fraction": 0.5162972807884216, "alphanum_fraction": 0.5554106831550598, "avg_line_length": 37.67226791381836, "blob_id": "7cdf1bb000388d5542bfa41b4dbe7e56964a4117", "content_id": "8bd0dcaafce98fa060aa8f1f4109cb1a8b2b92c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4602, "license_type": "no_license", "max_line_length": 114, "num_lines": 119, "path": "/code/Project/NNFunctions.py", "repo_name": "Intelligent-Systems-Phystech/2018-Project-24", "src_encoding": "UTF-8", "text": "\n# coding: utf-8\n\n# In[ ]:\n\n\nimport torch\nimport torch.nn as nn\nimport tqdm\nfrom torch.nn import functional as F \n \nclass IndConv2(nn.Module):\n def __init__(self, in_channels=1, out_channels=1, mode='nearest'):\n super(IndConv2, self).__init__()\n \n self.mode = mode\n self.in_channels = in_channels\n self.A00 = nn.Conv2d(in_channels, out_channels, (3,3))\n self.A01 = nn.Conv2d(in_channels, out_channels, (3,3))\n self.A02 = nn.Conv2d(in_channels, out_channels, (3,3))\n self.A10 = nn.Conv2d(in_channels, out_channels, (3,3))\n self.A11 = nn.Conv2d(in_channels, out_channels, (3,3))\n self.A12 = nn.Conv2d(in_channels, out_channels, (3,3))\n self.A20 = nn.Conv2d(in_channels, out_channels, (3,3))\n self.A21 = nn.Conv2d(in_channels, out_channels, (3,3))\n self.A22 = nn.Conv2d(in_channels, out_channels, (3,3))\n \n def forward(self, x):\n ins = F.interpolate(x.reshape(x.shape[0], self.in_channels, 3, 3), scale_factor=3, mode=self.mode)\n out = torch.ones((x.shape[0], self.in_channels, 3, 3)).type(torch.cuda.FloatTensor)\n \n out[:, :, 0, 0] = self.A00(ins[:, :, 2:5, 2:5])[:, :, 0, 0]\n out[:, :, 0, 2] = self.A02(ins[:, :, 2:5, 4:7])[:, :, 0, 0]\n out[:, :, 2, 2] = self.A22(ins[:, :, 4:7, 4:7])[:, :, 0, 0]\n out[:, :, 2, 0] = self.A20(ins[:, :, 4:7, 2:5])[:, :, 0, 0]\n out[:, :, 1, 0] = self.A10(ins[:, :, 3:6, 2:5])[:, :, 0, 0]\n out[:, :, 0, 1] = self.A01(ins[:, :, 2:5, 3:6])[:, :, 0, 0]\n out[:, :, 1, 2] = self.A12(ins[:, :, 3:6, 4:7])[:, :, 0, 0]\n out[:, :, 2, 1] = self.A21(ins[:, :, 4:7, 3:6])[:, :, 0, 0]\n out[:, :, 1, 1] = self.A11(ins[:, :, 3:6, 3:6])[:, :, 0, 0]\n\n return out\n \ndef net_training(net, train_loader, test_loader, criterion, learning_rate, N, train_MSE=None, test_MSE=None):\n optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate)\n if train_MSE is None:\n train_MSE = []\n if test_MSE is None:\n test_MSE = []\n for iter in tqdm.tqdm_notebook(range(N)):\n epoch_MSE = 0.0\n epoch_iter = 0\n error = []\n for item in train_loader:\n\n inputs = torch.tensor(item[0], dtype=torch.float32)\n labels = torch.tensor(item[1], dtype=torch.float32)\n\n optimizer.zero_grad()\n\n outputs = net(inputs)\n loss = criterion(outputs.squeeze(1), labels)\n loss.backward()\n optimizer.step()\n\n epoch_MSE += F.mse_loss(outputs.squeeze(1), labels)\n epoch_iter += 1\n errors = 0.\n for test_item in test_loader:\n inputs = torch.tensor(test_item[0], dtype=torch.float32)\n labels = torch.tensor(test_item[1], dtype=torch.float32)\n outputs = net(inputs)\n errors += F.mse_loss(outputs.squeeze(1), labels)\n test_MSE.append(errors.data)\n epoch_MSE /= epoch_iter\n train_MSE.append(epoch_MSE.data)\n return train_MSE, test_MSE\n\ndef net_cuda_training(net, train_loader, test_loader, criterion, learning_rate, N, train_MSE=None, test_MSE=None):\n \"\"\" Train model on GPU. Be careful maybe you have to change some tensors type to cuda.FloatTensor.\n \"\"\"\n optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate)\n if train_MSE is None:\n train_MSE = []\n if test_MSE is None:\n test_MSE = []\n for iter in tqdm.tqdm_notebook(range(N)):\n epoch_MSE = 0.0\n epoch_iter = 0\n error = []\n for item in train_loader:\n\n inputs = item[0].type(torch.cuda.FloatTensor)\n labels = item[1].type(torch.cuda.FloatTensor)\n\n optimizer.zero_grad()\n\n outputs = net(inputs)\n loss = criterion(outputs.squeeze(1), labels)\n loss.backward()\n optimizer.step()\n\n epoch_MSE += F.mse_loss(outputs.squeeze(1), labels)\n epoch_iter += 1\n errors = 0.\n for test_item in test_loader:\n inputs = item[0].type(torch.cuda.FloatTensor)\n labels = item[1].type(torch.cuda.FloatTensor)\n outputs = net(inputs)\n errors += F.mse_loss(outputs.squeeze(1), labels)\n test_MSE.append(errors.data)\n epoch_MSE /= epoch_iter\n train_MSE.append(epoch_MSE.data)\n return train_MSE, test_MSE\n\ndef rec_pic(net, X):\n \"\"\" Return recovered picture in numpy array format.\n X is array of pictures wich sizes satisfy to net.\n \"\"\"\n return net(torch.cuda.FloatTensor(X)).squeeze(1).type(torch.FloatTensor).detach().numpy()" } ]
3
Nagarajuvandali/Python-Algorithms
https://github.com/Nagarajuvandali/Python-Algorithms
ad8e594e70e93e46764e44786cf8a92b399cc520
2001e4be45704abca540d322faafba46d490589c
35f61d7e2e5a2f587d505fbc6cc2d3c435868db0
refs/heads/master
2020-07-18T03:50:45.146187
2019-09-09T15:15:18
2019-09-09T15:15:18
206,169,407
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5426540374755859, "alphanum_fraction": 0.5639810562133789, "avg_line_length": 20.3157901763916, "blob_id": "f1561b50a502c6a72be8295b0e4aa314e934edc1", "content_id": "e1b214c954d01fdfef67214a0fe9d9e72d0ff25e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 422, "license_type": "no_license", "max_line_length": 66, "num_lines": 19, "path": "/Binary Search.py", "repo_name": "Nagarajuvandali/Python-Algorithms", "src_encoding": "UTF-8", "text": "import random\r\n\r\n\r\ndef linear_search(data,target):\r\n for i in range(len(data)):\r\n if data[i] == target:\r\n c = True\r\n break\r\n else:\r\n c = False\r\n return c\r\n\r\n\r\ndata = [1, 2, 3, 4, 5, 6]\r\ntarget = random.randrange(0, 10)\r\n\r\nprint(\"The list you have entered is\", data)\r\nprint(\"The target value you want to match in the list is\", target)\r\nprint(linear_search(data, target))" } ]
1
TrendingTechnology/annchor
https://github.com/TrendingTechnology/annchor
985532e469a692358eb0802ccf02a9591c4643f8
02834cf7edf27928ad698ae98d2e8df7bf46dd29
985700f9e1c0a976438fb93a09b939dabba73fdb
refs/heads/main
2023-06-29T22:38:20.520186
2021-08-03T18:17:30
2021-08-03T18:17:30
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.575674831867218, "alphanum_fraction": 0.5990294218063354, "avg_line_length": 24.167938232421875, "blob_id": "93931c2beaa1a31ab3bfb03834358d3ad1a2cb82", "content_id": "f548c166f1fce35029524971acce24e874d789b2", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3297, "license_type": "permissive", "max_line_length": 78, "num_lines": 131, "path": "/annchor/tests/test_annchor.py", "repo_name": "TrendingTechnology/annchor", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom numba import njit\nimport Levenshtein as lev\nfrom pynndescent.distances import kantorovich\n\nfrom annchor import Annchor, BruteForce, compare_neighbor_graphs\nfrom annchor import Annchor, compare_neighbor_graphs\nfrom annchor.datasets import load_digits, load_strings\n\n\ndef test_compare_neighbor_graphs(seed=42):\n np.random.seed(seed)\n neighbor_graph = load_digits()[\"neighbor_graph\"]\n\n # Check self comparison is zero\n error = compare_neighbor_graphs(neighbor_graph, neighbor_graph, 30)\n assert error == 0\n\n # Check changing distances gives expected number of errors\n ixs, ds = neighbor_graph[0].copy(), neighbor_graph[1].copy()\n for i in range(ds.shape[0]):\n ds[i, np.random.randint(20, 100)] += np.random.random() + 0.01\n error = compare_neighbor_graphs(neighbor_graph, (ixs, ds), 100)\n assert error == ds.shape[0]\n\n # Check that these errors don't occur where we didn't inject them\n error = compare_neighbor_graphs(neighbor_graph, (ixs, ds), 20)\n assert error == 0\n\n\ndef test_digits(seed=42, niters=1):\n\n # Set k-NN\n k = 25\n\n # Load digits\n data = load_digits()\n X = data[\"X\"]\n M = data[\"cost_matrix\"]\n neighbor_graph = data[\"neighbor_graph\"]\n\n for it in range(niters):\n\n # Call ANNchor\n ann = Annchor(\n X,\n \"wasserstein\",\n func_kwargs={\"cost_matrix\": M},\n n_anchors=25,\n n_neighbors=k,\n n_samples=5000,\n p_work=0.16,\n random_seed=seed + it,\n )\n\n ann.fit()\n\n # Test accuracy\n error = compare_neighbor_graphs(neighbor_graph, ann.neighbor_graph, k)\n\n # 10 errors is relatively conservative in this parameter regime.\n # We should average much less.\n # 0-5 is typical, with a few outliers.\n assert error < 10\n\n\ndef test_strings(seed=42, niters=1):\n\n # Set k-NN, metric\n k = 15\n\n strings_data = load_strings()\n X = strings_data[\"X\"]\n neighbor_graph = strings_data[\"neighbor_graph\"]\n\n for it in range(niters):\n\n # Call ANNchor\n ann = Annchor(\n X,\n \"levenshtein\",\n n_anchors=23,\n n_neighbors=k,\n random_seed=seed + it,\n n_samples=5000,\n p_work=0.12,\n niters=4,\n )\n\n ann.fit()\n\n # Test accuracy\n error = compare_neighbor_graphs(neighbor_graph, ann.neighbor_graph, k)\n\n # 15 errors is relatively conservative in this parameter regime.\n # We should average much less.\n # 0-5 is typical, with a few outliers\n assert error < 15\n\n\ndef test_init():\n\n # Set k-NN, metric\n k = 15\n\n X = load_strings()[\"X\"]\n\n ann = Annchor(X, \"levenshtein\", p_work=1.1)\n assert ann.p_work == 1.0\n\n ann = Annchor(X, \"levenshtein\", p_work=0.0)\n\n assert ann.p_work == 2 * ann.n_anchors * ann.nx / ann.N\n\n\ndef test_brute_force():\n\n # Load digits\n data = load_digits()\n X = data[\"X\"]\n M = data[\"cost_matrix\"]\n neighbor_graph = data[\"neighbor_graph\"]\n\n bruteforce = BruteForce(X, \"wasserstein\", func_kwargs={\"cost_matrix\": M})\n bruteforce.fit()\n\n error = compare_neighbor_graphs(\n neighbor_graph, bruteforce.neighbor_graph, 100\n )\n\n assert error == 0\n" } ]
1
jamesward/playscalapython
https://github.com/jamesward/playscalapython
2e145d32f007337fac7b63bac1c32fedb2663790
0763640f260e33ea814caf9c3f8b8dc137623253
9cf39e22edc18345ea2701c1548774e8ade096a1
refs/heads/master
2020-04-27T04:50:04.192029
2011-10-18T22:13:54
2011-10-18T22:13:54
2,602,375
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6544811129570007, "alphanum_fraction": 0.6733490824699402, "avg_line_length": 17.021276473999023, "blob_id": "4a12fd8cc92382b1aca78fd0d5206e703377d9a5", "content_id": "1229755c3923d5c1f4d4e496302d8c3ec5ad04d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 848, "license_type": "no_license", "max_line_length": 89, "num_lines": 47, "path": "/README.md", "repo_name": "jamesward/playscalapython", "src_encoding": "UTF-8", "text": "Run locally\n-----------\n\nStart the Play JSON server:\n\n cd jsonserver\n play deps\n play run\n\nTest the JSON server: \n[http://localhost:9000](http://localhost:9000)\n\nStart the Python JSON client (and HTML server):\n\n cd jsonclient\n pip install -r requirements.txt\n python web.py\n\nTest the Python JSON client: \n[http://localhost:5000](http://localhost:5000)\n\n\nRun on Heroku\n-------------\n\nDeploy the Play JSON server:\n\n cd jsonserver\n git init\n git add .\n git commit -m init\n heroku create -s cedar\n git push heroku master\n\nDeploy the Python JSON client:\n\n cd jsonclient\n git init\n git add .\n git commit -m init\n heroku create -s cedar\n heroku config:add JSON_SERVICE_URL=http://replacewiththeurltotheplayapp.herokuapp.com\n git push heroku master\n\nTest the Python JSON client:\n\n heroku open\n\n" }, { "alpha_fraction": 0.4893617033958435, "alphanum_fraction": 0.6808510422706604, "avg_line_length": 14.666666984558105, "blob_id": "07090744ecc4aa31315e670e764906f689df8054", "content_id": "128c3040b9e03ef58da254f21d5c53eeebe51a9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 47, "license_type": "no_license", "max_line_length": 17, "num_lines": 3, "path": "/jsonclient/requirements.txt", "repo_name": "jamesward/playscalapython", "src_encoding": "UTF-8", "text": "Flask==0.7.2\nsimplejson==2.2.1\nrequests==0.6.4\n" }, { "alpha_fraction": 0.6034188270568848, "alphanum_fraction": 0.6239316463470459, "avg_line_length": 29.789474487304688, "blob_id": "fbe6f088a9167e69a4adc2b14fb66ffe71dc8a0a", "content_id": "e78a5d8eb3ceca2345f857064eed4f702639a9c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 585, "license_type": "no_license", "max_line_length": 90, "num_lines": 19, "path": "/jsonclient/web.py", "repo_name": "jamesward/playscalapython", "src_encoding": "UTF-8", "text": "import os\nimport simplejson\nimport requests\nfrom flask import Flask\napp = Flask(__name__)\n\[email protected](\"/\")\ndef hello():\n jsonString = requests.get(os.environ.get(\"JSON_SERVICE_URL\", \"http://localhost:9000\"))\n widgets = simplejson.loads(jsonString.content)\n htmlResponse = \"<html><body>\"\n for widget in widgets:\n htmlResponse += \"Widget \" + str(widget['id']) + \" = \" + widget['name'] + \"</br>\"\n htmlResponse += \"</body></html>\"\n return htmlResponse\n\nif __name__ == \"__main__\":\n port = int(os.environ.get(\"PORT\", 5000))\n app.run(host='0.0.0.0', port=port)\n" } ]
3
NaamaSa/Tradopoly_NS
https://github.com/NaamaSa/Tradopoly_NS
0179d43f3567b593ba735adc397f75cc0c06852d
87a85f7f63e6e78d1aeaf4634ce4a375b6a51b0b
40994497ffd5c005921b8c2ef625bb0ba908aae2
refs/heads/master
2023-06-16T20:07:39.359765
2021-06-20T07:42:40
2021-06-20T07:42:40
378,586,425
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6173800230026245, "alphanum_fraction": 0.6251621246337891, "avg_line_length": 41.05454635620117, "blob_id": "caa282bb2c7c464c3a94a62ee72d951950e675e5", "content_id": "e1674da5a694c5156e2c1a866e72e9450f44e5e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2315, "license_type": "no_license", "max_line_length": 188, "num_lines": 55, "path": "/Tradopoly_NS/Player.cs", "repo_name": "NaamaSa/Tradopoly_NS", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace Tradopoly_NS\n{\n public class Player\n {\n private string color;\n private int num;\n private int[] moneyList; // [500,100,50,20,10,5,1]\n private ArrayList cardsLists; // StreetArr, trainArr, companyArr, specialCardList\n private int totalMoney;\n private int x;\n private int y;\n\n public Player(string color, int num, int[] moneyList, string[] streetCardArr, string[] trainCardArr, string[] companyCardArr, string[] specialCardArr, int totalMoney, int x, int y)\n {\n this.color = color;\n this.num = num;\n this.moneyList = moneyList;\n this.cardsLists = new ArrayList();\n this.cardsLists.Add(streetCardArr);\n this.cardsLists.Add(trainCardArr);\n this.cardsLists.Add(companyCardArr);\n this.cardsLists.Add(specialCardArr);\n this.totalMoney = totalMoney;\n this.x = x;\n this.y = y;\n }\n\n //get\n public string GetColor() { return this.color; }\n public int GetNum() { return this.num; }\n public int[] GetMoneyList() { return this.moneyList; }\n public ArrayList GetCardsLists() { return this.cardsLists; }\n public int GetTotalMoney() { return this.totalMoney; }\n public int GetX() { return this.x; }\n public int GetY() { return this.y; }\n //set\n public void SetAddMoneyList(int i, int add) { this.moneyList[i] += add; }\n public void SetSubMoneyList(int i, int sub) { this.moneyList[i] -= sub; }\n public void SetAddStreetList(string card) { this.cardsLists.Insert(0, card); }\n public void SetAddTrainList(string card) { this.cardsLists.Insert(1, card); }\n public void SetAddCompanyList(string card) { this.cardsLists.Insert(2, card); }\n public void SetAddSpecialList(string card) { this.cardsLists.Insert(3, card); }\n public void SetSubTotalMoney(int money) { this.totalMoney -= money; }\n public void SetAddTotalMoney(int money) { this.totalMoney += money; }\n public void SetX(int x) { this.x = x; }\n public void SetY(int y) { this.y = y; }\n }\n}\n" }, { "alpha_fraction": 0.397024005651474, "alphanum_fraction": 0.4058167040348053, "avg_line_length": 27.43269157409668, "blob_id": "a97ccde31dc65563af8f9457d71babac7e95ae49", "content_id": "249504d77aa4ec759d42f848a4c54106e4366660", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2959, "license_type": "no_license", "max_line_length": 95, "num_lines": 104, "path": "/Tradopoly_NS/AwaitingPlayers.cs", "repo_name": "NaamaSa/Tradopoly_NS", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Threading;\n\nnamespace Tradopoly_NS\n{\n public partial class AwaitingPlayers : Form\n {\n public int num;\n public bool close;\n\n public AwaitingPlayers(int num)\n {\n InitializeComponent();\n this.num = num;\n this.close = false;\n Thread backgroundThread = new Thread(new ThreadStart(While_Not_Full));\n backgroundThread.Start();\n }\n\n public void While_Not_Full()\n {\n bool flag = false;\n if (this.num == 2)\n {\n Send(\"join_2\");\n while (!flag)\n {\n string[] msg = receive().Split(',');\n if(msg[0] == \"Full\")\n {\n _2Players p = new _2Players(int.Parse(msg[1]));\n flag = true;\n p.ShowDialog();\n this.Close();\n }\n }\n }\n else if (this.num == 3)\n {\n Send(\"join_3\");\n while (!flag)\n {\n string[] msg = receive().Split(',');\n if (msg[0] == \"Full\")\n {\n _3Players p = new _3Players(int.Parse(msg[1]));\n flag = true;\n p.ShowDialog();\n this.Close();\n }\n }\n }\n else if (this.num == 4)\n {\n Send(\"join_4\");\n while (!flag)\n {\n string[] msg = receive().Split(',');\n if (msg[0] == \"Full\")\n {\n _4Players p = new _4Players(int.Parse(msg[1]));\n flag = true;\n p.ShowDialog();\n this.Close();\n }\n }\n }\n }\n \n private void Timer1_Tick(object sender, EventArgs e)\n {\n if (this.close == true)\n {\n this.Close();\n timer1.Enabled = false;\n }\n }\n\n //sends message to server\n private void Send(string msg)\n {\n byte[] msgBuffer = Encoding.Default.GetBytes(msg);\n Program.sck.Send(msgBuffer, 0, msgBuffer.Length, 0);\n }\n\n //recieves message from server\n private string receive()\n {\n byte[] buffer = new byte[255];\n string received = Encoding.ASCII.GetString(buffer, 0, Program.sck.Receive(buffer));\n Console.WriteLine(received);\n return received;\n }\n\n }\n}\n" }, { "alpha_fraction": 0.4239281415939331, "alphanum_fraction": 0.44649365544319153, "avg_line_length": 41.516605377197266, "blob_id": "ad0f374e5be877555fb04938a6e2d7f075369ae4", "content_id": "c005ce96c86a2b6e248ad8819554abbf21557952", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 23046, "license_type": "no_license", "max_line_length": 195, "num_lines": 542, "path": "/Tradopoly_NS/4Players.cs", "repo_name": "NaamaSa/Tradopoly_NS", "src_encoding": "UTF-8", "text": "using System;\nusing System.Configuration;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Windows.Forms;\nusing System.Data.SqlClient;\nusing System.Timers;\nnamespace Tradopoly_NS\n{\n public partial class _4Players : Form\n {\n private SqlConnection conn;\n private SqlCommand cmd;\n private SqlDataReader dataReader;\n private const int MAXSIDE = 533;\n private const int MINSIDE = 37;\n private const int CORNERADD = 15;\n private const int DIFF = 47;\n private int x = MAXSIDE;\n private int y = MAXSIDE;\n private int xPlace = 10;\n private int yPlace = 10;\n private int diceVal;\n private const int SIZE = 11;\n private string[,] BOARD;\n private static Player player;\n private int index;\n private int jail;\n\n\n public _2Players(int index)\n {\n InitializeComponent();\n this.BOARD = new string[SIZE, SIZE];\n OpenSqlConnection();\n this.index = index;\n Thread backgroundThread = new Thread(new ThreadStart(receive));\n backgroundThread.Start();\n }\n\n private void OpenSqlConnection()\n {\n string connectionString = @\"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Park-Hamada Student\\Desktop\\Tradopoly_NS\\Tradopoly_NS\\Database1.mdf;Integrated Security=True\";\n this.conn = new SqlConnection(connectionString);\n }\n\n private void _2Players_Load(object sender, EventArgs e)\n {\n Console.WriteLine(\"enter\");\n setBoard(this.BOARD);\n int[] arrMoney = new int[] { 2, 4, 1, 1, 2, 1, 5 };\n player = new Player(IndexColor(), this.index, arrMoney, new string[22], new string[4], new string[2], new string[10], 1500, 10, 10);\n Console.WriteLine(player.ToString());\n }\n\n //find corresponding color\n private string IndexColor()\n {\n if (this.index == 0)\n return \"red\";\n else if (this.index == 1)\n return \"blue\";\n else if (this.index == 2)\n return \"yellow\";\n else\n return \"green\";\n }\n\n //set board\n private void setBoard(string[,] BOARD)\n {\n BOARD[0, 0] = \"f,d\";\n BOARD[1, 0] = \"red1,StreetCard,DeedCard,Cards\";\n BOARD[2, 0] = \"special1,SpecialCard,Cards\";\n BOARD[3, 0] = \"red2,StreetCard,DeedCard,Cards\";\n BOARD[4, 0] = \"red3,StreetCard,DeedCard,Cards\";\n BOARD[5, 0] = \"train3,TrainCard,DeedCard,Cards\";\n BOARD[6, 0] = \"yellow1,StreetCard,DeedCard,Cards\";\n BOARD[7, 0] = \"yellow2,StreetCard,DeedCard,Cards\";\n BOARD[8, 0] = \"water,DeedCard,Cards\";\n BOARD[9, 0] = \"yellow3,StreetCard,DeedCard,Card\";\n BOARD[10, 0] = \"f,d\";\n BOARD[10, 1] = \"green1,StreetCard,DeedCard,Card\";\n BOARD[10, 2] = \"green2,StreetCard,DeedCard,Card\";\n BOARD[10, 3] = \"special2,SpecialCard,Cards\";\n BOARD[10, 4] = \"green3,StreetCard,DeedCard,Card\";\n BOARD[10, 5] = \"train4,TrainCard\";\n BOARD[10, 6] = \"special3,SpecialCard,Cards\";\n BOARD[10, 7] = \"blue1,StreetCard,DeedCard,Card\";\n BOARD[10, 8] = \"pay,k\";\n BOARD[10, 9] = \"blue2,StreetCard,DeedCard,Card\";\n BOARD[10, 10] = \"f,k\";\n BOARD[9, 10] = \"brown1,StreetCard,DeedCard,Card\";\n BOARD[8, 10] = \"pay,d\";\n BOARD[7, 10] = \"brown2,StreetCard,DeedCard,Card\";\n BOARD[6, 10] = \"pay,Cards\";\n BOARD[5, 10] = \"train1,TrainCard,DeedCard,Card\";\n BOARD[4, 10] = \"lblue1,StreetCard,DeedCard,Card\";\n BOARD[3, 10] = \"special4,SpecialCard,Cards\";\n BOARD[2, 10] = \"lblue2,StreetCard,DeedCard,Card\";\n BOARD[1, 10] = \"lblue3,StreetCard,DeedCard,Card\";\n BOARD[0, 10] = \"f,t\";\n BOARD[0, 9] = \"pink1,StreetCard,DeedCard,Card\";\n BOARD[0, 8] = \"power,DeedCard,DeedCard,Card\";\n BOARD[0, 7] = \"pink2,StreetCard,DeedCard,Card\";\n BOARD[0, 6] = \"pink3,StreetCard,DeedCard,Card\";\n BOARD[0, 5] = \"train2,TrainCard,DeedCard,Card\";\n BOARD[0, 4] = \"orange1,StreetCard,DeedCard,Card\";\n BOARD[0, 3] = \"special5,SpecialCard,Cards\";\n BOARD[0, 2] = \"orange2,StreetCard,DeedCard,Card\";\n BOARD[0, 1] = \"orange3,StreetCard,DeedCard,Card\";\n }\n\n //roll picture is pressed\n private void pictureBox1_Click(object sender, EventArgs e)\n {\n //roll the dice\n int die1 = Logics.RollDice(pictureBox1);\n Thread.Sleep(50);\n int die2 = Logics.RollDice(pictureBox12);\n this.diceVal = die1 + die2;\n\n //move player\n if (this.x >= MINSIDE && this.x <= MAXSIDE && this.y == MAXSIDE) //buttom\n {\n int z = DIFF * this.diceVal; // how many pixels the player needs to move\n if (this.x - z > MINSIDE) //if the player destination is on the button\n {\n this.x = this.x - z;\n this.xPlace = this.xPlace - diceVal;\n Console.WriteLine(\"2\");\n }\n else if (this.x - z == MINSIDE - CORNERADD || this.x - z == MINSIDE + CORNERADD) //if the player destionation is on the bottom left corner\n {\n this.x = 15;\n this.y = 555;\n this.xPlace = 0;\n this.yPlace = 0;\n Console.WriteLine(\"3\");\n }\n else if (this.x - z < MINSIDE || this.x - z == MINSIDE + CORNERADD) //if the player's destination is on the left\n {\n z = z - this.x;\n this.y = MAXSIDE - z - 4 * CORNERADD;\n this.x = MINSIDE;\n this.yPlace = this.xPlace - diceVal + 10;\n this.xPlace = 0;\n Console.WriteLine(\"4\");\n }\n }\n else if (this.y >= MINSIDE && this.y <= MAXSIDE && this.x == MINSIDE) //left\n {\n int z = DIFF * this.diceVal; //how many pixels the player needs to move\n if (this.y - z > MINSIDE) //if the player destination is on the left\n {\n this.y = this.y - z;\n this.yPlace = this.yPlace - diceVal;\n }\n else if (this.y - z == MINSIDE - CORNERADD || this.y - z == MINSIDE + CORNERADD) //if the player destionation is on the top left corner\n {\n this.y = MINSIDE;\n this.yPlace = 0;\n this.xPlace = 0;\n }\n else if (this.y - z < MINSIDE) //if the player's destination is on the top\n {\n z = z - this.y;\n this.x = MINSIDE + z + 4 * CORNERADD;\n this.y = MINSIDE;\n this.xPlace = diceVal - this.yPlace;\n this.yPlace = 0;\n }\n }\n else if (this.x >= MINSIDE && this.x <= MAXSIDE && this.y == MINSIDE) //top\n {\n int z = DIFF * this.diceVal; //how many pixels the player needs to move\n if (this.x + z < MAXSIDE) //if the player destination is on the top\n {\n this.x = this.x + z;\n this.xPlace = this.xPlace + diceVal;\n }\n else if (this.x + z == MAXSIDE + CORNERADD || this.x + z == MAXSIDE - CORNERADD) //if the player destionation is on the top right corner\n {\n this.x = MAXSIDE;\n this.xPlace = 10;\n this.yPlace = 0;\n }\n else if (this.x + z > MAXSIDE) //if the player's destination is on the right\n {\n z = z - (MAXSIDE - this.x);\n this.y = MINSIDE + z + 2 * CORNERADD;\n this.x = MAXSIDE;\n this.yPlace = diceVal + this.xPlace - 10;\n this.xPlace = 10;\n }\n }\n else if (this.y >= MINSIDE && this.y <= MAXSIDE && this.x == MAXSIDE) //right\n {\n int z = DIFF * this.diceVal; //how many pixels the player needs to move\n if (this.y + z < MAXSIDE) //if the player destination is on the right\n {\n this.y = this.y + z;\n this.yPlace = this.yPlace + diceVal;\n }\n else if (this.y + z == MAXSIDE + CORNERADD || this.y + z == MAXSIDE - CORNERADD) //if the player destionation is on the bottom right corner\n {\n this.y = MAXSIDE;\n this.yPlace = 10;\n this.xPlace = 10;\n player.SetAddTotalMoney(400);\n label8.Text = player.GetTotalMoney().ToString();\n }\n else if (this.y + z > MAXSIDE) //if the player's destination is on the buttom\n {\n z = z - (MAXSIDE - this.y);\n this.x = MAXSIDE - z - 2 * CORNERADD;\n this.y = MAXSIDE;\n this.xPlace = 20 - this.yPlace - diceVal;\n this.yPlace = 10;\n player.SetAddTotalMoney(200);\n label8.Text = player.GetTotalMoney().ToString();\n }\n }\n\n player.SetX(this.xPlace);\n player.SetY(this.yPlace);\n\n //check if place on board is buyable\n this.conn.Open();\n string[] c = this.BOARD[this.xPlace, this.yPlace].Split(',');\n\n if (c[0].Contains(\"train\"))\n {\n string sql = $\"SELECT owned FROM [Table] WHERE name = train1, name = train2, name = train3, name = train4, \";\n this.cmd = new SqlCommand(sql, conn);\n this.dataReader = cmd.ExecuteReader();\n string output = \"\";\n while (this.dataReader.Read())\n {\n output = this.dataReader.GetValue(0) + \",\" + this.dataReader.GetValue(1);\n }\n if (output[int.Parse(c[0][c[0].Length - 1].ToString()) - 1] != player.GetNum() && output[int.Parse(c[0][c[0].Length - 1].ToString()) - 1] != 0)\n {\n int count = 0;\n for (int i = 0; i < 4; i++)\n {\n if (output[i] == output[int.Parse(c[0][c[0].Length - 1].ToString()) - 1])\n count++;\n }\n\n }\n }\n else if (c[0] != \"f\" && c[0] != \"pay\" && c[0] != \"get\" && !c[0].Contains(\"special\"))\n {\n string sql = $\"SELECT owned, price FROM [Table] WHERE name = '{c[0]}'\";\n this.cmd = new SqlCommand(sql, conn);\n this.dataReader = cmd.ExecuteReader();\n if (this.dataReader.Read())\n {\n int owned = int.Parse(this.dataReader.GetValue(0).ToString());\n string price = this.dataReader.GetValue(1).ToString();\n Console.WriteLine($\"this.dataReader: {owned}, {price}\");\n if (owned == 0)\n label2.Text = price.ToString();\n else if (owned != player.GetNum())\n {\n sql = $\"SELECT rent FROM [Table] WHERE name = '{c[0]}'\";\n this.cmd = new SqlCommand(sql, conn);\n this.dataReader = cmd.ExecuteReader();\n string rent = \"\";\n while (this.dataReader.Read())\n {\n rent = this.dataReader.GetValue(0).ToString();\n }\n\n player.SetSubTotalMoney(int.Parse(rent));\n label8.Text = player.GetTotalMoney().ToString();\n string m = $\"money,{player.GetNum()},{owned},{rent}\";\n Console.WriteLine($\"total: {player.GetTotalMoney()}\");\n //decreaseMoney(int.Parse(rent));\n send(m);\n }\n this.dataReader.Close();\n Console.WriteLine(\"9\");\n }\n }\n\n //sends message to other players about movement\n string msg = $\"movement,{player.GetNum()},{player.GetX().ToString()},{player.GetY().ToString()},2\";\n this.conn.Close();\n send(msg);\n }\n\n //pay picture is pressed\n private void pictureBox2_Click(object sender, EventArgs e)\n {\n try\n {\n Console.WriteLine($\"board: {this.BOARD[this.xPlace, this.yPlace]}\");\n string[] c = this.BOARD[this.xPlace, this.yPlace].Split(',');\n\n if (c[0] != \"f\" && c[0] != \"pay\" && c[0] != \"get\" && !c[0].Contains(\"special\"))\n {\n this.conn.Open();\n string sql = $\"SELECT owned, price FROM [Table] WHERE name = '{c[0]}'\";\n this.cmd = new SqlCommand(sql, conn);\n this.dataReader = cmd.ExecuteReader();\n string output = \"\";\n while (this.dataReader.Read())\n {\n output = this.dataReader.GetValue(0) + \",\" + this.dataReader.GetValue(1);\n }\n string[] arr = output.Split(',');\n int owned = int.Parse(arr[0]);\n int price = int.Parse(arr[1]);\n if ((c[1] == \"DeedCard\" || c[1] == \"StreetCard\" || c[1] == \"TrainCard\") && owned == 0)\n {\n if (player.GetTotalMoney() - price <= 0)\n {\n pictureBox1.Visible = false;\n pictureBox2.Visible = false;\n label1.Visible = false;\n label2.Visible = false;\n label16.Visible = true;\n label16.Text = $\"{player.GetColor()} lost!\";\n send($\"lose,{player.GetNum()}\");\n }\n else\n {\n sql = $\"UPDATE Table SET owned={player.GetNum()} WHERE email = '{c[0]}'\";\n this.cmd = new SqlCommand(sql, conn);\n if (c[1] == \"StreetCard\")\n player.SetAddStreetList(this.BOARD[this.xPlace, this.yPlace]);\n else if (c[1] == \"TrainCard\")\n {\n player.SetAddTrainList(this.BOARD[this.xPlace, this.yPlace]);\n string[] info = this.BOARD[this.xPlace, this.yPlace].Split(',');\n sql = $\"UPDATE Table SET owned=player.GetNum(), info[0]=player.GetNum() WHERE email = '{c[0]}'\";\n }\n else\n player.SetAddCompanyList(this.BOARD[this.xPlace, this.yPlace]);\n Console.WriteLine($\"price: {price}\");\n player.SetSubTotalMoney(price);\n Console.WriteLine($\"total: {player.GetTotalMoney()}\");\n decreaseMoney(price);\n label8.Text = player.GetTotalMoney().ToString();\n label5.Text = c[0];\n label7.Text = player.GetColor();\n string str = $\"property,{player.GetNum()},{c[0]},sold\";\n send(str);\n }\n }\n else if (owned != 0 && owned != player.GetNum()) // if owned by another player\n Console.WriteLine($\"{c[0]} is unavailable\");\n this.conn.Close();\n }\n }\n catch (Exception error)\n {\n Console.WriteLine(error);\n }\n }\n\n // decrease crash\n private void decreaseMoney(int total)\n {\n while (total > 0)\n {\n if (total % 500 != total && total % 500 <= int.Parse(label15.Text))\n {\n label15.Text = (int.Parse(label15.Text) - 500).ToString();\n total -= 500;\n }\n else if (total % 100 != total && total % 100 <= int.Parse(label14.Text))\n {\n label14.Text = (int.Parse(label14.Text) - 1).ToString();\n total -= 100;\n }\n else if (total % 50 != total && total % 50 <= int.Parse(label13.Text))\n {\n label13.Text = (int.Parse(label13.Text) - 1).ToString();\n total -= 50;\n }\n else if (total % 20 != total && total % 20 <= int.Parse(label12.Text))\n {\n label12.Text = (int.Parse(label12.Text) - 1).ToString();\n total -= 20;\n }\n else if (total % 10 != total && total % 10 <= int.Parse(label11.Text))\n {\n label11.Text = (int.Parse(label11.Text) - 1).ToString();\n total -= 10;\n }\n else if (total % 5 != total && total % 5 <= int.Parse(label10.Text))\n {\n label10.Text = (int.Parse(label10.Text) - 1).ToString();\n total -= 5;\n }\n else if (total % 1 != total && total % 1 <= int.Parse(label9.Text))\n {\n label9.Text = (int.Parse(label9.Text) - 1).ToString();\n total -= 1 * (total % 1);\n }\n }\n }\n\n //increase cash\n public void increaseMoney(int total)\n {\n while (total > 0)\n {\n if (total % 500 != total)\n {\n label15.Text = (int.Parse(label15.Text) - total % 500).ToString();\n total += 500 * (total % 500);\n }\n else if (total % 100 != total)\n {\n label14.Text = (int.Parse(label14.Text) - total % 100).ToString();\n total += 100 * (total % 100);\n }\n else if (total % 50 != total)\n {\n label13.Text = (int.Parse(label13.Text) - total % 50).ToString();\n total += 50 * (total % 50);\n }\n else if (total % 20 != total)\n {\n label12.Text = (int.Parse(label12.Text) - total % 20).ToString();\n total += 20 * (total % 20);\n }\n else if (total % 10 != total)\n {\n label11.Text = (int.Parse(label11.Text) - total % 10).ToString();\n total += 10 * (total % 10);\n }\n else if (total % 5 != total)\n {\n label10.Text = (int.Parse(label10.Text) - total % 5).ToString();\n total += 5 * (total % 5);\n }\n else if (total % 1 != total)\n {\n label9.Text = (int.Parse(label9.Text) - total % 1).ToString();\n total += 1 * (total % 1);\n }\n }\n }\n\n //a player moves\n private void moved(int numPlayer, int x, int y)\n {\n int xAxis, yAxis;\n if (x == 0) xAxis = MINSIDE;\n else if (x == 10) xAxis = MAXSIDE;\n else\n {\n xAxis = MINSIDE + CORNERADD + x * DIFF;\n }\n if (y == 0) yAxis = MINSIDE;\n else if (y == 10) yAxis = MAXSIDE;\n else\n {\n yAxis = MINSIDE + CORNERADD + y * DIFF;\n }\n if (numPlayer == 0)\n pictureBox3.Location = new Point(xAxis, yAxis);\n else if (numPlayer == 1)\n pictureBox11.Location = new Point(xAxis, yAxis);\n }\n\n //a player does something to a property\n private void property(int numPlayer, string playerColor, string propertyName, string activity)\n {\n this.conn.Open();\n if (activity == \"sold\")\n {\n string sql = $\"UPDATE Table SET owned=numPlayer WHERE name= = '{propertyName}'\";\n this.cmd = new SqlCommand(sql, conn);\n label5.Text = propertyName;\n label7.Text = playerColor;\n }\n }\n\n //a player pays money to another player\n private void money(int playerNum1, int playerNum2, int amount)\n {\n player.SetAddTotalMoney(amount);\n increaseMoney(amount);\n }\n\n //player send message to server\n private void send(string msg)\n {\n Console.WriteLine(msg);\n byte[] msgBuffer = Encoding.Default.GetBytes(msg);\n Program.sck.Send(msgBuffer, 0, msgBuffer.Length, 0);\n }\n\n //player wins the game\n public void win()\n {\n pictureBox1.Visible = false;\n pictureBox2.Visible = false;\n label1.Visible = false;\n label2.Visible = false;\n label16.Text = \"YOU WON!\";\n label16.Visible = true;\n }\n\n //player recieves message from server\n private void receive()\n {\n while (true)\n {\n byte[] buffer = new byte[255];\n string received = Encoding.ASCII.GetString(buffer, 0, Program.sck.Receive(buffer));\n string[] msg = received.Split(',');\n Console.WriteLine(received);\n if (msg[0] == \"movement\")\n {\n moved(int.Parse(msg[1]), int.Parse(msg[2]), int.Parse(msg[3]));\n }\n else if (msg[0] == \"property\")\n property(int.Parse(msg[1]), msg[2], msg[3], msg[4]);\n else if (msg[0] == \"money\" && int.Parse(msg[2]) == player.GetNum())\n money(int.Parse(msg[1]), int.Parse(msg[2]), int.Parse(msg[3]));\n else if (msg[0] == \"win\")\n win();\n }\n }\n\n }\n}\n" }, { "alpha_fraction": 0.4401306211948395, "alphanum_fraction": 0.4542815685272217, "avg_line_length": 29.955055236816406, "blob_id": "ecceb47e5ede6a9f3d434479f45dd04a6f30eace", "content_id": "62b30b0c6f406b921a0d2019f651922e58dd31b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2758, "license_type": "no_license", "max_line_length": 95, "num_lines": 89, "path": "/Tradopoly_NS/SignUp.cs", "repo_name": "NaamaSa/Tradopoly_NS", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Threading.Tasks;\nusing System.Net;\nusing System.Net.Sockets;\n\nnamespace Tradopoly_NS\n{\n public partial class SignUp : Form\n {\n public SignUp()\n {\n InitializeComponent();\n }\n\n //if signin button is pressed\n private void button1_Click(object sender, EventArgs e)\n {\n SignIn c = new SignIn();\n this.Hide();\n c.ShowDialog();\n this.Close();\n }\n \n //if signup button is pressed\n private void button2_Click(object sender, EventArgs e)\n {\n try\n {\n if (textBox2.Text == textBox3.Text)\n {\n string msg = $\"signup,{textBox4.Text},{textBox1.Text},{textBox3.Text}\";\n Send(msg);\n string back = receive();\n if (back == \"success\")\n {\n label7.Text = \"SUCCESS\";\n label7.Location = new Point(338, 352);\n label7.ForeColor = Color.Green;\n label1.Visible = false;\n label2.Visible = false;\n label3.Visible = false;\n label4.Visible = false;\n textBox1.Visible = false;\n textBox2.Visible = false;\n textBox3.Visible = false;\n textBox4.Visible = false;\n SignIn c = new SignIn();\n this.Hide();\n c.ShowDialog();\n this.Close();\n }\n else if (back == \"fail-email\")\n {\n label7.Text = \"FAIL - The email is already in use\";\n label7.Location = new Point(237, 352);\n label7.ForeColor = Color.Red;\n }\n }\n }\n catch (Exception error)\n {\n Console.WriteLine(error);\n }\n\n }\n\n //sends message to server\n private void Send(string msg)\n {\n byte[] msgBuffer = Encoding.Default.GetBytes(msg);\n Program.sck.Send(msgBuffer, 0, msgBuffer.Length, 0);\n }\n\n //recieves message from server\n private string receive()\n {\n byte[] buffer = new byte[255];\n string received = Encoding.ASCII.GetString(buffer, 0, Program.sck.Receive(buffer));\n return received;\n }\n\n }\n}\n\n" }, { "alpha_fraction": 0.5399208664894104, "alphanum_fraction": 0.5470178723335266, "avg_line_length": 34.911766052246094, "blob_id": "37031f13625ff677a4a6d20ad5012a39bacb96de", "content_id": "c8265b74186332285ccfccb963deb7e85f60cc49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7327, "license_type": "no_license", "max_line_length": 116, "num_lines": 204, "path": "/Server.py", "repo_name": "NaamaSa/Tradopoly_NS", "src_encoding": "UTF-8", "text": "\nimport socket\nimport sys\nimport sqlite3\nfrom threading import Thread\nimport time\nfrom sqlite3 import Error\n\nserver_socket = socket.socket()\nserver_socket.bind(('0.0.0.0', 8000))\nserver_socket.listen(5)\nclients_sockets = []\nmessages_to_send = []\nclient_list = []\nadmin_connected = False\ntwo_players_list = [[None, None]]\nthree_players_list = [[None, None, None]]\nfour_players_list = [[None, None, None, None]]\n\n\n# creates conncetion with sqlite\ndef create_connection(db_file):\n conn = None\n try:\n conn = sqlite3.connect(db_file)\n return conn\n except Exception as e:\n print(e)\n return conn\n\n\n# signs up user\ndef signup(info_list, client_socket):\n try:\n conn = create_connection(r\"C:\\Users\\Park-Hamada Student\\Desktop\\Tradopoly_NS\\users.db\")\n c = conn.cursor()\n email = info_list[1]\n username = info_list[2]\n password = info_list[3]\n c.execute(f\"SELECT * FROM users WHERE email = '{email}'\")\n conn.commit()\n exists = len(c.fetchall()) > 0\n if not exists:\n c.execute(f\"INSERT INTO users VALUES('{email}', '{username}', '{password}' )\")\n conn.commit()\n time.sleep(0.5)\n client_socket.send(\"success\".encode())\n else:\n time.sleep(0.5)\n client_socket.send(\"fail-email\".encode())\n except Error as e:\n print(e)\n\ndef client_game(list, c):\n for game in list:\n for client in game:\n if client == c:\n return game\n\n\n# sends messages to all clients\ndef send_waiting_message(message, num, client_socket):\n print(message + \",\" + num)\n if num == \"2\":\n game = client_game(two_players_list,client_socket)\n for client in game:\n client.send(message.encode())\n elif num == \"3\":\n game = client_game(three_players_list, client_socket)\n for client in game:\n client.send(message.encode())\n elif num == \"4\":\n game = client_game(four_players_list, client_socket)\n for client in game:\n client.send(message.encode())\n\n\n# function checks if user info is in database. if yes - returns 'success',\n# if no - returns 'fail - mail/password is incorrect'\ndef check_signin(info_list, client_socket):\n conn = create_connection(r\"C:\\Users\\Park-Hamada Student\\Desktop\\Tradopoly_NS\\users.db\")\n c = conn.cursor()\n email = info_list[1]\n password = info_list[2]\n sql = f\"SELECT * FROM users WHERE email='{email}' AND password = '{password}'\"\n c.execute(sql)\n conn.commit()\n data = c.fetchall()\n if len(data) > 0:\n client_socket.send(\"success\".encode())\n else:\n client_socket.send(\"fail\".encode())\n\n\n# client quits\ndef client_quit(current_socket):\n clients_sockets.remove(current_socket)\n print(\"Connection with client closed\")\n for c in client_list:\n if c.get_conn() is current_socket:\n if c.get_is_manager():\n string = \"code:2,@{}\".format(c.get_name())\n else:\n string = \"code:2,{}\".format(c.get_name())\n send_waiting_message(string)\n client_list.remove(c)\n\n\n# check the type of message\ndef check_message(client_socket, address):\n while True:\n try:\n data = client_socket.recv(1024).decode()\n print(data)\n info_list = data.split(\",\")\n if info_list[0] == \"signup\":\n signup(info_list, client_socket)\n elif info_list[0] == \"signin\":\n check_signin(info_list, client_socket)\n elif info_list[0].lower() == \"quit\": # client quits chats\n client_quit(client_socket)\n elif info_list[0].lower() == \"movement\": # client moves\n send_waiting_message(data, info_list[4], client_socket)\n elif info_list[0].lower() == \"property\": # client does something to property\n send_waiting_message(data, info_list[4], client_socket)\n elif info_list[0].lower() == \"money\": # client send money to another\n send_waiting_message(data, info_list[4], client_socket)\n elif info_list[0].lower() == \"join_2\": # client choose game with 2 players\n game = two_players_list[get_searching_game(two_players_list)]\n for client in game:\n if client is None:\n game[game.index(client)] = client_socket\n print(f\"game:{game}\")\n if None in game:\n client_socket.send(\"Not Full\".encode())\n else:\n two_players_list.insert(len(two_players_list), [None, None])\n for player in game:\n player.send(f\"Full,{game.index(player)}\".encode())\n break\n elif info_list[0].lower() == \"join_3\": # client choose game with 3 players\n game = three_players_list[get_searching_game(three_players_list)]\n for client in game:\n if client is None:\n client = client_socket\n if None in game:\n client_socket.send(\"Not Full\".encode())\n else:\n print(\"a\")\n three_players_list.insert(len(three_players_list), (None, None, None))\n for player in game:\n player.send(f\"Full,{game.index(player)}\".encode())\n elif info_list[0].lower() == \"join_4\": # client choose game with 4 players\n game = four_players_list[get_searching_game(four_players_list)]\n for client in game:\n if client is None:\n client = client_socket\n if None in game:\n client_socket.send(\"Not Full\".encode())\n else:\n four_players_list.insert(len(four_players_list), (None, None, None, None))\n for player in game:\n player.send(f\"Full,{game.index(player)}\".encode())\n elif info_list[0].lower() == \"lose\":\n print(\"lose\")\n except:\n pass\n\n\ndef get_searching_game(list):\n for tup in list:\n if None in tup:\n return list.index(tup)\n\n\ndef print_users():\n conn = create_connection(r\"C:\\Users\\Park-Hamada Student\\Desktop\\Tradopoly_NS\\users.db\")\n c = conn.cursor()\n print(c.execute(\n f\"SELECT * FROM users\").fetchall())\n conn.commit()\n\n\ndef main():\n while True:\n client_socket, address = server_socket.accept()\n print(\"new client\" + address[0])\n clients_sockets.append(client_socket)\n thread = Thread(target=check_message, args=(client_socket, address,))\n thread.start()\n\n\ndef create_table(conn, str):\n try:\n c=conn.cursor()\n c.execute(str)\n except Error as e:\n print(e)\n\n\nif __name__ == '__main__':\n conn = create_connection(r\"C:\\Users\\Park-Hamada Student\\Desktop\\Tradopoly_NS\\users.db\")\n str = \"CREATE TABLE IF NOT EXISTS users(email text PRIMARY KEY, username text NOT NULL, password text NOT NULL)\"\n create_table(conn, str)\n main()\n" }, { "alpha_fraction": 0.5941747426986694, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 23.5238094329834, "blob_id": "32f9b4bdb3c64e705ae1785ee413ebdc5a89d7de", "content_id": "b6a3cbae468346f49582303f37ee0055078b1502", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 517, "license_type": "no_license", "max_line_length": 136, "num_lines": 21, "path": "/Tradopoly_NS/Properties/Logics.cs", "repo_name": "NaamaSa/Tradopoly_NS", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Windows.Forms;\nusing System.Text;\n\nnamespace Tradopoly_NS\n{\n public class Logics\n {\n public static int RollDice(PictureBox px)\n {\n int dice = 0;\n Random rnd = new Random();\n dice = rnd.Next(1, 7);\n\n px.Image = Image.FromFile(@\"C:\\Users\\Park-Hamada Student\\Desktop\\Tradopoly_NS\\Tradopoly_NS\\Resources\\Dice\" + dice + \".PNG\");\n return dice;\n }\n }\n}\n" }, { "alpha_fraction": 0.5540540814399719, "alphanum_fraction": 0.5632678270339966, "avg_line_length": 25.24193572998047, "blob_id": "f955e0abd444492e7e9a47f0f873ac0857dcc893", "content_id": "a3c068de637df185d594000aa505c25002724893", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1630, "license_type": "no_license", "max_line_length": 95, "num_lines": 62, "path": "/Tradopoly_NS/FirstPage.cs", "repo_name": "NaamaSa/Tradopoly_NS", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Net;\nusing System.Net.Sockets;\n\nnamespace Tradopoly_NS\n{\n public partial class FirstPage : Form\n {\n public FirstPage()\n {\n InitializeComponent();\n }\n\n //2 players button is pressed\n private void button1_Click(object sender, EventArgs e)\n {\n this.Hide();\n AwaitingPlayers c = new AwaitingPlayers(2);\n c.ShowDialog();\n this.Close();\n }\n\n //3 players button is pressed\n private void button2_Click(object sender, EventArgs e)\n {\n this.Hide();\n AwaitingPlayers c = new AwaitingPlayers(3);\n c.ShowDialog();\n this.Close();\n }\n\n //4 players button is pressed\n private void button3_Click(object sender, EventArgs e)\n {\n this.Hide();\n AwaitingPlayers c = new AwaitingPlayers(4);\n c.ShowDialog();\n this.Close();\n }\n\n //sends message to server\n private void Send(string msg)\n {\n byte[] msgBuffer = Encoding.Default.GetBytes(msg);\n Program.sck.Send(msgBuffer, 0, msgBuffer.Length, 0);\n }\n\n //recieves message from server\n private string receive()\n {\n byte[] buffer = new byte[255];\n string received = Encoding.ASCII.GetString(buffer, 0, Program.sck.Receive(buffer));\n return received;\n }\n }\n}\n\n" }, { "alpha_fraction": 0.4740186929702759, "alphanum_fraction": 0.49046728014945984, "avg_line_length": 29.386363983154297, "blob_id": "05e545d77695c6dc7111cbc528cc86c76d3810d5", "content_id": "93ed127779fc4a72b7c64dfc3d09dfb2654b6ad4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2677, "license_type": "no_license", "max_line_length": 99, "num_lines": 88, "path": "/Tradopoly_NS/SignIn.cs", "repo_name": "NaamaSa/Tradopoly_NS", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Net;\nusing System.Net.Sockets;\n\nnamespace Tradopoly_NS\n{\n public partial class SignIn : Form\n {\n public SignIn()\n {\n InitializeComponent();\n IPAddress ipAddress = IPAddress.Parse(\"127.0.0.1\");\n IPEndPoint remoteEP = new IPEndPoint(ipAddress, 8000);\n Program.sck = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);\n Program.sck.Connect(remoteEP);\n }\n\n //sign in button\n private void button1_Click(object sender, EventArgs e)\n {\n try\n {\n string msg = $\"signin,{textBox1.Text},{textBox2.Text}\";\n Send(msg);\n string back = receive();\n if (back == \"success\")\n {\n label4.Text = \"SUCCESS\";\n label4.Location = new Point(338, 256);\n label4.ForeColor = Color.Green;\n\n label1.Visible = false;\n label2.Visible = false;\n label3.Visible = false;\n label4.Visible = false;\n textBox1.Visible = false;\n textBox2.Visible = false;\n\n FirstPage c = new FirstPage();\n this.Hide();\n c.ShowDialog();\n this.Close();\n }\n else if (back == \"fail\")\n {\n label4.Text = \"FAIL - email or password is inccorrect\";\n label4.Location = new Point(237, 256);\n label4.ForeColor = Color.Red;\n }\n\n }\n catch (Exception error)\n {\n Console.WriteLine(error);\n }\n }\n \n //sign up button\n private void button2_Click(object sender, EventArgs e)\n {\n this.Hide();\n SignUp c = new SignUp();\n c.ShowDialog();\n this.Close();\n }\n\n //sends message to server\n private void Send(string msg)\n {\n byte[] msgBuffer = Encoding.Default.GetBytes(msg);\n Program.sck.Send(msgBuffer, 0, msgBuffer.Length, 0);\n }\n\n //recieves message from server\n private string receive()\n {\n byte[] buffer = new byte[255];\n string received = Encoding.ASCII.GetString(buffer, 0, Program.sck.Receive(buffer));\n return received;\n }\n }\n}\n\n" } ]
8
LimJunBeom/SSDAutoLabel-master
https://github.com/LimJunBeom/SSDAutoLabel-master
a8afcaf4b35d37cff99d9eeb34c1506da36f0a3e
c1acbf472bab92142504a012c7ba97ec92babc4e
0bcfceaa70142f4952d94c61e00e787b67c8682e
refs/heads/main
2023-04-28T05:50:33.872910
2021-05-05T16:49:30
2021-05-05T16:49:30
364,645,941
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6623272895812988, "alphanum_fraction": 0.6724229454994202, "avg_line_length": 35.53398132324219, "blob_id": "db625752bde72472e46cce903670fa7be50b8d08", "content_id": "bccd3a43ed9116c1a41d8354994a17e732a986ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7528, "license_type": "no_license", "max_line_length": 146, "num_lines": 206, "path": "/classify.py", "repo_name": "LimJunBeom/SSDAutoLabel-master", "src_encoding": "UTF-8", "text": "######## Webcam Object Detection Using Tensorflow-trained Classifier #########\n#\n# Author: Evan Juras\n# Date: 9/28/19\n# Description: \n# This program uses a TensorFlow Lite object detection model to perform object \n# detection on an image or a folder full of images. It draws boxes and scores \n# around the objects of interest in each image.\n#\n# This code is based off the TensorFlow Lite image classification example at:\n# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/examples/python/label_image.py\n#\n# I added my own method of drawing boxes and labels using OpenCV.\n\n# Import packages\nimport os\nimport argparse\nimport cv2\nimport numpy as np\nimport sys\nimport glob\nimport importlib.util\nimport time\nimport shutil\n\n# Define and parse input arguments\nparser = argparse.ArgumentParser()\nparser.add_argument('--modeldir', help='Folder the .tflite file is located in',\n required=True)\nparser.add_argument('--graph', help='Name of the .tflite file, if different than detect.tflite',\n default='detect.tflite')\nparser.add_argument('--labels', help='Name of the labelmap file, if different than labelmap.txt',\n default='labelmap.txt')\nparser.add_argument('--threshold', help='Minimum confidence threshold for displaying detected objects',\n default=0.5)\n\nparser.add_argument('--imagedir', help='Name of the folder containing images to perform detection on. Folder must contain only images.',\n default=None)\nparser.add_argument('--failimagedir', help='Name of the folder containing images to perform fail detection on.',\n default=None)\nparser.add_argument('--successdir', help='Name of the xml folder containing images xml.',\n default=None)\nparser.add_argument('--edgetpu', help='Use Coral Edge TPU Accelerator to speed up detection',\n action='store_true')\n\nargs = parser.parse_args()\n\nMODEL_NAME = args.modeldir\nGRAPH_NAME = args.graph\nLABELMAP_NAME = args.labels\nmin_conf_threshold = float(args.threshold)\nuse_TPU = args.edgetpu\n\n# Parse input image name and directory. \nIM_DIR = args.imagedir\nFA_DIR = args.failimagedir\nSU_DIR = args.successdir\n\nCWD_PATH = os.getcwd()\n\nif IM_DIR:\n PATH_TO_IMAGES = os.path.join(CWD_PATH,IM_DIR)\n images = glob.glob(PATH_TO_IMAGES + '/*')\n\nif FA_DIR:\n PATH_TO_FAIMAGES = os.path.join(CWD_PATH,FA_DIR)\n failimages = glob.glob(PATH_TO_FAIMAGES)[0]\n \nif SU_DIR:\n PATH_TO_SUCCESS = os.path.join(CWD_PATH,SU_DIR)\n successimages = glob.glob(PATH_TO_SUCCESS)[0]\n\n\n\n# Import TensorFlow libraries\n# If tflite_runtime is installed, import interpreter from tflite_runtime, else import from regular tensorflow\n# If using Coral Edge TPU, import the load_delegate library\npkg = importlib.util.find_spec('tflite_runtime')\nif pkg:\n from tflite_runtime.interpreter import Interpreter\n if use_TPU:\n from tflite_runtime.interpreter import load_delegate\nelse:\n from tensorflow.lite.python.interpreter import Interpreter\n if use_TPU:\n from tensorflow.lite.python.interpreter import load_delegate\n\n# If using Edge TPU, assign filename for Edge TPU model\nif use_TPU:\n # If user has specified the name of the .tflite file, use that name, otherwise use default 'edgetpu.tflite'\n if (GRAPH_NAME == 'detect.tflite'):\n GRAPH_NAME = 'edgetpu.tflite'\n\n\n# Get path to current working directory\nCWD_PATH = os.getcwd()\n\n# Define path to images and grab all image filenames\n\n\n# Path to .tflite file, which contains the model that is used for object detection\nPATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,GRAPH_NAME)\n\n# Path to label map file\nPATH_TO_LABELS = os.path.join(CWD_PATH,MODEL_NAME,LABELMAP_NAME)\n\n# Load the label map\nwith open(PATH_TO_LABELS, 'r') as f:\n labels = [line.strip() for line in f.readlines()]\n\n# Have to do a weird fix for label map if using the COCO \"starter model\" from\n# https://www.tensorflow.org/lite/models/object_detection/overview\n# First label is '???', which has to be removed.\nif labels[0] == '???':\n del(labels[0])\n\n# Load the Tensorflow Lite model.\n# If using Edge TPU, use special load_delegate argument\nif use_TPU:\n interpreter = Interpreter(model_path=PATH_TO_CKPT,\n experimental_delegates=[load_delegate('libedgetpu.so.1.0')])\n print(PATH_TO_CKPT)\nelse:\n interpreter = Interpreter(model_path=PATH_TO_CKPT)\n\ninterpreter.allocate_tensors()\n\n# Get model details\ninput_details = interpreter.get_input_details()\noutput_details = interpreter.get_output_details()\nheight = input_details[0]['shape'][1]\nwidth = input_details[0]['shape'][2]\n\nfloating_model = (input_details[0]['dtype'] == np.float32)\n\ninput_mean = 127.5\ninput_std = 127.5\n\n# Loop over every image and perform detection\nfor image_path in images:\n start_time = time.time()\n # Load image and resize to expected shape [1xHxWx3]\n image = cv2.imread(image_path)\n image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n imH, imW, _ = image.shape \n image_resized = cv2.resize(image_rgb, (width, height))\n input_data = np.expand_dims(image_resized, axis=0)\n \n filename = image_path.split('/')[-1]\n print('image file name',filename)\n \n \n # Normalize pixel values if using a floating model (i.e. if model is non-quantized)\n if floating_model:\n input_data = (np.float32(input_data) - input_mean) / input_std\n\n # Perform the actual detection by running the model with the image as input\n interpreter.set_tensor(input_details[0]['index'],input_data)\n interpreter.invoke()\n \n num = []\n \n # Retrieve detection results\n boxes = interpreter.get_tensor(output_details[0]['index'])[0] # Bounding box coordinates of detected objects\n classes = interpreter.get_tensor(output_details[1]['index'])[0] # Class index of detected objects\n scores = interpreter.get_tensor(output_details[2]['index'])[0] # Confidence of detected objects\n #num = interpreter.get_tensor(output_details[3]['index'])[0] # Total number of detected objects (inaccurate and not needed)\n\n # Loop over all detections and draw detection box if confidence is above minimum threshold\n for i in range(len(scores)):\n if ((scores[i] > min_conf_threshold) and (scores[i] <= 1.0)):\n\n # Get bounding box coordinates and draw box\n # Interpreter can return coordinates that are outside of image dimensions, need to force them to be within image using max() and min()\n ymin = int(max(1,(boxes[i][0] * imH)))\n xmin = int(max(1,(boxes[i][1] * imW)))\n ymax = int(min(imH,(boxes[i][2] * imH)))\n xmax = int(min(imW,(boxes[i][3] * imW)))\n \n \n cv2.rectangle(image, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2)\n \n if scores[i] > 0.5:\n num.append(scores[i])\n\n \n \n if len(num) == 0:\n print('fail------------------')\n time.sleep(0.1)\n shutil.move(PATH_TO_IMAGES+'/'+filename, failimages+'/'+filename)\n \n if len(num) !=0:\n print('success')\n # All the results have been drawn on the image, now display the image\n #cv2.imshow('filename', image)\n \n end_time = time.time()\n process_time = end_time - start_time\n print(\"======== A frame took {:.3f} seconds=================\".format(process_time))\n # Press any key to continue to next image, or press 'q' to quit\n if cv2.waitKey(0) == ord('q'):\n break\n\n# Clean up\ncv2.destroyAllWindows()\n\n\n" }, { "alpha_fraction": 0.760343074798584, "alphanum_fraction": 0.7719475030899048, "avg_line_length": 41.17021179199219, "blob_id": "7b81204219202e0442b7e967628c9af58a3fa1db", "content_id": "f70cbb6630ba7ac4933ad18fcd77eb56a020967c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2924, "license_type": "no_license", "max_line_length": 191, "num_lines": 47, "path": "/README.md", "repo_name": "LimJunBeom/SSDAutoLabel-master", "src_encoding": "UTF-8", "text": "# SSDAutoLabel\nhttps://www.youtube.com/watch?v=hECRUHlTTqg\n\nI had SSD - Mobilenet.\n\nI needed more image dataset.\n\nI had to take pictures and label them with a labeling program. It was so annoying. So I made an Auto Labeling code using ssd model that I had.\n\nIf you have your own ssd model, change it and apply it. \n\npython3 autolabel.py --modeldir=model --imagedir=images --failimagedir=fail --successdir=success\n\nimagedir is images in folder failimagedir is folder that sended images that failed to detect drone successdir is folder that generated xml file\n\nput your model in model folder\n\nif you write 'space' key, then apear next picture. if you write 'd' key, then delete xml file and move strange image file to failfolder. so if you see not good label image, then enter 'd' key\n\nand if your yolo can not find object that you want to detect, my code will print fail and auto move the picture to failfolder\n\neventually, you just label pictures that fail to be detected\n\n1. classify detected pictures and not detected pictures\n python classify.py --modeldir=model --imagedir=images --failimagedir=fail --successdir=success\n2.make sure\n python3 autolabel.py --modeldir=model --imagedir=images --failimagedir=fail --successdir=succes\n저는 드론 ssd가 있었고 더 많은 이미지데이터셋을 원했습니다.\n\n그래서 수백장의 드론 사진을 찍었는데 라벨링하는 것이 너무 귀찮아서\n\n내가 가지고 있는 ssd mobilenet으로 라벨링을 하면 편하게 할수 있지 않을까 하여 작성해보았습니다.\n\n처음에는 사진들 넣고 쫙 돌렸으나 디텍팅이 되지않은 사진들도 있고 이상한곳에 디텍팅한 사진들도 있어서 잘 라벨링을 하는지 모니터링하면서 진행해야했습니다.\n\n따라서 만약에 라벨링이 잘되면 엔터를 눌러 다음 사진으로 넘어가세요. 자동으로 xml파일이 생성되어 있을겁니다.\n\n엔터를 누른 후 나온 다음 사진이 라벨링이 안되어 있으면 xml파일을 생성하지 않고 fail되었다고 print가 되며 그 사진은 ‘실패폴더’로 이동합니다. 또 라벨링은 되어있는데 엉뚱한 곳을 라벨링하고 있으면 ‘d’ 키를 누르세요\n\nd 키를 누르면 만들어진 xml파일이 삭제되고 그 사진은 ‘실패폴더’로 이동합니다.\n\n결국 저는 탐지 못한 드론 사진만 라벨링하면 됩니다.\n1. 먼저 classify.py로 드론이 감지되는 사진과 아닌 사진으로 나눕니다. 드론으로 감지안된 사진은 직접 라벨링해야합니다.\n2. 드론으로 감지된 사진폴더를 autolabel.py로 실행하여 사진한장씩 불러와서 라벨링이 잘되었는지 보면서 진행합니다 라벨링이 잘안되어있으면 \nd를 누르면 만들어진 xml파일도 삭제되고 성공폴더로 이동되어있던 사진도 돌아옵니다.\n\nhttps://blog.naver.com/khw11044/221926134482\n" } ]
2
jackiekazil/golden-ratio
https://github.com/jackiekazil/golden-ratio
b143cfdbce588400ca46cce358398b4d5cb67a40
7f41c8ec7abc105fe0ce2ec3c465b6fb8ca45057
3718fa357bb11a4feefbd8625a6b91e6ce50a6c8
refs/heads/master
2020-04-09T03:50:16.326101
2012-06-05T20:30:15
2012-06-05T20:30:15
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6507513523101807, "alphanum_fraction": 0.7084343433380127, "avg_line_length": 40.27000045776367, "blob_id": "25cf33177eae1b3cbcddfde6bb28d34784797c46", "content_id": "6ed59f7bdcb553edc0464c121034656547bcb00a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4127, "license_type": "no_license", "max_line_length": 204, "num_lines": 100, "path": "/README.md", "repo_name": "jackiekazil/golden-ratio", "src_encoding": "UTF-8", "text": "![Zoom previews](https://github.com/nvkelso/golden-ratio/raw/master/images/zoom_start_east_coast.png)\n\n_Legend: Grays = zooms 10 + 11, green = 12, light green = 13, orange = 14, yellow = 15, dark orange = 16, pink = 17, dark red = 18+_\n\n**When pre-rendering the whole world is too much, render less. But which less?**\n\nLand versus ocean is a basic proxy. But population and internet usage should also factor in.\n\nWe proxy which tiles are important by looking at:\n\n* Twitter Geocoded tweets\n* Flickr photo sharing\n* GeoIP addresses\n* General population density\n\n[READ MORE on the Stamen blog about Log Maps »](http://content.stamen.com/log_maps)\n\nThis first version is just for Twitter proxy.\n\nThe data you want is in:\n\n* data/twitter_bbox.tsv\n\nInitial version uses Twitter geotagged tweet density \"binary world\" bounding boxes curtsey of Eric Fischer.\n\nhttp://www.flickr.com/photos/walkingsf/6159680639/in/photostream/\n\nLater versions will include more proxies and refine the regions and country tagging. Also the ability to reference past tile view history (popularity) logs in addition to the existing forecasting ability.\n\nFor more image previews, see: http://www.flickr.com/photos/ke6cat/sets/72157629625222031/\n\nYou should see savings of 80% to 99% in which tiles get rendered from zoom 11 in.\n\n***Example coverage:***\n\n* Zoom 18 - Within 10 km of 70 global metros (DC but not Baltimore, SF but not San Jose, NYC but not Jersey)\n* Zoom 17 - Within 20 km of 250 metros (DC and Baltimore, SF and San Jose, NYC and Jersey)\n* Zoom 16 - Within 20 km of 2500 metro and micropolitan areas (picks up regional population centers like Santa Rosa CA, Harrisburg PA, Albany NY)\n* Zoom 15 - Most core metro areas and their inner suburbs, bounding box area threshold\n* Zoom 14 - Most core metro areas and their exurbs, bounding box area threshold\n* Zoom 13 - Metro and micorpolitan areas in 12. Now less than 1% of land area.\n* Zoom 12 - Most of NA, western Europe, elsewhere that are on the net. About 5% of land area and less than 2% of globe. \n* Zoom 11 - Not ocean, not unpopulated, is on the net. Ocean is about 71% of the surface: of the 29% of land, we're looking at just half of that.\n* Zoom 0 through 10 - global\n\n# Tools\n\n##seed_splitter\n\nHave 16 cores on your machine or need to render in the cloud? Split your large task list into accomplishable bits.\n\n###Usage:\n\n python seed_splitter.py <filename> <num_parts>\n \nWhere `<num_parts>` might be the number of cores on your machine minus 1 (eg: 16-1=5).\n\n##seed_parser\n\n###Usage:\n\nThis script will generate a set of zoom-specific files with tilestache-seed\ncommands from a bounding box file.\n\n python seed_parser.py -t '-c /usr/local/tilefarm/gunicorn/tilestache-watercolor.cfg -l watercolor ' -b 'twitter_bbox.tsv'\n\n##countTiles\n\n###Usage:\n\n python countTiles.py\n\nDefault output for US (excluding Alaska and Hawaii):\n\n Geographic area:\n -126.900000\t left most Longitude (minLong)\n 22.200000\t bottom most Latitude (minLat)\n -67.200000\t right most Longitude (maxLong)\n 50.000000\t top most Latitude (maxLat)\n Zoom coverage:\n 4\tleast detailed zoom\n 14\tmost detailed zoom\n Total tiles:\n 5,799,459 > 10,000,000\n \n SETUP cost: $71.74\n (One time cost: $13.75 storage, $57.99 posting)\n (Note: If there is a data update, apply this setup cost again.)\n \n MONTHLY viewing costs:\n 10,000 visits: $ 6.46, with cloudfront: $ 12.92\n 250,000 visits: $ 164.32, with cloudfront: $ 328.64\n 1,000,000 visits: $ 657.64, with cloudfront: $ 1,315.29\n 10,000,000 visits: $6,577.52,\t with cloudfront: $13,155.03\n \n (Assumption: Each map visitor will request 200 tiles (load map, pan pan pan pan pan)\n (Note: CloudFront is a distributed content delivery network that makes viewing your tiles faster...\n Amazon charges once for getting it out of the S3 bucket and into CF again for the CF view...\n If all the views are in the same spot, 1/2 the CF cost listed here. If viewing many random\n places,this value.)" }, { "alpha_fraction": 0.6573359370231628, "alphanum_fraction": 0.6689189076423645, "avg_line_length": 29.485294342041016, "blob_id": "61d1ef9d963b13d74810f65b02b79034ba8df75c", "content_id": "3a65d888b67b36f1be17e9cdbfb17a3dd861d962", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2072, "license_type": "no_license", "max_line_length": 105, "num_lines": 68, "path": "/tools/calculate_centroids.py", "repo_name": "jackiekazil/golden-ratio", "src_encoding": "UTF-8", "text": "# I had errors using this script\n# http://www.kralidis.ca/blog/2010/04/28/batch-centroid-calculations-with-python-and-ogr/\n\nimport sys\nimport osgeo.ogr as ogr\n\n# process args\nif len(sys.argv) < 4:\n print 'Usage: %s <format> <input> <output>' % sys.argv[0]\n sys.exit(1)\n\n# open input file\ndataset_in = ogr.Open(sys.argv[2])\nif dataset_in is None:\n print 'Open failed.\\n'\n sys.exit(2)\n\nlayer_in = dataset_in.GetLayer(0)\nfeature_in = layer_in.GetNextFeature()\n\n# create output\ndriver_out = ogr.GetDriverByName(sys.argv[1])\nif driver_out is None:\n print '%s driver not available.\\n' % sys.argv[1]\n sys.exit(3)\n\ndataset_out = driver_out.CreateDataSource(sys.argv[3])\nif dataset_out is None:\n print 'Creation of output file failed.\\n'\n sys.exit(4)\n\nlayer_out = dataset_out.CreateLayer(sys.argv[3], None, ogr.wkbPoint)\nif layer_out is None:\n print 'Layer creation failed.\\n'\n sys.exit(5)\n\n# setup attributes\nfeature_in_defn = layer_in.GetLayerDefn()\n\nfor i in range(feature_in_defn.GetFieldCount()):\n field_def = feature_in_defn.GetFieldDefn(i)\n if layer_out.CreateField(field_def) != 0:\n print 'Creating %s field failed.\\n' % field_def.GetNameRef()\n\nlayer_in.ResetReading()\nfeature_in = layer_in.GetNextFeature()\n\n# loop over input features, calculate centroid and output features\nwhile feature_in is not None:\n feature_out_defn = layer_out.GetLayerDefn()\n feature_out = ogr.Feature(feature_out_defn)\n for i in range(feature_out_defn.GetFieldCount()):\n try:\n #if feature_in is not \"NoneType\" :\n feature_out.SetField( feature_out_defn.GetFieldDefn(i).GetNameRef(), feature_in.GetField(i) )\n geom = feature_in.GetGeometryRef()\n centroid = geom.Centroid()\n feature_out.SetGeometry(centroid)\n if layer_out.CreateFeature(feature_out) != 0:\n print 'Failed to create feature.\\n'\n sys.exit(6)\n except:\n print \"Oops!\"\n feature_in = layer_in.GetNextFeature()\n\n# cleanup\ndataset_in.Destroy()\ndataset_out.Destroy()" }, { "alpha_fraction": 0.5312342643737793, "alphanum_fraction": 0.7015113234519958, "avg_line_length": 35.099998474121094, "blob_id": "74fa54b62ea62ce7e3650b7f272ddc719782b1ff", "content_id": "8a7b91e6fb4859926c0c975ecebdd5acc429b2bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 3970, "license_type": "no_license", "max_line_length": 92, "num_lines": 110, "path": "/reference/twitter_bbox/mapnik/Makefile", "repo_name": "jackiekazil/golden-ratio", "src_encoding": "UTF-8", "text": "#mexico 7/19.992/-100.867\n#lowlands 7/50.393/2.674\n#china 5/26.631/110.032\n#china2 4/31.36/109.66\n#northern europe 4/50.96/12.63\n#germany 5/50.905/10.015\n#us 4/37.72/-97.06\n#newyork 10/40.7312/-73.9114\n#sf 10/37.6532/-122.1921\n#california 7/36.008/-118.393\n#east coast 8/40.102/-75.258\n#east coast2 7/40.731/-75.514\n#brazil 8/-23.261/-45.453\n#lagos 7/6.398/2.857\n#lagos2 6/5.863/2.368\n#israel 7/33.455/34.420\n#lowlands2 7/52.586/8.746\n#london 8/51.758/-0.326\n#sydney 7/-36.123/148.203\n#canberra 6/-32.938/147.605\n#tokyo 8/35.686/137.912\n#japan 7/36.122/137.091\n\nall: index.html\n\nindex.html: \\\n\trenders/gr_mexico.png renders/gr_lowlands.png renders/gr_china.png \\\n\trenders/gr_china2.png renders/gr_northerneurope.png \\\n\trenders/gr_germany.png renders/gr_us.png \\\n\trenders/gr_newyork.png renders/gr_sf.png \\\n\trenders/gr_california.png renders/gr_eastcoast.png renders/gr_eastcoast2.png \\\n\trenders/gr_brazil.png renders/gr_lagos.png renders/gr_lagos2.png \\\n\trenders/gr_israel.png renders/gr_lowlands2.png renders/gr_london.png \\\n\trenders/gr_sydney.png renders/gr_canberra.png renders/gr_tokyo.png \\\n\trenders/gr_japan.png\n\nrenders/gr_mexico.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 19.992 -100.867 -z 7 -d 1824 1568 -o $@\n\nrenders/gr_lowlands.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 50.393 2.674 -z 7 -d 1824 1568 -o $@\n\nrenders/gr_china.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 26.631 110.032 -z 5 -d 1824 1568 -o $@\n\nrenders/gr_china2.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 31.36 109.66 -z 4 -d 1824 1568 -o $@\n\nrenders/gr_northerneurope.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 50.96 12.63 -z 5 -d 1824 1568 -o $@\n\nrenders/gr_germany.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 50.905 10.015 -z 5 -d 1824 1568 -o $@\n\nrenders/gr_us.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 37.72 -97.06 -z 4 -d 1824 1568 -o $@\n\nrenders/gr_newyork.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 40.7312 -73.9114 -z 10 -d 1824 1568 -o $@\n\nrenders/gr_sf.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 37.6532 -122.1921 -z 10 -d 1824 1568 -o $@\n\nrenders/gr_california.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 36.008 -118.393 -z 7 -d 1824 1568 -o $@\n\nrenders/gr_eastcoast.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 40.102 -75.258 -z 8 -d 1824 1568 -o $@\n\nrenders/gr_eastcoast2.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 40.731 -75.514 -z 7 -d 1824 1568 -o $@\n\nrenders/gr_brazil.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l -23.261 -45.453 -z 8 -d 1824 1568 -o $@\n\nrenders/gr_lagos.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 6.398 2.857 -z 7 -d 1824 1568 -o $@\n\nrenders/gr_lagos2.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 5.863 2.368 -z 6 -d 1824 1568 -o $@\n\nrenders/gr_israel.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 33.455 34.420 -z 7 -d 1824 1568 -o $@\n\nrenders/gr_lowlands2.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 52.586 8.746 -z 7 -d 1824 1568 -o $@\n\nrenders/gr_london.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 51.758 -0.326 -z 8 -d 1824 1568 -o $@\n\nrenders/gr_sydney.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l -36.123 148.203 -z 7 -d 1824 1568 -o $@\n\nrenders/gr_canberra.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l -32.938 147.605 -z 6 -d 1824 1568 -o $@\n\nrenders/gr_tokyo.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 35.686 137.912 -z 8 -d 1824 1568 -o $@\n\nrenders/gr_japan.png: style.xml\n\tpython mapnik-render.py -f fonts -s style.xml -l 36.122 137.091 -z 7 -d 1824 1568 -o $@\n\n\nstyle.xml: style.mml stylesheet.mss\n\tcascadenik-compile.py style.mml $@\n\tchmod a+r $@\n\nclean:\n\trm -f style.xml\n\trm -f renders/gr_*-*.png" }, { "alpha_fraction": 0.6090712547302246, "alphanum_fraction": 0.6144708395004272, "avg_line_length": 24.75, "blob_id": "14581020489daec8c560d299940348c48f94291b", "content_id": "c2f4c52983bb6a8b06261d8e0927a8e8ad64a910", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 926, "license_type": "no_license", "max_line_length": 78, "num_lines": 36, "path": "/tools/seed_splitter.py", "repo_name": "jackiekazil/golden-ratio", "src_encoding": "UTF-8", "text": "import sys, math\nimport os, stat\n\ntry:\n prog, filename, num_parts = sys.argv\nexcept ValueError:\n print >> sys.stderr, 'usage: %(prog) <filename> <num_parts>' % locals()\n sys.exit(1)\n \nfilename_base = filename.split('.').pop(0)\nnum_parts = int(num_parts)\n\nfp = open(filename, 'r')\ncontent = fp.read()\nlines = content.split('\\n')\n\nheader = \"\"\"#!/bin/sh\n\"\"\"\n\nlines_per_file = int(math.ceil(len(lines) / num_parts))\n\nfor part in range(num_parts):\n part_filename = '%s_part%d.sh' % (filename_base, part + 1)\n print >> sys.stderr, \"Working on part %d: %s\" % (part + 1, part_filename)\n \n part_lines = lines[0:lines_per_file]\n \n output = open(part_filename, 'w')\n print >> output, header\n print >> output, '\\n'.join(part_lines)\n output.close()\n \n mode = os.stat(part_filename).st_mode\n os.chmod(part_filename, mode | stat.S_IXUSR | stat.S_IXGRP)\n \n lines = lines[lines_per_file:]" }, { "alpha_fraction": 0.5780640244483948, "alphanum_fraction": 0.5800155997276306, "avg_line_length": 30.2439022064209, "blob_id": "6668671655c0d9a57ef2445c6bbeb69bca1c59ca", "content_id": "56a2e9be827c35fc6974ca3912b7b3590573713d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2562, "license_type": "no_license", "max_line_length": 125, "num_lines": 82, "path": "/tools/seed_parser.py", "repo_name": "jackiekazil/golden-ratio", "src_encoding": "UTF-8", "text": "\"\"\"\nThis script will generate a set of zoom-specific files with tilestache-seed\ncommands from a bounding box file.\n\n python seed_parser.py -t '-c /usr/local/tilefarm/gunicorn/tilestache-watercolor.cfg -l watercolor ' -b 'twitter_bbox.tsv'\n\n\n\"\"\"\n\n\nimport csv\nfrom optparse import OptionParser\n\nparser = OptionParser(usage=\"\"\"%prog [options]\n\nGenerates a set of tilestache-seed commands from a bounding box file.\nOne file is created per zoom level.\"\"\")\n\ndefaults = {'outfile': 'seed_script_', 'low_zoom': 9}\n\nparser.set_defaults(**defaults)\n\nparser.add_option('-b', '--bbox_data', dest='bbox_data',\n help='Path to bounding box file, typically required.')\n\nparser.add_option('-t', '--tilestache_args', dest='tilestache_args',\n help='Arguments to pass to tilestache, typically required.')\n\nparser.add_option('-z', '--low_zoom', dest='low_zoom', type='int',\n help='Lowest zoom to render. Default value is %s' % defaults['low_zoom'])\n\nparser.add_option('-o', '--outfile', dest='outfile',\n help= 'Prefix for output file. Default value is %s' % repr(defaults['outfile']))\n\nif __name__ == '__main__':\n (options, args) = parser.parse_args()\n\n try:\n # check required options\n \n\n if options.tilestach_args is None:\n raise Exception('Missing required tilestache arguments (--tilestache_args) parameter.')\n elif options.bbox_data is None:\n raise Exception('Missing required bounding box path (--bbox_data) parameter.')\n \n\n except:\n pass\n\n f = open(options.bbox_data)\n\n if options.bbox_data[-3:] == 'csv':\n bbox_dialect = 'excel'\n elif options.bbox_data[-3:] == 'tsv':\n bbox_dialect = 'excel-tab'\n else:\n raise Exception('bbox_data must be a .csv or .tsv file')\n \n reader = csv.DictReader(f, dialect = bbox_dialect)\n\n\n z_dict = {}\n\n for line in reader:\n \n if line['zoom_start'] not in z_dict:\n z_dict[line['zoom_start']] = ''\n\n zooms = range(9, int(line['zoom_start']) + 1)\n script_line = 'tilestache-seed.py ' + options.tilestache_args + \\\n '-b ' + ' '.join([line['bottom'], line['left'], line['top'], line['right']]) + \\\n ' -e jpg ' + ' '.join(map(str, zooms)) + '\\n'\n z_dict[line['zoom_start']] += script_line\n\n f.close()\n\n for i in z_dict:\n text = z_dict[i]\n f = open(options.outfile + i + '.txt', 'w')\n f.write(text)\n f.close()\n" } ]
5
devika30/Spam-vs-Ham-Detection
https://github.com/devika30/Spam-vs-Ham-Detection
0f0bfbf9c406511ac100e10d566f815d77e07b44
5ec0da5019d7418e801cf4614a7ae226951a5e3a
498742fe9f67deed5a474e7e9494bf86a156c15c
refs/heads/master
2022-09-30T00:42:39.462799
2020-05-26T07:48:38
2020-05-26T07:48:38
266,966,008
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.5790778398513794, "alphanum_fraction": 0.5835399031639099, "avg_line_length": 24.225000381469727, "blob_id": "10c1a83c8e3b3982e6c3a996d0f57e04550839af", "content_id": "dbba09b82da86b3f6886026339c22eaaa80931d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2017, "license_type": "no_license", "max_line_length": 116, "num_lines": 80, "path": "/main.py", "repo_name": "devika30/Spam-vs-Ham-Detection", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request\nimport os\nimport pickle as p\nimport os\nfrom sklearn import *\nfrom collections import Counter\nimport pickle \n\n\ndef load(clf_file):\n with open(clf_file,\"rb\") as fp:\n clf = p.load(fp)\n return clf\n\n\n\ndef make_dict():\n direc = \"emails/\"\n files = os.listdir(direc)\n emails = [direc + email for email in files]\n words = []\n c = len(emails)\n\n for email in emails:\n f = open(email,\"r\",encoding=\"utf8\", errors='ignore')\n blob = f.read()\n words += blob.split()\n\n\n for i in range(len(words)):\n if not words[i].isalpha():\n words[i] = \"\"\n\n dictionary = Counter(words)\n del dictionary[\"\"]\n return dictionary.most_common(3000)\n\n\n\ndef predict_with_text(text):\n print(\"============================\")\n print(text)\n print(\"============================\")\n features = []\n inp = text.split()\n for word in d:\n features.append(inp.count(word[0]))\n res = clf.predict([features])\n print(res)\n resdir = {\"0\":\"Ham\",\"1\":\"Spam\"}\n\n return resdir.get(str(res[0]))\n\n\nclf = load(\"text-classifier.mdl\")\nprint(\"model loaded\")\nd = make_dict()\n\n\napp = Flask(__name__)\nIMAGE_FOLDER = os.path.join('static', 'images')\[email protected]('/sms')\ndef showtemplate():\n return render_template('sms.html',imageurl = os.path.join(IMAGE_FOLDER,'bg.jpg'))\n\t\[email protected]('/predict', methods = ['POST','GET'])\ndef upload_file():\n if request.method == 'POST':\n f = request.files.get('file',None)\n print(request.files)\n if f:\n d = predict_with_text(f.read().decode())\n print(d)\n return render_template('sms.html',imageurl = os.path.join(IMAGE_FOLDER,'bg.jpg'),prediction = d.lower())\n return render_template('sms.html',imageurl = os.path.join(IMAGE_FOLDER,'bg.jpg'))\n if request.method == 'GET' :\n return render_template('sms.html',imageurl = os.path.join(IMAGE_FOLDER,'bg.jpg'))\n\t\t\nif __name__ == '__main__':\n app.run(debug = True)" }, { "alpha_fraction": 0.631321370601654, "alphanum_fraction": 0.6818923354148865, "avg_line_length": 38.54838562011719, "blob_id": "300f648d8513dd5f5a377859240d288b9d0502a3", "content_id": "b22a37c730ca208ca1af546c6543da7acd6d56cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1226, "license_type": "no_license", "max_line_length": 147, "num_lines": 31, "path": "/README.md", "repo_name": "devika30/Spam-vs-Ham-Detection", "src_encoding": "UTF-8", "text": "# SPAM AND HAM DETECTION \n* For model prediction **`Naive Bayes Classifier`** is used.\n* A dataset is used which contains random files of spam and ham,that uses feature vectorization for processing the data before sending it to model.\n* Implementation has been made in **`Flask`**. \n* Accuracy - **`96%`**\n\n#### Dataset Details\n\n| SPAM | HAM | TOTAL |\n| ------------- |:-------------:| -----: |\n| 1556 |1556 | 3112 |\n* No biased data is encountered.\n* 80% training data 20% testing data.\n\n#### Flask Installation Guide\n\n* [Flask Installation Guide](https://flask.palletsprojects.com/en/1.1.x/installation/)\n* Once Flask Installation and Virtual Environment setup has been done , execute the following command to start the server locally.\n```python\npython main.py\n```\n\n#### Output\n* A text file containing the message to be tested has to be uploaded and the result would be outputted.\n![view](https://user-images.githubusercontent.com/37765578/82870007-dbab7800-9f4c-11ea-8a20-5b96f960aa4d.png)\n\n#### Contributors\n* [Abhishek Mogaveera](https://github.com/abhishek971999)\n* [Devika Olkar](https://github.com/devika30/)\n\n###### Special Thanks to [Bhagyarsh](https://github.com/bhagyarsh) for guiding us !\n" } ]
2
thviet79/MutilLanguage
https://github.com/thviet79/MutilLanguage
1676a7be67dae7c14ee32b18d5331342d69f5a54
758f87ed9d0802864c2930e01e2bf014a09c7a67
5945effeb59275d2c2805810171d3ddd5bb482e2
refs/heads/main
2023-08-02T00:02:06.586635
2021-09-28T23:37:31
2021-09-28T23:37:31
411,468,324
0
0
MIT
2021-09-28T23:34:45
2021-09-22T21:59:08
2021-09-22T21:59:05
null
[ { "alpha_fraction": 0.6787287592887878, "alphanum_fraction": 0.6793580651283264, "avg_line_length": 38.712501525878906, "blob_id": "bfc48241c48dcb732b21aff3680c94fa321940ba", "content_id": "181b4b2f62b0f32c819b11d2b4de6f9f1ae0b2f0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3178, "license_type": "permissive", "max_line_length": 108, "num_lines": 80, "path": "/AutoCrawlData.py", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "import argparse\nimport pdb\nimport sys\nimport ConvertHtmlToText\nfrom CrawlWebSite import BaseWebsite\n\nclass VietLaoWebCrawl(BaseWebsite):\n\n def __init__(self, name, crawl_folder, accept_language):\n BaseWebsite.__init__(self, name, crawl_folder, accept_language)\n\n def checkForLatestNews(self, link, list_crawled=list()):\n\n return list_crawled + ConvertHtmlToText.getVietNamVietLaoLink(link=link,list_=list_crawled)\n\n pass\n\nclass VovWebsite(BaseWebsite):\n\n def __init__(self, name, crawl_folder, accept_language):\n BaseWebsite.__init__(self, name, crawl_folder, accept_language)\n\n def checkForLatestNews(self, link, list_crawled=list()):\n\n return list_crawled + ConvertHtmlToText.getVovLink(link=link,list_=list_crawled)\n\n pass\n\nclass VnanetWeb(BaseWebsite):\n def __init__(self, name, crawl_folder, accept_language):\n BaseWebsite.__init__(self, name, crawl_folder, accept_language)\n\n def checkForLatestNews(self, link, list_crawled=list()):\n return list_crawled + ConvertHtmlToText.getVnanetLink(link=link,list_=list_crawled)\n pass\n\nclass QuanDoiNhanDanWeb(BaseWebsite):\n def __init__(self, name, crawl_folder, accept_language):\n BaseWebsite.__init__(self, name, crawl_folder, accept_language)\n\n def checkForLatestNews(self, link, list_crawled=list()):\n return list_crawled + ConvertHtmlToText.getQDNDLink(link=link,list_=list_crawled)\n pass\n\nclass VietNamPlusCrawlerWeb(BaseWebsite):\n def __init__(self, name, crawl_folder, accept_language):\n BaseWebsite.__init__(self, name, crawl_folder, accept_language)\n\n def checkForLatestNews(self, link, list_crawled=list()):\n return list_crawled + ConvertHtmlToText.getVietNamPlusLink_Date_Titile(link=link,list_=list_crawled)\n pass\n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('-web', type=str, help='vov, vnanet, vietnamplus, qdnd, vietlao',default=1)\n parser.add_argument('-tgt_lang', type=str, help='Source Language.',default=\"lo\")\n parser.add_argument('-lim_sorce', type=str, help='Source Language.', default=\"lo\")\n return parser.parse_args(argv)\n\n# python AutoCrawlData.py -web vietnamplus -tgt_lang lo\n# python AutoCrawlData.py -web vov -tgt_lang lo\nif __name__ == '__main__':\n\n parser = parse_arguments(sys.argv[1:])\n\n if parser.web == \"vov\":\n web = VovWebsite(\"Vov\", \"VovCrawler\", [\"en\", \"ja\", \"km\", \"zh\", \"lo\", \"vi\"])\n web.auto_crawl_website(parser.tgt_lang)\n if parser.web == \"vietlao\":\n web = VietLaoWebCrawl(\"VietLao\", \"VietLaoVietNamCrawler\", [\"lo\", \"vi\"])\n web.auto_crawl_website(parser.tgt_lang)\n if parser.web == \"vnanet\":\n web = VnanetWeb(\"Vnanet\", \"VnanetCrawler\", [\"vi\", \"lo\", \"zh\", \"en\"])\n web.auto_crawl_website(parser.tgt_lang)\n if parser.web == \"vietnamplus\":\n web = VietNamPlusCrawlerWeb(\"VietNamPlus\", \"VietNamPlusCrawler\", [\"vi\", \"zh\", \"en\"])\n web.auto_crawl_website(parser.tgt_lang, type=\"date\")\n if parser.web == \"qdnd\":\n web = QuanDoiNhanDanWeb(\"QDND\", \"QDNDCrawler\", [\"lo\", \"vi\", \"zh\", \"en\"])\n web.auto_crawl_website(parser.tgt_lang, type=\"title\")\n\n" }, { "alpha_fraction": 0.572969913482666, "alphanum_fraction": 0.5777966976165771, "avg_line_length": 31.022727966308594, "blob_id": "80eb3ba30e58b5e7a8723f88e240874fc6498246", "content_id": "44be4e4d75108aa5ac4f1b9e5e9ab3df3f1dfc64", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7055, "license_type": "permissive", "max_line_length": 115, "num_lines": 220, "path": "/NhanDanCrawler.py", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "import ConvertHtmlToText\nimport Punctuation\nimport ChromeDriver\nimport os\nimport traceback\nimport SeparateDocumentToSentences\nimport SaveFile\nimport pdb\n\nimport Utility\n\n\ndef getNhanDanViContent(link, file_name, title, list_sign):\n if (os.path.isfile(file_name + \".txt\")):\n return\n list_src = list()\n try:\n\n content = ConvertHtmlToText.getTextFromTagsWithClass(link,\"div\", {\"class\": \"entry-content\"})\n\n if (content == None):\n return\n text = bytes(content.text, \"utf-8\").decode('utf-8', 'ignore')\n\n list_src.append(title)\n\n list_src = list_src + SeparateDocumentToSentences.slpit_text(text, list_sign)\n\n\n except:\n traceback.print_exc()\n pass\n return list_src\n\ndef getNhanDanZhContent(link, file_name, title, list_sign):\n\n if (os.path.isfile(file_name + \".txt\")):\n return\n\n list_src = list()\n try:\n\n content = ConvertHtmlToText.getTextFromTags(link,\"table\")\n\n if (content == None):\n return\n text = bytes(content.text, \"utf-8\").decode('utf-8', 'ignore')\n\n list_src.append(title)\n\n list_src = list_src + SeparateDocumentToSentences.slpit_text(text, list_sign)\n\n except:\n traceback.print_exc()\n pass\n return list_src\n\ndef checkForLatestNews(crawl_folder, tgt_lang_, folder_lang, listResourceFolder):\n \"\"\"\n :param resourceFile: resource file\n :param listResourceFolder: list folder in resource file\n :param crawl_folder: path to saved url folder\n :param tgt_lang_: target folder\n :param folder_lang: mutilple language folder\n :return:\n \"\"\"\n for folder in listResourceFolder:\n print(folder)\n\n link_file = open(crawl_folder + \"/linkauto/{}/{}.txt\".format(folder_lang, folder), \"r\", encoding=\"utf-8\")\n array_link = link_file.readline().replace('\\n', '').split(\"\\t\")\n link_file.close()\n\n if not os.path.isfile(\n crawl_folder + \"/link/{}/{}/link.txt\".format(\"vi\", folder)) or not os.path.isfile(\n crawl_folder + \"/link/{}/{}/link.txt\".format(tgt_lang_, folder)):\n # Tao thu muc\n if not os.path.exists((crawl_folder + \"/link/{}/{}/\".format(\"vi\", folder))):\n os.makedirs(crawl_folder + \"/link/{}/{}/\".format(\"vi\", folder))\n\n if not os.path.exists((crawl_folder + \"/link/{}/{}/\".format(tgt_lang_, folder))):\n os.makedirs(crawl_folder + \"/link/{}/{}/\".format(tgt_lang_, folder))\n\n # đọc file chứa link có định dạng src_link \\t max_page \\t tgt_link \\t max_page\n\n # Lay link tat ca cac bai viet.\n\n if not os.path.isfile(crawl_folder + \"/link/{}/{}/link.txt\".format(\"vi\", folder)):\n\n src_link = ConvertHtmlToText.getNhanDanAllViParagraph(ChromeDriver.getChromeDriver(),array_link[0])\n\n f = open(crawl_folder + \"/link/{}/{}/link.txt\".format(\"vi\", folder), \"w\", encoding=\"utf-8\")\n f.write(Utility.objectToJson(src_link))\n f.close()\n\n if not os.path.isfile(crawl_folder + \"/link/{}/{}/link.txt\".format(tgt_lang_, folder)):\n\n tgt_link = ConvertHtmlToText.getNhanDanAllZhpragraph(ChromeDriver.getChromeDriver(),array_link[1])\n\n f = open(crawl_folder + \"/link/{}/{}/link.txt\".format(tgt_lang_, folder), \"w\", encoding=\"utf-8\")\n f.write(Utility.objectToJson(tgt_link))\n f.close()\n\ndef crawlWithLanguage(language):\n \"\"\"\n :param language: \"en\",\"zh\"\n :return: None\n \"\"\"\n if (language != \"en\" and language != \"zh\"):\n raise Exception(\"Resource not supported\")\n # mount to current real part\n current_dir = os.path.dirname(os.path.realpath(__file__))\n map_Punctuation = Punctuation.getPunctuationForLanguage(language)\n\n _case = {\"TH1\": 0, \"TH2\": 1}\n\n Sentence_folder = current_dir + \"/Data/crawler_success/NhanDan/Sentence/\"\n Document_folder = current_dir + \"/Data/crawler_success/NhanDan/Document/\"\n\n src_lang_ = \"vi\"\n tgt_lang_ = language\n\n output_dir_success = [Sentence_folder, Document_folder]\n\n if not os.path.exists(Sentence_folder):\n os.makedirs(Sentence_folder)\n if not os.path.exists(Document_folder):\n os.makedirs(Document_folder)\n\n folder_lang = src_lang_ + \"-\" + tgt_lang_\n crawl_folder = current_dir + \"/NhanDanCrawler\"\n resourcePath = crawl_folder + \"/linkauto/\" + folder_lang + \".txt\"\n\n resourceFile = None\n\n if os.path.isfile(resourcePath):\n resourceFile = open(resourcePath, 'r', encoding='utf-8')\n\n if (resourceFile == None):\n messageString = \"{} - resource file not exist\".format(resourcePath)\n raise Exception(messageString)\n\n listResourceFolder = list()\n\n for line in resourceFile:\n listResourceFolder.append(line.strip())\n resourceFile.close()\n # check for the latest news\n checkForLatestNews(crawl_folder, tgt_lang_, folder_lang, listResourceFolder)\n # set all news in to list\n for folder in listResourceFolder:\n\n f = open(crawl_folder + \"/link/{}/{}/link.txt\".format(src_lang_, folder), \"r\", encoding=\"utf-8\")\n\n src_link = list()\n\n for line in f:\n line = line.replace(\"\\n\", \"\")\n if (line != \"\"):\n src_link.append(line.split(\"\\t\"))\n f.close()\n\n f = open(crawl_folder + \"/link/{}/{}/link.txt\".format(tgt_lang_, folder), \"r\", encoding=\"utf-8\")\n\n tgt_link = list()\n\n for line in f:\n line = line.replace(\"\\n\", \"\")\n if (line != \"\"):\n tgt_link.append(line.split(\"\\t\"))\n f.close()\n # sorting news\nif __name__ == '__main__':\n crawlWithLanguage(\"zh\")\n \"\"\"\n src_sign = list( map_vi2ja_end_sign.keys() )\n tgt_sign = list( map_vi2ja_end_sign.values() )\n\n\n \n for data in src_link:\n date_time = datetime.strptime(data[1], \"%Y/%m/%d\").strftime(\"%Y/%m/\")\n file_name = data[0].split(\"/\")[5]\n #pdb.set_trace()\n save_folder = TH1_folder +\"/\"+folder+\"/\" + date_time \n \n if not os.path.exists(save_folder):\n os.makedirs(save_folder)\n \n try: \n save_folder = save_folder +file_name\n getViContent(data[0], save_folder,data[2], src_sign)\n print(file_name)\n except:\n traceback.print_exc()\n \n # lay link \n \n for data in tgt_link:\n \n date_time = datetime.strptime(data[1].replace(\"\\xa0\",\"\"), \"%Y/%m/%d\").strftime(\"%Y/%m/\")\n file_name = data[0].split(\"-\")[1].replace(\".html\",\"\")\n \n save_folder = TH2_folder +\"/\"+folder+\"/\" + date_time \n \n if not os.path.exists(save_folder):\n os.makedirs(save_folder)\n \n save_folder = save_folder +file_name[0:15]\n \n try:\n getZhContent(data[0], save_folder,data[2], tgt_sign)\n print(file_name)\n except:\n traceback.print_exc() \n pdb.set_trace()\n pass\n \n os.system(\"cls\")\n \"\"\"" }, { "alpha_fraction": 0.5333787798881531, "alphanum_fraction": 0.5398584604263306, "avg_line_length": 22.599597930908203, "blob_id": "e8e79769707f918138ff0e00901a17fbeca9b1fa", "content_id": "49d1de22e544fea98528ef460d696a898f856f4a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 11785, "license_type": "permissive", "max_line_length": 121, "num_lines": 497, "path": "/xuly.php", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "\n<?php \n\t#error_reporting(0);\n\t\n\tfunction findFileWithArrayString($output, $cdir,$path_){\n\t\t$array = array();\n\t\tforeach($cdir as $key => $value){\n\t\t\t//echo $key ;\n\t\t\tif(strcmp($value,\".\")==0){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tif(strcmp($value,\"..\")==0){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tforeach($output as $path){\n\t\t\t\t\n\t\t\t\tif((!is_int(strpos($value, $path))) === false ){\n\t\t\t\t\tarray_push( $array, sprintf(\"%s%s\",$path_,$value) );\n\t\t\t\t\tbreak;\t\t\t\t\t\t\n\t\t\t\t}\t\n\t\t\t}\n\t\t\t\n\t\t}\t\t\n\t\treturn $array; \t\t\n\t}\n\t\n\tfunction FindAllFileInFolder($folder, &$file , $start, $end , & $current){\n\t\t\n\t\t$array_folder = array();\n\t\tif($handle = opendir($folder)){\n\t\t\t\t\t\n\t\t\twhile (false != ($entry = readdir($handle))) {\n\t\t\t\t#print($entry);\n\t\t\t\tarray_push($array_folder,$entry);\n\n\t\t\t\tif($entry != \".\" && $entry != \"..\"){\n\t\t\t\t\t\n\t\t\t\t\tif(strpos($entry, \".txt\") != false){\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif($start <= $current && $current < $end){\n\t\t\t\t\t\t\t$file[\"$folder/$entry\"] = $entry;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t$current = $current + 1;\n\t\t\t\t\t}else{\t\t\t\t\t\n\t\t\t\t\t\tFindAllFileInFolder(\"$folder/$entry\", $file, $start, $end , $current);\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\tclosedir($handle);\n\t\n\t\t\t#print_r($folders);\n\t\t\t\n\t\t\tforeach ( $array_folder as $f){\n\t\t\t\t$f = trim($f);\n\t\t\t\tif ($f == \"\" || $f == \" \"){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\tif($f != \".\" && $f != \"..\"){\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tif(strpos($f, \".txt\") != false){\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif($start <= $current && $current < $end){\n\t\t\t\t\t\t\t$file[\"$folder/$f\"] = $f;\n\t\t\t\t\t\t\t#echo($f);\n\t\t\t\t\t\t\t#echo(\"<br>\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t$current = $current + 1;\n\t\t\t\t\t}else{\t\n\t\t\t\t\t\tif ($f != \"\" || $f != \" \"){\n\t\t\t\t\t\t\tFindAllFileInFolder(\"$folder/$f\", $file, $start, $end , $current);\n\t\t\t\t\t\t} \n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tfunction AlignFile($dictionary, $src_lang ){\n\t\t\n\t\t$array_src = array();\n\t\t$array_tgt = array();\n\t\t\n\t\t\n\t\tforeach ($dictionary as $file_path => $file_name){\n\t\t\t#print_r($dictionary);\n\t\t\t#print(\"<br/>\");\n\t\t\tif(strpos($file_name, \"$src_lang.txt\") != false){\n\t\t\t\t$array_src[$file_path] = $file_name;\n\t\t\t}else{\n\t\t\t\t$array_tgt[$file_path] = $file_name;\t\t\t\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\t$file = array();\n\t\t\n\t\tforeach ($array_src as $src_file_path => $src_file_name){\n\t\t\t\n\t\t\t$name = str_replace(\"$src_lang.txt\",\"\",$src_file_name);\n\t\t\t\n\t\t\tforeach ($array_tgt as $tgt_file_path => $tgt_file_name){\n\t\t\t\t\n\t\t\t\tif( strpos($tgt_file_name, $name) !== false ){\n\t\t\t\t\t#print($tgt_file_name);\n\t\t\t\t\t#print(\" \");\n\t\t\t\t\t#print(strpos($tgt_file_name, $name));\n\t\t\t\t\t#print(\"<br/>\");\n\t\t\t\t\tarray_push($file, array($src_file_path, $src_file_name, $tgt_file_path, $tgt_file_name) );\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn $file;\n\t}\n\t\n\tfunction VovCase($src_lang, $tgt_lang, $start, $end , &$cur){\n\t\t\n\t\t$document = sprintf(\"Data/crawler_success/Vov/%s-%s/Document/\",$src_lang,$tgt_lang);\n\t\t$sentence = sprintf(\"Data/crawler_success/Vov/%s-%s/Sentence/\",$src_lang,$tgt_lang);\n\t\t\n\t\t$files_document = array();\n\t\t$cur = 0;\n\t\tFindAllFileInFolder($document, $files_document, $start, $end , $cur);\n\t\t\n\t\tif (!is_dir($document)) {\n\t\t\tprint(\"Ngôn Ngữ Tìm Kiếm Không Tồn Tại\") ;\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif(!isset($files_document)){\n\t\t\tFindAllFileInFolder($document, $files_document, $start, $end , $cur);\n\t\t}\n\t\t\n\t\t$files_document = AlignFile($files_document, $src_lang);\n\t\t#print_r($files_document);\n\t\t$cur = 0;\n\t\t$files_align = array();\n\t\tFindAllFileInFolder($sentence,$files_align, $start, $end, $cur);\n\t\t\n\t\treturn array($files_document, $files_align);\t\t\n\t}\n\t\n\tfunction TedCase($src_lang, $tgt_lang, $start, $end, $cur){\n\t\t$file = array();\n\t\t$align_file = array();\n\t\t\n\t\t$output = null;\n\t\t#echo \"python crawl_ted_transcript.py --src_lang \".'\"'.$src_lang.'\"'.\" --tgt_lang \".'\"'.$tgt_lang.'\"'.\" 2>&1\";\n\t\t#exec(\"python VovCrawl.py --src_lang \".'\"'.$src_lang.'\"'.\" --tgt_lang \".'\"'.$tgt_lang.'\"'.\" 2>&1\",$output);\n\t\t\n\t\t$document = sprintf(\"Data/crawler_success/TedTalk/%s-%s/Document/\",$src_lang,$tgt_lang);\n\t\t$sentence = sprintf(\"Data/crawler_success/TedTalk/%s-%s/Sentence/\",$src_lang,$tgt_lang);\n\t\t\n\t\tif (!is_dir($document)) {\n\t\t\tprint(\"Ngôn Ngữ Tìm Kiếm Không Tồn Tại\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t$files_document = array();\n\t\t$cur = 0;\n\t\tFindAllFileInFolder($document, $files_document, $start, $end , $cur);\n\t\t\n\t\tif(!isset($files_document)){\n\t\t\texec(\"python crawl_ted_transcript.py --src_lang \".'\"'.$src_lang.'\"'.\" --tgt_lang \".'\"'.$tgt_lang.'\"'.\" 2>&1\",$output);\n\t\t\tFindAllFileInFolder($document, $files_document, $start, $end , $cur);\n\t\t}\n\t\t\n\t\t$files_document = AlignFile($files_document, $src_lang);\n\t\t$cur = 0;\n\t\t$files_align = array();\n\t\tFindAllFileInFolder($sentence,$files_align, $start, $end, $cur);\n\t\t\n\t\treturn array($files_document, $files_align);\t\t\t\t\n\t\t\n\t}\n\t\n\tfunction VnanetCase($src_lang, $tgt_lang , $start, $end, $cur){\n\t\t$file = array();\n\t\t$align_file = array();\n\t\t\n\t\t$output = null;\n\t\t#echo \"python crawl_ted_transcript.py --src_lang \".'\"'.$src_lang.'\"'.\" --tgt_lang \".'\"'.$tgt_lang.'\"'.\" 2>&1\";\n\t\t#exec(\"python crawl_ted_transcript.py --src_lang \".'\"'.$src_lang.'\"'.\" --tgt_lang \".'\"'.$tgt_lang.'\"'.\" 2>&1\",$output);\n\t\t\n\t\t$document = sprintf(\"Data/crawler_success/Vnanet/%s-%s/Document/\",$src_lang,$tgt_lang);\n\t\t$sentence = sprintf(\"Data/crawler_success/Vnanet/%s-%s/Sentence/\",$src_lang,$tgt_lang);\n\t\t\n\t\tif (!is_dir($document)) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t$files_document = array();\n\t\t$cur = 0;\n\t\tFindAllFileInFolder($document, $files_document, $start, $end , $cur);\n\t\t\n\t\tif(!isset($files_document)){\n\t\t\texec(\"python VnanetCrawl.py --src_lang \".'\"'.$src_lang.'\"'.\" --tgt_lang \".'\"'.$tgt_lang.'\"'.\" 2>&1\",$output);\n\t\t\tFindAllFileInFolder($document, $files_document, $start, $end , $cur);\n\t\t}\n\t\t\n\t\t$files_document = AlignFile($files_document, $src_lang);\n\t\t$cur = 0;\n\t\t$files_align = array();\n\t\tFindAllFileInFolder($sentence,$files_align, $start, $end, $cur);\n\t\t\n\t\treturn array($files_document, $files_align);\t\t\t\t\n\t\t\n\t}\n\t\n\tfunction VietNamPlusCase($src_lang, $tgt_lang){\n\t\t$file = array();\n\t\t$align_file = array();\n\t\t\n\t\t$output = null;\n\t\t#echo \"python crawl_ted_transcript.py --src_lang \".'\"'.$src_lang.'\"'.\" --tgt_lang \".'\"'.$tgt_lang.'\"'.\" 2>&1\";\n\t\t#exec(\"python crawl_ted_transcript.py --src_lang \".'\"'.$src_lang.'\"'.\" --tgt_lang \".'\"'.$tgt_lang.'\"'.\" 2>&1\",$output);\n\t\t\n\t\t$document = sprintf(\"Data/crawler_success/VietNamPlus/%s-%s/Document/\",$src_lang,$tgt_lang);\n\t\t$sentence = sprintf(\"Data/crawler_success/VietNamPlus/%s-%s/Sentence/\",$src_lang,$tgt_lang);\n\t\t\n\t\tif (!is_dir($document)) {\n\t\t\tprint(\"Ngôn Ngữ Tìm Kiếm Không Tồn Tại\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t$files_document = array();\n\t\t$cur = 0;\n\t\tFindAllFileInFolder($document, $files_document, $start, $end , $cur);\n\t\t\n\t\tif(!isset($files_document)){\n\t\t\tFindAllFileInFolder($document, $files_document, $start, $end , $cur);\n\t\t}\n\t\t\n\t\t$files_document = AlignFile($files_document, $src_lang);\n\t\t$cur = 0;\n\t\t$files_align = array();\n\t\tFindAllFileInFolder($sentence,$files_align, $start, $end, $cur);\n\t\t\n\t\treturn array($files_document, $files_align);\t\t\t\t\n\t\t\n\t}\n\t\n\tfunction CoVietCase(){\n\t\t$file = array();\n\t\t$align_file = array();\n\t\t\n\t\t$output = null;\n\t\t#echo \"python crawl_ted_transcript.py --src_lang \".'\"'.$src_lang.'\"'.\" --tgt_lang \".'\"'.$tgt_lang.'\"'.\" 2>&1\";\n\t\t#exec(\"python crawl_ted_transcript.py --src_lang \".'\"'.$src_lang.'\"'.\" --tgt_lang \".'\"'.$tgt_lang.'\"'.\" 2>&1\",$output);\n\t\t\n\t\t$sentence = sprintf(\"Data/crawler_success/CoViet/\");\n\t\t\n\t\t$cur = 0;\n\t\t$files_align = array();\n\t\tFindAllFileInFolder($sentence,$files_align, 0, 10, $cur);\n\t\t\n\t\treturn array(array(), $files_align);\t\t\t\t\n\t\t\n\t}\n\t\n\tfunction KhmerboiCase(){\n\t\t$file = array();\n\t\t$align_file = array();\n\t\t\n\t\t$output = null;\n\t\t#echo \"python crawl_ted_transcript.py --src_lang \".'\"'.$src_lang.'\"'.\" --tgt_lang \".'\"'.$tgt_lang.'\"'.\" 2>&1\";\n\t\t#exec(\"python crawl_ted_transcript.py --src_lang \".'\"'.$src_lang.'\"'.\" --tgt_lang \".'\"'.$tgt_lang.'\"'.\" 2>&1\",$output);\n\n\t\t$sentence = sprintf(\"Data/crawler_success/Khmerboi/\");\n\t\t\n\t\t\n\t\t$cur = 0;\n\t\t$files_align = array();\n\t\tFindAllFileInFolder($sentence,$files_align, 0, 10, $cur);\n\t\t\n\t\treturn array( array() , $files_align);\t\t\t\t\n\t\t\n\t}\n\n\tif(isset($_REQUEST)){\n\t\t\n\t\t\n\t\t\n\t\t$src_lang = $_REQUEST['src_lang'];\n\t\t$tgt_lang = $_REQUEST['tgt_lang'];\n\t\t\n\t\t$src = $_REQUEST['src_lang'];\n\t\t$tgt = $_REQUEST['tgt_lang'];\n\t\t\n\t\t$web = $_REQUEST['web'];\n\t\t\n\t\t$page = isset($_REQUEST['page'])? $_REQUEST['page'] - 1: 0;\n\t\t\n\t\tif($page < 0){\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t$number_of_record = 20;\n\t\t$start = $page * $number_of_record;\n\t\t$end = $start + $number_of_record;\n\t\t$cur = 0 ;\n\t\t\n\t\tif(empty($src_lang)){\n\t\t\theader('Location:index.html');\n\t\t\texit();\n\t\t}\n\t\t\n\t\tif(empty($tgt_lang)){\n\t\t\theader('Location:index.html');\n\t\t\texit();\n\t\t}\n\t\t\n\t\tif(empty($web)){\n\t\t\theader('Location:index.html');\n\t\t\texit();\n\t\t}\n\t\t\n\t\tdate_default_timezone_set(\"Asia/Ho_Chi_Minh\");\n\t\t$output = null;\n\t\t\n\t\t$file = array();\n\t\t$align_file = array();\n\t\t\n\t\t$today = date(\"dmyyHis\"); \n\t\t\n\t\tif(strcmp($web,\"ted\")==0){\n\t\t\t\n\t\t\t$array = TedCase($src_lang, $tgt_lang, $start, $end, $cur);\n\t\t\t\n\t\t\t$file = $array[0];\n\t\t\t$align_file = $array[1];\n\t\t}\n\t\t\n\t\t\n\t\tif(strcmp($web,\"vov\")==0){\n\t\t\t\n\t\t\t$array = VovCase($src_lang, $tgt_lang, $start, $end, $cur);\n\t\t\t\n\t\t\t$file = $array[0];\n\t\t\t$align_file = $array[1];\n\t\t}\n\t\t\n\t\t\n\t\tif(strcmp($web,\"para\")==0){\n\t\t\techo \"chức năng hiện đang bảo trì\";\n\t\t}\n\t\t\n\t\tif(strcmp($web,\"vnanet\")==0){\n\t\t\t$array = VnanetCase($src_lang, $tgt_lang, $start, $end, $cur);\n\t\t\t\n\t\t\t$file = $array[0];\n\t\t\t$align_file = $array[1];\n\t\t}\n\t\t\n\t\tif(strcmp($web,\"vietnamplus\")==0){\n\t\t\t$array = VietNamPlusCase($src_lang, $tgt_lang, $start, $end, $cur);\n\t\t\t\n\t\t\t$file = $array[0];\n\t\t\t$align_file = $array[1];\n\t\t}\n\t\t\n\t\tif(strcmp($web,\"khmerboi\")==0){\n\t\t\t$array = KhmerboiCase();\n\t\t\t\n\t\t\t$file = $array[0];\n\t\t\t\n\t\t\t$align_file = $array[1];\n\t\t\t\n\t\t}\n\t\t\n\t\tif(strcmp($web,\"coviet\")==0){\n\t\t\t$array = CoVietCase($src_lang, $tgt_lang, $start, $end, $cur);\n\t\t\t\n\t\t\t$file = $array[0];\n\t\t\t$align_file = $array[1];\n\t\t}\n\t\t//print_r($file['sir_ken_robinson_bring_on_the_learning_revolution-vi']);\n\t\t\n\t\tif(empty($align_file)){\n\t\t\theader('Location:index.html');\n\t\t\texit();\n\t\t}\n\t\t\n\t\tswitch ($src_lang){\n\t\t\tcase \"lo\":\n\t\t\t\t$src_lang = \"Lào\";\n\t\t\t\tbreak;\n\t\t\tcase \"zh\":\n\t\t\t\t$src_lang = \"Trung Quốc\";\n\t\t\t\tbreak;\n\t\t\tcase \"km\":\n\t\t\t\t$src_lang = \"Khnmer\";\n\t\t\t\tbreak;\n\t\t\tcase \"kh\":\n\t\t\t\t$src_lang = \"Khnmer\";\n\t\t\t\tbreak;\t\n\t\t\tcase \"vi\":\n\t\t\t\t$src_lang = \"Việt Nam\";\n\t\t\t\tbreak;\n\t\t\tcase \"en\":\n\t\t\t\t$src_lang = \"Tiếng Anh\";\n\t\t\t\tbreak;\t\t\t\t\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tswitch ($tgt_lang){\n\t\t\tcase \"lo\":\n\t\t\t\t$tgt_lang = \"Lào\";\n\t\t\t\tbreak;\n\t\t\tcase \"zh\":\n\t\t\t\t$tgt_lang = \"Trung Quốc\";\n\t\t\t\tbreak;\n\t\t\tcase \"km\":\n\t\t\t\t$tgt_lang = \"Khnmer\";\n\t\t\t\tbreak;\n\t\t\tcase \"kh\":\n\t\t\t\t$tgt_lang = \"Khnmer\";\n\t\t\t\tbreak;\t\t\n\t\t\tcase \"vi\":\n\t\t\t\t$tgt_lang = \"Việt Nam\";\n\t\t\t\tbreak;\n\t\t\tcase \"en\":\n\t\t\t\t$tgt_lang = \"Tiếng Anh\";\t\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\t$max_page = ($cur / $number_of_record) + 1 ;\n\t\t\n\t\t\n\t\t\n\t\tif($page < $max_page){\n\t\t\n\t\t\t$next_page = $page + 2;\n\t\t}\n\t\telse{\n\t\t\t$next_page = $page + 1;\n\t\t}\n\t\t\n\t\tif($page <= 0){\n\t\t\t$prev_page = 1;\n\t\t}else{\n\t\t\t$prev_page = $page;\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\t$foldername = explode(\"/\",$_SERVER['REQUEST_URI'])[1];\t\n\t\t$url= \"http://\". $_SERVER['SERVER_NAME'].\":$_SERVER[SERVER_PORT]\".\"/\".$foldername .'/thuchiengionghang-demo.php';\n\t\t\n\t\t\n\t\t\n\t\t$data = array('file' => $file\n\t\t\t\t\t\t,'align_file' => $align_file\n\t\t\t\t\t\t,'src_lang' => $src_lang\n\t\t\t\t\t\t,'tgt_lang'=> $tgt_lang\n\t\t\t\t\t\t,'next_page' => $next_page\n\t\t\t\t\t\t,'prev_page' => $prev_page\n\t\t\t\t\t\t,'max_page' => $max_page\n\t\t\t\t\t\t,'src' => $src\n\t\t\t\t\t\t,'tgt' => $tgt\n\t\t\t\t\t\t,'web' => $web);\n\n\t\t\n\t\t$options = array(\n\t\t\t'http' => array(\n\t\t\t\t'header' => \"Content-type: application/x-www-form-urlencoded\\r\\n\",\n\t\t\t\t'method' => 'POST',\n\t\t\t\t'content' => http_build_query($data)\n\t\t\t)\n\t\t);\n\t\t\n\t\t$context = stream_context_create($options);\n\t\t$result = file_get_contents($url, false, $context);\n\t\tif ($result === FALSE) { \n\t\t\techo \"khong co trang \";\n\t\t}\n\t\t\n\t\techo($result);\n\t\t\n\t}\n?>" }, { "alpha_fraction": 0.5628546476364136, "alphanum_fraction": 0.5953335762023926, "avg_line_length": 25.75916290283203, "blob_id": "d88187b804912f7bc30ad776375887c561827c36", "content_id": "44bb5662893ddbd458d6c224ab91a2a39d48b67b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 20529, "license_type": "permissive", "max_line_length": 232, "num_lines": 764, "path": "/giongcau.php", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "<?php\n\t$i = 1;\n\t\n\t$line = 0;\n\t$lim = 10 + $line;\n\t$last = ($line > 10) ? 0: $lim - 10;\n\t\n ?>\n<!DOCTYPE html>\n<html>\n<head>\n\t<title>Thực hiện gióng hàng</title>\n\t<meta charset='UTF-8'>\n\t<link href=\"bootstrap-4.5.3-dist\\css\\bootstrap.min.css\">\n</head>\n<body>\n<iframe id=\"download_iframe\" style=\"display:none;\"><head> <meta charset=\"UTF-8\"> </head></iframe>\n<div style=\"width: 100%;height:100px;background:#gray;\" align=\"center\">\n\t<h1 style=\"color: #304499;\">Công cụ hỗ trợ soạn thảo ngữ liệu song ngữ</h1>\n</div>\n<div style=\"width: 100%;height: 50px;background:gray;\">\n\t<ul style=\"display: inline-block;\"class=\"menu\">\n\t\t<li style=\"list-style: none;float: left;height: 50px;width: 100px;text-align: center;margin-top: -15px;\"><a href=\"demo01.html\" style=\"text-decoration: none;line-height: 50px;color: white;\">Trang Chủ</a></li>\n\t\t<li style=\"list-style: none;float: left;height: 50px;width: 150px;text-align: center;margin-top: -15px;\"><a href=\"solieuthongke.html\" style=\"text-decoration: none;line-height: 50px;color: white;\">Thống kê ngữ liệu</a></li>\n\t\t<li style=\"list-style: none;float: left;height: 50px;width: 150px;text-align: center;margin-top: -15px;\"><a href=\"gionghangvb.html\" style=\"text-decoration: none;line-height: 50px;color: white;\">Gióng hàng văn bản</a></li>\n\t\t<li style=\"list-style: none;float: left;height: 50px;width: 150px;text-align: center;margin-top: -15px;\"><a href=\"gionghangcau.html\" style=\"text-decoration: none;line-height: 50px;color: white;\">Gióng hàng câu</a></li>\n\n\t</ul>\n\t\t<style type=\"text/css\">.menu li:hover{\n\t\t\tbackground: #A0A0A0;\n\t\t}\n\t.menu li a:hover{\n\t\tcolor: blue;\n\t}\n\ttable {\n width: 100%;\n height: auto; \n font-family: arial, sans-serif;\n border:1px solid #ddd;\n}\nth, td {\n padding: 8px;\n text-align: left;\n border-top: 1px solid #dee2e6;\n text-align: center;\n}\n tbody tr:nth-child(odd) {\n background-color: #f2f2f2;\n}\n.detele{\n\twidth: 60%;\n\theight: 30px;\n\tfont-size: 16px;\n\tmargin-left: 10px;\n}\n.detele-gh{\n\twidth: auto;height: 30px;\n\tfont-size: 16px;\n\t}\n.content{\n\twidth: 100%;height: auto;margin-top: 2%;\n}\n.content-1{\n\twidth: 60%;height: auto;margin-left: 10%;border: 2px solid #ddd;;padding-left: 15%;border-radius: \n\n}\n.website{\n\tmargin-right: 10px;\n\tmargin-left: 10px;\n\tfont-size: 18px;\n}\n.leangue{\n\twidth: 15%;\n\theight:30px;\n\tmargin-right: 20px;\n}\n.modal{\nmargin: 0% 3% 0% 3%; width: 100%;\n}\n.modal-table{\n\twidth: 90%;height: auto;text-align: center;font-size: 18px;margin-top: 15px;\n}\n.phantrang{margin-left:20px; width: 90%; height: auto;margin: 0% 3% 0% 3%;}\n.input1{width: 70px; height: 30px; text-align: center; margin-right: 15px;}\n.skip{width: 100px; height: 32px;}\n.extract{\n\twidth: 10%;\n\theight: 40px;\n\t}\n.phan{float:right;margin-top: 10px;}\n.pvg{list-style: none;float:left;}\n.export-data{\n\twidth: 5%;\n\theight: 40px;\n\tfloat:right;\n\tmargin-right: 54px;\n}\n.url{\n\twidth: 20%;\n\theight: 26px;\n}\nbody,html{\n\tmargin: 0;\n\tpadding: 0;\n\t}\n\n.export-data {\n background-color: #808080;\n width: auto;\n border: none;\n color: #ffffff;\n cursor: pointer;\n display: inline-block;\n font-family: 'BenchNine', Arial, sans-serif;\n font-size: 1em;\n font-size: 18px;\n line-height: 1em;\n margin: 10px 35px;\n outline: none;\n padding: 12px 30px 10px;\n position: relative;\n text-transform: uppercase;\n font-weight: 700;\n}\n\n.export-data:before,\n.export-data:after {\n border-color: transparent;\n -webkit-transition: all 0.25s;\n transition: all 0.25s;\n border-style: solid;\n border-width: 0;\n content: \"\";\n height: 24px;\n position: absolute;\n width: 24px;\n}\n\n.export-data:before {\n border-color: #808080;\n border-top-width: 2px;\n left: 0px;\n top: -5px;\n}\n\n.export-data:after {\n border-bottom-width: 2px;\n border-color: #808080;\n bottom: -5px;\n right: 0px;\n}\n\n.export-data:hover,\n.export-data.hover {\n background-color: #808080;\n}\n\n.export-data:hover:before,\n.export-data.hover:before,\n.export-data:hover:after,\n.export-data.hover:after {\n height: 100%;\n width: 100%;\n}\n\n.export{\n background-color: #808080;\n width: auto;\n border: none;\n color: #ffffff;\n cursor: pointer;\n display: inline-block;\n font-family: 'BenchNine', Arial, sans-serif;\n font-size: 1em;\n font-size: 18px;\n line-height: 1em;\n margin: 10px 35px;\n outline: none;\n padding: 12px 30px 10px;\n position: relative;\n text-transform: uppercase;\n font-weight: 700;\n}\n\n.export:before,\n.export:after {\n border-color: transparent;\n -webkit-transition: all 0.25s;\n transition: all 0.25s;\n border-style: solid;\n border-width: 0;\n content: \"\";\n height: 24px;\n position: absolute;\n width: 24px;\n}\n\n.export:before {\n border-color: #808080;\n border-top-width: 2px;\n left: 0px;\n top: -5px;\n}\n\n.export:after {\n border-bottom-width: 2px;\n border-color: #808080;\n bottom: -5px;\n right: 0px;\n}\n\n.export:hover,\n.export.hover {\n background-color: #808080;\n}\n\n.export:hover:before,\n.export.hover:before,\n.export:hover:after,\n.export.hover:after {\n height: 100%;\n width: 100%;\n}\n.btncon{\n background-color: #808080;\n width: 50%;\n border: none;\n color: #ffffff;\n cursor: pointer;\n display: inline-block;\n font-family: 'BenchNine', Arial, sans-serif;\n font-size: 1em;\n font-size: 18px;\n line-height: 1em;\n outline: none;\n position: relative;\n text-transform: uppercase;\n font-weight: 700;\n}\n\n.btncon:before,\n.btncon:after {\n border-color: transparent;\n -webkit-transition: all 0.25s;\n transition: all 0.25s;\n border-style: solid;\n border-width: 0;\n content: \"\";\n height: 24px;\n position: absolute;\n width: 24px;\n}\n\n.btncon:before {\n border-color: #808080;\n border-top-width: 2px;\n left: 0px;\n top: -5px;\n}\n\n.btncon:after {\n border-bottom-width: 2px;\n border-color: #808080;\n bottom: -5px;\n right: 0px;\n}\n\n.btncon:hover,\n.btncon.hover {\n background-color: #808080;\n}\n\n.btncon:hover:before,\n.btncon.hover:before,\n.btncon:hover:after,\n.btncon.hover:after {\n height: 100%;\n width: 100%;\n}\n.btncon-gh{\n background-color: #808080;\n width: auto;\n height: 15%;\n border: none;\n color: #ffffff;\n cursor: pointer;\n display: inline-block;\n font-family: 'BenchNine', Arial, sans-serif;\n font-size: 1em;\n font-size: 18px;\n line-height: 1em;\n outline: none;\n position: relative;\n text-transform: uppercase;\n font-weight: 700;\n}\n\n.btncon-gh:before,\n.btncon-gh:after {\n border-color: transparent;\n -webkit-transition: all 0.25s;\n transition: all 0.25s;\n border-style: solid;\n border-width: 0;\n content: \"\";\n height: 24px;\n position: absolute;\n width: 24px;\n}\n\n.btncon-gh:before {\n border-color: #808080;\n border-top-width: 2px;\n left: 0px;\n top: -5px;\n}\n\n.btncon-gh:after {\n border-bottom-width: 2px;\n border-color: #808080;\n bottom: -5px;\n right: 0px;\n}\n\n.btncon-gh:hover,\n.btncon-gh.hover {\n background-color: #808080;\n}\n\n.btncon-gh:hover:before,\n.btncon-gh.hover:before,\n.btncon-gh:hover:after,\n.btncon-gh.hover:after {\n height: 100%;\n width: 100%;\n}\n.modal-dialog{\n\tmargin-left: 15%;\n}\n.modal-content\n{\n\tmargin-left: 15%;\n\theight: 500px;\n}\n</style>\n</div>\n<div class=\"content\">\n\t<!-- \n\t<div class=\"content-1\">\n\t<p>\n\t\t<input type=\"radio\" id=\"dlcs\" onclick=\"chonDLgoc()\" checked=\"true\" />\n\t\t\t<label for=\"age1\" style=\"font-size: 18px\">Dữ Liệu Có Sẵn</label>\n\t\t<input type=\"radio\" id=\"dlcs1\" onclick=\"chonDLkhac()\"/>\n\t\t\t<label for=\"age2\" style=\"font-size: 18px\">Dữ Liệu Khác</label>\n\t</p>\n\t<p>\n\t\t<span style=\"font-size: 18px\">Nguồn Dữ Liệu</span>\n\t\t<select name=\"web\" id=\"data-exsit\" style=\"width: 10%;height: 30px;\">\n\t\t\t<option></option>\n\t\t\t<option>VOV</option>\n\t\t\t<option>Wikipedia</option>\n\t\t\t<option>Ted talk</option>\n\t\t\t<option>Subtitle</option>\n\t\t\t<option>Paracrawl</option>\n\t\t</select>\n\t\t<span class=\"website\"> Link Website</span>\n\t\t<input id=\"urlnn1\" type=\"text\" style=\"margin-right: 10px;\" class=\"url\" disabled=\"true\">\n\t\t<input id=\"urlnn2\" type=\"text\" class=\"url\" disabled=\"true\">\n\t</p>\n\t<p>\n\t\t<span style=\"font-size: 18px\">Cặp Ngôn Ngữ</span>\n\t\t<select name=\"src_lang\" id=\"src_lang\"class=\"leangue\">\n\t\t\t<option></option>\n\t\t\t<option value=\"vi\">Vietnamese</option>\n\t\t\t<option value=\"km\">Khmer</option>\n\t\t\t<option value=\"zh\">Chinese</option>\n\t\t\t<option value=\"lo\">Laos</option>\n\t\t\t<option value=\"en\">English</option>\n\t\t</select>\n\t\t<span>\n\t\t\t<select name=\"tgt_lang\" id=\"tgt_lang\" class=\"leangue\">\n\t\t\t\t<option></option>\n\t\t\t\t<option value=\"en\">English</option>\n\t\t\t\t<option value=\"lo\">Laos</option>\n\t\t\t\t<option value=\"zh\">Chinese</option>\n\t\t\t\t<option value=\"km\">Khmer</option>\n\t\t\t\t<option value=\"vi\">Vietnamese</option>\n\t\t\t</select>\n\t\t</span>\n\t</p>\n\t-->\n\t\n\t\n</div>\n\t<div style=\"margin: 1% 3% 0% 3%; width: 100%;\" id=\"modal_cau\">\n\t\t<table style=\"width: 90%;height: auto;text-align: center;font-size: 18px;margin-top: 15px;\">\n\t\t\t<tr>\t\t\t\t\n\t\t\t\t<th style=\"width: 3%;\"><input id=\"btncheck_vb\" type=\"checkbox\" name=\"\"></th>\n\t\t\t\t<th style=\"width: 35%;\"><?php echo $_REQUEST['src_lang']; ?></th>\n\t\t\t\t<th style=\"width: 35%;\"><?php echo $_REQUEST['tgt_lang']; ?></th>\n\t\t\t\t<th style=\"width: 5%;\">Độ đo</th>\n\t\t\t\t<th style=\"width: 10%;\">Edit</th>\n\t\t\t\t\n\t\t\t</tr>\n\t\t\t\n\t\t\t<?php\n\t\t\t\t$align_files = $_REQUEST['file'];\n\t\t\t\t//echo(getcwd());\n\t\t\t\tif(!isset($align_files)){\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t$file = fopen($align_files, \"r\") or die(\"Unable to open file!\");\n\t\t\t\t\n\t\t\t\twhile(!feof($file)): \n\t\t\t\t\n\t\t\t\t$str = explode(\"\\t\",fgets($file));\n\t\t\t\tif(!isset($str[0])){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(!isset($str[1])){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\n\t\t\t\t?>\n\t\t\t\t<tr id=\"line_<?php echo $i;?>\" class=\"line\">\n\t\t\t\t\t<td><input id=\"check_all\" type=\"checkbox\" name=\"name\"></td>\n\t\t\t\t\t\n\t\t\t\t\t<td style=\"text-align:left;\"> \n\t\t\t\t\t\t\t<span id=\"src_line_<?php echo $i;?>\" class=\"content_line\" ><?php echo $str[0] ; ?></span>\n\t\t\t\t\t<td style=\"text-align:left;\"> \n\t\t\t\t\t\t\t<span id=\"tgt_line_<?php echo $i;?>\" class=\"content_line\" ><?php echo $str[1]; ?></span>\t\t\t\t\n\t\t\t\t\t</td>\n\t\t\t\t\t<td>0.5</td>\n\t\t\t\t\t<td><button style=\"width: 40%;height: 30px;\" id=\"detele\"class=\"btncon\" onclick=\"remove('line_<?php echo $i;?>')\">Xoá</button>\n\t\t\t\t\t\t<button style=\"width: 40%;height: 30px;margin-left:10px;\"id=\"edit\"onclick=\"popupOpen(<?php echo $i++; ?>)\"class=\"btncon\">Edit</button>\n\t\t\t\t\t</td>\n\t\t\t\t<tr>\n\t\t\t<?php if(!isset($file)){\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tendwhile;\n\t\t\t\tfclose($file);\n\t\t\t?>\n\t</table>\n\t<div class=\"phantrang\" >\n\t\t<p> \n\t\t\t<button id=\"previ\" style=\"font-weight: bold; width: 150px;text-decoration: none; \" onclick=\"paging(0,10)\">\n\t\t\t\t<span aria-hidden=\"true\" id=\"\">←</span> Trước\n\t\t\t</button>\n\t\t\t<button id=\"next\" style=\"font-weight: bold; width: 150px;text-decoration: none;\" onclick=\"paging(10,20)\">Sau\n\t\t\t\t<span aria-hidden=\"true\">→</span>\n\t\t\t</button>\n\t\t\t\n\t\t\t<button class=\"export-data\" id=\"export-data\" onclick=\"getAllContent('content_line')\"> Export Data</button>\n\t\t\t<button class=\"export-data\" id=\"export-all\" onclick=\"getAllContent('content_line')\">Save All</button>\n\t\t\t<button type=\"submit\" class=\"export-data\">Checks Exist</button>\n\t\t</p> \n\t</div> \n\t</div>\n\t</div>\n</div>\n\t<div class=\"modal-dialog\" id=\"popup\" style=\"top:100px; display:none;position:fixed;z-index:100;width:55%;background-color: #BDBDBD\" onload=\"paging(true)\">\n\t\t\t\t\t<div class=\"modal-content\" style=\"position:relative\">\n\t\t\t\t\t\t<div class=\"modal-header\" style=\"height: 100px; \">\n\t\t\t\t\t\t\t<button type=\"button\" onclick=\"popupClose()\" data-dismiss=\"modal\" style=\"margin-top: 3px;margin-left:-90px;margin-bottom: 30px; position:relative ;\">×</button>\n\t\t\t\t\t\t\t<!-- <h4 class=\"modal-title\">Chỉnh sửa ngữ liệu song ngữ</h4> -->\n\t\t\t\t\t\t\t<h4 class=\"modal-title\" style=\"font-size: 16px;margin-top: -1%;\">\n\t\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t\t<div class=\"col-md-5\">\n\t\t\t\t\t\t\t\t\t\t<label for=\"field4\">\n\t\t\t\t\t\t\t\t\t\t\t<span>Status:\n\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"required\"></span>\n\t\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t\t\t<select name=\"select_status_ctmL6RA47mkLvRFaT\" style=\"padding: 5px; width: 195px;\">\n\t\t\t\t\t\t\t\t\t\t\t\t<option value=\"sure\">Sure</option>\n\t\t\t\t\t\t\t\t\t\t\t\t<option value=\"notSure\">Not Sure</option>\n\t\t\t\t\t\t\t\t\t\t\t\t<option value=\"needReview\">Need Review</option>\n\t\t\t\t\t\t\t\t\t\t\t\t<option value=\"veryNeedReview\">Really Need Review</option>\n\t\t\t\t\t\t\t\t\t\t\t</select>\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t<label for=\"field4\" style=\"margin-top: 5px\">\n\t\t\t\t\t\t\t\t\t\t\t<span>Topic:\n\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"required\"></span>\n\t\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t\t\t<select name=\"select_topic_ctmL6RA47mkLvRFaT\" style=\"padding: 5px; margin-left: 7px; width: 195px\">\n\t\t\t\t\t\t\t\t\t\t\t<option value=\"\">None</option>\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t</select>\n\t\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<div class=\"col-md-3\">\n\t\t\t\t\t\t\t\t\t\t<label for=\"field4\">\n\t\t\t\t\t\t\t\t\t\t\tEdit count: 0 \n\t\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<div class=\"col-md-4\" style=\"width: 220px;\">\n\t\t\t\t\t\t\t\t\t\t<label for=\"field4\">\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</h4>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"modal-body\" style=\"margin-top: 2%;\">\n\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<div class=\"col-sm-6\" style=\"position:absolute;left:-120px;\">\n\t\t\t\t\t\t\t\t\t<div class=\"col-sm-6\" >\n\t\t\t\t\t\t\t\t\t\t<div class=\"col-sm-12\" style=\"font-weight: bold; font-size: 18px; \"><?php echo $_REQUEST['src_lang']; ?></div>\n\t\t\t\t\t\t\t\t\t\t<div class=\"col-sm-12\">\n\t\t\t\t\t\t\t\t\t\t\t<label for=\"field2\">\n\t\t\t\t\t\t\t\t\t\t\t\t<!-- <textarea rows=\"10\" cols=\"49.8\" \n\t\t\t\t\t\t\t\t\t\t\t\tstyle=\"max-width: 100%; color: black;\" \n\t\t\t\t\t\t\t\t\t\t\t\tname=\"vietnamese_sentence_{{_id}}\">{{#if vnSentenceEdited}}{{vnSentenceEdited}}{{else}}{{vietnamese_sentence}}{{/if}}</textarea> -->\n\t\t\t\t\t\t\t\t\t\t\t\t<div><input id=\"line\" type=\"hidden\" value=\"\" /></div>\n\t\t\t\t\t\t\t\t\t\t\t\t<!-- comment to remove redundant spaces -->\n\t\t\t\t\t\t\t\t\t\t\t\t<div id=\"vietnamese_sentence_ctmL6RA47mkLvRFaT\" style=\"width:380px; max-width: 100%; color: black; border: 1px solid black; height: 206px; font-weight: normal; padding: 5px; overflow-y: auto;\" contenteditable=\"true\"><!--\n\t\t\t\t\t\t\t\t\t\t\t\t--><!-- \n\t\t\t\t\t\t\t\t\t\t\t\t\t--><!-- \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t--><!--\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t--><span id=\"src_line\" style=\"color: black;\"></span><!--\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t--><!-- \n\t\t\t\t\t\t\t\t\t\t\t\t\t--><!-- \n\t\t\t\t\t\t\t\t\t\t\t\t--><!--\n\t\t\t\t\t\t\t\t\t\t\t --></div>\n\t\t\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t</div>\t\t\t\t\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"col-sm-6\" style=\"position:absolute; left:50%;\">\n\t\t\t\t\t\t\t\t\t\t<div class=\"col-sm-12\" >\n\t\t\t\t\t\t\t\t\t\t<div class=\"col-sm-12\" style=\"font-weight: bold; font-size: 18px; \"><?php echo $_REQUEST['tgt_lang']; ?></div>\n\t\t\t\t\t\t\t\t\t\t\t<label for=\"field2\">\n\t\t\t\t\t\t\t\t\t\t\t\t<!-- <textarea rows=\"10\" cols=\"49.8\" \n\t\t\t\t\t\t\t\t\t\t\t\tstyle=\"max-width: 100%; color: black;\" \n\t\t\t\t\t\t\t\t\t\t\t\tname=\"japanese_sentence_{{_id}}\">{{#if jpSentenceEdited}}{{jpSentenceEdited}}{{else}}{{japanese_sentence}}{{/if}}</textarea> -->\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t<!-- comment to remove redundant spaces -->\n\t\t\t\t\t\t\t\t\t\t\t\t<div id=\"japanese_sentence_ctmL6RA47mkLvRFaT\" style=\"width:380px; max-width: 100%; color: black; border: 1px solid black; height: 206px; font-weight: normal; padding: 5px; overflow-y: auto;\" contenteditable=\"true\"><!--\n\t\t\t\t\t\t\t\t\t\t\t\t--><!-- \n\t\t\t\t\t\t\t\t\t\t\t\t\t--><!-- \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t--><!--\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t--><span id=\"tgt_line\" style=\"color: black;\"></span><!--\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t--><!-- \n\t\t\t\t\t\t\t\t\t\t\t\t\t--><!-- \n\t\t\t\t\t\t\t\t\t\t\t\t--><!--\n\t\t\t\t\t\t\t\t\t\t\t --></div>\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div class=\"row\" style=\"position:absolute; bottom:20px; left:27%; height:40px\">\n\t\t\t\t\t\t\t\t<div class=\"col-md-8\">\n\t\t\t\t\t\t\t\t\t<button type=\"button\" id=\"Save_Edit\" class=\"btn-save-edit btn btn-primary btn-lg center-block\" data-dismiss=\"modal\" style=\"width: 200px; margin-top: 25px; \n\t\t\t\t\t\t\t\t\t\t\t margin-right: 45px; float: right;\">Save Editing</button>\n\t\t\t\t\t\t\t\t</div>\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<div class=\"col-md-4\">\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<!-- <div class=\"modal-footer\">\n\t\t\t\t\t\t\t\t<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n\t\t\t\t\t\t\t</div> -->\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n</div>\n\t<script>\n\t\n\tfunction paging(start,end){\n\t\tvar lines = document.getElementsByClassName('line');\n\t\t\t\t\n\t\tfor(var line = 0; line < lines.length; line++){\n\t\t\t\n\t\t\t\n\t\t\tif(line >= start && line < end){\n\t\t\t\tlines[line].style.display = \"table-row\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tlines[line].style.display = \"none\";\n\t\t}\n\t\t\n\t\tvar startN = 0;\n\t\tvar endN = 10;\n\t\t\n\t\tif(end + 10 < lines.length){\n\t\t\tstartN = start + 10;\n\t\t\tendN = end + 10;\t\n\t\t}else{\n\t\t\t\n\t\t\tstartN = start;\n\t\t\t\n\t\t\tif(end <\t lines.length){\n\t\t\t\t//alert(endN);\n\t\t\t\t//alert(lines.length);\n\t\t\t\tstartN = lines.length - (lines.length - end);\n\t\t\t}\t\n\t\t\tendN = lines.length;\t\t\t\n\t\t\t\n\t\t}\n\t\t//alert(\"paging\\(true,\"+start+\",\"+end+\"\\)\");\n\t\t\n\t\tdocument.getElementById(\"next\").setAttribute(\"onclick\",\"paging\\(\"+startN+\",\"+endN+\"\\)\");\t\n\t\t\n\t\tvar startL = 0;\n\t\tvar endL = 10;\n\t\t\n\t\tif(endN != lines.length){\n\t\t\tif(start - 10 > 0){\n\t\t\t\tstartL = start - 10;\n\t\t\t\tendL = end - 10;\n\t\t\t\t\n\t\t\t} else{\n\t\t\t\tif(start - 10 == 0){\n\t\t\t\t\tstartL = 0;\n\t\t\t\t\tendL = 10;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tstartL = startN - 10;\n\t\t\tendL = startN;\n\t\t}\n\t\t\t//alert(\"paging(true,\"+start+\",\"+end\")\");\n\t\t\t\n\t\t\n\t\t\n\t\t\t\n\t\t\t\t\n\t\t\n\t\n\t\tdocument.getElementById(\"previ\").setAttribute(\"onclick\",\"paging\\(\"+startL+\",\"+endL+\"\\)\");\n\t\t\n\t}\n\t\n\tfunction remove(id){\n\t\tdocument.getElementById(id).remove();\n\t}\n\t\n\tfunction chonDLgoc (){\n\t\tdocument.getElementById(\"dlcs1\").checked = false;\n\t\t//document.getElementById(\"data-exsit\").disabled = false;\n\t\tdocument.getElementById(\"urlnn1\").disabled = true;\n\t\tdocument.getElementById(\"urlnn2\").disabled = true;\n\t}\n\tfunction chonDLkhac (){\n\t\tdocument.getElementById(\"dlcs\").checked = false;\n\t\t//document.getElementById(\"data-exsit\").disabled = true;\n\t\tdocument.getElementById(\"urlnn1\").disabled = false;\n\t\tdocument.getElementById(\"urlnn2\").disabled = false;\n\t}\n\t\n\t/*\n\tdocument.getElementById(\"btncheck\").onclick = function(){\n\n\t\tvar checkboxes = document.getElementsByName('name');\n\t\tif (document.getElementById(\"btncheck\").checked == false) \n\t\t{\n\t\t\tfor (var i = 0; i < checkboxes.length; i++){\n checkboxes[i].checked = false;\n }\n\t\t}\n\t\telse if(document.getElementById(\"btncheck\").checked == true)\n\t\t{\n\t\t\tfor (var i = 0; i < checkboxes.length; i++){\n checkboxes[i].checked = true;\n }\n\t\t}\n\t}*/\n\t\n\tdocument.getElementById(\"btncheck_vb\").onclick = function(){\n\n\t\tvar checkboxes = document.getElementsByName('name2');\n\t\tif (document.getElementById(\"btncheck_vb\").checked == false) \n\t\t{\n\t\t\tfor (var i = 0; i < checkboxes.length; i++){\n checkboxes[i].checked = false;\n }\n\t\t}\n\t\telse if(document.getElementById(\"btncheck_vb\").checked == true)\n\t\t{\n\t\t\tfor (var i = 0; i < checkboxes.length; i++){\n checkboxes[i].checked = true;\n }\n\t\t}\n\t}\n\t\n\tfunction popupOpen(id) {\n\t\n\tdocument.getElementById(\"popup\").style.display = \"block\";\t\n\tdocument.getElementById(\"src_line\").innerHTML = document.getElementById(\"src_line_\"+id).innerHTML;\n\tdocument.getElementById(\"tgt_line\").innerHTML = document.getElementById(\"tgt_line_\"+id).innerHTML;\n\tdocument.getElementById(\"line\").value = id;\n\t\n\t}\n\t\n\tfunction saveRecordLine(){\n\t\tvar id = document.getElementById(\"line\").value;\n\t\tif(id != \"\"){\n\t\t\tdocument.getElementById(\"src_line_\"+id).innerHTML = document.getElementById(\"src_line\").innerHTML;\n\t\t\tdocument.getElementById(\"tgt_line_\"+id).innerHTML = document.getElementById(\"tgt_line\").innerHTML;\n\t\t}\n\t\t\n\t}\n\t\n\tdocument.getElementById(\"Save_Edit\").onclick = function(){\n\t\tpopupClose();\n\t\tsaveRecordLine();\n\t}\t\n\t\n\t\t\n\tfunction popupClose() {\n\t\t\n\tdocument.getElementById(\"popup\").style.display = \"none\";\t\n\t\n\t\t\n\t}\n\t\n\tfunction getAllContent(_class){\n\t\tvar content = document.getElementsByClassName(_class);\n\t\tvar frame = document.getElementById('download_iframe');\n\t\n\t\tvar contents = \"\";\n\t\tfor (var i = 0; i < content.length; i+= 2){\n\t\t\tcontents += content[i].innerHTML +'\\t'+ content[i + 1].innerHTML;\n\t\t\t//alert(content[i].innerHTML +'\\t'+ content[i + 1].innerHTML);\n\t\t}\n\t\t//alert(contents);\n\t\tvar xhr = new XMLHttpRequest();\n\t\txhr.onreadystatechange = function(){\n\t\t\tif (xhr.readyState === 4) {\n\t\t\t\t//respoce recived\n\t\t\t\t\n\t\t\t\tvar res = xhr.responseText;\n\t\t\t\t\n\t\t\t\tif(res != ' ' || res != ''){\n\t\t\t\t\t\n\t\t\t\t\tvar link = document.createElement('a');\n\t\t\t\t\tlink.style.display = \"none\";\n\t\t\t\t\tlink.setAttribute('download','');\n\t\t\t\t\tlink.href=res;\n\t\t\t\t\t\n\t\t\t\t\tlink.click();\n\t\t\t\t\tlink.remove();\n\t\t\t\t}\n\t\t\t\n }\n\t\t\t\n\t\t}\n xhr.open(\"POST\",'luufile.php',true);\n\t\txhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');\n\t\t\n\t\txhr.send(JSON.stringify({\"name\":'<?php echo $_REQUEST['file']; ?>',\"data\":contents }));\n\t}\n\t\n</script>\n\n</body>\n</html>\n" }, { "alpha_fraction": 0.6676269173622131, "alphanum_fraction": 0.6705077290534973, "avg_line_length": 37.04109573364258, "blob_id": "a914f2ce2afc890518dbbbed48fef3ac5d042ca1", "content_id": "b92b38d4b47b3fca6c382ed51a6d6b1586d373c3", "detected_licenses": [ "MIT", "GPL-3.0-or-later" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2777, "license_type": "permissive", "max_line_length": 118, "num_lines": 73, "path": "/VnCoreNLP/src/main/java/vn/corenlp/parser/DependencyParser.java", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "package vn.corenlp.parser;\n\nimport edu.emory.mathcs.nlp.common.util.NLPUtils;\nimport edu.emory.mathcs.nlp.component.template.NLPComponent;\n\nimport edu.emory.mathcs.nlp.component.template.lexicon.GlobalLexica;\nimport edu.emory.mathcs.nlp.component.template.node.FeatMap;\nimport edu.emory.mathcs.nlp.component.template.node.NLPNode;\nimport edu.emory.mathcs.nlp.decode.NLPDecoder;\nimport org.apache.log4j.Logger;\nimport vn.pipeline.LexicalInitializer;\nimport vn.pipeline.Word;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class DependencyParser {\n private NLPDecoder nlpDecoder ;\n public final static Logger LOGGER = Logger.getLogger(DependencyParser.class);\n private static DependencyParser dependencyParser;\n public static DependencyParser initialize() throws IOException {\n if(dependencyParser == null) {\n dependencyParser = new DependencyParser();\n }\n return dependencyParser;\n }\n\n public DependencyParser() throws IOException {\n LOGGER.info(\"Loading Dependency Parsing model\");\n nlpDecoder = new NLPDecoder();\n List<NLPComponent<NLPNode>> components = new ArrayList();\n\n String modelPath = System.getProperty(\"user.dir\") + \"/models/dep/vi-dep.xz\";\n if (!new File(modelPath).exists()) throw new IOException(\"DependencyParser: \" + modelPath + \" is not found!\");\n GlobalLexica lexica = LexicalInitializer.initialize(true).initializeLexica();\n if(lexica != null) {\n components.add(lexica);\n }\n components.add(NLPUtils.getComponent(modelPath));\n nlpDecoder.setComponents(components);\n\n }\n\n public void tagSentence(List<Word> sentenceWords) {\n NLPNode[] decodedNodes = nlpDecoder.decode(toNodeArray(sentenceWords));\n for(int i = 0; i < sentenceWords.size(); i++) {\n Word word = sentenceWords.get(i);\n word.setHead(decodedNodes[i + 1].getDependencyHead().getID());\n word.setDepLabel(decodedNodes[i + 1].getDependencyLabel());\n if(word.getPosTag() != null && word.getPosTag().equals(\"CH\")) word.setDepLabel(\"punct\");\n }\n }\n\n private NLPNode[] toNodeArray(List<Word> sentenceWords) {\n NLPNode[] nlpNodes = new NLPNode[sentenceWords.size() + 1];\n nlpNodes[0] = new NLPNode();\n for(int i = 0; i < sentenceWords.size(); i++) {\n Word word = sentenceWords.get(i);\n //int id, String form, String lemma, String posTag, FeatMap feats\n nlpNodes[i + 1] = new NLPNode(word.getIndex(), word.getForm(), word.getForm(),\n word.getPosTag(), new FeatMap());\n\n }\n return nlpNodes;\n }\n\n public static void main(String[] args) {\n\n\n }\n}\n" }, { "alpha_fraction": 0.5895729064941406, "alphanum_fraction": 0.5945646166801453, "avg_line_length": 30.64912223815918, "blob_id": "7a9dd6b00a991028c37ef0f88197c10ca3e5efa7", "content_id": "bbdb562cbbf5091e1a65b5ac5b3cd46abe61de9a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1803, "license_type": "permissive", "max_line_length": 141, "num_lines": 57, "path": "/TedTalkCrawler.py", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "import os\nfrom datetime import datetime\nimport ConvertHtmlToText\nimport Punctuation\n\n\n\n\n\ndef crawlWithLanguage(language):\n \"\"\"\n :param language: \"en\", \"ja\", \"km\", \"zh\", \"lo\"\n :return: None\n \"\"\"\n if (language != \"en\" and language != \"ja\" and language != \"km\" and language != \"zh\" and language != \"lo\"):\n raise Exception(\"Resource not supported\")\n # mount to current real part\n current_dir = os.path.dirname(os.path.realpath(__file__))\n map_Punctuation = Punctuation.getPunctuationForLanguage(language)\n\n _case = {\"TH1\": 0, \"TH2\": 1}\n\n Sentence_folder = current_dir + \"/Data/crawler_success/TedTalk/Sentence/\"\n Document_folder = current_dir + \"/Data/crawler_success/TedTalk/Document/\"\n\n src_lang_ = language\n tgt_lang_ = \"vi\"\n\n output_dir_success = [Sentence_folder, Document_folder]\n\n if not os.path.exists(Sentence_folder):\n os.makedirs(Sentence_folder)\n if not os.path.exists(Document_folder):\n os.makedirs(Document_folder)\n\n all_talk_names = {}\n i = 1\n while( i > 0):\n path = \"https://www.ted.com/talks?sort=newest&language=\" + tgt_lang_ + \"&page=%d&sort=newest\" % (i)\n\n all_talk_names = {}\n if ConvertHtmlToText.enlist_talk_names(path, all_talk_names, src_lang_, tgt_lang_):\n #\n # FOR TEST A SPECIFIC LINKS\n # all_talk_names = [\"/talks/frank_gehry_as_a_young_rebel\"]\n\n for i in all_talk_names:\n now = datetime.now()\n batch_name = now.strftime(\"/%Y-%m_%M/\")\n\n ConvertHtmlToText.extract_talk('https://www.ted.com' + i + '/transcript', i[7:], output_dir_success,\"\", src_lang_, tgt_lang_)\n i = i + 1\n continue\n i = -1\n print(\"no more talk\")\n break\n#crawlWithLanguage(\"en\")" }, { "alpha_fraction": 0.5713427662849426, "alphanum_fraction": 0.5995365381240845, "avg_line_length": 27.769136428833008, "blob_id": "c398d2a8db7247aacdf00658b88790d92621adfe", "content_id": "a9df41fc5ddc6ca5d8f30cb96d8e2338eb14bdda", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 23587, "license_type": "permissive", "max_line_length": 249, "num_lines": 810, "path": "/thuchiengionghang-demo.php", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "<?php\n\t#error_reporting(0);\n\t//date_default_timezone_set('Asia/Ho_Chi_Minh');\n\t\n\t//echo $today;\n ?>\n<!DOCTYPE html>\n<html>\n<head>\n\t<title>Thực hiện gióng hàng</title>\n\t<meta charset='UTF-8'>\n\t<script>\n\t\n\t\tfunction dowload_file(item, tag, uri){\n\t\t\t\t\tvar string = item.value.split(\"&\")\n\t\t\t\t\ttag.href = uri;\n\t\t\t\t\ttag.click();\n\t\t\t\t\tsetTimeout(function(){\n\t\t\t\t\tconsole.log(\"Download slowly\");\t\n\t\t}, 1500);\n\t\t}\n\t\t\n\t\tfunction dowload_all_file(child_class, _case){\n\t\t\tvar checkboxes = document.getElementsByClassName(child_class);\n\t\t\t\n\t\t\tvar link = document.createElement(\"a\");\n\t\t\tlink.style.display = \"none\";\t\n\t\t\tlink.setAttribute('download', '');\n\t\t\t\n\t\t\tdocument.body.appendChild(link);\t\t\t\n\t\t\tfor(var i = 0; i < checkboxes.length; i++){\n\t\t\t\tif(_case == 1){\n\t\t\t\t\tvar string = checkboxes[i].value.split(\"&\")\n\t\t\t\t\tdowload_file(checkboxes[i],link,string[0]);\n\t\t\t\t\tdowload_file(checkboxes[i],link,string[1]);\n\t\t\t\t} \n\t\t\t\tif(_case == 0){\n\t\t\t\t\t//alert(checkboxes[i].value);\n\t\t\t\t\tdowload_file(checkboxes[i], link, checkboxes[i].value);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tlink.remove();\n\t\t}\n\t\n\t\tfunction download_file_checked(child_class, _case){\n\t\t\tvar checkboxes = document.getElementsByClassName(child_class);\n\t\t\t/*var frame = document.getElementById(\"download_iframe\");\n\t\t\tvar xhr = new XMLHttpRequest();\n\t\t\txhr.responseType = 'blob';\n\t\t\t\tfor(var i = 0; i < checkboxes.length; i++){\n\t\t\t\t\tif(checkboxes[i].checked){\n\t\t\t\t\t\tvar string = checkboxes[i].value.split(\"&\")\n\t\t\t\t\t\txhr.open('GET',\"./crawl_ted_talk_success_TH2/\" + string[0],true);\n\t\t\t\t\t\txhr.send();\n\t\t\t\t\t\t\n\t\t\t\t\t\txhr.open('GET',\"./crawl_ted_talk_success_TH2/\" + string[1],true);\n\t\t\t\t\t\txhr.send();\n\t\t\t\t\t\t//alert(checkboxes[i].value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t*/\n\t\t\tvar link = document.createElement(\"a\");\n\t\t\tlink.style.display = \"none\";\t\n\t\t\tlink.setAttribute('download', '');\n\t\t\t\n\t\t\tdocument.body.appendChild(link);\t\t\t\n\t\t\tfor(var i = 0; i < checkboxes.length; i++){\n\t\t\t\tif(checkboxes[i].checked){\n\t\t\t\t\tif(_case == 1){\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tvar string = checkboxes[i].value.split(\"&\")\n\t\t\t\t\t\tdowload_file(checkboxes[i],link, string[0]);\n\t\t\t\t\t\tdowload_file(checkboxes[i],link, string[1]);\n\t\t\t\t\t} \n\t\t\t\t\t\n\t\t\t\t\tif(_case == 0){\n\t\t\t\t\t\tdowload_file(checkboxes[i],link,\"./\" + checkboxes[i].value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tlink.remove();\n\t\t}\n\t\t\n\t\t\n\t\tfunction setCheckedCheckBox(item){\n\t\t\tif(item != null){\n\t\t\t\titem.checked = true;\n\t\t\t}\n\t\t}\n\t\t\n\t\tfunction checkAllCheckBox(id,child_class){\n\t\t\t\n\t\t\tvar checkAllButton = document.getElementById(id);\n\t\t\t\n\t\t\tif(checkAllButton.checked){\n\t\t\t\t\n\t\t\t\tvar checkboxes = document.getElementsByClassName(child_class);\n\t\t\t\tvar lim = checkboxes.length;\n\t\t\t\t\n\t\t\t\tfor(var i = 0; i < lim; i++){\n\t\t\t\t\tcheckboxes[i].checked = true;\n\t\t\t\t\t\n\t\t\t\t\t//setCheckedCheckBox(checkboxes[i]);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\t\n\t\n\t</script>\n</head>\n<body>\n<iframe id=\"download_iframe\" style=\"display:none;\"><head> <meta charset=\"UTF-8\"> </head></iframe>\n<div style=\"width: 100%;height:100px;background:#gray;\" align=\"center\">\n\t<h1 style=\"color: #304499;\">Công cụ hỗ trợ soạn thảo ngữ liệu song ngữ</h1>\n</div>\n<div style=\"width: 100%;height: 50px;background:gray;\">\n\t<ul style=\"display: inline-block;\"class=\"menu\">\n\t\t<li style=\"list-style: none;float: left;height: 50px;width: 100px;text-align: center;margin-top: -15px;\"><a href=\"index.html\" style=\"text-decoration: none;line-height: 50px;color: white;\">Trang Chủ</a></li>\n\t\t<li style=\"list-style: none;float: left;height: 50px;width: 150px;text-align: center;margin-top: -15px;\"><a href=\"solieuthongke.html\" style=\"text-decoration: none;line-height: 50px;color: white;\">Thống kê ngữ liệu</a></li>\n\t\t<li style=\"list-style: none;float: left;height: 50px;width: 150px;text-align: center;margin-top: -15px;\"><a href=\"gionghangvb.html\" style=\"text-decoration: none;line-height: 50px;color: white;\">Gióng hàng văn bản</a></li>\n\t\t<li style=\"list-style: none;float: left;height: 50px;width: 150px;text-align: center;margin-top: -15px;\"><a href=\"gionghangcau.html\" style=\"text-decoration: none;line-height: 50px;color: white;\">Gióng hàng câu</a></li>\n\t</ul>\n<style type=\"text/css\">\n.menu li:hover{\n\tbackground: #A0A0A0;\n}\n.menu li a:hover{\ncolor: blue;\n}\ntable {\nwidth: 100%;\nheight: auto; \nfont-family: arial, sans-serif;\nborder:1px solid #ddd;\n}\nth, td {\n padding: 8px;\n text-align: left;\n border-top: 1px solid #dee2e6;\n text-align: center;\n}\n tbody tr:nth-child(odd) {\n background-color: #f2f2f2;\n}\n.detele{\n\twidth: 60%;\n\theight: 30px;\n\tfont-size: 16px;\n\tmargin-left: 10px;\n}\n.detele-gh{\n\twidth: auto;height: 30px;\n\tfont-size: 16px;\n\t}\n.content{\n\twidth: 100%;height: auto;margin-top: 2%;\n}\n.content-1{\n\twidth: 60%;height: auto;margin-left: 10%;border: 2px solid #ddd;;padding-left: 15%;border-radius: \n\n}\n.website{\n\tmargin-right: 10px;\n\tmargin-left: 10px;\n\tfont-size: 18px;\n}\n.leangue{\n\twidth: 15%;\n\theight:30px;\n\tmargin-right: 20px;\n}\n.modal{\nmargin: 0% 3% 0% 3%; width: 100%;\n}\n.modal-table{\n\twidth: 90%;height: auto;text-align: center;font-size: 18px;margin-top: 15px;\n}\n.phantrang{margin-left:20px; width: 90%; height: auto;margin: 0% 3% 0% 3%;}\n.input1{width: 70px; height: 30px; text-align: center; margin-right: 15px;}\n.skip{width: 100px; height: 32px;}\n.extract{\n\twidth: 10%;\n\theight: 40px;\n\t}\n.phan{float:right;margin-top: 10px;}\n.pvg{list-style: none;float:left;}\n.export-data{\n\twidth: 5%;\n\theight: 40px;\n\tfloat:right;\n\tmargin-right: 54px;\n}\n.url{\n\twidth: 20%;\n\theight: 26px;\n}\nbody,html{\n\tmargin: 0;\n\tpadding: 0;\n\t}\n\n.export-data {\n background-color: #808080;\n width: auto;\n border: none;\n color: #ffffff;\n cursor: pointer;\n display: inline-block;\n font-family: 'BenchNine', Arial, sans-serif;\n font-size: 1em;\n font-size: 18px;\n line-height: 1em;\n margin: 10px 35px;\n outline: none;\n padding: 12px 30px 10px;\n position: relative;\n text-transform: uppercase;\n font-weight: 700;\n}\n\n.export-data:before,\n.export-data:after {\n border-color: transparent;\n -webkit-transition: all 0.25s;\n transition: all 0.25s;\n border-style: solid;\n border-width: 0;\n content: \"\";\n height: 24px;\n position: absolute;\n width: 24px;\n}\n\n.export-data:before {\n border-color: #808080;\n border-top-width: 2px;\n left: 0px;\n top: -5px;\n}\n\n.export-data:after {\n border-bottom-width: 2px;\n border-color: #808080;\n bottom: -5px;\n right: 0px;\n}\n\n.export-data:hover,\n.export-data.hover {\n background-color: #808080;\n}\n\n.export-data:hover:before,\n.export-data.hover:before,\n.export-data:hover:after,\n.export-data.hover:after {\n height: 100%;\n width: 100%;\n}\n\n.export{\n background-color: #808080;\n width: auto;\n border: none;\n color: #ffffff;\n cursor: pointer;\n display: inline-block;\n font-family: 'BenchNine', Arial, sans-serif;\n font-size: 1em;\n font-size: 18px;\n line-height: 1em;\n margin: 10px 35px;\n outline: none;\n padding: 12px 30px 10px;\n position: relative;\n text-transform: uppercase;\n font-weight: 700;\n}\n\n.export:before,\n.export:after {\n border-color: transparent;\n -webkit-transition: all 0.25s;\n transition: all 0.25s;\n border-style: solid;\n border-width: 0;\n content: \"\";\n height: 24px;\n position: absolute;\n width: 24px;\n}\n\n.export:before {\n border-color: #808080;\n border-top-width: 2px;\n left: 0px;\n top: -5px;\n}\n\n.export:after {\n border-bottom-width: 2px;\n border-color: #808080;\n bottom: -5px;\n right: 0px;\n}\n\n.export:hover,\n.export.hover {\n background-color: #808080;\n}\n\n.export:hover:before,\n.export.hover:before,\n.export:hover:after,\n.export.hover:after {\n height: 100%;\n width: 100%;\n}\n.btncon{\n background-color: #808080;\n width: 50%;\n border: none;\n color: #ffffff;\n cursor: pointer;\n display: inline-block;\n font-family: 'BenchNine', Arial, sans-serif;\n font-size: 1em;\n font-size: 18px;\n line-height: 1em;\n outline: none;\n position: relative;\n text-transform: uppercase;\n font-weight: 700;\n}\n\n.btncon:before,\n.btncon:after {\n border-color: transparent;\n -webkit-transition: all 0.25s;\n transition: all 0.25s;\n border-style: solid;\n border-width: 0;\n content: \"\";\n height: 24px;\n position: absolute;\n width: 24px;\n}\n\n.btncon:before {\n border-color: #808080;\n border-top-width: 2px;\n left: 0px;\n top: -5px;\n}\n\n.btncon:after {\n border-bottom-width: 2px;\n border-color: #808080;\n bottom: -5px;\n right: 0px;\n}\n\n.btncon:hover,\n.btncon.hover {\n background-color: #808080;\n}\n\n.btncon:hover:before,\n.btncon.hover:before,\n.btncon:hover:after,\n.btncon.hover:after {\n height: 100%;\n width: 100%;\n}\n.btncon-gh{\n background-color: #808080;\n width: auto;\n height: 15%;\n border: none;\n color: #ffffff;\n cursor: pointer;\n display: inline-block;\n font-family: 'BenchNine', Arial, sans-serif;\n font-size: 1em;\n font-size: 18px;\n line-height: 1em;\n outline: none;\n position: relative;\n text-transform: uppercase;\n font-weight: 700;\n}\n\n.btncon-gh:before,\n.btncon-gh:after {\n border-color: transparent;\n -webkit-transition: all 0.25s;\n transition: all 0.25s;\n border-style: solid;\n border-width: 0;\n content: \"\";\n height: 24px;\n position: absolute;\n width: 24px;\n}\n\n.btncon-gh:before {\n border-color: #808080;\n border-top-width: 2px;\n left: 0px;\n top: -5px;\n}\n\n.btncon-gh:after {\n border-bottom-width: 2px;\n border-color: #808080;\n bottom: -5px;\n right: 0px;\n}\n\n.btncon-gh:hover,\n.btncon-gh.hover {\n background-color: #808080;\n}\n\n.btncon-gh:hover:before,\n.btncon-gh.hover:before,\n.btncon-gh:hover:after,\n.btncon-gh.hover:after {\n height: 100%;\n width: 100%;\n}\n.modal-dialog{\n\tmargin-left: 15%;\n}\n.modal-content\n{\n\tmargin-left: 15%;\n\theight: 500px;\n}\n</style>\n</div>\n<div class=\"content\">\n\t<!-- \n\t<div class=\"content-1\">\n\t<p>\n\t\t<input type=\"radio\" id=\"dlcs\" onclick=\"chonDLgoc()\" checked=\"true\" />\n\t\t\t<label for=\"age1\" style=\"font-size: 18px\">Dữ Liệu Có Sẵn</label>\n\t\t<input type=\"radio\" id=\"dlcs1\" onclick=\"chonDLkhac()\"/>\n\t\t\t<label for=\"age2\" style=\"font-size: 18px\">Dữ Liệu Khác</label>\n\t</p>\n\t<p>\n\t\t<span style=\"font-size: 18px\">Nguồn Dữ Liệu</span>\n\t\t<select name=\"web\" id=\"data-exsit\" style=\"width: 10%;height: 30px;\">\n\t\t\t<option></option>\n\t\t\t<option>VOV</option>\n\t\t\t<option>Wikipedia</option>\n\t\t\t<option>Ted talk</option>\n\t\t\t<option>Subtitle</option>\n\t\t\t<option>Paracrawl</option>\n\t\t</select>\n\t\t<span class=\"website\"> Link Website</span>\n\t\t<input id=\"urlnn1\" type=\"text\" style=\"margin-right: 10px;\" class=\"url\" disabled=\"true\">\n\t\t<input id=\"urlnn2\" type=\"text\" class=\"url\" disabled=\"true\">\n\t</p>\n\t<p>\n\t\t<span style=\"font-size: 18px\">Cặp Ngôn Ngữ</span>\n\t\t<select name=\"src_lang\" id=\"src_lang\"class=\"leangue\">\n\t\t\t<option></option>\n\t\t\t<option value=\"vi\">Vietnamese</option>\n\t\t\t<option value=\"km\">Khmer</option>\n\t\t\t<option value=\"zh\">Chinese</option>\n\t\t\t<option value=\"lo\">Laos</option>\n\t\t\t<option value=\"en\">English</option>\n\t\t</select>\n\t\t<span>\n\t\t\t<select name=\"tgt_lang\" id=\"tgt_lang\" class=\"leangue\">\n\t\t\t\t<option></option>\n\t\t\t\t<option value=\"en\">English</option>\n\t\t\t\t<option value=\"lo\">Laos</option>\n\t\t\t\t<option value=\"zh\">Chinese</option>\n\t\t\t\t<option value=\"km\">Khmer</option>\n\t\t\t\t<option value=\"vi\">Vietnamese</option>\n\t\t\t</select>\n\t\t</span>\n\t</p>\n\t-->\n\t<div style=\"margin-left: 29%;\">\n\t\t<button class=\"export\" id=\"extract-vb\" onclick=\"\">Extract Văn Bản</button>\n\t\t<button class=\"export\" id=\"extract-cau\" onclick=\"\">Extract Câu song ngữ</button>\n\t</div>\n\t\n</div>\n\n\t<div class=\"modal\" id=\"modal_ghvb\">\n\t\t<table class=\"modal-table\">\n\t\t\t<tr>\n\t\t\t\t<th style=\"width: 3%;\"><input id=\"btncheck_vb\" type=\"checkbox\" onclick=\"checkAllCheckBox('btncheck_vb','checkbox_child_1')\" name=\"\"></th>\n\t\t\t\t<th style=\"width: 35%;\"><?php echo $_POST['src_lang']; ?></th>\n\t\t\t\t<th style=\"width: 35%;\"><?php echo $_POST['tgt_lang']; ?></th>\n\t\t\t\t<th style=\"width: 5%;\">Độ đo</th>\n\t\t\t\t<th style=\"width: 10%;\">Edit</th>\n\t\t\t\t<th style=\"width: 10%;\">Gióng Hàng</th>\n\t\t\t</tr>\n\t\t\t<?php\n\t\t\t\t\n\t\t\t\t$hadFile = true;\n\t\t\t\t\n\t\t\t\tif(!isset($_REQUEST['file'])){\n\t\t\t\t\t\n\t\t\t\t\t$hadFile = false;\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\tif($hadFile):\n\t\t\t\t\t\n\t\t\t\t\t$files = $_REQUEST['file'];\t\n\t\t\t\t\tforeach ($files as $file ): ?>\n\t\t\t\t\t\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t\n\t\t\t\t\t\t<td><input class=\"checkbox_child_1 ckb_child\" type=\"checkbox\" value=\"<?php print($file[0]);\n\t\t\t\t\t\techo \"&\";\n\t\t\t\t\t\techo $file[2]; ?>\" name=\"name2\"></td>\n\t\t\t\t\t\t<td style=\"text-align:left;\"> \n\t\t\t\t\t\t\t<a href=\"<?php echo $file[0]; ?>\" download>\n\t\t\t\t\t\t\t\t<?php echo $file[1]; ?>\n\t\t\t\t\t\t\t</a> \n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td style=\"text-align:left;\"> <a href=\"./<?php echo $file[2]; ?>\" download>\n\t\t\t\t\t\t\t\t<?php echo $file[3]; ?>\n\t\t\t\t\t\t\t\t</a> \n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td>0.2</td>\n\t\t\t\t\t\t<td><button style=\"width: 40%;height: 30px;\" id=\"detele\"class=\"btncon\">Xoá</button>\n\t\t\t\t\t\t\t<button style=\"width: 40%;height: 30px;margin-left:10px;\"id=\"edit\" onclick=\"popupOpen()\" class=\"btncon\">Edit</button>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td><button class=\"btncon-gh\" id=\"gionghang1\" class=\"btncon\">Gióng hàng</button></td>\n\t\t\t\t\t</tr>\n\t\t\t\t<?php \n\t\t\t\t\tendforeach;\n\t\t\t\tendif\n\t\t\t\t\n\t\t\t\t?>\n\t\t</table>\n\t\t<div class=\"phantrang\">\n\t\t<p>\n\t\t\t<input type=\"text\" placeholder=\"1 - 2\" class=\"input1\"> \n\t\t\t\t<a href=\"xuly.php?web=<?php echo $_REQUEST['web']; ?>&src_lang=<?php echo $_REQUEST['src']; ?>&tgt_lang=<?php echo $_REQUEST['tgt']; ?>&page=<?php echo $_REQUEST['prev_page'];?>\" style=\"font-weight: bold; width: 150px;text-decoration: none; \">\n\t\t\t\t\t<span aria-hidden=\"true\" id=\"\">←</span> Trước\n\t\t\t\t</a>\n\t\t\t\t<a href=\"xuly.php?web=<?php echo $_REQUEST['web']; ?>&src_lang=<?php echo $_REQUEST['src']; ?>&tgt_lang=<?php echo $_REQUEST['tgt']; ?>&page=<?php echo $_REQUEST['next_page'];?>\" style=\"font-weight: bold; width: 150px;text-decoration: none;\">Sau\n\t\t\t\t\t<span aria-hidden=\"true\">→</span>\n\t\t\t\t</a>\n\t\t\t\t<button class=\"export-data\" id=\"export-data\" onclick=\"download_file_checked('checkbox_child_1',1)\" > Export Data</button>\n\t\t\t\t<button class=\"export-data\" id=\"export-all\" onclick=\"dowload_all_file('checkbox_child_1',1) \">Save All</button>\n\t\t</p> \n\t</div>\n\t</div>\n\t<div style=\"margin: 1% 3% 0% 3%; width: 100%;display: none;\" id=\"modal_cau\">\n\t\t<table style=\"width: 90%;height: auto;text-align: center;font-size: 18px;margin-top: 15px;\">\n\t\t\t<tr>\t\t\t\t\n\t\t\t\t<th style=\"width: 3%;\"><input id=\"btncheck_cau\" class=\"checkbox_child\" type=\"checkbox\" onclick=\"checkAllCheckBox('btncheck_cau','checkbox_child')\" name=\"\"></th>\n\t\t\t\t<th colspan='2' style=\"width: 35%;\"><?php echo $_POST['src_lang']; ?></th>\n\t\t\t\t\n\t\t\t\t<th style=\"width: 5%;\">Độ đo</th>\n\t\t\t\t<th style=\"width: 10%;\">Edit</th>\n\t\t\t\t\n\t\t\t</tr>\n\t\t\t\n\t\t\t<?php\n\t\t\t\t$align_files = $_REQUEST['align_file'];\n\t\t\t\t\t\t\t\t\n\t\t\t\tif(!isset($align_files)){\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tforeach ($align_files as $file_path=> $file_name ): \n\t\t\t?>\n\t\t\t<tr>\n\t\t\t\t<td><input class=\"checkbox_child ckb_child\" type=\"checkbox\" value=\"<?php echo $file_path; ?>\" name=\"name2\"></td>\n\t\t\t\t<td colspan=\"2\" style=\"text-align:left;\"> \n\t\t\t\t\t<a href=\"giongcau.php?file=<?php echo $file_path;?>&src_lang=<?php echo $_POST['src_lang']; ?>&tgt_lang=<?php echo $_POST['tgt_lang']?>\" target=\"_blank\">\n\t\t\t\t\t\t<?php echo $file_name; ?>\n\t\t\t\t\t</a> \n\t\t\t\t</td>\n\t\t\t\t\n\t\t\t\t<td>0.2</td>\n\t\t\t\t<td>\n\t\t\t\t\t<button style=\"width: 40%;height: 30px;\" id=\"detele\"class=\"btncon\">Xoá</button>\n\t\t\t\t\t<button style=\"width: 40%;height: 30px;margin-left:10px;\"id=\"edit\"onclick=\"popupOpen()\"class=\"btncon\">Edit</button>\n\t\t\t\t</td>\n\t\t\t\t\n\t\t\t<tr>\n\t\t\t<?php if(!isset($align_files)){\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tendforeach \n\t\t\t?>\n\t</table>\n\t<div class=\"phantrang\">\n\t\t<p>\n\t\t\t<input type=\"text\" placeholder=\"1 - 2\" class=\"input1\"> \n\t\t\t\t<a href=\"xuly.php?web=<?php echo $_REQUEST['web']; ?>&src_lang=<?php echo $_REQUEST['src']; ?>&tgt_lang=<?php echo $_REQUEST['tgt']; ?>&page=<?php echo $_REQUEST['prev_page'];?>\" style=\"font-weight: bold; width: 150px;text-decoration: none; \">\n\t\t\t\t\t<span aria-hidden=\"true\" id=\"\">←</span> Trước\n\t\t\t\t</a>\n\t\t\t\t<a href=\"xuly.php?web=<?php echo $_REQUEST['web']; ?>&src_lang=<?php echo $_REQUEST['src']; ?>&tgt_lang=<?php echo $_REQUEST['tgt']; ?>&page=<?php echo $_REQUEST['next_page'];?>\" style=\"font-weight: bold; width: 150px;text-decoration: none;\">Sau\n\t\t\t\t\t<span aria-hidden=\"true\">→</span>\n\t\t\t\t</a>\n\t\t\t\t<button class=\"export-data\" id=\"export-data\" onclick=\"download_file_checked('checkbox_child',0)\" > Export Data</button>\n\t\t\t\t<button class=\"export-data\" id=\"export-all\" onclick=\"dowload_all_file('checkbox_child',0) \">Save All</button>\n\t\t\t\t<button class=\"export-data\">Checks Exist</button>\n\t\t</p> \n\t</div> \n\t</div>\n\t</div>\n</div>\n\t<div class=\"modal-dialog\" id=\"popup\" style=\"top:100px;display:none;position:fixed;z-index:100;width:70%;background-color: #BDBDBD\">\n\t\t\t\t\t<div class=\"modal-content\">\n\t\t\t\t\t\t<div class=\"modal-header\" style=\"height: 100px;\">\n\t\t\t\t\t\t\t<button type=\"button\" onclick=\"popupClose()\" data-dismiss=\"modal\" style=\"margin-top: 3px;margin-bottom: 30px;\">×</button>\n\t\t\t\t\t\t\t<!-- <h4 class=\"modal-title\">Chỉnh sửa ngữ liệu song ngữ</h4> -->\n\t\t\t\t\t\t\t<h4 class=\"modal-title\" style=\"font-size: 16px;margin-top: -1%;\">\n\t\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t\t<div class=\"col-md-5\">\n\t\t\t\t\t\t\t\t\t\t<label for=\"field4\">\n\t\t\t\t\t\t\t\t\t\t\t<span>Status:\n\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"required\"></span>\n\t\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t\t\t<select name=\"select_status_ctmL6RA47mkLvRFaT\" style=\"padding: 5px; width: 195px;\">\n\t\t\t\t\t\t\t\t\t\t\t\t<option value=\"sure\">Sure</option>\n\t\t\t\t\t\t\t\t\t\t\t\t<option value=\"notSure\">Not Sure</option>\n\t\t\t\t\t\t\t\t\t\t\t\t<option value=\"needReview\">Need Review</option>\n\t\t\t\t\t\t\t\t\t\t\t\t<option value=\"veryNeedReview\">Really Need Review</option>\n\t\t\t\t\t\t\t\t\t\t\t</select>\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t<label for=\"field4\" style=\"margin-top: 5px\">\n\t\t\t\t\t\t\t\t\t\t\t<span>Topic:\n\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"required\"></span>\n\t\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t\t\t<select name=\"select_topic_ctmL6RA47mkLvRFaT\" style=\"padding: 5px; margin-left: 7px; width: 195px\">\n\t\t\t\t\t\t\t\t\t\t\t<option value=\"tourism\">Tourism</option>\n\t\t\t\t\t\t\t\t\t\t\t<option value=\"law_commercial\">Commercial law</option>\n\t\t\t\t\t\t\t\t\t\t\t<option value=\"ja_culture\">Japanese culture</option>\n\t\t\t\t\t\t\t\t\t\t\t<option value=\"law_investiment\">Investment law</option>\n\t\t\t\t\t\t\t\t\t\t\t<option value=\"law_tourism\">Tourism law</option>\n\t\t\t\t\t\t\t\t\t\t\t<option value=\"other_topic\">Other topics</option>\n\t\t\t\t\t\t\t\t\t\t\t</select>\n\t\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<div class=\"col-md-3\">\n\t\t\t\t\t\t\t\t\t\t<label for=\"field4\">\n\t\t\t\t\t\t\t\t\t\t\tEdit count: 0 \n\t\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<div class=\"col-md-4\" style=\"width: 220px;\">\n\t\t\t\t\t\t\t\t\t\t<label for=\"field4\">\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</h4>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"modal-body\" style=\"margin-top: 2%;\">\n\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t<div class=\"col-md-6\">\n\t\t\t\t\t\t\t\t\t<div class=\"row\" style=\"font-weight: bold; font-size: 18px;\">Vietnamese</div>\n\t\t\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t\t\t<label for=\"field2\">\n\t\t\t\t\t\t\t\t\t\t\t<!-- <textarea rows=\"10\" cols=\"49.8\" \n\t\t\t\t\t\t\t\t\t\t\tstyle=\"max-width: 100%; color: black;\" \n\t\t\t\t\t\t\t\t\t\t\tname=\"vietnamese_sentence_{{_id}}\">{{#if vnSentenceEdited}}{{vnSentenceEdited}}{{else}}{{vietnamese_sentence}}{{/if}}</textarea> -->\n\n\t\t\t\t\t\t\t\t\t\t\t<!-- comment to remove redundant spaces -->\n\t\t\t\t\t\t\t\t\t\t\t<div id=\"vietnamese_sentence_ctmL6RA47mkLvRFaT\" style=\"width: 465px; max-width: 100%; color: black; border: 1px solid black; height: 206px; font-weight: normal; padding: 5px; overflow-y: auto;\" contenteditable=\"true\"><!--\n\t\t\t\t\t\t\t\t\t\t\t--><!-- \n\t\t\t\t\t\t\t\t\t\t\t\t--><!-- \n\t\t\t\t\t\t\t\t\t\t\t\t\t--><!--\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t--><span style=\"color: black;\">Tiếp tục khắc phục hậu quả bão lũ ở các tình miền Trung.</span><!--\n\t\t\t\t\t\t\t\t\t\t\t\t\t--><!-- \n\t\t\t\t\t\t\t\t\t\t\t\t--><!-- \n\t\t\t\t\t\t\t\t\t\t\t--><!--\n\t\t\t\t\t\t\t\t\t\t --></div>\n\t\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t\t\t<div class=\"col-md-6\">\n\t\t\t\t\t\t\t\t\t<div class=\"row\" style=\"font-weight: bold; font-size: 18px;\">Khmer</div>\n\t\t\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t\t\t<label for=\"field2\">\n\t\t\t\t\t\t\t\t\t\t\t<!-- <textarea rows=\"10\" cols=\"49.8\" \n\t\t\t\t\t\t\t\t\t\t\tstyle=\"max-width: 100%; color: black;\" \n\t\t\t\t\t\t\t\t\t\t\tname=\"japanese_sentence_{{_id}}\">{{#if jpSentenceEdited}}{{jpSentenceEdited}}{{else}}{{japanese_sentence}}{{/if}}</textarea> -->\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t<!-- comment to remove redundant spaces -->\n\t\t\t\t\t\t\t\t\t\t\t<div id=\"japanese_sentence_ctmL6RA47mkLvRFaT\" style=\"width: 465px; max-width: 100%; color: black; border: 1px solid black; height: 206px; font-weight: normal; padding: 5px; overflow-y: auto;\" contenteditable=\"true\"><!--\n\t\t\t\t\t\t\t\t\t\t\t--><!-- \n\t\t\t\t\t\t\t\t\t\t\t\t--><!-- \n\t\t\t\t\t\t\t\t\t\t\t\t\t--><!--\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t--><span style=\"color: black;\">បន្តសកម្មភាពជំនះពុះពារនូវផលវិបាកបណ្តាមកពីព្យុះនិងទឹកជំនន់នៅតំបន់ភាគកណ្តាលវៀតណាម</span><!--\n\t\t\t\t\t\t\t\t\t\t\t\t\t--><!-- \n\t\t\t\t\t\t\t\t\t\t\t\t--><!-- \n\t\t\t\t\t\t\t\t\t\t\t--><!--\n\t\t\t\t\t\t\t\t\t\t --></div>\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t<div class=\"col-md-8\">\n\t\t\t\t\t\t\t\t\t<button type=\"submit\" class=\"btn-save-edit btn btn-primary btn-lg center-block\" data-dismiss=\"modal\" style=\"width: 200px; margin-top: 25px; \n\t\t\t\t\t\t\t\t\t\t\t margin-right: 45px; float: right;\">Save Editing</button>\n\t\t\t\t\t\t\t\t</div>\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<div class=\"col-md-4\">\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<!-- <div class=\"modal-footer\">\n\t\t\t\t\t\t\t\t<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n\t\t\t\t\t\t\t</div> -->\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n</div>\n<script>\n\tfunction chonDLgoc (){\n\t\tdocument.getElementById(\"dlcs1\").checked = false;\n\t\tdocument.getElementById(\"data-exsit\").disabled = false;\n\t\tdocument.getElementById(\"urlnn1\").disabled = true;\n\t\tdocument.getElementById(\"urlnn2\").disabled = true;\n\t}\n\tfunction chonDLkhac (){\n\t\tdocument.getElementById(\"dlcs\").checked = false;\n\t\tdocument.getElementById(\"data-exsit\").disabled = true;\n\t\tdocument.getElementById(\"urlnn1\").disabled = false;\n\t\tdocument.getElementById(\"urlnn2\").disabled = false;\n\t}\n\tdocument.getElementById(\"extract-vb\").onclick = function(){\n\t\tdocument.getElementById(\"modal_ghvb\").style.display = \"block\";\n\t\tdocument.getElementById(\"modal_cau\").style.display = \"none\";\n\t\t\n\t}\n\tdocument.getElementById(\"extract-cau\").onclick = function(){\n\t\tdocument.getElementById(\"modal_ghvb\").style.display = \"none\";\n\t\tdocument.getElementById(\"modal_cau\").style.display = \"block\";\n\t\t\n\t}\n\t/*\n\tdocument.getElementById(\"btncheck\").onclick = function(){\n\n\t\tvar checkboxes = document.getElementsByName('name[]');\n\t\tif (document.getElementById(\"btncheck\").checked == false) \n\t\t{\n\t\t\tfor (var i = 0; i < checkboxes.length; i++){\n checkboxes[i].checked = false;\n }\n\t\t}\n\t\telse if(document.getElementById(\"btncheck\").checked == true)\n\t\t{\n\t\t\tfor (var i = 0; i < checkboxes.length; i++){\n checkboxes[i].checked = true;\n }\n\t\t}\n\t}\n\tdocument.getElementById(\"btncheck_vb\").onclick = function(){\n\n\t\tvar checkboxes = document.getElementsByName('name2');\n\t\tif (document.getElementById(\"btncheck_vb\").checked == false) \n\t\t{\n\t\t\tfor (var i = 0; i < checkboxes.length; i++){\n checkboxes[i].checked = false;\n }\n\t\t}\n\t\telse if(document.getElementById(\"btncheck_vb\").checked == true)\n\t\t{\n\t\t\tfor (var i = 0; i < checkboxes.length; i++){\n checkboxes[i].checked = true;\n }\n\t\t}\n\t}\n\t function popupOpen() {\n\t\n\tdocument.getElementById(\"popup\").style.display = \"block\";\n\t\t\n\tdocument.getElementById(\"overlay\").style.display = \"block\";\n\t\t\n\t}\n\t\t\n\t// Popup Close\n\t\t\n\tfunction popupClose() {\n\t\t\n\tdocument.getElementById(\"popup\").style.display = \"none\";\n\t\t\n\tdocument.getElementById(\"overlay\").style.display = \"none\";\n\t\t\n\t}\n\t*/\n\t\n</script>\n</body>\n</html>\n" }, { "alpha_fraction": 0.5522273182868958, "alphanum_fraction": 0.5591397881507874, "avg_line_length": 42.43333435058594, "blob_id": "71b5066165459fabc307e9cd1e8b283ce1d5ad82", "content_id": "b3e0ce7ea2afe3098f50e36b0a4fe992cbcf6ef8", "detected_licenses": [ "MIT", "GPL-3.0-or-later" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1341, "license_type": "permissive", "max_line_length": 131, "num_lines": 30, "path": "/VnCoreNLP/src/test/java/VnCoreNLPExample.java", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "import vn.pipeline.*;\nimport java.io.*;\npublic class VnCoreNLPExample {\n public static void main(String[] args) throws IOException {\n \n // \"wseg\", \"pos\", \"ner\", and \"parse\" refer to as word segmentation, POS tagging, NER and dependency parsing, respectively. \n String[] annotators = {\"wseg\", \"pos\", \"ner\", \"parse\"}; \n VnCoreNLP pipeline = new VnCoreNLP(annotators); \n \n String str = \"Ông Nguyễn Khắc Chúc đang làm việc tại Đại học Quốc gia Hà Nội. \"\n + \"Bà Lan, vợ ông Chúc, cũng làm việc tại đây.\"; \n Annotation annotation = new Annotation(str); \n pipeline.annotate(annotation); \n \n System.out.println(annotation.toString());\n // 1 Ông Nc O 4 sub \n // 2 Nguyễn_Khắc_Chúc Np B-PER 1 nmod\n // 3 đang R O 4 adv\n // 4 làm_việc V O 0 root\n // ...\n \n //Write to file\n PrintStream outputPrinter = new PrintStream(\"output.txt\");\n pipeline.printToFile(annotation, outputPrinter); \n \n // You can also get a single sentence to analyze individually \n Sentence firstSentence = annotation.getSentences().get(0);\n System.out.println(firstSentence.toString());\n }\n}" }, { "alpha_fraction": 0.49796029925346375, "alphanum_fraction": 0.5156377553939819, "avg_line_length": 34.69902801513672, "blob_id": "a744f30ce2e5b7dbdf05bd3e0acb7cfef98a17ed", "content_id": "aaaabbebd842e79e8b3b720624645dca01b6ce48", "detected_licenses": [ "MIT", "GPL-3.0-or-later" ], "is_generated": false, "is_vendor": false, "language": "Maven POM", "length_bytes": 3677, "license_type": "permissive", "max_line_length": 130, "num_lines": 103, "path": "/VnCoreNLP/pom.xml", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>VnCoreNLP</groupId>\n <artifactId>VnCoreNLP</artifactId>\n <version>1.1.1</version>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.3</version>\n <configuration>\n <source>1.8</source>\n <target>1.8</target>\n </configuration>\n </plugin>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-shade-plugin</artifactId>\n <version>3.1.0</version>\n <executions>\n <execution>\n <phase>package</phase>\n <goals>\n <goal>shade</goal>\n </goals>\n <configuration>\n <shadedArtifactAttached>false</shadedArtifactAttached>\n <transformers>\n <!-- add Main-Class to manifest file -->\n <transformer implementation=\"org.apache.maven.plugins.shade.resource.ManifestResourceTransformer\">\n <mainClass>vn.pipeline.VnCoreNLP</mainClass>\n </transformer>\n </transformers>\n </configuration>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n </properties>\n\n <dependencies>\n\n <dependency>\n <groupId>com.optimaize.languagedetector</groupId>\n <artifactId>language-detector</artifactId>\n <version>0.6</version>\n </dependency>\n\n <dependency>\n <groupId>vncorenlp</groupId>\n <artifactId>marmot</artifactId>\n <version>1.0</version>\n </dependency>\n\n <dependency>\n <groupId>edu.emory.mathcs.nlp</groupId>\n <artifactId>nlp4j-api</artifactId>\n <version>1.1.3</version>\n </dependency>\n\n <dependency>\n <groupId>log4j</groupId>\n <artifactId>log4j</artifactId>\n <version>1.2.17</version>\n </dependency>\n\n <dependency>\n <groupId>org.slf4j</groupId>\n <artifactId>slf4j-log4j12</artifactId>\n <version>1.7.5</version>\n </dependency>\n\n <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->\n <dependency>\n <groupId>org.slf4j</groupId>\n <artifactId>slf4j-api</artifactId>\n <version>1.7.25</version>\n </dependency>\n\n <!--mvn install:install-file -Dfile=lib/marmot.jar -DgroupId=vncorenlp -DartifactId=marmot -Dversion=1.0 -Dpackaging=jar-->\n </dependencies>\n <repositories>\n <repository>\n <id>vncorenlp</id>\n <name>vncorenlp thirdparty repo</name>\n <url>https://github.com/vncorenlp/thirdparty/raw/repository/</url>\n <snapshots>\n <enabled>true</enabled>\n <updatePolicy>always</updatePolicy>\n </snapshots>\n </repository>\n </repositories>\n\n</project>\n" }, { "alpha_fraction": 0.39419087767601013, "alphanum_fraction": 0.42323651909828186, "avg_line_length": 39, "blob_id": "20a38876b1fa3f6f68607760f1539c11d3e33690", "content_id": "4f0c823677fa6a954054ecc0eb0225223aa8d17a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 484, "license_type": "permissive", "max_line_length": 87, "num_lines": 12, "path": "/Punctuation.py", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "\ndef getPunctuationForLanguage(language):\n \"\"\"\n :return Punctuation in dictionary follow language\n :key Vietnamese punctuation\n :var Language destination punctuaction\n \"\"\"\n if(language == \"km\"):\n return {\".\": \"\\u17d4\", \"?\": \"\\uff1f\", \"!\": \"\\uff01\", \";\": \";\", \"...\": \"\\u2026\"}\n if(language == \"zh\"):\n return {\".\": \"\\u3002\", \"?\": \"?\", \"!\": \"!\", \";\": \";\", \"...\": \"...\"}\n\n return {\".\": \".\", \"?\": \"?\", \"!\": \"!\", \";\": \";\", \"...\": \"...\"}\n\n" }, { "alpha_fraction": 0.6410648822784424, "alphanum_fraction": 0.6429008841514587, "avg_line_length": 38.85365676879883, "blob_id": "a4780c5f3a55266e146b77efd1a22d83c5b86726", "content_id": "25741966259efc83ed65eebe96e739924c99fd18", "detected_licenses": [ "MIT", "GPL-3.0-or-later" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3268, "license_type": "permissive", "max_line_length": 99, "num_lines": 82, "path": "/VnCoreNLP/src/main/java/vn/pipeline/LexicalInitializer.java", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "package vn.pipeline;\n\nimport edu.emory.mathcs.nlp.component.template.lexicon.GlobalLexica;\n\nimport org.apache.log4j.Logger;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.logging.Handler;\nimport java.util.logging.Level;\n\npublic class LexicalInitializer {\n private static LexicalInitializer lexicalInitializer;\n private HashMap<String, String> lexicalMap ;\n private boolean initLexica = false;\n private GlobalLexica globalLexica;\n\n public final static Logger LOGGER = Logger.getLogger(LexicalInitializer.class);\n\n public LexicalInitializer(boolean initLexica) throws IOException {\n\n this.initLexica = initLexica;\n this.lexicalMap = new HashMap<>();\n \n String lexicalPath = System.getProperty(\"user.dir\") + \"/models/ner/vi-500brownclusters.xz\";\n if (!new File(lexicalPath).exists())\n throw new IOException(\"LexicalInitializer: \" + lexicalPath + \" is not found!\");\n lexicalMap.put(\"word_clusters\", lexicalPath);\n \n lexicalPath = System.getProperty(\"user.dir\") + \"/models/ner/vi-pretrainedembeddings.xz\";\n if (!new File(lexicalPath).exists())\n throw new IOException(\"LexicalInitializer: \" + lexicalPath + \" is not found!\");\n lexicalMap.put(\"word_embeddings\", lexicalPath);\n }\n\n public static LexicalInitializer initialize(boolean initLexica) throws IOException {\n if (lexicalInitializer == null) {\n lexicalInitializer = new LexicalInitializer(initLexica);\n lexicalInitializer.initializeLexica();\n }\n return lexicalInitializer;\n }\n\n public GlobalLexica initializeLexica() {\n if (globalLexica == null && initLexica)\n try {\n\n DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();\n DocumentBuilder docBuilder = dbfac.newDocumentBuilder();\n Document xmlDoc = docBuilder.newDocument();\n Element root = xmlDoc.createElement(\"root\");\n Element lexicals = xmlDoc.createElement(\"lexica\");\n for(String lexicalName : lexicalMap.keySet()) {\n Element lexical = xmlDoc.createElement(lexicalName);\n lexical.setAttribute(\"field\", \"word_form_lowercase\");\n if(!new File(lexicalMap.get(lexicalName)).exists()) return null;\n lexical.appendChild(xmlDoc.createTextNode(lexicalMap.get(lexicalName)));\n lexicals.appendChild(lexical);\n }\n root.appendChild(lexicals);\n\n java.util.logging.Logger globalLogger = java.util.logging.Logger.getLogger(\"\");\n globalLogger.setLevel(Level.OFF);\n Handler[] handlers = globalLogger.getHandlers();\n for(Handler handler : handlers) {\n globalLogger.removeHandler(handler);\n }\n\n globalLexica = new GlobalLexica<>(root);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return globalLexica;\n }\n\n\n}\n" }, { "alpha_fraction": 0.5262048244476318, "alphanum_fraction": 0.5298192501068115, "avg_line_length": 28.91891860961914, "blob_id": "abfc0c68238a3fc517d53346846090463eca699a", "content_id": "06d6111808fb3ee551946c830517fc29a49e169d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3336, "license_type": "permissive", "max_line_length": 97, "num_lines": 111, "path": "/SaveFile.py", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "import datetime\nimport os\nimport Utility\nimport AlignmentNews\ndef saveSentences (src_text, tgt_text, file_path, src_lang_, tgt_lang_):\n time = datetime.datetime.now()\n\n if src_text and tgt_text:\n\n if not src_text or not tgt_text:\n print(\"empty file: \" + file_path)\n else:\n f = open(file_path+\"-\" + src_lang_ + \"-\" + tgt_lang_ + \".txt\", \"w\", encoding='utf-8')\n\n # code này để tạm thời\n lim_src = len(src_text)\n lim_tgt = len(tgt_text)\n lim = lim_tgt if lim_tgt >= lim_src else lim_src\n text_src = \"\"\n text_tgt = \"\"\n for index in range(0, lim):\n\n if (index < lim_src):\n text_src = src_text[index]\n\n if (index < lim_tgt):\n text_tgt = tgt_text[index]\n # if tgt_text[index] != \"\" and\n f.write(text_src + \"\\t\" + text_tgt + \"\\n\")\n\n text_src = \"\"\n text_tgt = \"\"\n f.close()\n\ndef saveDocument (src_text, tgt_text, file_path, src_lang_, tgt_lang_):\n\n if src_text and tgt_text:\n f = open(file_path + \".{}.txt\".format(src_lang_), \"w\", encoding='utf-8')\n for line in src_text:\n f.write(line + \"\\n\")\n f.close()\n\n f = open(file_path + \".{}.txt\".format(tgt_lang_), \"w\", encoding='utf-8')\n for line in tgt_text:\n f.write(line + \"\\n\")\n f.close()\n return\n\ndef save_data(src_text, file_path):\n if not src_text:\n print(\"empty file: \")\n else:\n if os.path.isfile(file_path + \".txt\"):\n return\n\n f = open(file_path + \".txt\", \"w\", encoding='utf-8')\n\n # code này để tạm thời\n lim_src = len(src_text)\n\n f.write(src_text + \"\\n\")\n\n f.close()\n\n return\n\ndef saveJsonFile(file_path, link_dict):\n f = open(file_path, \"w\", encoding=\"utf-8\")\n f.write(Utility.objectToJson(link_dict))\n f.close()\n\ndef saveTranslatedTitle(crawl_folder,src_lang, tgt_lang, list_tgt_title, translated = False):\n list_translate = AlignmentNews.translate(src_lang, tgt_lang, list_tgt_title)\n\n if not translated:\n f = open(crawl_folder + \"/link/title.txt\", \"w\", encoding=\"utf-8\")\n for x, y in zip(list_translate, list_tgt_title):\n f.write(Utility.objectToJson({\"vi\": x, tgt_lang: y}))\n f.write(\"\\n\")\n f.close()\n return\n\n f = open(crawl_folder + \"/link/title.txt\", \"a\", encoding=\"utf-8\")\n for x, y in zip(list_translate, list_tgt_title):\n f.write(Utility.objectToJson({\"vi\": x, tgt_lang: y}))\n f.write(\"\\n\")\n f.close()\n\ndef openTranslatedTitle(crawl_folder, tgt_link):\n list_trans = list()\n f = open(crawl_folder + \"/link/title.txt\", \"r\", encoding=\"utf-8\")\n for line in f:\n list_trans.append(Utility.stringJsonToOject(line.strip()))\n f.close()\n\n for link in tgt_link:\n start = 0\n for title in list_trans:\n if (title['lo'] == link['title']):\n link['title'] = title['vi']\n break\n start = start + 1\n del (list_trans[start])\n\ndef loadJsonFile(file_path):\n f = open(file_path, \"r\", encoding=\"utf-8\")\n for line in f:\n src_link = Utility.stringJsonToOject(line)\n f.close()\n\n return src_link" }, { "alpha_fraction": 0.5216637849807739, "alphanum_fraction": 0.5272096991539001, "avg_line_length": 27.564355850219727, "blob_id": "b71a1e160cab12e73e4f51a7a0a72a72cbdfce02", "content_id": "af197ad0d8d7cd75bc6f2beb92f8afca9053b6db", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2889, "license_type": "permissive", "max_line_length": 113, "num_lines": 101, "path": "/AlignmentNews.py", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "import os\nimport pdb\nimport re\nimport time\nimport traceback\nimport urllib\nfrom datetime import datetime\n\nfrom multipledispatch import dispatch\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport SentenceAlign\nimport ChromeDriver\n\nimport Utility\n\n\n@dispatch(str, str, list)\ndef translate(src_lang, tgt_lang, list_text):\n list_transed_text = list()\n # sl la nguon ngu nguon\n # tl la nguon ngu dich\n\n count = 1\n search_text = \"\"\n sign = \";\"\n # f = open(\"link.test.txt\", \"w\", encoding=\"utf-8\")\n loop = 0\n\n driver = ChromeDriver.getChromeDriver()\n print(len(list_text))\n try:\n for text in list_text:\n rawtext = text\n text = text.replace(\"?\", \"\").replace(\".\", \"?\").replace(\".\", \"\")\n print(loop)\n while (True):\n\n text = text.replace(\"?\", \"\").replace(\".\", \"?\").replace(\".\", \"\")\n #\n # pdb.set_trace()\n search_text = urllib.parse.quote_plus(text)\n\n # search_text = urllib.parse.quote_plus(search_text)\n url = \"https://translate.google.com/?sl={}&tl={}&text={}&op=translate\".format(tgt_lang, src_lang,\n search_text)\n driver.get(url)\n\n content_translate_text = WebDriverWait(driver, 5).until(\n lambda driver: driver.find_element_by_class_name('J0lOec'))\n\n list_ = content_translate_text.text.replace(\"\\n\", \"\")\n if (tgt_lang != \"zh-CN\"):\n list_transed_text.append({src_lang: list_, tgt_lang: rawtext})\n else:\n list_transed_text.append({src_lang: list_, \"zh\": rawtext})\n break\n print(list_)\n time.sleep(1)\n loop = loop + 1\n except Exception as e:\n print(e)\n time.sleep(3)\n pass\n # f.close()\n\n return list_transed_text\n\n\nimport requests\n\n\ndef vizhApi(src_source, tgt_source):\n url = \"http://nmtuet.ddns.net:9977/sentences_align\"\n\n payload = Utility.objectToJson({\"type\": \"vi-lo\",\n \"source\": src_source,\n \"target\": tgt_source})\n\n headers = {\n 'Content-Type': 'application/json'\n }\n\n response = requests.request(\"POST\", url, headers=headers, data=payload)\n\n print(response.text)\n\n\ndef viloApi(src_source, tgt_source):\n url = \"http://nmtuet.ddns.net:9988/scores/sentences\"\n\n payload = Utility.objectToJson({\"type\": \"vi-lo\",\n \"source\": src_source,\n \"target\": tgt_source})\n\n headers = {\n 'Content-Type': 'application/json'\n }\n\n response = requests.request(\"POST\", url, headers=headers, data=payload)\n\n print(response.text)\n" }, { "alpha_fraction": 0.5110175609588623, "alphanum_fraction": 0.5201782584190369, "avg_line_length": 25.74834442138672, "blob_id": "a4a636169ace7a7e48fc07f195807cad34e6f6f6", "content_id": "aa7e55748eed68380b256c7faaf73e7182acdf2b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4211, "license_type": "permissive", "max_line_length": 132, "num_lines": 151, "path": "/SeparateDocumentToSentences.py", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "import pdb\nimport re\n\nimport Utility\nimport Punctuation\n\ndef slpit_text_by_sign(text, sign):\n list_text = text.split(sign);\n if (len(list_text) == 1):\n return None\n\n return list_text\n\n\ndef add_sign_to_text(text, sign):\n text += sign\n return text\n\ndef slipt_with_sign(text, sign):\n\n text = text.strip()\n\n last_index = 0\n length = len(text)\n list_text = \"\"\n next_index = 0\n index = 0\n pre_index = 0\n\n for index in range(length):\n if ((index + 1) < length):\n next_index = index + 1\n pre_index = index - 1\n if text[index] == sign:\n\n # print( \"position {} is digit {} is letters {}\".format(index , text[next_index].isdigit(), text[next_index].isalpha()))\n #pdb.set_trace()\n if (text[next_index] != sign):\n\n if (text[last_index: index] != \"\" and text[last_index: index] != \" \"):\n if( re.search(r'[\\u0e80-\\u0eff]', text[pre_index]) or\n (text[pre_index].isalpha() and text[pre_index].islower()) or\n re.search(r'[\\u4e00-\\u9fff]', text[pre_index],re.UNICODE) ):\n\n add_text = text[last_index: index]\n add_text = re.sub(\"^[\\s]+\", \"\", add_text)\n #pdb.set_trace()\n\n if not text[next_index].isdigit() and not text[next_index].isalpha():\n\n list_text = list_text + add_text + text[index] +\"\\n\"\n last_index = next_index\n continue\n\n if (re.search(r'[\\u4e00-\\u9fff]', text[next_index])):\n\n list_text = list_text + add_text + text[index]\n last_index = next_index\n index = next_index\n\n if (last_index != index):\n list_text = list_text + text[last_index: index + 1]\n return list_text\n\ndef add_sign_to_list(list_text, sign, list_sign):\n if (len(list_text) <= 0):\n return list()\n while (list_text[-1] == ''):\n list_text.pop(len(list_text) - 1)\n\n new_list = list()\n old_text = \"\"\n last_index = 0\n for text in list_text:\n\n if (text == ''):\n old_text = add_sign_to_text(old_text, sign)\n if last_index > 0:\n new_list[last_index - 1] = old_text\n continue\n\n isSign = False\n last_character = text[len(text) - 1]\n\n for end_sign in list_sign:\n\n if (last_character == end_sign):\n isSign = True\n\n if not (isSign):\n old_text = add_sign_to_text(text, sign)\n else:\n old_text = text\n\n old_text = old_text.strip()\n\n new_list.append(old_text)\n\n last_index += 1\n return new_list\n\ndef remake_list_text(raw_text, add_list, sign, list_sign):\n new_list = raw_text[:]\n position = add_list[0]\n list_text = add_list[1]\n\n list_text = add_sign_to_list(list_text, sign, list_sign)\n\n for text in list_text:\n if (text == ''):\n continue\n new_list.insert(position, text)\n position = position + 1\n\n new_list.pop(position)\n\n # print(new_list)\n\n return new_list\n\ndef slpit_text(text, list_sign):\n # print(text)\n\n last_sign_index = len(list_sign) - 1\n\n # print(\"new list\")\n skip = 0\n for sign in list_sign:\n\n if (sign == list_sign[last_sign_index]):\n continue\n index = 0\n\n text = slipt_with_sign(text, sign)\n\n text = Utility.formatDocumentWithComma(text, list_sign[0])\n #pdb.set_trace()\n return text\n\ndef saveTestFile(list_sentence):\n f = open(\"result.txt\", \"w\", encoding=\"utf-8\")\n\n for line in list_sentence:\n f.write(line + \"\\n\")\n f.close()\n\n\nif __name__ == '__main__':\n map_ = Punctuation.getPunctuationForLanguage(\"lo\")\n text = \"ທ່ານນາງ Kamala Harris ຢັ້ງຢືນວ່າ ການພົວພັນຮ່ວມມືຫວຽດນາມ-ອາເມລິກາ ໃນຂົງເຂດເສດຖະກິດ, ຄວາມໝັ້ນຄົງພວມເພີ່ມທະວີ; ee; \"\n print(slpit_text(text, list_sign=list(map_.keys())))\n" }, { "alpha_fraction": 0.4405257999897003, "alphanum_fraction": 0.4453350305557251, "avg_line_length": 33.50184631347656, "blob_id": "90123ad2ee878719259741f1c9f696dd36b11c30", "content_id": "e5abd85a45b868365b7d9832f07ae44fad789d9d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9365, "license_type": "permissive", "max_line_length": 183, "num_lines": 271, "path": "/CanThoPlanOne.py", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\nimport urllib\nimport urllib.request\nimport requests\nimport os\nfrom datetime import datetime\nimport re\nimport pdb\nimport traceback\nimport sys\nimport json\nimport TextToLine as ttl\nfrom multipledispatch import dispatch\n\ndef save_data(src_text, file_path): \n \n if not src_text:\n print(\"empty file: \")\n else:\n if os.path.isfile(file_path +\".txt\"):\n return\n \n f = open(file_path +\".txt\", \"w\", encoding='utf-8') \n \n #code này để tạm thời\n lim_src = len(src_text) \n \n text_src = \"\"\n \n for index in range(0, lim_src):\n \n text_src = src_text[index] \n #if tgt_text[index] != \"\" and \n f.write(text_src+\"\\n\") \n text_src = \"\"\n \n f.close()\n \n return\n\ndef getLink(url):\n list_url = list()\n \n \n try:\n page_index = 1\n \n while( True ):\n print(url.format(page_index))\n #pdb.set_trace()\n response = requests.get(url.format(page_index))\n soup = BeautifulSoup(response.text, \"lxml\")\n \n div_tag = soup.findAll(\"div\", {\"class\":\"boxtinmoi\"})\n \n if not div_tag:\n break\n \n li_tags = div_tag[0].findAll(\"li\")\n \n \n if not li_tags:\n break\n \n for li_tag in li_tags:\n \n href = li_tag.a.attrs['href']\n title = li_tag.a.h3.text\n title = title.replace(\"\\n\",\"\")\n title = title.replace(\"\\t\",\"\")\n title = title.replace(\"\\a\",\"\")\n title = title.replace(\"\\r\",\"\")\n title = title.replace(\"&nbsp\",\"\")\n \n \n response = requests.get(href)\n soup = BeautifulSoup(response.text, \"lxml\")\n \n if( soup.find( \"span\", {\"class\":\"pubdate\"}) ):\n date = soup.find( \"span\", {\"class\":\"pubdate\"}).text\n date = date.split(\"-\")[0].strip()\n date = date.replace(\"\\t\",\"\").replace(\"&nbsp\",\"\")\n list_url.append( (href, date, title) )\n page_index = page_index + 1\n except:\n traceback.print_exc()\n pass \n return list_url\n \ndef getContent(url, title , lang):\n response = requests.get(url)\n soup = BeautifulSoup(response.text, \"lxml\")\n \n list_sentence = list()\n \n list_sentence.append(title)\n \n if(lang == \"vi\"):\n list_sign = list(map_vi2ja_end_sign.keys())\n else: \n list_sign = list(map_vi2ja_end_sign.values())\n \n div_tag = soup.find(\"div\", {\"id\":\"newscontents\"})\n \n list_sentence = list_sentence + ttl.slpit_text(div_tag.text,list_sign)\n \n return list_sentence\n \ndef crawlFormLink(url , title ,file_path, lang):\n\n sentences = getContent(url, title , lang)\n \n file_name = url.split(\"-\")\n file_name = file_name[len(file_name) - 1]\n \n \n \n file_path = file_path + \"{}.{}\".format(file_name, lang)\n print(file_path +\".txt\")\n \n if os.path.isfile(file_path +\".txt\"):\n \n return\n print(file_name)\n \n save_data(sentences, file_path)\n \n \nmap_vi2ja_end_sign = {}\n\nif __name__ == '__main__':\n \n src_lang_ = \"vi\"\n tgt_lang_ = \"km\"\n \n current_dir = os.path.dirname(os.path.realpath(__file__))\n \n with open(current_dir + \"/Sign/sign-default.txt\", 'r',encoding='utf8') as file:\n map_vi2ja_end_sign = json.load(file)\n \n if os.path.exists(current_dir + \"/Sign/sign-\"+tgt_lang_+\".txt\"):\n with open(current_dir + \"/Sign/sign-\"+tgt_lang_+\".txt\", 'r') as file:\n map_vi2ja_end_sign = json.load(file)\n \n TH1_folder = current_dir + \"/Data/crawler_success/CanTho/vi/\"\n TH2_folder = current_dir + \"/Data/crawler_success/CanTho/km/\"\n \n if not os.path.exists(TH1_folder):\n os.makedirs(TH1_folder)\n\n if not os.path.exists(TH2_folder):\n os.makedirs(TH2_folder)\n \n folder_lang = src_lang_+\"-\"+tgt_lang_\n \n crawl_folder = current_dir + \"/CanThoCrawler\"\n \n file_resoucre = crawl_folder+\"/linkauto/\"+folder_lang+\".txt\"\n \n f = None\n \n if os.path.isfile(file_resoucre):\n f = open(file_resoucre,'r', encoding='utf-8')\n \n else:\n folder_lang = tgt_lang_+\"-\"+src_lang_\n file_resoucre = crawl_folder+folder_lang+\".txt\"\n \n if os.path.isfile(file_resoucre):\n f = open(file_resoucre,'r', encoding='utf-8') \n \n \n folder_list = list()\n \n if(f != None):\n \n for line in f: \n folder_list.append(line.replace('\\n','')) \n f.close()\n \n for folder in folder_list:\n \n src_link = list()\n tgt_link = list()\n \n print(folder)\n #kiem tra xem folder co ton tai hay khong\n if not os.path.isfile(crawl_folder+\"/link/{}/{}/link.txt\".format(src_lang_, folder)) or not os.path.isfile(crawl_folder+\"/link/{}/{}/link.txt\".format(tgt_lang_, folder)):\n # Tao thu muc\n \n if not os.path.exists(( crawl_folder+\"/link/{}/{}/\".format(src_lang_, folder ))):\n os.makedirs(crawl_folder+\"/link/{}/{}/\".format(src_lang_, folder) )\n \n if not os.path.exists(( crawl_folder+\"/link/{}/{}/\".format(tgt_lang_, folder ))): \n os.makedirs(crawl_folder+\"/link/{}/{}/\".format(tgt_lang_, folder) )\n \n link_file = open(crawl_folder+\"/linkauto/{}/{}.txt\".format(folder_lang, folder) , \"r\", encoding=\"utf-8\")\n array_link = link_file.readline().replace('\\n','').split(\"\\t\")\n link_file.close()\n \n #Lay link tat ca cac bai viet. Roi dua vao giong hang.\n if not os.path.isfile(crawl_folder+\"/link/{}/{}/link.txt\".format(src_lang_, folder)):\n \n src_link = getLink(array_link[0])\n f = open(crawl_folder+\"/link/{}/{}/link.txt\".format(src_lang_, folder), \"w\", encoding=\"utf-8\" )\n for line in src_link:\n \n f.write( \"{}\\t{}\\t{}\\n\".format(line[0], line[1], line[2]) )\n f.close()\n \n if not os.path.isfile(crawl_folder+\"/link/{}/{}/link.txt\".format(tgt_lang_, folder)):\n \n tgt_link = getLink(array_link[1])\n f = open(crawl_folder+\"/link/{}/{}/link.txt\".format(tgt_lang_, folder), \"w\", encoding=\"utf-8\" )\n for line in tgt_link:\n \n f.write( \"{}\\t{}\\t{}\\n\".format(line[0], line[1], line[2]) )\n f.close() \n else:\n \n f = open(crawl_folder+\"/link/{}/{}/link.txt\".format(src_lang_, folder), \"r\", encoding=\"utf-8\" )\n \n for line in f:\n line = line.replace(\"\\n\",\"\")\n if(line != \"\" and line != \" \"):\n src_link.append(line.split(\"\\t\"))\n f.close()\n \n f = open(crawl_folder+\"/link/{}/{}/link.txt\".format(tgt_lang_, folder), \"r\", encoding=\"utf-8\" )\n \n for line in f:\n line = line.replace(\"\\n\",\"\")\n if(line != \"\" and line != \" \"):\n tgt_link.append(line.split(\"\\t\"))\n f.close()\n \n \n link_file = open(crawl_folder+\"/linkauto/{}/{}.txt\".format(folder_lang, folder) , \"r\", encoding=\"utf-8\")\n array_link = link_file.readline().replace('\\n','').split(\"\\t\")\n link_file.close()\n \n for link in src_link:\n try:\n time = datetime.strptime(link[1] , '%d/%m/%Y')\n time = time.strftime(\"%Y/%m\")\n \n save_folder = \"{}/{}/{}/\".format(TH1_folder, folder, time)\n if not os.path.exists(save_folder):\n os.makedirs(save_folder)\n \n \n crawlFormLink(link[0] , link[2] ,save_folder, \"vi\")\n \n except:\n traceback.print_exc()\n \n for link in tgt_link:\n try:\n time = datetime.strptime(link[1] , '%d/%m/%Y')\n time = time.strftime(\"%Y/%m\")\n \n save_folder = \"{}/{}/{}/\".format(TH2_folder, folder, time)\n if not os.path.exists(save_folder):\n os.makedirs(save_folder)\n \n \n crawlFormLink(link[0] , link[2] ,save_folder, \"km\")\n \n except:\n traceback.print_exc()\n os.system(\"cls\") " }, { "alpha_fraction": 0.5628523826599121, "alphanum_fraction": 0.5653581023216248, "avg_line_length": 40.28879165649414, "blob_id": "99b2719cb75dd826f631b1991ef07f2d377add91", "content_id": "48e6d8fa7ed88cc0ea333ee82e944bab6809d95a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9630, "license_type": "permissive", "max_line_length": 143, "num_lines": 232, "path": "/CrawlWebSite.py", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "import os\nimport pdb\n\nimport AlignmentNews\nimport PageContent\nimport Punctuation\nimport SaveFile\nimport SentenceAlign\nimport requests\nimport datetime\n\nimport Utility\n\n\nclass BaseWebsite:\n\n def __init__(self, name, crawl_folder, accept_language):\n \"\"\"\n :param name: tên của trang wed\n :param crawl_folder: thư mục tải VD:\n :param accept_language: mảng các nguôn ngữ được trong trang web VD: [\"en\", \"ja\", \"km\", \"zh\", \"lo\", \"vi\"]\n \"\"\"\n self.crawlFolder = crawl_folder\n self.accept_language = accept_language\n self.name = name\n\n def crawlWithLanguage(self, language):\n \"\"\"\n :param language: [\"en\", \"ja\", \"km\", \"zh\", \"lo\", \"vi\"]\n :return: None\n \"\"\"\n if language not in self.accept_language:\n raise Exception(\"Resource not supported\")\n\n def checkForLatestNews(self, link=None, list_crawled=None):\n return None\n\n def getNewsContent(self, link, language):\n\n html = requests.get(link).content\n if self.name == \"Vov\":\n return PageContent.getVovNewsContent(html)\n if self.name == \"QDND\":\n return PageContent.getQuanDoiNhanDan(html, language)\n if self.name == \"Vnanet\":\n return PageContent.getVnanetNewsContet(html)\n if self.name == \"VietNamPlus\":\n return PageContent.getVietNamPlusNewsContent(html)\n if self.name == \"VietLao\":\n return PageContent.getVietLaoVietNamNewsContent(html)\n if self.name == \"NhanDan\":\n return PageContent.getNhanDanNewsContent(html, language)\n\n def bilingualNews(self, type, src_link, tgt_link, tgt):\n print(\"sort data\")\n self.sortBy(src_link, type)\n self.sortBy(tgt_link, type)\n\n print(\"find bilingual\")\n if (type == \"date\"):\n return SentenceAlign.AlignByTitleAndDateNews(src_link, tgt_link, tgt=tgt, score_lim=0.1, score=0.8)\n if (type == \"title\"):\n return SentenceAlign.AlignByTitleNews(src_link, tgt_link, tgt=tgt, score_lim=0.1, score=0.8)\n\n def saveDocument(self, src_link, tgt_link, tgt_lang, document_folder):\n file_name = src_link.split(\"/\")\n file_name = file_name[len(file_name) - 1]\n if os.path.isfile(os.path.join(document_folder, file_name+\".{}.txt\".format(\"vi\"))):\n return\n\n src_document = self.getNewsContent(src_link, language=\"vi\")\n tgt_document = self.getNewsContent(tgt_link, language=tgt_lang)\n\n SaveFile.saveDocument(src_text=src_document, tgt_text=tgt_document, file_path=os.path.join(document_folder, file_name), src_lang_=\"vi\",\n tgt_lang_=tgt_lang)\n\n def sortBy(self, lict_dict, type=\"date\"):\n \"\"\"\n Sort list of dictionary by title or time\n :param lict_dict:\n :param type:\n :return: None\n \"\"\"\n if (type == \"date\"):\n lict_dict.sort(key=lambda x: datetime.datetime.strptime(x.get('date'), \"%d/%m/%Y\"),reverse=True)\n if (type == \"title\"):\n lict_dict.sort(key=lambda x: len(x.get('title').strip()),reverse=True)\n lict_dict.reverse()\n\n def auto_crawl_website(self, target_lang, type=\"date\"):\n resource_lang = \"vi\"\n self.crawlWithLanguage(resource_lang)\n self.crawlWithLanguage(target_lang)\n\n current_dir = os.path.dirname(os.path.realpath(__file__))\n map_punctuation = Punctuation.getPunctuationForLanguage(target_lang)\n _case = {\"TH1\": 0, \"TH2\": 1}\n\n sentence_folder = current_dir + \"/Data/crawler_success/{}/Sentence/\".format(self.name)\n document_folder = current_dir + \"/Data/crawler_success/{}/Document/\".format(self.name)\n\n output_dir_success = [sentence_folder, document_folder]\n\n if not os.path.exists(sentence_folder):\n os.makedirs(sentence_folder)\n if not os.path.exists(document_folder):\n os.makedirs(document_folder)\n\n folder_lang = \"{}-{}\".format(resource_lang, target_lang)\n\n crawl_folder = current_dir + \"/{}\".format(self.crawlFolder)\n resource_path = crawl_folder + \"/linkauto/{}.txt\".format(folder_lang)\n resource_file = None\n\n if os.path.isfile(resource_path):\n resource_file = open(resource_path, 'r', encoding='utf-8')\n\n if resource_file == None:\n message_string = \"{} - resource file not exist\".format(resource_path)\n raise Exception(message_string)\n\n list_resource_folder = list()\n for line in resource_file:\n list_resource_folder.append(line.strip())\n resource_file.close()\n\n src_link = list()\n tgt_link = list()\n list_tgt_title = list()\n if os.path.isfile(crawl_folder + \"/link/{}/link.txt\".format(resource_lang)):\n src_link = SaveFile.loadJsonFile(crawl_folder + \"/link/{}/link.txt\".format(resource_lang))\n if os.path.isfile(crawl_folder + \"/link/{}/link.txt\".format(target_lang)):\n tgt_link = SaveFile.loadJsonFile(crawl_folder + \"/link/{}/link.txt\".format(target_lang))\n\n for folder in list_resource_folder:\n print(folder)\n # Kiểm tra xem các file, có file link hay chưa\n array_link = list()\n link_file = open(crawl_folder + \"/linkauto/{}/{}.txt\".format(folder_lang, folder), \"r\",\n encoding=\"utf-8\")\n for line in link_file:\n array_link.append(line.replace('\\n', '').split(\"\\t\"))\n link_file.close()\n\n if not os.path.isfile(\n crawl_folder + \"/link/{}/link.txt\".format(resource_lang)) or not os.path.isfile(\n crawl_folder + \"/link/{}/link.txt\".format(target_lang)):\n # Tao thu muc\n if not os.path.exists((crawl_folder + \"/link/{}/\".format(resource_lang))):\n os.makedirs(crawl_folder + \"/link/{}/\".format(resource_lang))\n if not os.path.exists((crawl_folder + \"/link/{}/\".format(target_lang))):\n os.makedirs(crawl_folder + \"/link/{}/\".format(target_lang))\n \"\"\"\n for line in array_link:\n if line[0] != \"\" and line[0] != \" \":\n src_link = self.checkForLatestNews(line[0], src_link)\n for line in array_link:\n if line[1] != \"\" and line[1] != \" \":\n tgt_link = self.checkForLatestNews(line[1], tgt_link)\n \"\"\"\n\n if src_link:\n SaveFile.saveJsonFile(\n file_path=crawl_folder + \"/link/{}/link.txt\".format(resource_lang),\n link_dict=src_link)\n if tgt_link:\n SaveFile.saveJsonFile(\n file_path=crawl_folder + \"/link/{}/link.txt\".format(target_lang),\n link_dict=tgt_link)\n\n if os.path.isfile(crawl_folder + \"/link/{}/title.txt\".format(target_lang)):\n list_tgt_title = SaveFile.loadJsonFile(crawl_folder + \"/link/{}/title.txt\".format(target_lang))\n\n if not os.path.isfile(crawl_folder + \"/link/{}/title.txt\".format(target_lang)):\n temp = tgt_link.copy()\n for x in temp:\n list_tgt_title.append(x[\"title\"])\n\n if (target_lang == 'zh'):\n list_translate = AlignmentNews.translate(\"vi\", 'zh-CN', list_tgt_title)\n else:\n list_translate = AlignmentNews.translate(\"vi\", target_lang, list_tgt_title)\n\n SaveFile.saveJsonFile(crawl_folder + \"/link/{}/title.txt\".format(target_lang), link_dict=list_translate)\n\n if len(tgt_link) > len(list_tgt_title):\n # Tạo một bản copy\n temp = tgt_link.copy()\n # Tạo vòng lặp xóa các tiêu đề đã dịch\n for title in list_tgt_title:\n start = 0\n lim = len(tgt_link)\n while start < lim:\n try:\n if (temp[start]['title'] == title[target_lang]):\n del (temp[start])\n break\n except:\n pdb.set_trace()\n start = start + 1\n\n list_trans = list()\n # Thêm các tiêu đề vào trong danh sách\n for x in temp:\n list_trans.append(x[\"title\"])\n\n if (target_lang == 'zh'):\n list_tgt_title += AlignmentNews.translate(\"vi\", 'zh-CN', list_trans)\n else:\n list_tgt_title += AlignmentNews.translate(\"vi\", target_lang, list_trans)\n\n SaveFile.saveJsonFile(crawl_folder + \"/link/{}/title.txt\".format(target_lang), link_dict=list_tgt_title)\n #pdb.set_trace()\n for link in tgt_link:\n start = 0\n lim = len(list_tgt_title)\n while (start < lim):\n if link[\"title\"] == list_tgt_title[start][target_lang]:\n link[\"title\"] = list_tgt_title[start][resource_lang]\n del(list_tgt_title[start])\n break\n\n pair_link = self.bilingualNews(type, src_link=src_link, tgt_link=tgt_link, tgt=target_lang)\n\n\n if not os.path.exists(crawl_folder + \"/link/{}-{}\".format(resource_lang, target_lang)):\n os.makedirs(crawl_folder + \"/link/{}-{}\".format(resource_lang, target_lang))\n\n SaveFile.saveJsonFile(crawl_folder + \"/link/{}-{}/link.txt\".format(resource_lang, target_lang), pair_link)\n pdb.set_trace()\n for link in pair_link:\n self.saveDocument( link[resource_lang], link[target_lang], target_lang, document_folder)" }, { "alpha_fraction": 0.7153920531272888, "alphanum_fraction": 0.718296229839325, "avg_line_length": 37.25925827026367, "blob_id": "a2b015c36996ff6bd8ecd7dfbbb1eccab967ca52", "content_id": "641bb112f6b6fa3803891766584876afd15cb382", "detected_licenses": [ "MIT", "GPL-3.0-or-later" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1033, "license_type": "permissive", "max_line_length": 91, "num_lines": 27, "path": "/VnCoreNLP/src/main/java/vn/pipeline/Utils.java", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "package vn.pipeline;\n\nimport com.optimaize.langdetect.DetectedLanguage;\nimport com.optimaize.langdetect.LanguageDetector;\nimport com.optimaize.langdetect.LanguageDetectorBuilder;\nimport com.optimaize.langdetect.ngram.NgramExtractors;\nimport com.optimaize.langdetect.profiles.LanguageProfileReader;\n\nimport java.io.IOException;\nimport java.util.List;\n\npublic class Utils {\n private static LanguageDetector languageDetector = null;\n public static String detectLanguage(String text) throws IOException{\n if(languageDetector == null) {\n languageDetector = LanguageDetectorBuilder.create(NgramExtractors.standard())\n .shortTextAlgorithm(0)\n .withProfiles(new LanguageProfileReader().readAllBuiltIn())\n .build();\n }\n List<DetectedLanguage> detectedLanguages = languageDetector.getProbabilities(text);\n if(detectedLanguages.size() > 0)\n return detectedLanguages.get(0).getLocale().getLanguage();\n return \"N/A\";\n }\n\n}\n" }, { "alpha_fraction": 0.6238381862640381, "alphanum_fraction": 0.6295790076255798, "avg_line_length": 31.66964340209961, "blob_id": "d7d0b238f2e29b41794c2adbb20036b0b31dd542", "content_id": "6b22ac52adf473a0ba2617cffbfc5a0dcdfa9b28", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3714, "license_type": "permissive", "max_line_length": 109, "num_lines": 112, "path": "/PageContent.py", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\nimport Utility\nimport requests\nimport pdb\n\ndef getTextFromTagsWithClass(html, tag, class_):\n soup = BeautifulSoup(html, \"lxml\")\n text = \"\"\n\n for tag_text in soup.findAll(tag, class_=class_):\n\n tagText = Utility.formatString(tag_text.text)\n tagText = tagText.replace(\"\\n+\", \" \")\n tagText = tagText.replace(\"/.\", \"\")\n tagText = tagText.strip()\n # ký tự lạ xuất hiện tại một số bài báo\n\n if tagText and not tagText == \"\":\n text += tagText\n\n text = bytes(text, \"utf-8\").decode('utf-8', 'ignore')\n return text\n\ndef getTextFromTagsWithId(html, tag, id_):\n soup = BeautifulSoup(html, \"lxml\")\n text = \"\"\n\n for tag_text in soup.findAll(tag, {\"id\":id_} ):\n #\n tagText = Utility.formatString(tag_text.text)\n tagText = tagText.replace(\"\\n+\", \" \")\n tagText = tagText.replace(\"/.\", \"\")\n tagText = tagText.strip()\n # ký tự lạ xuất hiện tại một số bài báo\n\n if tagText and not tagText == \"\":\n text += tagText\n\n text = bytes(text, \"utf-8\").decode('utf-8', 'ignore')\n return text\n\ndef getTextFromTags(html, tag):\n soup = BeautifulSoup(html, \"lxml\")\n text = \"\"\n\n for j in soup.findAll(tag):\n\n text_in_timestamp = Utility.formatString(j.text)\n text_in_timestamp = text_in_timestamp.replace(\"/.\", \"\")\n text_in_timestamp = text_in_timestamp.strip()\n if text_in_timestamp:\n text += text_in_timestamp\n\n text = bytes(text, \"utf-8\").decode('utf-8', 'ignore')\n return text\n\n# từ đây là các hàm để lấy dự liệu các trang web theo từ tên miền\ndef getVovNewsContent(html):\n \"\"\"\n :param html: VOV HTML content\n :return:\n \"\"\"\n return getTextFromTagsWithClass(html, \"article\", \"article\")\n\ndef getVnanetNewsContet(html):\n return getTextFromTagsWithClass(html, \"div\", \"detail\")\n\ndef getCanThoNewsContent(html):\n return getTextFromTagsWithId(html, tag=\"div\", id_=\"newscontents\")\n\ndef getVietLaoVietNamNewsContent(html):\n return getTextFromTagsWithClass(html, tag=\"div\", class_=\"post\")\n\ndef getVietNamPlusNewsContent(html):\n return getTextFromTagsWithClass(html, \"div\", \"article-body\")\n\ndef getTNUNewsContent(html, lang = \"vi\"):\n content = \"\"\n if (lang == \"zh\" or lang == \"en\"):\n content = getTextFromTagsWithId(html, tag=\"div\", id=\"wrapper\")\n return content\n\n return getTextFromTagsWithId(html, tag=\"div\", id=\"container\")\n\ndef getQuanDoiNhanDan(html, lang = \"vi\"):\n if lang == \"vi\":\n return getTextFromTagsWithId(html = html, tag =\"div\", id_=\"dnn_VIEWSINDEX_ctl00_viewhinone\")\n if lang == \"en\":\n return getTextFromTagsWithClass(html, tag=\"div\", class_=\"NewsNexttop\")\n if lang == \"zh\":\n text = getTextFromTagsWithClass(html, tag=\"div\", class_=\"detail-post hnoneview\")\n if (text != \" \" or text != \"\"):\n return text\n\n return getTextFromTagsWithClass(html, tag=\"div\", class_=\"col-sm-8\")\n\n if lang == \"km\":\n text = getTextFromTagsWithClass(html, tag=\"div\", class_=\"detail-post hnoneview\")\n if(text != \" \" or text != \"\"):\n return text\n return getTextFromTagsWithClass(html, tag=\"div\", class_=\"bgqdnd\")\n\n if lang == \"lo\":\n return getTextFromTagsWithId(html=html, tag=\"div\", id_=\"dnn_NewsView_Main_ctl00_viewhinone\")\n\ndef getNhanDanNewsContent(html, lang = \"vi\"):\n if lang != \"vi\":\n return getTextFromTagsWithClass(html, \"div\", \"col-sm-8\")\n\n return getTextFromTagsWithClass(html, \"div\", \"detail-page\")\n\n#print(getQuanDoiNhanDan(requests.get(\"https://kh.qdnd.vn/preview/pid/27/newid/513765\").content, lang= \"km\"))" }, { "alpha_fraction": 0.7102425694465637, "alphanum_fraction": 0.7102425694465637, "avg_line_length": 42.67647171020508, "blob_id": "104eaa895f5efd17f5fb47aa770d34ce987a226b", "content_id": "5e5212c377306b2738d0ebec7d5c4e4a7bd6387c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1570, "license_type": "permissive", "max_line_length": 98, "num_lines": 34, "path": "/ChromeDriver.py", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "import pdb\nimport os\nfrom selenium import webdriver\n\"\"\"\nhàm này dùng để tránh bị websites phát hiện là công cụ chạy test tự động\n\"\"\"\ndef getChromeDriver():\n options = webdriver.ChromeOptions()\n\n \n options.add_experimental_option(\"excludeSwitches\", [\"enable-automation\"])\n options.add_experimental_option('useAutomationExtension', False)\n # đặt ngôn ngữ việt công cụ\n options.add_argument(\"--lang=vi\")\n # tạo nơi lưu trữ thông tin user-cookie\n #options.add_argument(\"user-data-dir=C:\\\\User\\\\Admin\\\\AppData\\\\Google\\\\Chrome\\\\User Data\\\\\")\n # loại bỏ các bảo vệ của chrome, và thông báo software auto ....\n options.add_argument(\"--disable-extensions\");\n options.add_argument(\"--disable-security\");\n options.add_argument(\"--no-sandbox\");\n options.add_argument(\"--disable-dev-shm-usage\")\n options.add_argument(\"--allow-running-insecure-content\");\n # đặt định dạng tiếng việt\n options.add_argument(\"accept-language=vi\")\n # tránh nhận dạnh của các trang web là trình duyệt tự động.\n options.add_argument('--disable-blink-features=AutomationControlled')\n #options.add_experimental_option(\"excludeSwitches\", [\"enable-automation\"])\n options.add_experimental_option('useAutomationExtension', False)\n\n \n driver = webdriver.Chrome(os.path.abspath(os.getcwd()+\"/chromedriver\"),options= options)\n driver.execute_script(\"Object.defineProperty(navigator, 'webdriver', {get: () => undefined})\")\n #pdb.set_trace()\n return driver" }, { "alpha_fraction": 0.6119617223739624, "alphanum_fraction": 0.6133971214294434, "avg_line_length": 35.68421173095703, "blob_id": "544b9b9b78e1d51d24cbc915d00b5063676fbad8", "content_id": "794a3bd38580f98d41f6e8e373fca2465a718bab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2090, "license_type": "permissive", "max_line_length": 102, "num_lines": 57, "path": "/TNUCrawler.py", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "import Punctuation\nimport os\nimport ConvertHtmlToText\nimport datetime\nimport SeparateDocumentToSentences\n\ndef extractContentNews(src_link, language):\n content = \"\"\n if (language == \"zh\" or language == \"en\"):\n content = ConvertHtmlToText.getTextFromTagsWithId(src_link= src_link,tag= \"div\",id= \"wrapper\")\n return content\n\n return ConvertHtmlToText.getTextFromTagsWithId(src_link = src_link, tag= \"div\", id=\"container\")\ndef crawlWithLanguage(language):\n \"\"\"\n :param language: \"en\", \"zh\"\n :return: None\n \"\"\"\n if(language != \"en\" and language != 'zh'):\n raise Exception(\"Resource not supported\")\n\n current_dir = os.path.dirname(os.path.realpath(__file__))\n map_Punctuation = Punctuation.getPunctuationForLanguage(language)\n\n resource_file = \"{}/TNUCrawler/{}-{}.txt\".format(current_dir,\"vi\",language)\n\n Document_folder = current_dir + \"/Data/crawler_success/TNU/Document/\"\n if not os.path.exists(Document_folder):\n os.makedirs(Document_folder)\n\n f = open(resource_file, \"r\",encoding=\"utf-8\")\n\n if not f:\n raise Exception(\"Resource file not exist\")\n\n for line in f:\n src_link, tgt_link, mutil_page = (line.split(\"\\t\"))\n file_name = datetime.datetime.now().timestamp()\n\n list_src = SeparateDocumentToSentences.slpit_text( text = extractContentNews(src_link, \"vi\")\n ,list_sign= list(map_Punctuation.keys()) )\n\n file = open(Document_folder+\"{}.vi.txt\".format(file_name), \"w\", encoding=\"utf-8\")\n for line in list_src:\n file.write(\"{} \\n\".format(line))\n file.close()\n\n list_tgt = SeparateDocumentToSentences.slpit_text( text= extractContentNews(tgt_link, \"zh\")\n , list_sign=list(map_Punctuation.keys()))\n file = open(Document_folder + \"{}.{}.txt\".format(file_name, language), \"w\", encoding=\"utf-8\")\n for line in list_tgt:\n file.write(\"{} \\n\".format(line))\n file.close()\n\n f.close()\n\ncrawlWithLanguage(\"zh\")" }, { "alpha_fraction": 0.7022669911384583, "alphanum_fraction": 0.7123425602912903, "avg_line_length": 28.62686538696289, "blob_id": "e32fb2d63571bc8934be763d8eb7ea9ee23f3ce2", "content_id": "6d131b6459c6191004bf32e8a84969c83a56943d", "detected_licenses": [ "MIT", "GPL-3.0-or-later" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1985, "license_type": "permissive", "max_line_length": 629, "num_lines": 67, "path": "/VnCoreNLP/TagsetDescription.md", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "## POS tags, NER types and dependency labels in VnCoreNLP\n\nThe following sections are to briefly describe [POS tags](https://github.com/vncorenlp/VnCoreNLP/blob/master/VLSP2013_POS_tagset.pdf), [NER types](http://vlsp.org.vn/vlsp2016/eval/ner) and [dependency labels](https://github.com/vncorenlp/VnCoreNLP/blob/master/VnDT-treebank-description.pdf) used in VnCoreNLP. See details in [Link-to-POS-tag-description](https://github.com/vncorenlp/VnCoreNLP/blob/master/VLSP2013_POS_tagset.pdf), [Link-to-NER-type-description](http://vlsp.org.vn/vlsp2016/eval/ner) and [Link-to-dependency-label-description](https://github.com/vncorenlp/VnCoreNLP/blob/master/VnDT-treebank-description.pdf). \n\n### POS tags\n\n|Label| Meaning |\n|---|---|\n| Np | Proper noun |\n| Nc | Classifier noun | \n| Nu | Unit noun | \n| N | Noun | \n| Ny | Abbreviated noun | \n| Nb | (Foreign) borrowed noun|\n| V | Verb| \n|Vb |(Foreign) borrowed verb|\n|A| Adjective|\n|P| Pronoun|\n|R |Adverb|\n|L| Determiner|\n|M |Numeral/Quantity|\n|E |Preposition|\n|C |Subordinating conjunction|\n|Cc |Coordinating conjunction|\n|I |Interjection/Exclamation|\n|T |Particle/Auxiliary, modal words|\n|Y |Abbreviation|\n|Z |Bound morpheme|\n|X |Un-definition/Other|\n|CH |Punctuation and symbols|\n\n### NER types\n\n|Label| Meaning |\n|---|---|\n| PER | Names of persons |\n| LOC | Names of locations | \n| ORG| Names of organizations| \n| MISC|Names of miscellaneous entities|\n\n### Top 21 most frequent dependency labels\n\nThese following labels has an appearance rate of at least 0.2%:\n\n|Label| Meaning |\n|---|---|\n|adv|Adverbial | \n|amod| Adjective modifier |\n|conj| Conjunction |\n|coord| Coordination |\n|dep| Default label |\n|det| Determiner |\n|dir| Direction |\n|dob| Direct object |\n|iob| Indirect object |\n|loc| Location |\n|mnr| Manner |\n|nmod| Noun modifier |\n|pmod| Prepositional modifier |\n|pob| Object of a preposition |\n|prd| Predicate |\n|prp| Purpose |\n|punct| Punctuation |\n|root| Root |\n|sub| Subject |\n|tmp|Temporal|\n|vmod| Verb modifier |\n" }, { "alpha_fraction": 0.623902440071106, "alphanum_fraction": 0.6268292665481567, "avg_line_length": 31.539682388305664, "blob_id": "fb568d82a5508dcb234a5c4fe671cf8ce6af89aa", "content_id": "f0cafa6b54df604de7fb33d7e0cdc0f0c52f4c8a", "detected_licenses": [ "MIT", "GPL-3.0-or-later" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2050, "license_type": "permissive", "max_line_length": 140, "num_lines": 63, "path": "/VnCoreNLP/src/main/java/vn/corenlp/postagger/PosTagger.java", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "package vn.corenlp.postagger;\n\nimport marmot.morph.MorphTagger;\nimport marmot.morph.Sentence;\nimport marmot.morph.Word;\n\nimport marmot.util.FileUtils;\nimport org.apache.log4j.Logger;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class PosTagger {\n private static PosTagger posTagger = null;\n private MorphTagger tagger;\n public final static Logger LOGGER = Logger.getLogger(PosTagger.class);\n public PosTagger() throws IOException {\n LOGGER.info(\"Loading POS Tagging model\");\n String modelPath = System.getProperty(\"user.dir\") + \"/models/postagger/vi-tagger\";\n if (!new File(modelPath).exists()) throw new IOException(\"PosTagger: \" + modelPath + \" is not found!\");\n tagger = FileUtils.loadFromFile(modelPath);\n\n }\n\n public static PosTagger initialize() throws IOException {\n if(posTagger == null) {\n posTagger = new PosTagger();\n }\n return posTagger;\n }\n\n public List<vn.pipeline.Word> tagSentence(String sentence) throws IOException {\n List<vn.pipeline.Word> output = new ArrayList<>();\n String line = sentence.trim();\n if (line.length() == 0) {\n return output;\n }\n String[] tokenstrs = line.split(\" \");\n LinkedList tokens = new LinkedList();\n\n for(int i = 0; i < tokenstrs.length; ++i) {\n if (!tokenstrs[i].isEmpty()) {\n Word word = new Word(tokenstrs[i]);\n tokens.add(word);\n }\n }\n\n Sentence marmotSentence = new Sentence(tokens);\n Object lemma_tags = tagger.tagWithLemma(marmotSentence);\n for(int i = 0; i < marmotSentence.size(); ++i) {\n List<String> token_lemma_tags = (List)((List)lemma_tags).get(i);\n vn.pipeline.Word word = new vn.pipeline.Word((i + 1), marmotSentence.getWord(i).getWordForm(), (String)token_lemma_tags.get(1));\n output.add(word);\n\n }\n return output;\n }\n\n\n}\n" }, { "alpha_fraction": 0.6053376793861389, "alphanum_fraction": 0.6395795345306396, "avg_line_length": 40.37239456176758, "blob_id": "db6067d2b23ecacf31a5b910efeb95449e2cbaab", "content_id": "e1c39490a529d5684333756f0c2ec10a9bfb6d30", "detected_licenses": [ "GPL-3.0-or-later", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 16060, "license_type": "permissive", "max_line_length": 2014, "num_lines": 384, "path": "/VnCoreNLP/Readme.md", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "#### Table of contents\n1. [Introduction](#introduction)\n2. [Installation](#install)\n2. [Usage for Python users](#python)\n3. [Usage for Java users](#java)\n4. [Experimental results](#exp)\n\n# VnCoreNLP: A Vietnamese natural language processing toolkit <a name=\"introduction\"></a>\n\nVnCoreNLP is an NLP annotation pipeline for Vietnamese, providing rich linguistic annotations through key NLP components of **word segmentation**, **POS tagging**, **named entity recognition** (NER) and **dependency parsing**:\n\n* **ACCURATE** – VnCoreNLP is the most accurate toolkit for Vietnamese NLP, obtaining state-of-the-art results on standard benchmark datasets.\n* **FAST** – VnCoreNLP is fast, so it can be used for dealing with large-scale data.\n* **Easy-To-Use** – Users do not have to install external dependencies. Users can run processing pipelines from either the command-line or the API.\n\n**The general architecture and experimental results of VnCoreNLP can be found in the following related papers:**\n\n1. Thanh Vu, Dat Quoc Nguyen, Dai Quoc Nguyen, Mark Dras and Mark Johnson. **2018**. [VnCoreNLP: A Vietnamese Natural Language Processing Toolkit](http://aclweb.org/anthology/N18-5012). In *Proceedings of the 2018 Conference of the North American Chapter of the Association for Computational Linguistics: Demonstrations*, [NAACL 2018](http://naacl2018.org), pages 56-60. [[.bib]](http://aclweb.org/anthology/N18-5012.bib)\n2. Dat Quoc Nguyen, Dai Quoc Nguyen, Thanh Vu, Mark Dras and Mark Johnson. **2018**. [A Fast and Accurate Vietnamese Word Segmenter](http://www.lrec-conf.org/proceedings/lrec2018/summaries/55.html). In *Proceedings of the 11th International Conference on Language Resources and Evaluation*, [LREC 2018](http://lrec2018.lrec-conf.org/en/), pages 2582-2587. [[.bib]](https://dblp.uni-trier.de/rec/bibtex/conf/lrec/NguyenNVDJ18)\n3. Dat Quoc Nguyen, Thanh Vu, Dai Quoc Nguyen, Mark Dras and Mark Johnson. **2017**. [From Word Segmentation to POS Tagging for Vietnamese](http://aclweb.org/anthology/U17-1013). In *Proceedings of the 15th Annual Workshop of the Australasian Language Technology Association*, [ALTA 2017](http://alta2017.alta.asn.au), pages 108-113. [[.bib]](http://aclweb.org/anthology/U17-1013.bib)\n\nPlease **CITE** paper [1] whenever VnCoreNLP is used to produce published results or incorporated into other software. If you are dealing in depth with either word segmentation or POS tagging, you are also encouraged to cite paper [2] or [3], respectively. \n\nIf you are looking for light-weight versions, VnCoreNLP's word segmentation and POS tagging components have also been released as independent packages [RDRsegmenter](https://github.com/datquocnguyen/RDRsegmenter) [2] and [VnMarMoT](https://github.com/datquocnguyen/VnMarMoT) [3], resepectively.\n\n\n## Installation <a name=\"install\"></a>\n\n- `Python 3.4+` if using a Python wrapper of VnCoreNLP. To install this wrapper, users have to run the following command:\n\n `$ pip3 install vncorenlp` \n \n _A special thanks goes to Khoa Duong ([@dnanhkhoa](https://github.com/dnanhkhoa)) for creating this wrapper!_\n \n- `Java 1.8+` \n- File `VnCoreNLP-1.1.1.jar` (27MB) and folder `models` (115MB) are placed in the same working folder.\n\n\n\n## Usage for Python users <a name=\"python\"></a>\n\n**Assume that the Python wrapper of VnCoreNLP is already installed via: `$ pip3 install vncorenlp`**\n\n### Use as a service\n\n1. Run the following command: \n```\n # To perform word segmentation, POS tagging, NER and then dependency parsing\n $ vncorenlp -Xmx2g <FULL-PATH-to-VnCoreNLP-jar-file> -p 9000 -a \"wseg,pos,ner,parse\"\n \n # To perform word segmentation, POS tagging and then NER\n # $ vncorenlp -Xmx2g <FULL-PATH-to-VnCoreNLP-jar-file> -p 9000 -a \"wseg,pos,ner\"\n # To perform word segmentation and then POS tagging\n # $ vncorenlp -Xmx2g <FULL-PATH-to-VnCoreNLP-jar-file> -p 9000 -a \"wseg,pos\"\n # To perform word segmentation only\n # $ vncorenlp -Xmx500m <FULL-PATH-to-VnCoreNLP-jar-file> -p 9000 -a \"wseg\"\n```\n\n The service is now available at `http://127.0.0.1:9000`.\n\n2. Use the service in your `python` code:\n\n```python\nfrom vncorenlp import VnCoreNLP\nannotator = VnCoreNLP(address=\"http://127.0.0.1\", port=9000) \n\n# Input \ntext = \"Ông Nguyễn Khắc Chúc đang làm việc tại Đại học Quốc gia Hà Nội. Bà Lan, vợ ông Chúc, cũng làm việc tại đây.\"\n\n# To perform word segmentation, POS tagging, NER and then dependency parsing\nannotated_text = annotator.annotate(text) \n\n# To perform word segmentation only\nword_segmented_text = annotator.tokenize(text)\n```\n\n- `print(annotated_text)` # JSON format\n\n```\n{'sentences': [[{'index': 1, 'form': 'Ông', 'posTag': 'Nc', 'nerLabel': 'O', 'head': 4, 'depLabel': 'sub'}, {'index': 2, 'form': 'Nguyễn_Khắc_Chúc', 'posTag': 'Np', 'nerLabel': 'B-PER', 'head': 1, 'depLabel': 'nmod'}, {'index': 3, 'form': 'đang', 'posTag': 'R', 'nerLabel': 'O', 'head': 4, 'depLabel': 'adv'}, {'index': 4, 'form': 'làm_việc', 'posTag': 'V', 'nerLabel': 'O', 'head': 0, 'depLabel': 'root'}, {'index': 5, 'form': 'tại', 'posTag': 'E', 'nerLabel': 'O', 'head': 4, 'depLabel': 'loc'}, {'index': 6, 'form': 'Đại_học', 'posTag': 'N', 'nerLabel': 'B-ORG', 'head': 5, 'depLabel': 'pob'}, {'index': 7, 'form': 'Quốc_gia', 'posTag': 'N', 'nerLabel': 'I-ORG', 'head': 6, 'depLabel': 'nmod'}, {'index': 8, 'form': 'Hà_Nội', 'posTag': 'Np', 'nerLabel': 'I-ORG', 'head': 6, 'depLabel': 'nmod'}, {'index': 9, 'form': '.', 'posTag': 'CH', 'nerLabel': 'O', 'head': 4, 'depLabel': 'punct'}], [{'index': 1, 'form': 'Bà', 'posTag': 'Nc', 'nerLabel': 'O', 'head': 9, 'depLabel': 'sub'}, {'index': 2, 'form': 'Lan', 'posTag': 'Np', 'nerLabel': 'B-PER', 'head': 1, 'depLabel': 'nmod'}, {'index': 3, 'form': ',', 'posTag': 'CH', 'nerLabel': 'O', 'head': 1, 'depLabel': 'punct'}, {'index': 4, 'form': 'vợ', 'posTag': 'N', 'nerLabel': 'O', 'head': 1, 'depLabel': 'nmod'}, {'index': 5, 'form': 'ông', 'posTag': 'Nc', 'nerLabel': 'O', 'head': 4, 'depLabel': 'nmod'}, {'index': 6, 'form': 'Chúc', 'posTag': 'Np', 'nerLabel': 'B-PER', 'head': 5, 'depLabel': 'nmod'}, {'index': 7, 'form': ',', 'posTag': 'CH', 'nerLabel': 'O', 'head': 1, 'depLabel': 'punct'}, {'index': 8, 'form': 'cũng', 'posTag': 'R', 'nerLabel': 'O', 'head': 9, 'depLabel': 'adv'}, {'index': 9, 'form': 'làm_việc', 'posTag': 'V', 'nerLabel': 'O', 'head': 0, 'depLabel': 'root'}, {'index': 10, 'form': 'tại', 'posTag': 'E', 'nerLabel': 'O', 'head': 9, 'depLabel': 'loc'}, {'index': 11, 'form': 'đây', 'posTag': 'P', 'nerLabel': 'O', 'head': 10, 'depLabel': 'pob'}, {'index': 12, 'form': '.', 'posTag': 'CH', 'nerLabel': 'O', 'head': 9, 'depLabel': 'punct'}]]}\n```\n\n- `print(word_segmented_text)`\n\n```\n[['Ông', 'Nguyễn_Khắc_Chúc', 'đang', 'làm_việc', 'tại', 'Đại_học', 'Quốc_gia', 'Hà_Nội', '.'], ['Bà', 'Lan', ',', 'vợ', 'ông', 'Chúc', ',', 'cũng', 'làm_việc', 'tại', 'đây', '.']]\n```\n\n\n\n\n### Use without the service\n\n```python\nfrom vncorenlp import VnCoreNLP\n\n# To perform word segmentation, POS tagging, NER and then dependency parsing\nannotator = VnCoreNLP(\"<FULL-PATH-to-VnCoreNLP-jar-file>\", annotators=\"wseg,pos,ner,parse\", max_heap_size='-Xmx2g') \n\n# To perform word segmentation, POS tagging and then NER\n# annotator = VnCoreNLP(\"<FULL-PATH-to-VnCoreNLP-jar-file>\", annotators=\"wseg,pos,ner\", max_heap_size='-Xmx2g') \n# To perform word segmentation and then POS tagging\n# annotator = VnCoreNLP(\"<FULL-PATH-to-VnCoreNLP-jar-file>\", annotators=\"wseg,pos\", max_heap_size='-Xmx2g') \n# To perform word segmentation only\n# annotator = VnCoreNLP(\"<FULL-PATH-to-VnCoreNLP-jar-file>\", annotators=\"wseg\", max_heap_size='-Xmx500m') \n \n# Input \ntext = \"Ông Nguyễn Khắc Chúc đang làm việc tại Đại học Quốc gia Hà Nội. Bà Lan, vợ ông Chúc, cũng làm việc tại đây.\"\n\n# To perform word segmentation, POS tagging, NER and then dependency parsing\nannotated_text = annotator.annotate(text)\n\n# To perform word segmentation only\nword_segmented_text = annotator.tokenize(text) \n\n```\n\n_For more details, we refer users to [https://github.com/dnanhkhoa/python-vncorenlp](https://github.com/dnanhkhoa/python-vncorenlp)._\n\n\n## Usage for Java users <a name=\"java\"></a>\n\n### Using VnCoreNLP from the command line\n\nYou can run VnCoreNLP to annotate an input raw text corpus (e.g. a collection of news content) by using following commands:\n\n // To perform word segmentation, POS tagging, NER and then dependency parsing\n $ java -Xmx2g -jar VnCoreNLP-1.1.1.jar -fin input.txt -fout output.txt\n // To perform word segmentation, POS tagging and then NER\n $ java -Xmx2g -jar VnCoreNLP-1.1.1.jar -fin input.txt -fout output.txt -annotators wseg,pos,ner\n // To perform word segmentation and then POS tagging\n $ java -Xmx2g -jar VnCoreNLP-1.1.1.jar -fin input.txt -fout output.txt -annotators wseg,pos\n // To perform word segmentation\n $ java -Xmx2g -jar VnCoreNLP-1.1.1.jar -fin input.txt -fout output.txt -annotators wseg \n\n\n### Using VnCoreNLP from the API\n\nThe following code is a simple and complete example:\n\n```java\nimport vn.pipeline.*;\nimport java.io.*;\npublic class VnCoreNLPExample {\n public static void main(String[] args) throws IOException {\n \n // \"wseg\", \"pos\", \"ner\", and \"parse\" refer to as word segmentation, POS tagging, NER and dependency parsing, respectively. \n String[] annotators = {\"wseg\", \"pos\", \"ner\", \"parse\"}; \n VnCoreNLP pipeline = new VnCoreNLP(annotators); \n \n String str = \"Ông Nguyễn Khắc Chúc đang làm việc tại Đại học Quốc gia Hà Nội. Bà Lan, vợ ông Chúc, cũng làm việc tại đây.\"; \n \n Annotation annotation = new Annotation(str); \n pipeline.annotate(annotation); \n \n System.out.println(annotation.toString());\n // 1 Ông Nc O 4 sub \n // 2 Nguyễn_Khắc_Chúc Np B-PER 1 nmod\n // 3 đang R O 4 adv\n // 4 làm_việc V O 0 root\n // ...\n \n //Write to file\n PrintStream outputPrinter = new PrintStream(\"output.txt\");\n pipeline.printToFile(annotation, outputPrinter); \n \n // You can also get a single sentence to analyze individually \n Sentence firstSentence = annotation.getSentences().get(0);\n System.out.println(firstSentence.toString());\n }\n}\n```\n\n<img width=\"1039\" alt=\"vncorenlpexample\" src=\"https://user-images.githubusercontent.com/33695776/37561346-aca1fd68-2aa0-11e8-8bd8-530577b0b5cf.png\">\n\nSee VnCoreNLP's open-source in folder `src` for API details. \n\n## Experimental results <a name=\"exp\"></a>\n\nWe briefly present experimental setups and obtained results in the following subsections. See details in papers [1,2,3] above or at [NLP-progress](http://nlpprogress.com/vietnamese/vietnamese.html).\n\n### Word segmentation \n\n* Training data: 75k manually word-segmented training sentences from the VLSP 2013 word segmentation shared task.\n* Test data: 2120 test sentences from the VLSP 2013 POS tagging shared task.\n\n<table>\n <tr>\n <td><b>Model<b></td>\n <td><b>F1 (%)</td>\n <td><b>Speed</b> (words/second)</td>\n </tr>\n <tr>\n <td>VnCoreNLP (i.e. RDRsegmenter)</td>\n <td><b>97.90</b></td>\n <td><b>62k</b> / _</td>\n </tr>\n <tr>\n <td>UETsegmenter</td>\n <td>97.87</td>\n <td>48k / 33k*</td>\n </tr>\n <tr>\n <td>vnTokenizer</td>\n <td>97.33</td>\n <td> _ / 5k*</td>\n </tr>\n <tr>\n <td>JVnSegmenter-Maxent</td>\n <td>97.00</td>\n <td> _ / 1k*</td>\n </tr>\n <tr>\n <td>JVnSegmenter-CRFs</td>\n <td>97.06</td>\n <td> _ / 1k*</td>\n </tr>\n <tr>\n <td>DongDu</td>\n <td>96.90</td>\n <td> _ / 17k*</td>\n </tr>\n</table>\n\n* Speed is computed on a personal computer of Intel Core i7 2.2 GHz, except when specifically mentioned. \\* denotes that the speed is computed on a personal computer of Intel Core i5 1.80 GHz.\n* See paper [2] for more details.\n\n### POS tagging \n\n* 27,870 sentences for training and development from the VLSP 2013 POS tagging shared task:\n * 27k sentences are used for training.\n * 870 sentences are used for development.\n* Test data: 2120 test sentences from the VLSP 2013 POS tagging shared task.\n\n<table>\n <tr>\n <td><b>Model<b></td>\n <td><b>Accuracy (%)</td>\n <td><b>Speed</td>\n </tr>\n <tr>\n <td>VnCoreNLP (i.e. VnMarMoT)</td>\n <td><b>95.88</b></td>\n <td>25k</td>\n </tr>\n <tr>\n <td>RDRPOSTagger</td>\n <td> 95.11 </td>\n <td> <b> 180k</td>\n </tr>\n <tr>\n <td>BiLSTM-CRF</td>\n <td>95.06</td>\n <td> 3k</td>\n </tr>\n <tr>\n <td>BiLSTM-CRF + CNN-char</td>\n <td>95.40</td>\n <td> 2.5k</td>\n </tr>\n <tr>\n <td>BiLSTM-CRF + LSTM-char</td>\n <td>95.31</td>\n <td> 1.5k</td>\n </tr>\n</table>\n\n* See paper [3] for more details.\n\n### Named entity recognition\n* 16,861 sentences for training and development from the VLSP 2016 NER shared task:\n * 14,861 sentences are used for training.\n * 2k sentences are used for development.\n* Test data: 2,831 test sentences from the VLSP 2016 NER shared task.\n* **NOTE** that in the VLSP 2016 NER data, each word representing a full personal name are separated into syllables that constitute the word. The VLSP 2016 NER data also consists of gold POS and chunking tags as [reconfirmed by VLSP 2016 organizers](https://drive.google.com/file/d/1XzrgPw13N4C_B6yrQy_7qIxl8Bqf7Uqi/view?usp=sharing). This scheme results in an unrealistic scenario for a pipeline evaluation: \n * The standard annotation for Vietnamese word segmentation and POS tagging forms each full name as a word token, thus all word segmenters have been trained to output a full name as a word and all POS taggers have been trained to assign a POS label to the entire full-name.\n * Gold POS and chunking tags are NOT available in a real-world application.\n* For a realistic scenario, contiguous syllables constituting a full name are merged to form a word. Then, POS tags are predicted by using our tagging component. The results are as follows:\n\n<table>\n <tr>\n <td><b>Model<b></td>\n <td><b>F1</td>\n <td><b>Speed</td>\n </tr>\n <tr>\n <td>VnCoreNLP</td>\n <td><b>88.55</td>\n <td><b>18k</td>\n </tr>\n <tr>\n <td>BiLSTM-CRF</td>\n <td>86.48</td>\n <td> 2.8k</td>\n </tr>\n <tr>\n <td>BiLSTM-CRF + CNN-char</td>\n <td>88.28</td>\n <td> 1.8k</td>\n </tr>\n <tr>\n <td>BiLSTM-CRF + LSTM-char</td>\n <td>87.71</td>\n <td> 1.3k</td>\n </tr>\n <tr>\n <td>BiLSTM-CRF + predicted POS</td>\n <td>86.12</td>\n <td> _ </td>\n </tr>\n <tr>\n <td>BiLSTM-CRF + CNN-char + predicted POS </td>\n <td>88.06</td>\n <td> _</td>\n </tr>\n <tr>\n <td>BiLSTM-CRF + LSTM-char + predicted POS</td>\n <td>87.43</td>\n <td> _ </td>\n </tr>\n</table>\n\n* Here, for VnCoreNLP, we include the time POS tagging takes in the speed.\n* See paper [1] for more details.\n\n### Dependency parsing\n\n* The last 1020 sentences of the [benchmark Vietnamese dependency treebank VnDT](http://vndp.sourceforge.net) are used for test, while the remaining 9k+ sentences are used for training & development. LAS and UAS scores are computed on all\ntokens (i.e. including punctuation). \n\n<table>\n <tr>\n <th colspan=\"2\"><b>Model</b></th>\n <th> <b>LAS</b> (%)</th>\n <th><b>UAS</b> (%)</th>\n <th><b>Speed</th>\n </tr>\n <tr>\n <td rowspan=\"5\">Gold POS</td>\n <td>VnCoreNLP</td>\n <td><b>73.39</td>\n <td>79.02</td>\n <td>_</td>\n </tr>\n <tr>\n <td>BIST-bmstparser</td>\n <td>73.17</td>\n <td><b>79.39</td>\n <td>_</td>\n </tr>\n <tr>\n <td>BIST-barchybrid</td>\n <td>72.53</td>\n <td>79.33</td>\n <td>_</td>\n </tr>\n <tr>\n <td>MSTparser</td>\n <td>70.29</td>\n <td>76.47</td>\n <td>_</td>\n </tr>\n <tr>\n <td>MaltParser</td>\n <td>69.10</td>\n <td>74.91</td>\n <td>_</td>\n </tr>\n <tr>\n <td rowspan=\"2\">Predicted POS</td>\n <td>VnCoreNLP</td>\n <td><b>70.23</td>\n <td>76.93</td>\n <td><b>8k</td>\n </tr>\n <tr>\n <td>jPTDP</td>\n <td>69.49</td>\n <td><b>77.68</td>\n <td>700</td>\n </tr>\n</table>\n\n* See paper [1] for more details.\n" }, { "alpha_fraction": 0.5415452122688293, "alphanum_fraction": 0.5516682863235474, "avg_line_length": 28.54067039489746, "blob_id": "23ed578989df2e9e61578ae4fbf1e622b75d3904", "content_id": "1a01d9e93743af42e610668360925514daaf3f8c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12427, "license_type": "permissive", "max_line_length": 125, "num_lines": 418, "path": "/SentenceAlign.py", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "import numpy.linalg\nfrom vncorenlp import VnCoreNLP\nimport pdb\nimport re\nimport numpy as np\nimport math\nimport datetime\nimport random\nimport sys\n\nvector = dict()\nlist_stopwords = list()\n\ndef compareTitle(src_title, tgt_title):\n\n count = 0\n for word in src_title:\n if (word in tgt_title):\n count = count + 1\n\n return (count / len(tgt_title))\n\ndef loadStopWords():\n f = open(\"stopwords.txt\", \"r\", encoding=\"utf-8\")\n for line in f:\n line = line.strip()\n list_stopwords.append(line)\n f.close()\n\ndef removeStopWord(words):\n global list_stopwords\n list_new_word = list()\n\n for word in words:\n if word not in list_stopwords:\n if(word.strip() != \"\"):\n list_new_word.append(word)\n return list_new_word\n\ndef loadVectorEmbbeding(vector):\n f = open(\"dict.txt\", \"r\", encoding=\"utf-8\")\n for line in f:\n line = line.strip()\n\n line = line.split(\" \")\n key = str(line[0])\n\n if('@@' in key):\n continue\n #print(line[1])\n\n if(key.lower() in vector):\n continue\n vector[key.lower()] = int(line[1])\n f.close()\n\ndef cosineSinmilar(src_vector, tgt_vector):\n #pdb.set_trace()\n y = np.sqrt(np.sum(np.square(src_vector))) * np.sqrt(np.sum(np.square(tgt_vector)))\n if y == 0:\n return 0\n x = np.sum(src_vector * tgt_vector)\n if x == 0:\n return 0\n return x / y\n\ndef wordToVector(word):\n\n global vector\n if word in vector:\n return vector[word]\n else:\n return random.randrange(1000, 20000)\n\ndef TF_IDF(src_sentence, tgt_sentence):\n dict_words = {}\n dict_src = {}\n dict_tgt = {}\n TF_IDF_CountWords(dict_words, dict_src, src_sentence)\n\n\n TF_IDF_CountWords(dict_words, dict_tgt, tgt_sentence)\n\n TF_IDF_Document_Point(dict_words, dict_src, dict_tgt)\n TF_IDF_Document_Point(dict_words, dict_tgt, dict_src)\n\n\n\n tf_idf_sorce = cosineSinmilar(TF_IDF_Vector(dict_words, dict_src), TF_IDF_Vector(dict_words, dict_tgt))\n\n if tf_idf_sorce > 0.97:\n return tf_idf_sorce\n\n if len(dict_tgt) > len(dict_src):\n size = len(dict_tgt)\n else:\n size = len(dict_src)\n \"\"\"\n x = DissSimilarVector(dict_src, dict_tgt, size)\n x2 = DissSimilarVector(dict_tgt, dict_src, size)\n \n distance = cosineSinmilar(x, x2)\n print(distance)\n sorce = 0.0\n\n if distance >0.2 and distance < 0.3:\n sorce = 0.025\n\n if distance >0.4 and distance < 0.6:\n sorce = 0.035\n\n if distance >0.6 and distance < 0.8:\n sorce = 0.04\n\n if distance >0.8:\n sorce = 0.045\n \"\"\"\n\n return tf_idf_sorce\n\ndef TF_IDF_CountWords(dict_words, dict_, words):\n\n for word in words:\n if word not in dict_words:\n dict_words[word] = 1\n else:\n dict_words[word] = dict_words[word] + 1\n\n if word not in dict_:\n dict_[word] = 1\n else:\n dict_[word] = dict_[word] + 1\n\ndef TF_IDF_Document_Point(dict_words, dict_src, dict_tgt ):\n\n idf = {}\n for word in dict_src :\n\n number_of_word_in_sentences = dict_src[word]\n number_of_sentences_contains = 1\n\n tf = (number_of_word_in_sentences / dict_words[word])\n\n if word in dict_tgt:\n number_of_sentences_contains = number_of_sentences_contains + 1\n\n #idf = math.log(2/number_of_sentences_contains)\n idf = math.log(2/number_of_sentences_contains,10)\n dict_src[word] = tf * idf\n\ndef TF_IDF_Vector(dict_words, dict_src):\n vector = np.zeros(len(dict_words))\n\n start = 0\n for word in dict_words:\n if word in dict_src:\n if(dict_src[word] == 0):\n vector[start] = 1\n else:\n vector[start] = dict_src[word]\n else:\n vector[start] = -1\n start = start + 1\n return vector\n\ndef DissSimilarVector(dict_src, dict_tgt,size):\n vector = np.ones(size)\n\n start = 0\n # for each word not in dict_tgt\n for word_src in dict_src:\n\n if word_src not in dict_tgt:\n vector[start] = -wordToVector(word_src)\n print(wordToVector(word_src))\n start += 1\n continue\n\n vector[start] = wordToVector(word_src)\n start += 1\n print(vector)\n return vector\n\ndef sentenceToTokenize(sentences):\n global annotator\n flag = False\n\n word_segmented_text = annotator.tokenize(sentences)\n tokenSentence = \"\"\n\n for sentence in word_segmented_text[0]:\n if(sentence !=\"\" or sentence!= \"\" ):\n if(sentence == \"_\"):\n tokenSentence = tokenSentence.strip() + sentence\n flag = True\n continue\n if flag:\n flag = False\n tokenSentence = tokenSentence + sentence\n continue\n tokenSentence = tokenSentence + \" \" + sentence\n\n return tokenSentence.strip()\n\ndef preprocessString(list_dict_src, token=True):\n start = 0\n length = len(list_dict_src)\n\n while (start < length):\n\n sentence = list_dict_src[start]['title']\n\n sentence = sentence.strip()\n sentence = re.sub(\"[!.,@#$%^&*()?<>“]+\", \"\", sentence)\n sentence = re.sub(\"[-]+\", \" \", sentence)\n sentence = re.sub(\"\\s+\", \" \", sentence)\n\n if(token):\n sentence = sentenceToTokenize(sentence)\n sentence = sentence.lower()\n list_dict_src[start]['title'] = sentence\n if (token):\n list_dict_src[start][\"words\"] = removeStopWord(sentence.split(\" \"))\n else:\n list_dict_src[start][\"words\"] = sentence.split(\" \")\n start = start + 1\n\n\"\"\"\nAlign News By Title And Date\n\"\"\"\ndef AlignByTitleAndDateNews(list_dict_src, list_dict_tgt, tgt, date_range=20, score_lim=0.4, score=0.8, token=True):\n \"\"\"\n\n :param list_dict_src: danh sách các dictionary chứa link, date, title ngôn ngữ nguồn\n :param list_dict_tgt: danh sách các dictionary chứa link, date, title ngôn ngữ đích được dịch sang ngôn ngữ nguồn\n :param tgt: ngôn ngữ đích\n :param date_range: giới hạn thời gian\n :param score_lim: ngưỡng thấp nhất có thể lấy\n :param score: ngưỡng bắt đầu\n :param token: có token các\n :return:\n\n \"\"\"\n for link in list_dict_src:\n src_datetime = datetime.datetime.strptime(link['date'], \"%d/%m/%Y\")\n link['date'] = src_datetime\n\n for link in list_dict_tgt:\n tgt_datetime = datetime.datetime.strptime(link['date'], \"%d/%m/%Y\")\n link['date'] = tgt_datetime\n\n preprocessString(list_dict_src, token=token)\n preprocessString(list_dict_tgt, token=token)\n\n lim_src = len(list_dict_src)\n lim_tgt = len(list_dict_tgt)\n\n list_align_title = list()\n print(len(list_dict_src), len(list_dict_tgt))\n while score >= score_lim:\n print(score)\n start_src = 0\n\n checkPoint = 0\n time = - date_range\n while (start_src < lim_src):\n max_ = 0\n start_tgt = checkPoint\n true_tgt = 0\n print(start_tgt)\n\n while (start_tgt < lim_tgt):\n\n delta = list_dict_src[start_src]['date'] - list_dict_tgt[start_tgt]['date']\n # thoi gian vuot qua khoang date_range\n\n if(abs(delta.days) > date_range):\n break\n\n if delta.days < 0 and time > delta.days:\n time = delta.days\n checkPoint = start_tgt\n\n if(token):\n true_sore = TF_IDF(list_dict_src[start_src][\"words\"], list_dict_tgt[start_tgt]['words'])\n else:\n true_sore = compareTitle(list_dict_src[start_src][\"words\"], list_dict_tgt[start_tgt]['words'])\n\n if (max_ < true_sore):\n max_ = true_sore\n true_tgt = start_tgt\n\n if(max_ >= 1.0):\n break\n\n\n start_tgt = start_tgt + 1\n # print(list_dict_src[start_src]['title'], max_)\n if (max_ < score_lim):\n del (list_dict_src[start_src])\n lim_src = len(list_dict_src)\n continue\n\n if max_ > score:\n f = open(\"thongke.csv\", \"a\", encoding=\"utf-8\")\n f.write(\"{} \\t {} \\t {}\\n\".format(list_dict_src[start_src]['title'], list_dict_tgt[true_tgt]['title'], max_))\n f.close()\n list_align_title.append({\"vi\": list_dict_src[start_src]['url'], tgt: list_dict_tgt[true_tgt]['url']})\n\n del (list_dict_src[start_src])\n del (list_dict_tgt[true_tgt])\n\n lim_src = len(list_dict_src)\n lim_tgt = len(list_dict_tgt)\n continue\n\n start_src = start_src + 1\n\n score = score - 0.1\n return list_align_title\n\ndef AlignByTitleNews(list_dict_src, list_dict_tgt , tgt, score_lim=0.35, score=0.75, token = True):\n\n src = \"vi\"\n\n if(len(list_dict_src) > len(list_dict_tgt)):\n temp_list = list_dict_src.copy()\n list_dict_src = list_dict_tgt\n list_dict_tgt = temp_list\n temp = tgt\n tgt = \"vi\"\n src = temp\n\n\n lim_src = len(list_dict_src)\n lim_tgt = len(list_dict_tgt)\n print(len(list_dict_src), len(list_dict_tgt))\n preprocessString(list_dict_src)\n preprocessString(list_dict_tgt)\n\n list_align_title = list()\n\n while score >= score_lim:\n print(score)\n start_src = 0\n\n checkPoint = 0\n\n while (start_src < lim_src):\n max_ = 0\n start_tgt = checkPoint\n true_tgt = 0\n # print(start_tgt)\n\n while (start_tgt < lim_tgt):\n # so sánh title\n if(token):\n true_sore = TF_IDF(list_dict_src[start_src]['words'],\n list_dict_tgt[start_tgt]['words'])\n else:\n true_sore = compareTitle(list_dict_src[start_src][\"words\"], list_dict_tgt[start_tgt]['words'])\n if (max_ < true_sore):\n max_ = true_sore\n true_tgt = start_tgt\n\n if (max_ >= 1.0):\n break\n\n if (true_sore < score):\n start_tgt = start_tgt + 1\n continue\n\n start_tgt = start_tgt + 1\n\n # print(list_dict_src[start_src]['title'], max_)\n if (max_ < score_lim):\n del (list_dict_src[start_src])\n lim_src = len(list_dict_src)\n continue\n\n if max_ > score:\n print(list_dict_src[start_src]['title'] + \" / \" + list_dict_tgt[true_tgt]['title'], max_)\n\n list_align_title.append({src: list_dict_src[start_src]['url'], tgt: list_dict_tgt[true_tgt]['url']})\n\n del (list_dict_src[start_src])\n del (list_dict_tgt[true_tgt])\n\n lim_src = len(list_dict_src)\n lim_tgt = len(list_dict_tgt)\n continue\n\n start_src = start_src + 1\n\n score = score - 0.1\n return list_align_title\n# To perform word segmentation, POS tagging and then NER\n# annotator = VnCoreNLP(\"<FULL-PATH-to-VnCoreNLP-jar-file>\", annotators=\"wseg,pos,ner\", max_heap_size='-Xmx2g')\n# To perform word segmentation and then POS tagging\n# annotator = VnCoreNLP(\"<FULL-PATH-to-VnCoreNLP-jar-file>\", annotators=\"wseg,pos\", max_heap_size='-Xmx2g')\n# To perform word segmentation only\n# annotator = VnCoreNLP(\"<FULL-PATH-to-VnCoreNLP-jar-file>\", annotators=\"wseg\", max_heap_size='-Xmx500m')\nloadVectorEmbbeding(vector)\nloadStopWords()\nannotator = VnCoreNLP(\"./VnCoreNLP/VnCoreNLP-1.1.1.jar\", annotators=\"wseg,pos,ner,parse\", max_heap_size='-Xmx2g',port=8887)\n\nif __name__ == '__main__':\n\n # Input\n text_origin = \"việt_nam hợp_tác hàn_quốc\"\n text_trans = \"việt_nam hợp_tác lào\"\n # To perform word segmentation, POS tagging, NER and then dependency parsing\n #annotated_text = annotator.annotate(text)\n #print(sentenceToTokenize(text_trans).split(\" \"))\n #print(sentenceToTokenize(text_origin).split(\" \"))\n print(removeStopWord(text_trans.split(\" \")))\n print(removeStopWord(text_origin.split(\" \")))\n print(TF_IDF(removeStopWord(text_trans.split(\" \")), removeStopWord(text_origin.split(\" \"))))\n" }, { "alpha_fraction": 0.5204917788505554, "alphanum_fraction": 0.5245901346206665, "avg_line_length": 19.375, "blob_id": "58169d20dd1bdd6493d4d0fe6ad3be6202ca56fb", "content_id": "0fd3b88b2fd4036812d30e4a3cc4ab3117db463e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 488, "license_type": "permissive", "max_line_length": 63, "num_lines": 24, "path": "/luufile.php", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "<?php\n\tif(isset($_POST)){\n\t\t$inputJSON = file_get_contents('php://input');\n\t\t\n\t\tif(!empty($inputJSON)){\n\t\t\t$input = json_decode($inputJSON,true);\n\t\t\tif (file_exists($input['name'])) {\n\t\t\t\t\n\t\t\t\t$array = explode(\"/\",$input['name']);\n\t\t\t\t\n\t\t\t\t$filename = sprintf(\"%s/%d-%s\",$array[0],time(),$array[1]);\n\t\t\t\t\n\t\t\t\t$myfile = fopen($filename, \"a\");\n\t\t\t\tfwrite($myfile,$input['data']);\n\t\t\t\tfclose($myfile);\n\t\t\t\techo $filename;\n\t\t\t\t\n\t\t\t\t//echo readfile ($input['name']);\n\t\t\t\texit;\n\t\t\t}\n\t\t}\n\t}\n\t\n?>" }, { "alpha_fraction": 0.5342116951942444, "alphanum_fraction": 0.5428956151008606, "avg_line_length": 31.265701293945312, "blob_id": "5628af02cb6cb7707e80917aaeadc44e049d7118", "content_id": "a5726a38288b3cfa6da2d8f2e0a5f13a328ac130", "detected_licenses": [ "MIT", "GPL-3.0-or-later" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6691, "license_type": "permissive", "max_line_length": 96, "num_lines": 207, "path": "/VnCoreNLP/src/main/java/vn/corenlp/tokenizer/StringUtils.java", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "package vn.corenlp.tokenizer;\n\nimport java.util.HashSet;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class StringUtils\n{\n\n public static void testFoundByRegex(String s, String regex)\n {\n System.out.println(\"Test string: \" + s);\n\n Pattern pattern = Pattern.compile(regex);\n Matcher matcher = pattern.matcher(s);\n if (matcher.find()) {\n System.out.println(s.substring(0, matcher.start()));\n System.out.println(s.substring(matcher.start(), matcher.end()));\n System.out.println(s.substring(matcher.end()));\n }\n }\n\n public static String char2Hex(Character c)\n {\n return String.format(\"\\\\u%04x\", (int) c);\n }\n\n public static Character hex2Char(String hex)\n {\n int hexToInt = Integer.parseInt(hex.substring(2), 16);\n return (char) hexToInt;\n }\n\n public static boolean hasPunctuation(String s)\n {\n for (int i = 0; i < s.length(); i++) {\n if (!Character.isLetterOrDigit(s.charAt(i)))\n return true;\n }\n\n return false;\n }\n\n public static boolean isPunctuation(String s)\n {\n for (int i = 0; i < s.length(); i++) {\n if (Character.isLetterOrDigit(s.charAt(i)))\n return false;\n }\n\n return true;\n }\n\n public static boolean isNumeric(String s) {\n return s != null && s.matches(\"[-+]?\\\\d*\\\\.?\\\\d+\");\n }\n\n // Modified by Dat Quoc Nguyen\n public static boolean isBrace(String string)\n {\n if (string.equals(\"”\") || string.equals(\"�\") || string.equals(\"'\") || string.equals(\")\")\n || string.equals(\"}\") || string.equals(\"]\")) {\n return true;\n }\n return false;\n }\n\n public static HashSet<String> VN_abbreviation;\n public static HashSet<String> VN_exception;\n static {\n VN_abbreviation = new HashSet<String>();\n VN_exception = new HashSet<String>();\n\n VN_abbreviation.add(\"M.City\");\n VN_abbreviation.add(\"V.I.P\");\n VN_abbreviation.add(\"PGS.Ts\");\n VN_abbreviation.add(\"MRS.\");\n VN_abbreviation.add(\"Mrs.\");\n VN_abbreviation.add(\"Man.United\");\n VN_abbreviation.add(\"Mr.\");\n VN_abbreviation.add(\"SHB.ĐN\");\n VN_abbreviation.add(\"Gs.Bs\");\n VN_abbreviation.add(\"U.S.A\");\n VN_abbreviation.add(\"TMN.CSG\");\n VN_abbreviation.add(\"Kts.Ts\");\n VN_abbreviation.add(\"R.Madrid\");\n VN_abbreviation.add(\"Tp.\");\n VN_abbreviation.add(\"T.Ư\");\n VN_abbreviation.add(\"D.C\");\n VN_abbreviation.add(\"Gs.Tskh\");\n VN_abbreviation.add(\"PGS.KTS\");\n VN_abbreviation.add(\"GS.BS\");\n VN_abbreviation.add(\"KTS.TS\");\n VN_abbreviation.add(\"PGS-TS\");\n VN_abbreviation.add(\"Co.\");\n VN_abbreviation.add(\"S.H.E\");\n VN_abbreviation.add(\"Ths.Bs\");\n VN_abbreviation.add(\"T&T.HN\");\n VN_abbreviation.add(\"MR.\");\n VN_abbreviation.add(\"Ms.\");\n VN_abbreviation.add(\"T.T.P\");\n VN_abbreviation.add(\"TT.\");\n VN_abbreviation.add(\"TP.\");\n VN_abbreviation.add(\"ĐH.QGHN\");\n VN_abbreviation.add(\"Gs.Kts\");\n VN_abbreviation.add(\"Man.Utd\");\n VN_abbreviation.add(\"GD-ĐT\");\n VN_abbreviation.add(\"T.W\");\n VN_abbreviation.add(\"Corp.\");\n VN_abbreviation.add(\"ĐT.LA\");\n VN_abbreviation.add(\"Dr.\");\n VN_abbreviation.add(\"T&T\");\n VN_abbreviation.add(\"HN.ACB\");\n VN_abbreviation.add(\"GS.KTS\");\n VN_abbreviation.add(\"MS.\");\n VN_abbreviation.add(\"Prof.\");\n VN_abbreviation.add(\"GS.TS\");\n VN_abbreviation.add(\"PGs.Ts\");\n VN_abbreviation.add(\"PGS.BS\");\n VN_abbreviation.add(\"BT.\");\n VN_abbreviation.add(\"Ltd.\");\n VN_abbreviation.add(\"ThS.BS\");\n VN_abbreviation.add(\"Gs.Ts\");\n VN_abbreviation.add(\"SL.NA\");\n //VN_abbreviation.add(\"P.\");\n VN_abbreviation.add(\"Th.S\");\n VN_abbreviation.add(\"Gs.Vs\");\n VN_abbreviation.add(\"PGs.Bs\");\n VN_abbreviation.add(\"T.O.P\");\n VN_abbreviation.add(\"PGS.TS\");\n VN_abbreviation.add(\"HN.T&T\");\n VN_abbreviation.add(\"SG.XT\");\n VN_abbreviation.add(\"O.T.C\");\n VN_abbreviation.add(\"TS.BS\");\n VN_abbreviation.add(\"Yahoo!\");\n VN_abbreviation.add(\"Man.City\");\n VN_abbreviation.add(\"MISS.\");\n VN_abbreviation.add(\"HA.GL\");\n VN_abbreviation.add(\"GS.Ts\");\n VN_abbreviation.add(\"TBT.\");\n VN_abbreviation.add(\"GS.VS\");\n VN_abbreviation.add(\"GS.TSKH\");\n VN_abbreviation.add(\"Ts.Bs\");\n VN_abbreviation.add(\"M.U\");\n VN_abbreviation.add(\"Gs.TSKH\");\n VN_abbreviation.add(\"U.S\");\n VN_abbreviation.add(\"Miss.\");\n VN_abbreviation.add(\"GD.ĐT\");\n VN_abbreviation.add(\"PGs.Kts\");\n //VN_abbreviation.add(\"Q.\");\n VN_abbreviation.add(\"St.\");\n VN_abbreviation.add(\"Ng.\");\n VN_abbreviation.add(\"Inc.\");\n VN_abbreviation.add(\"Th.\");\n VN_abbreviation.add(\"N.O.V.A\");\n\n VN_exception.add(\"Wi-fi\");\n VN_exception.add(\"17+\");\n VN_exception.add(\"km/h\");\n VN_exception.add(\"M7\");\n VN_exception.add(\"M8\");\n VN_exception.add(\"21+\");\n VN_exception.add(\"G3\");\n VN_exception.add(\"M9\");\n VN_exception.add(\"G4\");\n VN_exception.add(\"km3\");\n VN_exception.add(\"m/s\");\n VN_exception.add(\"km2\");\n VN_exception.add(\"5g\");\n VN_exception.add(\"4G\");\n VN_exception.add(\"8K\");\n VN_exception.add(\"3g\");\n VN_exception.add(\"E9\");\n VN_exception.add(\"U21\");\n VN_exception.add(\"4K\");\n VN_exception.add(\"U23\");\n VN_exception.add(\"Z1\");\n VN_exception.add(\"Z2\");\n VN_exception.add(\"Z3\");\n VN_exception.add(\"Z4\");\n VN_exception.add(\"Z5\");\n VN_exception.add(\"Jong-un\");\n VN_exception.add(\"u19\");\n VN_exception.add(\"5s\");\n VN_exception.add(\"wi-fi\");\n VN_exception.add(\"18+\");\n VN_exception.add(\"Wi-Fi\");\n VN_exception.add(\"m2\");\n VN_exception.add(\"16+\");\n VN_exception.add(\"m3\");\n VN_exception.add(\"V-League\");\n VN_exception.add(\"Geun-hye\");\n VN_exception.add(\"5G\");\n VN_exception.add(\"4g\");\n VN_exception.add(\"Z3+\");\n VN_exception.add(\"3G\");\n VN_exception.add(\"km/s\");\n VN_exception.add(\"6+\");\n VN_exception.add(\"u21\");\n VN_exception.add(\"WI-FI\");\n VN_exception.add(\"u23\");\n VN_exception.add(\"U19\");\n VN_exception.add(\"6s\");\n VN_exception.add(\"4s\");\n }\n\n}\n" }, { "alpha_fraction": 0.48351311683654785, "alphanum_fraction": 0.48899412155151367, "avg_line_length": 29.126815795898438, "blob_id": "de99594fbe50b535daf62e7b1fafde859d6693ed", "content_id": "0c4e50c2d5f52d795b1ad710a4750c8aa7bc1337", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22912, "license_type": "permissive", "max_line_length": 119, "num_lines": 757, "path": "/ConvertHtmlToText.py", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "import os\nimport pdb\nimport time\nimport traceback\nimport urllib\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nimport ChromeDriver\nimport Utility\nimport urllib.request\nimport SaveFile\nimport datetime as dt\nimport re\nfrom selenium.webdriver.support.ui import WebDriverWait\n\n\ndef getTextFromTagsWithClass(src_link, tag, class_):\n soup = BeautifulSoup(urllib.request.urlopen(src_link).read(), \"lxml\")\n text = \"\"\n\n for tag_text in soup.findAll(tag, class_=class_):\n tagText = Utility.formatString(tag_text.text)\n tagText = tagText.replace(\"\\n+\", \" \")\n tagText = tagText.replace(\"/.\", \"\")\n tagText = tagText.strip()\n # ký tự lạ xuất hiện tại một số bài báo\n\n if tagText and not tagText == \"\":\n text += tagText\n\n return text\n\n\ndef getTextFromTagsWithId(src_link, tag, id):\n soup = BeautifulSoup(urllib.request.urlopen(src_link).read(), \"lxml\")\n text = \"\"\n\n for tag_text in soup.findAll(tag, {\"id\": id}):\n # pdb.set_trace()\n tagText = Utility.formatString(tag_text.text)\n tagText = tagText.replace(\"\\n+\", \" \")\n tagText = tagText.replace(\"/.\", \"\")\n tagText = tagText.strip()\n # ký tự lạ xuất hiện tại một số bài báo\n\n if tagText and not tagText == \"\":\n text += tagText\n\n return text\n\n\ndef getTextFromTags(src_link, tag):\n soup = BeautifulSoup(urllib.request.urlopen(src_link).read(), \"lxml\")\n text = \"\"\n\n for j in soup.findAll(tag):\n\n text_in_timestamp = Utility.formatString(j.text)\n text_in_timestamp = text_in_timestamp.replace(\"/.\", \"\")\n text_in_timestamp = text_in_timestamp.strip()\n if text_in_timestamp:\n text += text_in_timestamp\n\n return text\n\n\ndef getVovParagragh(driver, url, tag_time=\"time\"):\n not_get_web = True\n while (not_get_web):\n try:\n driver.get(url)\n not_get_web = False\n except:\n print(\"Loi khong get link duoc {}\".format(url))\n pdb.set_trace()\n time.sleep(2)\n pass\n time.sleep(0.5)\n try:\n times = WebDriverWait(driver, 5).until(lambda driver: driver.find_elements_by_tag_name(tag_time))\n list_time = list()\n for time_ in times:\n list_time.append(time_.text)\n source = driver.page_source\n except:\n return None\n return source\n\n\ndef getVovLink(link, list_=list()):\n \"\"\"\n :param src_link:\n :param dict_:\n :return:\n \"\"\"\n # src_link chua max_mage va url de lay bai viet\n\n base_url = \"https://vovworld.vn/\"\n\n index = 1\n print(\"Page: \")\n list_link = list()\n driver = ChromeDriver.getChromeDriver()\n\n while (index > 0):\n print(index)\n pdb.set_trace()\n html = getVovParagragh(driver, url=\"{}{}\".format(link, index))\n\n if not html:\n break\n\n soup = BeautifulSoup(html, \"lxml\")\n\n container = soup.findAll(\"div\", \"l-grid__main\")\n\n for paragraphs in container:\n\n list_paragraph = paragraphs.findAll(\"article\", \"story\")\n index_time = 0\n\n if not list_paragraph:\n index = - 1\n break\n\n for paragraph in list_paragraph:\n\n if (paragraph.h2.a.attrs['href'] != None):\n hadIt = False\n # print(\"Kiểm tra link trùng\")\n # pdb.set_trace()\n for link_dict in list_:\n if (link_dict['url'] == str(base_url + urllib.parse.quote_plus(paragraph.a['href']))):\n hadIt = True\n break\n\n if hadIt:\n # pdb.set_trace()\n index = - 1\n break\n\n datetime = paragraph.time.text\n\n titile = paragraph.h2.text.replace(\"\\n\", \"\").replace(\"\\s+\", \"\").strip()\n\n if datetime:\n if titile:\n dic = {\"url\": base_url + urllib.parse.quote_plus(paragraph.a['href']),\n \"date\": datetime,\n \"title\": titile}\n\n list_link.append(dic)\n\n index_time = index_time + 1\n continue\n else:\n print(\"khong co duong dan: \"+paragraph.h2.text.replace(\"\\n\", \"\").replace(\"\\s+\", \"\").strip())\n index = index + 1\n\n driver.close()\n\n return list_link\n\n\ndef getVnanetParagragh(driver, url):\n \"\"\"\n :param driver: selenium driver\n :param url:\n :return:\n \"\"\"\n try:\n driver.get(url)\n print(url)\n xx = driver.find_element_by_id(\"idviewsmores\")\n\n while (True):\n if xx:\n button = xx.find_element_by_tag_name(\"a\").click()\n time.sleep(1)\n\n xx = driver.find_element_by_id(\"idviewsmores\")\n print(xx)\n\n else:\n break\n except:\n pass\n\n return driver.page_source\n\n\ndef getVnanetLink(link, list_):\n list_link = list()\n\n driver = webdriver.Chrome(executable_path=os.path.abspath(os.getcwd() + \"/chromedriver.exe\"))\n source = getVnanetParagragh(driver, link)\n soup = BeautifulSoup(source, \"lxml\")\n\n paragraphs = soup.findAll(\"div\", {\"id\": \"listScroll\"})\n\n hadIt = False\n\n for paragraph in paragraphs:\n all_link = paragraph.findAll(\"a\", {\"class\": \"fon1\"})\n array_time = paragraph.findAll(\"p\", {\"class\": \"fon3\"})\n all_title = paragraph.findAll(\"h3\")\n count = 0\n\n for link in all_link:\n\n href_array = link.attrs['href'].split(\"/\")\n href_array[4] = urllib.parse.quote_plus(href_array[4])\n\n crawl_link = \"{}//{}/{}/{}/{}\".format(href_array[0], href_array[2], href_array[3], href_array[4],\n href_array[5])\n\n for list_dict in list_:\n if crawl_link == list_dict['url']:\n hadIt = True\n break\n if hadIt:\n break\n\n time = array_time[count].text.split(\" \")[0]\n\n title = all_title[count].text\n\n title = title.replace(\"\\t\", \"\").replace(\"\\n\", \"\").replace(\"*\", \"\").replace(\"|\", \"\").replace(\"\\u200b\",\n \" \").replace(\n \"/\", \"\").replace(\"?\", \"\").replace(\"*\", \"\")\n\n dic = {\"url\": urllib.parse.quote_plus(crawl_link),\n \"date\": time,\n \"title\": title}\n\n list_link.append(dic)\n\n count = count + 1\n if hadIt:\n break\n driver.close()\n\n return list_link\n\n\ndef getQDNDParagragh(driver, url):\n driver.get(url)\n time.sleep(0.5)\n return driver.page_source\n\n\ndef getQDNDLink(link, list_):\n list_link = list()\n driver = webdriver.Chrome(executable_path=os.path.abspath(os.getcwd() + \"/chromedriver.exe\"))\n index = 1\n\n Running = True\n\n while (Running):\n try:\n source = getQDNDParagragh(driver, link.format(index))\n WebDriverWait(driver, 200).until(lambda driver: driver.find_elements_by_tag_name('img'))\n soup = BeautifulSoup(source, \"lxml\")\n\n content = soup.find(\"div\", {\"class\": \"list-news-category\"})\n if not content:\n content = soup.find(\"div\", {\"class\": \"ctrangc3\"})\n\n paragraphs = content.findAll(\"article\", {\"class\": \"\"})\n if not paragraphs:\n paragraphs = soup.findAll(\"div\", {\"class\": \"pcontent\"})\n if not paragraphs:\n paragraphs = soup.findAll(\"div\", {\"class\": \"pcontent3\"})\n if not paragraphs:\n break\n\n for paragraph in paragraphs:\n try:\n href = paragraph.find(\"a\").attrs['href']\n title = paragraph.find(\"h3\").text\n title = title.replace(\"\\\"\", \" \")\n title = title.replace(\"\\'\", \" \")\n title = title.strip()\n dic = {\"url\": href,\n \"title\": title}\n for link_dict in list_:\n if link_dict['url'] == dic[\"url\"]:\n Running = False\n break\n list_link.append(dic)\n except:\n pass\n\n index = index + 1\n except:\n print(\"ngu 10 s\")\n time.sleep(10)\n pass\n driver.close()\n return list_link\n\n\ndef enlist_talk_names(path, dict_, src_lang_, tgt_lang_):\n status = False\n time.sleep(2)\n try:\n r = urllib.request.urlopen(path).read()\n soup = BeautifulSoup(r, \"lxml\")\n talks = soup.find_all(\"a\")\n\n for i in talks:\n href = i.attrs['href'].replace(\"?language=\" + tgt_lang_, \"\")\n if href.find('/talks/') == 0:\n if dict_.get(href) != 1:\n dict_[href] = 1\n status = True\n except Exception as e:\n print(e)\n print(\"error page couldn't get link\")\n\n return status\n\n\ndef get_links_and_langs(target_link, target_lang, all_link, src_lang_, tgt_lang_):\n for soup in all_link:\n # kiểm tra đường dẫn có bằng None hay không và tìm\n if (soup.get('href') != None and soup.attrs['href'].find('?language=') != -1):\n # kiểm tra xem ngôn ngữ có trùng với ngôn ngữ ở nguồn và đích hay không\n position = soup.attrs['href'].find('?language=') + 10\n lang = soup.get('href')[position:]\n #\n if (src_lang_ == lang or tgt_lang_ == lang\n and len(target_lang) < 2):\n target_link.append(soup)\n target_lang.append(lang)\n\n\n\"\"\"\nsrc_params a list of vi transcript segments\ntgt_params a list of ja transcript segments \n\"\"\"\n\n\ndef get_transcript(src_params, tgt_params, target_link, tgt_lang_):\n for j in target_link:\n if j.get('href') != None and j.attrs['href'].find('?language=') != -1:\n if (j.attrs['hreflang'] == None):\n return\n lang = j.attrs['hreflang']\n path = j.attrs['href']\n time.sleep(1.0)\n r1 = urllib.request.urlopen(path).read()\n soup1 = BeautifulSoup(r1, \"lxml\")\n text_params = []\n # each <p>\n\n for tag in soup1.find(\"div\", class_=\"Grid\"):\n\n try:\n p_tag = tag.p\n text_in_timestamp = convert_2_speech_per_line(p_tag.text).strip()\n if text_in_timestamp:\n text_params.append(text_in_timestamp)\n except:\n continue\n pass\n\n if lang == tgt_lang_:\n tgt_params += text_params\n else:\n src_params += text_params\n\n\ndef convert_2_speech_per_line(ori_text):\n # tmp_text = ori_text.replace('\\t', '\\n')\n tmp_text = ori_text.replace('\\n', ' ').replace('\\t', '\\n')\n while tmp_text.find(\" \") != -1:\n tmp_text = tmp_text.replace(' ', ' ')\n while tmp_text.find(\"\\n\\n\") != -1:\n tmp_text = tmp_text.replace('\\n\\n', '\\n')\n tmp_text = tmp_text.strip()\n return tmp_text\n\n\ndef merge_all_params(list_param, spliting_param_by_empty_line=False):\n final_text = \"\"\n spliting_param_char = '\\n\\n' if spliting_param_by_empty_line else '\\n'\n for param in list_param:\n final_text += param.strip() + spliting_param_char\n return final_text.strip()\n\n\n\"\"\" \nThere are many cases.\nCurrenty, they are:\n+ TH1: format using script in <p> tag (== timestamp) => Success or Fail in each timestamp\n+ TH2: format using script of the whole subtitles .vi and .ja. => Success or Fail in the whole transcript of subtitle\n\nsrc_params a list of vi transcript segments\ntgt_params a list of ja transcript segments \n\"\"\"\n\n\ndef format_subtitle_and_saving(src_params, tgt_params,\n output_dir_fail, output_dir_success, talk_name, src_lang_, tgt_lang_):\n if (tgt_lang_.find(\"zh\") != -1):\n\n list_text = list()\n for param in src_params:\n param = param.replace(\".\", \"\")\n list_text.append(param)\n src_params = list_text\n\n list_text = list()\n for param in tgt_params:\n param = param.replace(\"。\", \"\")\n list_text.append(param)\n tgt_params = list_text\n\n if (src_lang_.find(\"zh\") != -1):\n list_text = list()\n for param in tgt_params:\n param = param.replace(\".\", \"\")\n list_text.append(param)\n\n tgt_params = list_text\n\n list_text = list()\n for param in src_params:\n param = param.replace(\"。\", \"\")\n list_text.append(param)\n\n if not os.path.exists(output_dir_success[0] + \"{}-{}\".format(tgt_lang_, src_lang_)):\n os.makedirs(output_dir_success[0] + \"{}-{}\".format(tgt_lang_, src_lang_))\n\n if not os.path.exists(output_dir_success[1] + \"{}-{}\".format(tgt_lang_, src_lang_)):\n os.makedirs(output_dir_success[1] + \"{}-{}\".format(tgt_lang_, src_lang_))\n\n SaveFile.saveSentences(src_text=tgt_params,\n tgt_text=src_params,\n file_path=output_dir_success[0] + \"{}-{}/{}\".format(tgt_lang_, src_lang_, talk_name),\n src_lang_=tgt_lang_,\n tgt_lang_=src_lang_)\n\n SaveFile.saveDocument(src_text=tgt_params,\n tgt_text=src_params,\n file_path=output_dir_success[1] + \"{}-{}/{}\".format(tgt_lang_, src_lang_, talk_name),\n src_lang_=tgt_lang_,\n tgt_lang_=src_lang_)\n\n return\n\n\n\"\"\"\nformat_and_save by using the script in <p> not the whole script of subtitle in .ja and .vi\nthere are two cases:\n+ success: The output data does not need to align by hand\n+ fail: The output data needs to be aligned by hand\n\nsrc_params a list of vi transcript segments\ntgt_params a list of ja transcript segments \n\"\"\"\n\n\ndef extract_talk(path, talk_name, output_dir_success, output_dir_fail, src_lang_, tgt_lang_):\n # if talk_name in os.path.isfile(output_dir_success[0]+):\n # return\n\n while (True):\n try:\n time.sleep(2)\n r = urllib.request.urlopen(path).read()\n soup = BeautifulSoup(r, \"lxml\")\n\n # GET links and langs\n target_link = []\n target_lang = []\n all_link = soup.findAll('link')\n\n # Lấy link dẫn tới chuỗi nguồn và đích.\n get_links_and_langs(target_link, target_lang, all_link, src_lang_, tgt_lang_)\n\n # GET DATA\n tgt_params = []\n src_params = []\n\n if len(target_link) != 2:\n print(\"talk {} - error\".format(talk_name))\n return\n print(\"talk {}\".format(talk_name))\n get_transcript(src_params, tgt_params, target_link, tgt_lang_)\n\n if (format_subtitle_and_saving(src_params, tgt_params\n , output_dir_fail, output_dir_success, talk_name, src_lang_, tgt_lang_)):\n print(talk_name)\n break\n except Exception as e:\n time.sleep(2)\n traceback.print_exc()\n pass\n\n\ndef getNhanDanAllViParagraph(driver, url):\n # driver = ChromeDriver.getChromeDriver()\n\n list_src = list()\n index = 1\n count_fail = 1\n while (True):\n try:\n\n driver.get(url.format(index))\n\n WebDriverWait(driver, 200).until(lambda driver: driver.find_elements_by_tag_name('article'))\n\n soup = BeautifulSoup(driver.page_source, \"lxml\")\n articles = soup.findAll(\"article\")\n\n while (articles == None):\n time.sleep(6)\n count_fail = count_fail + 1\n driver.get(url.format(index))\n\n if (count_fail == 7):\n break\n\n if not articles:\n break\n\n for article in articles:\n\n div = article.find(\"div\", {\"class\": \"box-title\"})\n title = div.a.attrs['title'].replace(\"\\n\", \"\").replace(\"\\t\", \"\")\n\n if (div == None):\n continue\n\n href = div.a.attrs['href']\n href = href.replace(\"%2F\", \"/\")\n\n date_box = article.find(\"div\", {\"class\": \"box-meta-small\"})\n\n if (date_box == None):\n continue\n if not date_box:\n continue\n date_time = date_box.text\n date_time = dt.datetime.strptime(date_time.split(\" \")[1], '%d/%m/%Y').strftime(\"%Y/%m/%d\")\n\n if not href in list_src:\n print(href)\n\n dic = {\"url\": href,\n \"title\": title,\n \"date\": date_time}\n list_src.append(dic)\n\n\n except:\n traceback.print_exc()\n\n break\n pass\n index = index + 1\n\n driver.delete_all_cookies()\n driver.close()\n return list_src\n\n\ndef getNhanDanAllZhpragraph(driver, url):\n list_ = list()\n index = 1\n count_fail = 1\n\n while (True):\n try:\n\n driver.get(url.format(index))\n\n soup = BeautifulSoup(driver.page_source, \"lxml\")\n\n WebDriverWait(driver, 200).until(lambda driver: driver.find_elements_by_tag_name('div'))\n divs = soup.findAll(\"div\", {\"class\": \"media-body\"})\n\n if (divs == None):\n break\n\n if not divs:\n break\n # pdb.set_trace()\n\n for div in divs:\n\n if (div.h3 == None):\n continue\n\n title = div.h3.text.replace(\"\\n\", \"\").replace(\"\\t\", \"\")\n\n href = div.h3.a.attrs['href']\n\n date_box = div.find(\"small\", {\"class\": \"text-muted\"})\n\n if (date_box == None):\n continue\n\n if not divs:\n break\n\n date_time = date_box.text.replace(\"nbsp;\", \"\").split(\" \")[0]\n date_time = date_time.replace(\"\\xa0\", \"\")\n date_time = date_time.replace(\"年\", \"/\").replace(\"月\", \"/\").replace(\"日\", \"\")\n\n dic = {\"url\": href,\n \"title\": title,\n \"date\": date_time}\n\n if not dic in list_:\n # pdb.set_trace()\n\n list_.append(dic)\n\n\n except:\n traceback.print_exc()\n pass\n index = index + 15\n driver.close()\n\n return list_\n\n\ndef getVietNamVietLaoLink(link, list_):\n index = 1\n list_link = list()\n dict_ = dict()\n hadIt = False\n driver = ChromeDriver.getChromeDriver()\n while (True):\n\n if hadIt:\n break\n driver.get(link.format(index))\n divs = driver.find_elements_by_xpath(\"//div[@class='post-meta']\")\n\n if not divs:\n break\n\n time.sleep(1)\n\n for div in divs:\n\n if hadIt:\n break\n link_string = div.find_element_by_xpath(\".//a\").get_attribute('href')\n titile_string = div.find_element_by_xpath(\".//a\").get_attribute('title')\n titile_string = titile_string.replace(\"\\\"\", \"\")\n\n for link_dict in list_:\n if link_dict['url'] == link_string:\n hadIt = True\n break\n\n new = re.sub(\"\\\"\", \"\\'\", titile_string)\n\n time_string = div.find_element_by_xpath(\".//li\").text\n\n time_ = re.sub(\"\\\"\", \"\\'\", time_string)\n\n #print(\"{} - {}\".format(titile_string, new))\n\n dict_ = {\"url\": link_string, \"date\": time_, \"title\": new}\n list_link.append(dict_)\n index = index + 1\n driver.delete_all_cookies()\n driver.close()\n\n return list_link\n\n\ndef getVietNamPlusLink_Date_Titile(link, list_):\n base_link = \"https://www.vietnamplus.vn/\"\n lang = \"vi\"\n if (\"zh\" in link):\n lang = \"zh\"\n base_link = \"https://zh.vietnamplus.vn/\"\n\n if (base_link == None):\n return\n\n list_link = list()\n driver = webdriver.Chrome(executable_path=os.path.abspath(os.getcwd() + \"/chromedriver.exe\"))\n hadLink = False\n index = 1\n #pdb.set_trace()\n while(index > 0):\n\n driver.get(link.format(index))\n\n soup = BeautifulSoup(driver.page_source, \"lxml\")\n\n div_clear_fix = soup.findAll(\"div\", {\"class\": \"clearfix\"})\n\n if (div_clear_fix != None):\n articles = div_clear_fix[0].findAll(\"article\", class_=\"story\")\n\n if (articles != None):\n for article in articles:\n if (article.time != None):\n time = article.time.text.strip()\n\n # time = \"2021年2月12日14:12\"\n if (lang != \"vi\"):\n time = time.replace('年', '-').replace('月', '-').replace('日', ' ')\n time = dt.datetime.strptime(time, '%Y-%m-%d %H:%M')\n time = time.strftime(\"%d-%m-%Y\")\n else:\n # pdb.set_trace()\n time = dt.datetime.strptime(time, '%d/%m/%Y - %H:%M')\n time = time.strftime(\"%d-%m-%Y\")\n\n else:\n time = dt.datetime.strptime(str(dt.datetime.now()).strip(\" \")[0: 10], \"%Y-%m-%d\")\n time = time.strftime(\"%d-%m-%Y\")\n\n href = base_link + urllib.parse.quote_plus(article.h2.a.attrs['href'])\n\n\n for exists_link in list_:\n\n if (exists_link[\"url\"] == href):\n hadLink = True\n break\n\n for exists_link in list_link:\n if (exists_link[\"url\"] == href):\n hadLink = True\n break\n\n if hadLink:\n break\n\n title = article.h2.text\n title = title.replace(\"\\n\", \"\").replace(\"/\", \"\").replace(\"*\", \"\").replace(\"{\", \"\").replace(\"}\", \"\")\n title = re.sub(\"\\s+\", \" \", title).strip()\n\n dic = {\"url\": href,\n \"title\": title,\n \"date\": time}\n\n list_link.append(dic)\n index += 1\n continue\n break\n driver.close()\n\n return list_link\n" }, { "alpha_fraction": 0.46762049198150635, "alphanum_fraction": 0.49585843086242676, "avg_line_length": 24.538461685180664, "blob_id": "c6e46bbfabe14895cf7500d321046d67165427d3", "content_id": "a6b027025063a864ef7cc1a9e667bbb2c07938aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2694, "license_type": "permissive", "max_line_length": 101, "num_lines": 104, "path": "/Utility.py", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "import re\nimport json\nimport pdb\n\ndef deleteEmojify(text):\n regrex_pattern = re.compile(pattern=\"[\"\n u\"\\U0001F600-\\U0001F64F\" # emoticons\n u\"\\U0001F300-\\U0001F5FF\" # symbols & pictographs\n u\"\\U0001F680-\\U0001F6FF\" # transport & map symbols\n u\"\\U0001F1E0-\\U0001F1FF\" # flags (iOS)\n u\"\\U0001F1E0-\\U0001F1FF\"\n \"]+\", flags=re.UNICODE)\n\n return regrex_pattern.sub(r'', text)\n\n\ndef formatString(text):\n text = deleteEmojify(text)\n text = formatSentence(text)\n return text\n\ndef removeNBSP(text):\n return text.replace(\"&nbsp\", '')\n\ndef splipWithEndLine(text):\n list_ = list()\n leng = len(text) - 1\n next_ = 0\n start = 0\n crop_at = 0\n\n while start < leng:\n if(next_ >= leng):\n break\n\n\n if(text[start] != '\\n'):\n start = start + 1\n next_ = start\n continue\n\n if(text[next_] !='\\n'):\n line = text[crop_at: start + 1]\n line = formatSentence(line)\n #pdb.set_trace()\n\n\n list_.append(line)\n crop_at = next_\n start = next_\n\n\n continue\n\n next_ = next_ + 1\n\n if(crop_at != next_):\n list_.append(formatSentence(text[crop_at: start + 1]))\n\n newString = \"\"\n\n for line in list_:\n if line == \"\" or line == \"\":\n continue\n newString += \"{}\".format(line)\n\n return newString\n\ndef formatSentence(text):\n text = bytes(text, \"utf-8\").decode('utf-8', 'ignore')\n\n text = text.replace('\\a', \" \")\n text = text.replace('\\r', \" \")\n\n text = re.sub('\\xa0', \" \", text)\n text = re.sub(\"&nbsp\", \" \", text)\n text = re.sub(\"\\u200b\", \" \", text)\n text = re.sub(\"./\", \" \", text)\n text = re.sub(\"•\", \"\", text)\n text = re.sub(\"\\”\", \"\", text)\n text = re.sub(\"\", \"\", text)\n text = re.sub(\"\\t+\", \" \", text)\n text = re.sub(' +', \" \", text)\n\n return text\n\ndef formatDocumentWithComma(text, comma):\n text = re.sub(\"[\\n]+?[ ]+?[\\n]+\", \"\\n\", text)\n # trường hợp trên đáng ra phải bao quá hết cả ở dưới nhưng vì 1 lý do nào đó mà không có tác dụng\n text = re.sub(\"[\\n]+?[ ]+\", \"\\n\", text)\n text = splipWithEndLine(text)\n\n\n text = text.replace(\"…\", \"{}{}{}\".format(comma, comma, comma))\n\n\n return text\n\ndef stringJsonToOject(str):\n return json.loads(str)\n\ndef objectToJson(object):\n jsonSTring = json.dumps(object, ensure_ascii = False).encode('utf8')\n return jsonSTring.decode()\n" }, { "alpha_fraction": 0.7588757276535034, "alphanum_fraction": 0.7633135914802551, "avg_line_length": 134.10000610351562, "blob_id": "af9f728791caa7903326458435f106778433afa9", "content_id": "6d0722baa5bdd853c0e1a048cc99c3aa7a4972c0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1352, "license_type": "permissive", "max_line_length": 510, "num_lines": 10, "path": "/README.md", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "# Multilingual Web Crawler\nCrawl Multilingual language News Website Content like VovWorld, VNAnet, VietNamPlus, QuanDoiNhanDan, etc\n\nThis tools made by me with help of instructors **Dr. Tran Hong Viet** (thviet79) and **masters Bui Van Tan**\n\nThis tool is by for Window and Linux users, it purpose to crawl rare Language such as **Laotian, Khmer** and popular language like **Chinese, English** etc you can add more if you want\n\nFirst, I'll talk about my Folders and Files organize and how it work. For each website News you have 1 Folder, it contains link of categories manually collected in linkauto Folder. When the tool run it'll check this folder to get all the news link, title (and date) at first run time. At second time etc, it with check the latest news of the website then add it to resource to save time (time it's knowledge and sleep =)).\n\nSecond, it's our approach to detecting bilingual news. As you know news has **title and date (some not in numeric format)**. Beacause news is very lagre resource so compare them is very time consuming. So we set ***date range*** around 15 days or 1 month. It reduce a lot of unnecessary canculating. With title we **translate it from Machine translation** (googleApi etc) to translate it to **Vietnamese**. After that titles will be tokenize by **VNCoreNLP** then use **TF-IDF** to compare them similar or not. \n" }, { "alpha_fraction": 0.44397589564323425, "alphanum_fraction": 0.4528614580631256, "avg_line_length": 32.453399658203125, "blob_id": "0a01125cf9be2552fdd63698127f704465376b20", "content_id": "dd95f058c8c91529aebb3c9126d353cd0fa009b2", "detected_licenses": [ "MIT", "GPL-3.0-or-later" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 13332, "license_type": "permissive", "max_line_length": 191, "num_lines": 397, "path": "/VnCoreNLP/src/main/java/vn/corenlp/tokenizer/Tokenizer.java", "repo_name": "thviet79/MutilLanguage", "src_encoding": "UTF-8", "text": "package vn.corenlp.tokenizer;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n\n/**\n * This class contains methods used for tokenization step.\n *\n * @author tuanphong94\n * @link https://github.com/phongnt570/UETsegmenter/blob/master/src/vn/edu/vnu/uet/nlp/tokenizer/tokenizer.tokenizer.java\n *\n */\npublic class Tokenizer {\n /**\n * @param s\n * @return List of tokens from s\n * @throws IOException\n */\n public static List<String> tokenize(String s) throws IOException {\n if (s == null || s.trim().isEmpty()) {\n return new ArrayList<String>();\n }\n\n String[] tempTokens = s.trim().split(\"\\\\s+\");\n if (tempTokens.length == 0) {\n return new ArrayList<String>();\n }\n\n List<String> tokens = new ArrayList<String>();\n\n for (String token : tempTokens) {\n if (token.length() == 1 || !StringUtils.hasPunctuation(token)) {\n tokens.add(token);\n continue;\n }\n\n if (token.endsWith(\",\")) {\n tokens.addAll(tokenize(token.substring(0, token.length() - 1)));\n tokens.add(\",\");\n continue;\n }\n\n if (StringUtils.VN_abbreviation.contains(token)) {\n tokens.add(token);\n continue;\n }\n\n\n if (token.endsWith(\".\") && Character.isAlphabetic(token.charAt(token.length() - 2))) {\n if ((token.length() == 2 && Character.isUpperCase(token.charAt(token.length() - 2))) || (Pattern.compile(Regex.SHORT_NAME).matcher(token).find())) {\n tokens.add(token);\n continue;\n }\n tokens.addAll(tokenize(token.substring(0, token.length() - 1)));\n tokens.add(\".\");\n continue;\n }\n\n if (StringUtils.VN_exception.contains(token)) {\n tokens.add(token);\n continue;\n }\n\n boolean tokenContainsAbb = false;\n for (String e : StringUtils.VN_abbreviation) {\n int i = token.indexOf(e);\n if (i < 0)\n continue;\n\n tokenContainsAbb = true;\n tokens = recursive(tokens, token, i, i + e.length());\n break;\n }\n if (tokenContainsAbb)\n continue;\n\n boolean tokenContainsExp = false;\n for (String e : StringUtils.VN_exception) {\n int i = token.indexOf(e);\n if (i < 0)\n continue;\n\n tokenContainsExp = true;\n tokens = recursive(tokens, token, i, i + e.length());\n break;\n }\n if (tokenContainsExp)\n continue;\n\n List<String> regexes = Regex.getRegexList();\n\n boolean matching = false;\n for (String regex : regexes) {\n if (token.matches(regex)) {\n tokens.add(token);\n matching = true;\n break;\n }\n }\n if (matching) {\n continue;\n }\n\n for (int i = 0; i < regexes.size(); i++) {\n Pattern pattern = Pattern.compile(regexes.get(i));\n Matcher matcher = pattern.matcher(token);\n\n if (matcher.find()) {\n if (i == Regex.getRegexIndex(\"url\")) {\n String[] elements = token.split(Pattern.quote(\".\"));\n boolean hasURL = true;\n for (String ele : elements) {\n if (ele.length() == 1 && Character.isUpperCase(ele.charAt(0))) {\n hasURL = false;\n break;\n }\n for (int j = 0; j < ele.length(); j++) {\n if (ele.charAt(j) >= 128) {\n hasURL = false;\n break;\n }\n }\n }\n if (hasURL) {\n tokens = recursive(tokens, token, matcher.start(), matcher.end());\n } else {\n continue;\n }\n }\n\n else if (i == Regex.getRegexIndex(\"month\")) {\n int start = matcher.start();\n\n boolean hasLetter = false;\n\n for (int j = 0; j < start; j++) {\n if (Character.isLetter(token.charAt(j))) {\n tokens = recursive(tokens, token, matcher.start(), matcher.end());\n hasLetter = true;\n break;\n }\n }\n\n if (!hasLetter) {\n tokens.add(token);\n }\n }\n\n else {\n tokens = recursive(tokens, token, matcher.start(), matcher.end());\n }\n\n matching = true;\n break;\n }\n }\n\n if (matching)\n continue;\n else\n tokens.add(token);\n }\n\n return tokens;\n }\n\n private static List<String> recursive(List<String> tokens, String token, int beginMatch, int endMatch)\n throws IOException {\n if (beginMatch > 0)\n tokens.addAll(tokenize(token.substring(0, beginMatch)));\n tokens.addAll(tokenize(token.substring(beginMatch, endMatch)));\n\n if (endMatch < token.length())\n tokens.addAll(tokenize(token.substring(endMatch)));\n\n return tokens;\n }\n\n public static List<String> joinSentences(List<String> tokens) {\n List<String> sentences = new ArrayList<>();\n\n List<String> sentence = new ArrayList<>();\n for (int i = 0; i < tokens.size(); i++) {\n String token = tokens.get(i);\n String nextToken = null;\n if (i != tokens.size() - 1) {\n nextToken = tokens.get(i + 1);\n }\n String beforeToken = null;\n if (i > 0) {\n beforeToken = tokens.get(i - 1);\n }\n\n sentence.add(token);\n\n if (i == tokens.size() - 1) {\n sentences.add(joinSentence(sentence));\n return sentences;\n }\n\n if (i < tokens.size() - 2 && token.equals(StringConst.COLON)) {\n if (Character.isDigit(nextToken.charAt(0)) && tokens.get(i + 2).equals(StringConst.STOP)\n || tokens.get(i + 2).equals(StringConst.COMMA)) {\n sentences.add(joinSentence(sentence));\n sentence.clear();\n continue;\n }\n }\n\n if (token.matches(Regex.EOS_PUNCTUATION)) {\n\n // Added by Dat Quoc Nguyen\n if (nextToken.equals(\"\\\"\") || nextToken.equals(\"''\")) {\n int count = 0;\n for (String senToken : sentence) {\n if (senToken.equals(\"\\\"\") || senToken.equals(\"''\"))\n count += 1;\n }\n if (count % 2 == 1)\n continue;\n }\n\n // If the current sentence is in the quote or in the brace\n if (StringUtils.isBrace(nextToken) || nextToken.isEmpty() || Character.isLowerCase(nextToken.charAt(0))\n || nextToken.equals(StringConst.COMMA) || Character.isDigit(nextToken.charAt(0))) {\n continue;\n }\n\n // Sentence starts with its order number\n if (sentence.size() == 2 && token.equals(StringConst.STOP)) {\n if (Character.isDigit(beforeToken.charAt(0))) {\n continue;\n }\n if (Character.isLowerCase(beforeToken.charAt(0))) {\n continue;\n }\n if (Character.isUpperCase(beforeToken.charAt(0))) {\n if (beforeToken.length() == 1) {\n continue;\n }\n }\n }\n\n sentences.add(joinSentence(sentence));\n sentence.clear();\n }\n }\n\n return sentences;\n }\n\n public static String joinSentence(List<String> tokens) {\n StringBuffer sent = new StringBuffer();\n int length = tokens.size();\n String token;\n for (int i = 0; i < length; i++) {\n token = tokens.get(i);\n if (token.isEmpty() || token == null || token.equals(StringConst.SPACE)) {\n continue;\n }\n sent.append(token);\n if (i < length - 1)\n sent.append(StringConst.SPACE);\n }\n return sent.toString().trim();\n }\n}\n\ninterface StringConst\n{\n public static final String BOS = \"<s>\";\n public static final String EOS = \"</s>\";\n\n public static final String SPACE = \" \";\n public static final String COMMA = \",\";\n public static final String STOP = \".\";\n public static final String COLON = \":\";\n public static final String UNDERSCORE = \"_\";\n}\n\nclass Regex\n{\n\n public static final String ELLIPSIS = \"\\\\.{2,}\";\n\n public static final String EMAIL = \"([\\\\w\\\\d_\\\\.-]+)@(([\\\\d\\\\w-]+)\\\\.)*([\\\\d\\\\w-]+)\";\n\n public static final String FULL_DATE = \"(0?[1-9]|[12][0-9]|3[01])(\\\\/|-|\\\\.)(1[0-2]|(0?[1-9]))((\\\\/|-|\\\\.)\\\\d{4})\";\n\n public static final String MONTH = \"(1[0-2]|(0?[1-9]))(\\\\/)\\\\d{4}\";\n\n public static final String DATE = \"(0?[1-9]|[12][0-9]|3[01])(\\\\/)(1[0-2]|(0?[1-9]))\";\n\n public static final String TIME = \"(\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\d)|((0?\\\\d|1\\\\d|2[0-3])(:|h)(0?\\\\d|[1-5]\\\\d)(’|'|p|ph)?)\";\n\n public static final String MONEY = \"\\\\p{Sc}\\\\d+([\\\\.,]\\\\d+)*|\\\\d+([\\\\.,]\\\\d+)*\\\\p{Sc}\";\n\n public static final String PHONE_NUMBER = \"(\\\\(?\\\\+\\\\d{1,2}\\\\)?[\\\\s\\\\.-]?)?\\\\d{2,}[\\\\s\\\\.-]?\\\\d{3,}[\\\\s\\\\.-]?\\\\d{3,}\";\n\n public static final String URL = \"(((https?|ftp):\\\\/\\\\/|www\\\\.)[^\\\\s/$.?#].[^\\\\s]*)|(https?:\\\\/\\\\/)?(www\\\\.)?[-a-zA-Z0-9@:%._\\\\+~#=]{2,256}\\\\.[a-z]{2,6}\\\\b([-a-zA-Z0-9@:%_\\\\+.~#?&//=]*)\";\n\n public static final String NUMBER = \"[-+]?\\\\d+([\\\\.,]\\\\d+)*%?\\\\p{Sc}?\";\n\n public static final String PUNCTUATION = \",|\\\\.|:|\\\\?|!|;|-|_|\\\"|'|“|”|\\\\||\\\\(|\\\\)|\\\\[|\\\\]|\\\\{|\\\\}|⟨|⟩|«|»|\\\\\\\\|\\\\/|\\\\‘|\\\\’|\\\\“|\\\\â€�|…|…|‘|’|·\";\n\n public static final String SPECIAL_CHAR = \"\\\\~|\\\\@|\\\\#|\\\\^|\\\\&|\\\\*|\\\\+|\\\\-|\\\\–|<|>|\\\\|\";\n\n public static final String EOS_PUNCTUATION = \"(\\\\.+|\\\\?|!|…)\";\n\n public static final String NUMBERS_EXPRESSION = NUMBER + \"([\\\\+\\\\-\\\\*\\\\/]\" + NUMBER + \")*\";\n\n public static final String SHORT_NAME = \"([\\\\p{L}]+([\\\\.\\\\-][\\\\p{L}]+)+)|([\\\\p{L}]+-\\\\d+)\";\n\n public static final String WORD_WITH_HYPHEN = \"\\\\p{L}+-\\\\p{L}+(-\\\\p{L}+)*\";\n\n public static final String ALLCAP = \"[A-Z]+\\\\.[A-Z]+\";\n\n private static List<String> regexes = null;\n\n private static List<String> regexIndex = null;\n\n public static List<String> getRegexList()\n {\n if (regexes == null) {\n regexes = new ArrayList<String>();\n regexIndex = new ArrayList<String>();\n\n regexes.add(ELLIPSIS);\n regexIndex.add(\"ELLIPSIS\");\n\n regexes.add(EMAIL);\n regexIndex.add(\"EMAIL\");\n\n regexes.add(URL);\n regexIndex.add(\"URL\");\n\n regexes.add(FULL_DATE);\n regexIndex.add(\"FULL_DATE\");\n\n regexes.add(MONTH);\n regexIndex.add(\"MONTH\");\n\n regexes.add(DATE);\n regexIndex.add(\"DATE\");\n\n regexes.add(TIME);\n regexIndex.add(\"TIME\");\n\n regexes.add(MONEY);\n regexIndex.add(\"MONEY\");\n\n regexes.add(PHONE_NUMBER);\n regexIndex.add(\"PHONE_NUMBER\");\n\n regexes.add(SHORT_NAME);\n regexIndex.add(\"SHORT_NAME\");\n\n regexes.add(NUMBERS_EXPRESSION);\n regexIndex.add(\"NUMBERS_EXPRESSION\");\n\n regexes.add(NUMBER);\n regexIndex.add(\"NUMBER\");\n\n regexes.add(WORD_WITH_HYPHEN);\n regexIndex.add(\"WORD_WITH_HYPHEN\");\n\n regexes.add(PUNCTUATION);\n regexIndex.add(\"PUNCTUATION\");\n\n regexes.add(SPECIAL_CHAR);\n regexIndex.add(\"SPECIAL_CHAR\");\n\n regexes.add(ALLCAP);\n regexIndex.add(\"ALLCAP\");\n\n }\n\n return regexes;\n }\n\n public static int getRegexIndex(String regex)\n {\n return regexIndex.indexOf(regex.toUpperCase());\n }\n public static void main(String[] args) throws IOException {\n List<String> tokens = Tokenizer.tokenize(\"93% 9-10 anh-yeu-em\");\n\n for(String token : tokens) {\n System.out.print(token + \" \");\n }\n }\n}" } ]
30
chimodzi/lab_files
https://github.com/chimodzi/lab_files
4bb8ff983fe2051130bcd489c4c6cec18969c2cd
bc42d0a60224a2bb94bb6a1646ec3740274cb96d
8a716773a829eb81c7f91f8bcec268be76017c78
refs/heads/main
2023-08-18T12:53:04.736113
2021-09-23T08:10:32
2021-09-23T08:10:32
407,537,677
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7846153974533081, "alphanum_fraction": 0.7846153974533081, "avg_line_length": 31.5, "blob_id": "b73a121724dff778b8d586a851f92a863362fee9", "content_id": "ae909ed120533ca72f5cbd830a1799c89b982a8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 65, "license_type": "no_license", "max_line_length": 52, "num_lines": 2, "path": "/README.md", "repo_name": "chimodzi/lab_files", "src_encoding": "UTF-8", "text": "# lab_files\nProgram is creating files for 'KNU' laboratory works\n" }, { "alpha_fraction": 0.5772861242294312, "alphanum_fraction": 0.5796459913253784, "avg_line_length": 40.91139221191406, "blob_id": "616f567b1fc0033287dd32547654c51c27089ae7", "content_id": "72fcad04b3cc99227ab71dbc68ca7b99049fb1a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3840, "license_type": "no_license", "max_line_length": 114, "num_lines": 79, "path": "/file_creator.py", "repo_name": "chimodzi/lab_files", "src_encoding": "UTF-8", "text": "\"\"\"Программа создаёт файлы для лабораторной работы\"\"\"\r\nimport os.path, json\r\nfrom tkinter import Tk, filedialog\r\n\r\n\r\ndef ask_directory():\r\n \"\"\"предлагает пользователю выбрать папку\"\"\"\r\n if input(\"если вы хотите выбрать папку для создания файлов введите 'YES',\"\r\n \" если хотите создать файлы в папке программы нажмите 'ENTER': \").upper() == 'YES':\r\n root = Tk() # pointing root to Tk() to use it as Tk() in program.\r\n root.withdraw() # Hides small tkinter window.\r\n root.attributes('-topmost', True) # Opened windows will be active. above all windows despite of selection.\r\n file_directory = filedialog.askdirectory() # Returns opened path as str\r\n return file_directory\r\n return ''\r\n\r\n\r\ndef json_data(data, used_directory=True):\r\n \"\"\"подтягивает данные из data.json\"\"\"\r\n with open('lessons.json', 'r') as lessons_data:\r\n lessons = json.load(lessons_data)\r\n first_task, last_task = map(int, lessons[f\"{data['last_lesson'] + 1}\"].split())\r\n if used_directory:\r\n with open('data.json', 'w+') as user_data:\r\n data['last_lesson'] += 1\r\n json.dump(data, user_data)\r\n return data['user_name'], data['last_lesson'], (first_task, last_task), data['directory']\r\n else:\r\n data['directory'] = ask_directory()\r\n with open('data.json', 'w+') as user_data:\r\n data['last_lesson'] += 1\r\n json.dump(data, user_data)\r\n return data['user_name'], data['last_lesson'], (first_task, last_task), data['directory']\r\n\r\n\r\ndef new_data(data):\r\n \"\"\"позволяет пользователю ввести новые данные\"\"\"\r\n surname = input('Введите свою фамилию: ')\r\n lesson = int(input('Ведите номер урока: '))\r\n first_task, last_task = map(int, input('Введите 1-ое и последнее задание ').split())\r\n data['user_name'] = surname\r\n data['last_lesson'] = lesson\r\n with open('data.json', 'w+') as user_data:\r\n data['directory'] = directory = ask_directory()\r\n json.dump(data, user_data)\r\n return surname, lesson, (first_task, last_task), directory\r\n\r\ndef get_data():\r\n \"\"\"функция получает данные\"\"\"\r\n with open('data.json', 'r') as user_data:\r\n try:\r\n data = json.load(user_data)\r\n except json.decoder.JSONDecodeError:\r\n data = {}\r\n if data:\r\n if data['directory']:\r\n if input(f\"Введите 'YES' если вы хотите использовать фамилию: {data['user_name']}\"\r\n f\" и создать файлы для {data['last_lesson'] + 1}-го \"\r\n f\"занятия в папке {data['directory']}: \").upper() == 'YES':\r\n return json_data(data)\r\n else:\r\n if input(f\"Введите 'YES' если вы хотите использовать фамилию: {data['user_name']}\"\r\n f\" и создать файлы для {data['last_lesson'] + 1}-го занятия: \").upper() == 'YES':\r\n return json_data(data, False)\r\n return new_data(data)\r\n\r\n\r\ndef create_files():\r\n \"\"\"создаёт файлы\"\"\"\r\n surname, lesson, (first_task, last_task), directory = get_data()\r\n if directory:\r\n for task in range(first_task, last_task + 1):\r\n f = open(f\"{directory}/\" + f'{surname}_{lesson}_{task}.py', 'w+')\r\n else:\r\n for task in range(first_task, last_task + 1):\r\n f = open(f'{surname}_{lesson}_{task}.py', 'w+')\r\n\r\nif __name__ == '__main__':\r\n create_files()\r\n" } ]
2
ykorman/ufb_schedule
https://github.com/ykorman/ufb_schedule
123901a42fadbecfaa7c40aafa49f7d7ecdff8c9
b25266b744813ebc1753923640c00d2a96f91607
a1f2a23029979731e95e0246cc6583526fc9504f
refs/heads/master
2021-01-22T23:58:33.785049
2012-12-29T21:22:44
2012-12-29T21:22:44
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7466592192649841, "alphanum_fraction": 0.7488864064216614, "avg_line_length": 47.5405387878418, "blob_id": "cb9d602eaef66f1a98580c400824a0a1c73789d9", "content_id": "8f2d26f3c2d0c82fc96b27f4eb39a4334fdcee00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1796, "license_type": "no_license", "max_line_length": 200, "num_lines": 37, "path": "/schedule/views.py", "repo_name": "ykorman/ufb_schedule", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport datetime\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import RequestContext\nfrom django.contrib.auth.decorators import login_required\nfrom django.template import Context, loader\nfrom django.shortcuts import get_object_or_404, render_to_response\nfrom schedule.models import Registration, Workout, Trainee\n\n@login_required(login_url='login')\ndef trainee_schedule(request):\n my_regs = Registration.objects.filter(trainee__user__username__exact=request.user.username)\n trainee = Trainee.objects.get(user__exact=request.user)\n t = loader.get_template('my_schedule.html')\n c = Context({'my_regs': my_regs, 'username': request.user.username, 'credit': trainee.credit, })\n# return HttpResponse('hello Mr. ' + request.user.username + '\\n' + str(reg))\n return HttpResponse(t.render(c))\n\n@login_required(login_url='login')\ndef workout_select(request):\n available_workouts = Workout.objects.filter(when__gt=datetime.datetime.now())\n trainee = Trainee.objects.get(user__exact=request.user)\n return render_to_response('workout_select.html', { 'available_workouts': available_workouts, 'username': request.user.username, 'credit': trainee.credit, }, context_instance=RequestContext(request))\n\n@login_required(login_url='login')\ndef workout_register(request):\n try:\n selected_workout = Workout.objects.get(pk=request.POST['workout'])\n except (KeyError, Workout.DoesNotExist):\n return render_to_response('workout_select.html', {\n 'error_message': \"You didn't select a workout.\",\n }, context_instance=RequestContext(request))\n else:\n trainee = Trainee.objects.get(user=request.user)\n reg = Registration(trainee=trainee, workout=selected_workout)\n reg.save()\n return HttpResponseRedirect('my_schedule')\n" }, { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 29.83333396911621, "blob_id": "3c450339d193260262dc62f2dadfbb6fe9cb92e6", "content_id": "dc35afd0e2fee9b5dd5201ed822319961096c791", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 186, "license_type": "no_license", "max_line_length": 58, "num_lines": 6, "path": "/schedule/admin.py", "repo_name": "ykorman/ufb_schedule", "src_encoding": "UTF-8", "text": "from schedule.models import Trainee, Workout, Registration\nfrom django.contrib import admin\n\nadmin.site.register(Trainee)\nadmin.site.register(Workout)\nadmin.site.register(Registration)\n\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.7036231756210327, "avg_line_length": 28.978260040283203, "blob_id": "3fc4ce115c6ca3f1a05a5ee3f636ddfd6e1b9847", "content_id": "661cc1e00046236808dbb737eb47ed27254f167d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1500, "license_type": "no_license", "max_line_length": 98, "num_lines": 46, "path": "/schedule/models.py", "repo_name": "ykorman/ufb_schedule", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom django.contrib.auth import models as auth_models\n\n# Create your models here.\n\nclass Trainee(models.Model):\n user = models.OneToOneField(auth_models.User, verbose_name=u'שם מתאמן')\n credit = models.PositiveSmallIntegerField(verbose_name=u'קרדיט')\n \n def __unicode__(self):\n return unicode(self.user)\n\n class Meta:\n app_label = u'לוח אימונים'\n verbose_name = u'מתאמן'\n verbose_name_plural = u'מתאמנים'\n db_table = 'schedule_trainee' \n\n\nclass Workout(models.Model):\n when = models.DateTimeField(verbose_name=u'תאריך ושעת האימון')\n numOfTrainees = models.PositiveSmallIntegerField(verbose_name=u'מספר מתאמנים רשום', default=12)\n lenghInMinutes = models.PositiveSmallIntegerField(verbose_name=u'אורך האימון בדקות', default=60)\n \n def __unicode__(self):\n return unicode(self.when)\n\n class Meta:\n app_label = u'לוח אימונים'\n verbose_name = u'אימון'\n verbose_name_plural = u'אימונים'\n db_table = 'schedule_workout' \n\nclass Registration(models.Model):\n trainee = models.ForeignKey(Trainee)\n workout = models.ForeignKey(Workout)\n \n def __unicode__(self):\n return unicode(str(self.trainee.user) + ' on ' + str(self.workout.when))\n \n class Meta:\n app_label = u'לוח אימונים'\n verbose_name = u'רישום'\n verbose_name_plural = u'רישומים'\n db_table = 'schedule_registration' \n" }, { "alpha_fraction": 0.6835680603981018, "alphanum_fraction": 0.6835680603981018, "avg_line_length": 37.03571319580078, "blob_id": "b594ac7d15142f3f85c041eae86501c2f7dfad97", "content_id": "49e24208e2ac5383407b7f8c3ff60f829c2efdb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1065, "license_type": "no_license", "max_line_length": 100, "num_lines": 28, "path": "/urls.py", "repo_name": "ykorman/ufb_schedule", "src_encoding": "UTF-8", "text": "from django.conf.urls.defaults import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'ufb_schedule.views.home', name='home'),\n # url(r'^ufb_schedule/', include('ufb_schedule.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n\n # auth\n url(r'^schedule/login$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),\n url(r'^schedule/logout$', 'django.contrib.auth.views.logout', {'template_name': 'logout.html'}),\n\n # schedule\n url(r'^schedule/my_schedule$', 'schedule.views.trainee_schedule'),\n # select workout\n url(r'^schedule/workout_select$', 'schedule.views.workout_select'),\n # workout register\n url(r'^schedule/workout_register$', 'schedule.views.workout_register'),\n)\n" } ]
4
Miftaudeen/django-swingtime
https://github.com/Miftaudeen/django-swingtime
5d7cd4a7b1def633e2838d175892000d66674358
a2ef774eecf65c5440b39aead79c97aca8ef6a07
6e1a4e4a991c881a955efec2f478046dc4f8a1ef
refs/heads/master
2020-03-19T06:23:37.990805
2018-06-04T15:50:22
2018-06-04T15:50:22
136,015,280
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 30, "blob_id": "0873037e794fad9299d0a598abbaee7cd887b8c8", "content_id": "97da32a7d7909cc11071fd430f8a62ed7142a05e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 65, "license_type": "permissive", "max_line_length": 32, "num_lines": 2, "path": "/src/swingtime/tests/sample_tests.py", "repo_name": "Miftaudeen/django-swingtime", "src_encoding": "UTF-8", "text": "\nfrom django.test import TestCase\nfrom django.db import models\n\n\n" }, { "alpha_fraction": 0.6092519760131836, "alphanum_fraction": 0.6092519760131836, "avg_line_length": 41.33333206176758, "blob_id": "6fd69a4672c5ea7ccb10a6cba7d893cc0d87b793", "content_id": "230af215a24a9f1b12c43718073daf1c50f58f79", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1016, "license_type": "permissive", "max_line_length": 100, "num_lines": 24, "path": "/demo/urls.py", "repo_name": "Miftaudeen/django-swingtime", "src_encoding": "UTF-8", "text": "import os\nfrom django.conf import settings\nfrom django.contrib import admin\nfrom django.views.static import serve\nfrom django.urls import path, include\nfrom django.views.generic import TemplateView, RedirectView\n\nadmin.autodiscover()\ndoc_root = os.path.join(os.path.dirname(settings.PROJECT_DIR), 'docs/build/html')\n\nurlpatterns = ['',\n path('^$', TemplateView, {'template': 'intro.html'}, name='demo-home'),\n path(r'^karate/', include('karate.urls')),\n path(r'^admin/docs/', include('django.contrib.admindocs.urls')),\n path(r'^admin/', include(admin.site.urls)),\n path(r'^docs/?$', RedirectView, dict(url='/docs/index.html')),\n path(r'^docs/(?P<path>.*)$', serve, dict(document_root=doc_root, show_indexes=False))\n ]\n\nif settings.DEBUG:\n data = dict(document_root=settings.MEDIA_ROOT, show_indexes=True)\n urlpatterns += ['',\n path(r'^media/(?P<path>.*)$', serve, data),\n ]\n" }, { "alpha_fraction": 0.5928753018379211, "alphanum_fraction": 0.5928753018379211, "avg_line_length": 42.66666793823242, "blob_id": "417fc519765702f5fd105a26a2b47e717df5b0a1", "content_id": "49ec21656673609eb402f8c5ea2250e40155b03b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 393, "license_type": "permissive", "max_line_length": 96, "num_lines": 9, "path": "/demo/karate/urls.py", "repo_name": "Miftaudeen/django-swingtime", "src_encoding": "UTF-8", "text": "from django.urls import path, include\nfrom django.views.generic import TemplateView\nfrom . import views\n\nurlpatterns = ['',\n path(r'^$', TemplateView, {'template': 'karate.html'}, name='karate-home'),\n path(r'^swingtime/events/type/([^/]+)/$', views.event_type, name='karate-event'),\n path(r'^swingtime/', include('swingtime.urls')),\n ]\n" }, { "alpha_fraction": 0.7446808218955994, "alphanum_fraction": 0.7446808218955994, "avg_line_length": 42, "blob_id": "fbcd217173d0a9f402e36a805c37cd10d942a24e", "content_id": "de94643debf5eb8bcb32dac9ce11ac6660483d32", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 47, "license_type": "permissive", "max_line_length": 42, "num_lines": 1, "path": "/src/swingtime/tests/__init__.py", "repo_name": "Miftaudeen/django-swingtime", "src_encoding": "UTF-8", "text": "\n\n\nfrom swingtime.tests.sample_tests import *\n\n" }, { "alpha_fraction": 0.5965517163276672, "alphanum_fraction": 0.6034482717514038, "avg_line_length": 21.384614944458008, "blob_id": "dd0dd3abb906405bd87e07ba3e31d745c6a5a817", "content_id": "1bb0c1ff5f184a3f07c939a501a2887af0f69461", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 290, "license_type": "permissive", "max_line_length": 44, "num_lines": 13, "path": "/setup.py", "repo_name": "Miftaudeen/django-swingtime", "src_encoding": "UTF-8", "text": "from setuptools import setup, find_packages\n\nsetup(\n name = \"django-swingtime\",\n version = \"0.1-dev\",\n description = \"planning app for django.\",\n author = 'Lacombe Antonin',\n packages = find_packages('src'),\n package_dir = {'': 'src'},\n install_requires = [\n 'setuptools',\n ],\n)" } ]
5
mcallb/youtube-stream
https://github.com/mcallb/youtube-stream
48695768274c16a7522ba427cc8711d0282eb9c2
c491013361fec2f26c468d74e4aeef660b19231b
db25928fd2895193463f4bcbf7fa65ef32dd9fdb
refs/heads/master
2021-01-18T02:37:20.535905
2017-03-08T02:01:02
2017-03-08T02:01:02
84,266,693
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6208053827285767, "alphanum_fraction": 0.6322147846221924, "avg_line_length": 26.10909080505371, "blob_id": "f1e3d71c6bb62e8d953157d706b5fc975dc18e3f", "content_id": "d5725a55b6d1a6fb56df8f24d3cb7d705a2fde7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1490, "license_type": "no_license", "max_line_length": 72, "num_lines": 55, "path": "/youtube-check.py", "repo_name": "mcallb/youtube-stream", "src_encoding": "UTF-8", "text": "import os, sys\nimport requests\nimport boto3\nfrom credstash import getSecret\n\n#os.environ[\"AWS_PROFILE\"] = \"mcallb\"\n\nyoutube_api_key = getSecret('youtube-api-key')\n\nurl = 'https://www.googleapis.com/youtube/v3/search'\nheaders = {'Cache-Control': 'no-cache'}\npayload = {\n 'part': 'snippet,id',\n 'channelId': 'UCe3yFIa92jfAHEu4Ql4u69A',\n 'type': 'video',\n 'eventType': 'live',\n 'key': youtube_api_key\n}\n\ndef send_sqs_message(message):\n sqs = boto3.resource('sqs')\n queue = sqs.get_queue_by_name(QueueName='youtube_stream_status')\n response = queue.send_message(MessageBody=message)\n\ndef read_sqs_messages():\n sqs = boto3.resource('sqs')\n queue = sqs.get_queue_by_name(QueueName='youtube_stream_status')\n messages = queue.receive_messages()\n for message in messages:\n print message.body\n message.delete()\n\ndef lambda_handler(event, context):\n try:\n r = requests.get(url, params=payload, headers=headers)\n except requests.exceptions.RequestException as e:\n print e\n sys.exit(1)\n\n parsed_json = r.json()\n\n if r.status_code <> 200:\n print 'Something bad happened status code: %s' % (r.status_code)\n sys.exit(1)\n else:\n\n try:\n # The stream is live\n parsed_json['items'][0]['snippet']['liveBroadcastContent']\n send_sqs_message(\"live\")\n except IndexError:\n # The stream is down\n send_sqs_message(\"down\")\n\n #read_sqs_messages()" } ]
1
stellaconyer/Week1Exercise
https://github.com/stellaconyer/Week1Exercise
bc9dbf509c944af38a0bff6c33aa1a189b12735c
e3f8a9798dafc3d0fa3f980312ea3fe40f942e24
e2fcffe1d167f73f69ce298a9d64f524c7e06503
refs/heads/master
2022-05-01T13:05:26.408607
2013-09-28T17:14:38
2013-09-28T17:14:38
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.720895528793335, "alphanum_fraction": 0.7298507690429688, "avg_line_length": 29.5, "blob_id": "1552cd1c896a813a402130117d6bd34c56c747fb", "content_id": "218db9136a8be608bddf6c16615360197dac03aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 670, "license_type": "no_license", "max_line_length": 64, "num_lines": 22, "path": "/week1project.py", "repo_name": "stellaconyer/Week1Exercise", "src_encoding": "UTF-8", "text": "import os\nimport shutil\n\n#create container folder for alphabet folders\nos.mkdir(\"alphabet_folder\")\n\n#create a separate folder for each letter of the alphabet\nfor i in range(97,123):\n letter = chr(i)\n os.mkdir(\"alphabet_folder/%s\" % letter)\n\n#create list of alphabet folders and list of user files\nalphabet_list = os.listdir(\"alphabet_folder\")\nuser_files = os.listdir(\"originalfiles\")\n \n#move each user file into a folder that corresponds to the first\n#letter of the user file\nfor a_user_file in zip_files:\n\tfirst_letter = a_user_file[0]\n\tsrc = \"originalfiles/%s\" % a_user_file\n\tdest = \"alphabet_folder/%s/%s\" % (first_letter, a_user_file)\n\tshutil.move(src,dest)" } ]
1
rakeshv191987/movie_recommender
https://github.com/rakeshv191987/movie_recommender
03a6088c4346ce1ee4986a833be724aa4fadb2ec
20e84567b50c2f053473ceb6228bab8b75c61524
f7859c89ede9fc1ec472154ac82a00c4334e8f4f
refs/heads/master
2020-05-22T12:24:57.000213
2014-10-14T15:04:59
2014-10-14T15:04:59
24,512,461
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5514211058616638, "alphanum_fraction": 0.5675851702690125, "avg_line_length": 33.52434539794922, "blob_id": "9e962371c55bd0ca49cce0f3f94d70adde8be2ee", "content_id": "c14f50a10fdd093424a7fd646f28d8c9f90f05ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9218, "license_type": "no_license", "max_line_length": 124, "num_lines": 267, "path": "/rec.py", "repo_name": "rakeshv191987/movie_recommender", "src_encoding": "UTF-8", "text": "# Run as $ python rec.py\n\nfrom math import sqrt\nimport random\nimport operator\n\ndef loadMovieLens(path='./data'):\n\t# Get movie titles\n\tmovies={}\n\tfor line in open(path+'/movies.dat'):\n\t\t(id,title)=line.split('|')[0:2]\n\t\tmovies[id]=title\n\t# Load data\n\tprefs={}\n\tfor line in open(path+'/ratings.dat'):\n\t\t(user,movieid,rating)=line.split('\\t')[0:3]\n\t\tprefs.setdefault(user,{})\n\t\tprefs[user][movies[movieid]]=float(rating)\n\treturn prefs\n\n# Pearson co-relation formula\ndef sim_pearson(prefs,p1,p2):\n\t# Get the list of mutually rated items \n\tsi={} \n\tfor item in prefs[p1]: \n\t\tif item in prefs[p2]: \n\t\t\tsi[item]=1 \n\t# Find the number of elements \n\tn=len(si) \n\t# if they are no ratings in common, return 0 \n\tif n==0:\n\t\t return 0 \n\t# Add up all the preferences \n\tsum1=sum([prefs[p1][it] for it in si]) \n\tsum2=sum([prefs[p2][it] for it in si]) \n\t# Sum up the squares \n\tsum1Sq=sum([pow(prefs[p1][it],2) for it in si]) \n\tsum2Sq=sum([pow(prefs[p2][it],2) for it in si]) \n\t# Sum up the products \n\tpSum=sum([prefs[p1][it]*prefs[p2][it] for it in si]) \n\t# Calculate Pearson score \n\tnum=pSum-(sum1*sum2/n) \n\tden=sqrt((sum1Sq-pow(sum1,2)/n)*(sum2Sq-pow(sum2,2)/n)) \n\tif den==0:\n\t\treturn 0 \n\tr=num/den\n\t# print 'the r is: ', r\n\treturn r\n\n# Returns a distance-based similarity score for person1 and person2\n# Euclidean distance score\ndef sim_distance(prefs,person1,person2): \n\t# Get the list of shared_items \n\tsi={} \n\tfor item in prefs[person1]: \n\t\tif item in prefs[person2]: \n\t\t\tsi[item]=1 \n\t# if they have no ratings in common, return 0 \n\tif len(si)==0: \n\t\treturn 0 \n\t# Add up the squares of all the differences \n\tsum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2) for item in prefs[person1] if item in prefs[person2]])\n\treturn 1/(1+sum_of_squares)\n\n# Adjusted cosine formula\ndef sim_cosine(prefs, p1, p2):\n\t si={}\n\t for item in prefs[p1]:\n\t if item in prefs[p2]: si[item]=1\n\t n = len(si)\n\t if n == 0 : return 0\n\t # calculate the averge rationg made by both users\n\t sum1 = sum([prefs[p1][it] for it in prefs[p1]]) \n\t sum2 = sum([prefs[p2][it] for it in prefs[p2]])\n\t ave_1 = sum1/len(prefs[p1])\n\t ave_2 = sum2/len(prefs[p2])\n\n\t pSum = sum([(prefs[p1][it]-ave_1) * (prefs[p2][it]-ave_2) for it in si])\n\t #\n\n\t sum1Sq = sum([pow(prefs[p1][it]-ave_1, 2) for it in si])\n\t sum2Sq = sum([pow(prefs[p2][it]-ave_2, 2) for it in si])\n\t #\n\t den = sqrt(sum1Sq) * sqrt(sum2Sq)\n\t if den == 0 : return 0\n\t r = pSum/den\n\t #print 'the r is : ', r\n\t return r\n\n\ndef calculateSimilarItems(prefs,n=30):\n\t# Create a dictionary of items showing which other items they\n\t# are most similar to.\n\tresult={}\n\t# Invert the preference matrix to be item-centric\n\titemPrefs = transformPrefs(prefs)\n\tc=0\n\tfor item in itemPrefs:\n\t\t# Status updates for large datasets\n\t\tc+=1\n\t\tif (c % 100 == 0): \n\t\t\tprint \"%d / %d\" % (c,len(itemPrefs))\n\t\t# Find the most similar items to this one\n\t\tscores=topMatches(itemPrefs,item,n=n,similarity=sim_pearson)\n\t\tresult[item]=scores\n\treturn result\n\ndef transformPrefs(prefs):\n\tresult={} \n\tfor person in prefs: \n\t\t# print 'person is',person\n\t\tfor item in prefs[person]: \n\t\t\t# print 'item in prefs[person]: ', item\n\t\t\tresult.setdefault(item,{}) \n\t\t\t# Flip item and person \n\t\t\tresult[item][person]=prefs[person][item] \n\treturn result\n\t\ndef topMatches(prefs,person,n=5,similarity=sim_pearson):\n\tscores=[(similarity(prefs,person,other),other) for other in prefs if other!=person]\n\t# Sort the list so the highest scores appear at the top \n\tscores.sort( )\n\tscores.reverse( )\n\treturn scores\n\n# User based CF recommendations\ndef getRecommendations(prefs,person,similarity=sim_pearson):\n\ttotals={} \n\tsimSums={} \n\tfor other in prefs: \n\t\t# don't compare me to myself \n\t\tif other==person: \n\t\t\tcontinue \n\t\tsim=similarity(prefs,person,other) \n\t\t# ignore scores of zero or lower \n\t\tif sim<=0: \n\t\t\tcontinue \n\t\tfor item in prefs[other]: \n\t\t\t# only score movies I haven't seen yet \n\t\t\tif item not in prefs[person] or prefs[person][item]==0: \n\t\t\t\t# Similarity * Score \n\t\t\t\ttotals.setdefault(item,0) \n\t\t\t\ttotals[item]+=prefs[other][item]*sim \n\t\t\t\t# Sum of similarities \n\t\t\t\tsimSums.setdefault(item,0) \n\t\t\t\tsimSums[item]+=sim\n\t# Create the normalized list\n\trankings=[(total/simSums[item],item) for item,total in totals.items()]\n\t# Return the sorted list \n\trankings.sort( ) \n\trankings.reverse( ) \n\treturn rankings\n\n# Item based CF recommendations\ndef getRecommendedItems(prefs,itemMatch,user):\n\tcount = 0\n\tuserRatings=prefs[user]\n\tscores={}\n\ttotalSim={}\n\t# Loop over items rated by this user\n\t# print 'user ratings items',userRatings.items()\n\tfor (item,rating) in userRatings.items():\n\t\t#print userRatings.items()\n\t\t# Loop over items similar to this one\n\n\t\tprint item\n\t\t# print len(itemMatch['Mr. Saturday Night (1992)'])\n\t\tt2 = open('b.txt', 'w+')\n\t\tt2.write(str(itemMatch))\n\t\tt2.close()\n\t\t# print itemMatch\n\t\tif not itemMatch.has_key(item):\n\t\t\tcount += 1\n\t\t\tprint 'not found'\n\t\t\tcontinue\n\t\tprint 'found'\n\t\t# print 'item match for one item: ',itemMatch[item]\n\t\tfor (similarity,item2) in itemMatch[item]:\n\t\t\t# Ignore if this user has already rated this item\n\t\t\tif item2 in userRatings: \n\t\t\t\tcontinue\n\t\t\tif similarity == 0: \n\t\t\t\tcontinue\n\t\t\t# Weighted sum of rating times similarity\n\t\t\tscores.setdefault(item2,0)\n\t\t\tscores[item2]+=(similarity)*rating\n\t\t\t# Sum of all the similarities\n\t\t\ttotalSim.setdefault(item2,0)\n\t\t\ttotalSim[item2] = totalSim[item2]+abs(similarity)\n\tprint 'the # of movies only watched by this user is: ',count\n\t# Divide each total score by total weighting to get an average \n\t# print 'what is this: ',totalSim[item]\n\t# print 'the total sim for one item is: ', totalSim[item2]\n\trankings=[(score/totalSim[item],item) for item,score in scores.items()]\n\t# Return the rankings from highest to lowest \n\trankings.sort( )\n\trankings.reverse( )\n\treturn rankings\n\n# Calculate RMSE values\ndef getRMSE(real_list, evaluate_list):\n\tresult = []\n\t# find all the squares\n\tfor real_movie in real_list:\n\t\tfor eval_movie in evaluate_list:\n\t\t\tif real_movie[0] == eval_movie[1]:\n\t\t\t\tprint 'find same movie'\n\t\t\t\tresult.append(pow(real_movie[1]-eval_movie[0], 2))\n\t\t\t\tbreak\n\t# sum up all the squares\n\tsum1 = sum([it for it in result])\n\t# Calculate the rmse\n\trmse = sqrt(sum1/len(real_list))\n\treturn rmse\n\ntotal = []\nfor this in range(0, 2):\n\tr = []\n\trmse = []\n\tfor i in range(0,1):\n\t\tb = random.randint(1,941)\n\t\tr.append(b)\n\n\t#uid = '925'\n\tfor one in r:\n\t\tuid = str(one)\n\t\tprefs = loadMovieLens()\n\t\tout1 = str(prefs)\n\t\tcopy = prefs.copy()\n\t\tdel copy[uid]\n\t\t# prune the prefs dataset\n\t\tremoved_list = []\n\t\tx = prefs[uid]\n\t\tuserLength = len(x)\n\t\tprint 'original user movie size is: ', userLength\n\t\tsorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))\n\t\tsorted_x.reverse()\n\t\tpruned_list = sorted_x[:userLength/2]\n\t\tpruned_user = {}\n\t\tfor item in pruned_list:\n\t\t\tpruned_user[item[0]] = item[1]\n\t\tremoved_list = sorted_x[userLength/2:]\n\t\tprint 'removed list b size is:', len(removed_list)\n\t\tprefs[uid] = pruned_user\n\t\t\n\t\titemsim = calculateSimilarItems(copy)\n\t\t#print itemsim\n\t\tevaluate_list = getRecommendedItems(prefs,itemsim,uid)\n\t\t#evaluate_list = getRecommendations(prefs,uid,similarity=sim_pearson)\n\t\tresult = getRMSE(removed_list , evaluate_list)\n\t\t####print 'removed list b is: ', removed_list\n\t\t####print 'evaluate_list is: ', evaluate_list[:100]\n\t\tprint 'user movie size is: ',len(prefs[uid]) \n\t\t#print 'itemsim size is:', len(itemsim)\n\t\tprint 'evaluate list size is: ', len(evaluate_list)\n\t\tprint 'rmse is: ', result \n\t\trmse.append((one, result))\n\t\t\n\tprint rmse\n\tsum_r = sum([item[1] for item in rmse])\n\taverage_r = sum_r/len(rmse)\n\t#print 'the smaples users are: ', r \n\t#print 'the average rmse of 10 samples is : ', average_r\n\ttotal.append(average_r)\n\t\nsum_final = sum([one for one in total])\nprint 'the average rmse is: ', sum_final/len(total)\n" }, { "alpha_fraction": 0.6226330995559692, "alphanum_fraction": 0.6279795169830322, "avg_line_length": 30.977941513061523, "blob_id": "9559ab01e54bfcab2a39da8355471531516cab9a", "content_id": "11d3eaacdf2dd2462c2ad64dc6af9db6e74cc0f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 4489, "license_type": "no_license", "max_line_length": 99, "num_lines": 136, "path": "/Rcode_for_graphs/analysis.R", "repo_name": "rakeshv191987/movie_recommender", "src_encoding": "UTF-8", "text": "#\r\n# exploratory analysis and plots for movielens data\r\n#\r\n\r\nrequire(data.table) # install.packages('data.table')\r\nrequire(plyr) # install.packages('plyr')\r\nrequire(ggplot2) # install.packages('ggplot2')\r\nrequire(scales) # install.packages('scales')\r\n\r\nsetwd(\"C:/Users/Rakesh/MS-COURSES/ML-f13/project/ml-100k/ml-100k\")\r\n# set plot theme\r\ntheme_set(theme_bw())\r\n\r\ndata.dir <- './'\r\n\r\n# read ratings from csv file\r\nsystem.time(\r\n ratings <- read.delim(sprintf('%s/u.csv', data.dir),\r\n sep='\\t', header=F,\r\n col.names=c('user.id','movie.id','rating','timestamp'),\r\n colClasses=c('integer','integer','numeric','integer'))\r\n)\r\nprint(object.size(ratings), units=\"Mb\")\r\n\r\n####################\r\n# brief look at data\r\n####################\r\n\r\n#head(ratings)\r\n#nrow(ratings)\r\n#ncol(ratings)\r\nstr(ratings)\r\n\r\n# convert to data table for quick aggregations\r\nratings <- data.table(ratings)\r\n\r\n####################\r\n# aggregate stats\r\n####################\r\n\r\n# compute aggregate stats\r\nsummary(ratings$rating)\r\n\r\n# plot distribution of ratings\r\np <- ggplot(data=ratings, aes(x=rating))\r\np <- p + geom_histogram()\r\np <- p + scale_y_continuous(labels=comma)\r\np <- p + xlab('Rating') + ylab('Count of Users')\r\nggsave(p, file=\"figures/rating_dist.pdf\", width=4, height=4)\r\n\r\n\r\n####################\r\n# per-movie stats\r\n####################\r\n\r\n# group ratings by movie\r\nsetkey(ratings, \"movie.id\")\r\n\r\n# aggregate ratings by movie, computing mean and number of ratings\r\nmovie.stats <- ratings[, list(num.ratings=length(rating), mean.rating=mean(rating)), by=\"movie.id\"]\r\n\r\n# compare to:\r\n# movie.stats <- ddply(ratings, \"movie.id\", summarize,\r\n# num.ratings=length(rating),\r\n# mean.rating=mean(rating))\r\n\r\n# compute movie-level summary stats\r\nsummary(movie.stats)\r\n\r\n# plot distribution of movie popularity\r\np <- ggplot(data=movie.stats, aes(x=num.ratings))\r\np <- p + geom_histogram()\r\np <- p + scale_x_continuous(labels=comma)\r\np <- p + scale_y_continuous(labels=comma)\r\np <- p + xlab('Number of Ratings got by Movie') + ylab('Count')\r\nggsave(p, file=\"figures/movie_popularity_dist.pdf\", width=4, height=4)\r\n\r\n# plot distribution of mean ratings by movie\r\np <- ggplot(data=movie.stats, aes(x=mean.rating))\r\np <- p + stat_density()\r\np <- p + scale_x_continuous(labels=comma)\r\np <- p + scale_y_continuous(labels=comma)\r\np <- p + theme(axis.text.y=element_blank(), axis.ticks.y=element_blank())\r\np <- p + xlab('Mean Rating by Movie') + ylab('Density')\r\nggsave(p, file=\"figures/mean_rating_by_movie_dist.pdf\", width=4, height=4)\r\n\r\n# rank movies by popularity and compute cdf\r\nsetkey(movie.stats, \"num.ratings\")\r\nmovie.stats <- transform(movie.stats,\r\n rank=rank(-num.ratings),\r\n cdf=rev(cumsum(rev(num.ratings)))/sum(num.ratings))\r\n\r\n# plot CCDF of movie popularity\r\np <- ggplot(data=movie.stats, aes(x=rank, y=cdf))\r\np <- p + geom_line()\r\np <- p + scale_x_continuous(labels=comma)\r\np <- p + scale_y_continuous(labels=percent)\r\np <- p + xlab('Movie Rank') + ylab('CDF')\r\nggsave(p, file=\"figures/movie_popularity_cdf.pdf\", width=4, height=4)\r\n\r\n\r\n####################\r\n# per-user stats\r\n####################\r\n\r\n# group ratings by user\r\nsetkey(ratings, \"user.id\")\r\n\r\n# aggregate ratings by user, computing mean and number of ratings\r\nuser.stats <- ratings[, list(num.ratings=length(rating), mean.rating=mean(rating)), by=\"user.id\"]\r\n\r\n# compute user-level stats\r\nsummary(user.stats)\r\n\r\n# plot distribution of user activity\r\np <- ggplot(data=user.stats, aes(x=num.ratings))\r\np <- p + geom_histogram()\r\np <- p + scale_x_continuous(labels=comma)\r\np <- p + scale_y_continuous(labels=comma)\r\np <- p + xlab('Number of Ratings by User') + ylab('Count')\r\nggsave(p, file=\"figures/user_activity_dist.pdf\", width=4, height=4)\r\n\r\n\r\nratings.with.movie.stats <- merge(ratings, movie.stats, by=\"movie.id\")\r\n\r\nsetkey(ratings.with.movie.stats, \"user.id\")\r\nuser.stats <- ratings.with.movie.stats[, list(median.rank=median(rank)), by=\"user.id\"]\r\n\r\n# plot distribution of user eccentricity\r\np <- ggplot(data=user.stats, aes(x=median.rank))\r\np <- p + stat_density()\r\np <- p + scale_x_log10(labels=comma)\r\np <- p + scale_y_continuous(labels=comma)\r\np <- p + theme(axis.text.y=element_blank(), axis.ticks.y=element_blank())\r\np <- p + xlab('User eccentricity') + ylab('Density')\r\nggsave(p, file=\"figures/user_eccentricity_dist.pdf\", width=4, height=4)\r\n\r\n\r\n" }, { "alpha_fraction": 0.6462167501449585, "alphanum_fraction": 0.6854805946350098, "avg_line_length": 33.463768005371094, "blob_id": "b9644f31299aed1dd95ec7e549ce4087392234f9", "content_id": "cff7b58058a4140a08adbea77635c1e01a591839", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2449, "license_type": "no_license", "max_line_length": 84, "num_lines": 69, "path": "/Rcode_for_graphs/recommend.R", "repo_name": "rakeshv191987/movie_recommender", "src_encoding": "WINDOWS-1252", "text": "# Load required library\r\nlibrary(recommenderlab) # package being evaluated\r\nlibrary(ggplot2) # For plots\r\n \r\n# Load the data we are going to work with\r\ndata(MovieLense)\r\nMovieLense\r\n# 943 x 1664 rating matrix of class ‘realRatingMatrix’ with 99392 ratings.\r\n \r\n# Visualizing a sample of this\r\nimage(sample(MovieLense, 500), main = \"Raw ratings\")\r\n\r\n# Visualizing ratings\r\nqplot(getRatings(MovieLense), binwidth = 1,\r\nmain = \"Histogram of ratings\", xlab = \"Rating\")\r\nsummary(getRatings(MovieLense)) # Skewed to the right\r\n# Min. 1st Qu. Median Mean 3rd Qu. Max.\r\n# 1.00 3.00 4.00 3.53 4.00 5.00\r\n\r\n# How about after normalization?\r\nqplot(getRatings(normalize(MovieLense, method = \"Z-score\")),\r\nmain = \"Histogram of normalized ratings\", xlab = \"Rating\")\r\nsummary(getRatings(normalize(MovieLense, method = \"Z-score\"))) # seems better\r\n# Min. 1st Qu. Median Mean 3rd Qu. Max.\r\n# -4.8520 -0.6466 0.1084 0.0000 0.7506 4.1280 \r\n\r\n# How many movies did people rate on average\r\nqplot(rowCounts(MovieLense), binwidth = 10,\r\nmain = \"Movies Rated on average\",\r\nxlab = \"# of users\",\r\nylab = \"# of movies rated\")\r\n# Seems people get tired of rating movies at a logarithmic pace. But most rate some.\r\n\r\n# What is the mean rating of each movie\r\nqplot(colMeans(MovieLense), binwidth = .1,\r\nmain = \"Mean rating of Movies\",\r\nxlab = \"Rating\",\r\nylab = \"# of movies\")\r\n \r\n# The big spike on 1 suggests that this could also be intepreted as binary\r\n# In other words, some people don't want to see certain movies at all.\r\n# Same on 5 and on 3.\r\n# We will give it the binary treatment later\r\n\r\nrecommenderRegistry$get_entries(dataType = \"realRatingMatrix\")\r\n# We have a few options\r\n \r\n# Let's check some algorithms against each other\r\nscheme <- evaluationScheme(MovieLense, method = \"split\", train = .9,\r\nk = 1, given = 10, goodRating = 4)\r\n \r\nscheme\r\n\r\nalgorithms <- list(\r\n# `random items` = list(name = \"RANDOM\", param = NULL),\r\n# `popular items` = list(name = \"POPULAR\", param = NULL),\r\n `user-based CF` = list(name = \"UBCF\", param = list(method = \"Cosine\", nn = 50)),\r\n `item-based CF` = list(name = \"IBCF\", param = list(method = \"Cosine\", k = 50)),\r\n 'SVD CF' = list(name = \"SVD\", param=list(method = \"Cosine\"))\r\n )\r\n\r\n# run algorithms, predict next n movies\r\nresults <- evaluate(scheme, algorithms, n=c(1, 3, 5, 10, 15, 20))\r\n \r\n# Draw ROC curve\r\nplot(results, annotate = 1:4, legend=\"topleft\")\r\n \r\n# See precision / recall\r\nplot(results, \"prec/rec\", annotate=3)" } ]
3
Kuzj/Adafruit_Python_BME280
https://github.com/Kuzj/Adafruit_Python_BME280
9c41b00a0d40cf552a04cbb3bfddd383472a5eca
f028724cb1109b2c3acc353edc436b84e628409e
82b6a61b30a94a25f8475150bf74826d88148ff6
refs/heads/master
2020-11-27T01:54:04.626606
2020-04-06T15:11:54
2020-04-06T15:11:54
229,262,803
0
0
MIT
2019-12-20T12:41:07
2019-12-17T20:12:55
2018-08-13T04:47:20
null
[ { "alpha_fraction": 0.5752401351928711, "alphanum_fraction": 0.6027747988700867, "avg_line_length": 37.727272033691406, "blob_id": "07e82e78310e930af0683966b341fe7b2c1d74a1", "content_id": "adf3e5b880c17de67127665a0dc4a139f98d5409", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4685, "license_type": "permissive", "max_line_length": 87, "num_lines": 121, "path": "/_spidev.py", "repo_name": "Kuzj/Adafruit_Python_BME280", "src_encoding": "UTF-8", "text": "import logging\nimport spidev\n\nlogging.basicConfig()\n\nWRITE = 0x7F\n\nclass Device(object):\n def __init__(self, bus, dev):\n self._dev = spidev.SpiDev()\n self._dev.open(bus,dev)\n self._logger = logging.getLogger('Spi.Device.Bus.{0}.Dev.{1}'.format(bus, dev))\n #self._logger.setLevel(logging.DEBUG)\n\n def write8(self, register, value):\n \"\"\"Write an 8-bit value to the specified register.\"\"\"\n value = value & 0xFF\n #self._bus.write_byte_data(self._dev, register, value)\n to_send = []\n to_send.append(register&WRITE)\n to_send.append(value)\n self._dev.xfer2(to_send)\n self._logger.debug(\"Wrote 0x%02X to register 0x%02X\",\n value, register)\n\n def write16(self, register, value):\n \"\"\"Write a 16-bit value to the specified register.\"\"\"\n value = value & 0xFFFF\n #self._bus.write_word_data(self._dev, register, value)\n to_send = []\n to_send.append(register&WRITE)\n to_send.append(value >> 8)\n to_send.append(value&0xff)\n self._logger.debug(\"Wrote 0x%04X to register pair 0x%02X, 0x%02X\",\n value, register, register+1)\n\n def writeList(self, register, data):\n \"\"\"Write bytes to the specified register.\"\"\"\n #self._bus.write_i2c_block_data(self._dev, register, data)\n to_send = []\n to_send.append(register&WRITE)\n to_send.extend(data)\n self._logger.debug(\"Wrote to register 0x%02X: %s\",\n register, data)\n\n def readList(self, register, length):\n \"\"\"Read a length number of bytes from the specified register. Results\n will be returned as a bytearray.\"\"\"\n #results = self._bus.read_i2c_block_data(self._dev, register, length)\n to_send = []\n to_send.append(register)\n to_send.extend([0]*length)\n results = self._dev.xfer2(to_send)[1:]\n self._logger.debug(\"Read the following from register 0x%02X: %s\",\n register, results)\n return results\n\n def readU8(self, register):\n \"\"\"Read an unsigned byte from the specified register.\"\"\"\n #result = self._bus.read_byte_data(self._dev, register) & 0xFF\n to_send = []\n to_send.append(register)\n to_send.append(0)\n result = self._dev.xfer2(to_send)[1]\n self._logger.debug(\"Read 0x%02X from register 0x%02X\",\n result, register)\n return result\n\n def readS8(self, register):\n \"\"\"Read a signed byte from the specified register.\"\"\"\n result = self.readU8(register)\n if result > 127:\n result -= 256\n return result\n\n def readU16(self, register, little_endian=True):\n \"\"\"Read an unsigned 16-bit value from the specified register, with the\n specified endianness (default little endian, or least significant byte\n first).\"\"\"\n #result = self._bus.read_word_data(self._dev,register) & 0xFFFF\n to_send = []\n to_send.append(register)\n to_send.extend([0,0])\n reg,d1,d2 = self._dev.xfer2(to_send)\n result = ((d1<<8)+d2)\n self._logger.debug(\"Read 0x%04X from register pair 0x%02X, 0x%02X\",\n result, register, register+1)\n # Swap bytes if using big endian because read_word_data assumes little\n # endian on ARM (little endian) systems.\n if not little_endian:\n result = ((result << 8) & 0xFF00) + (result >> 8)\n return result\n\n def readS16(self, register, little_endian=True):\n \"\"\"Read a signed 16-bit value from the specified register, with the\n specified endianness (default little endian, or least significant byte\n first).\"\"\"\n result = self.readU16(register, little_endian)\n if result > 32767:\n result -= 65536\n return result\n\n def readU16LE(self, register):\n \"\"\"Read an unsigned 16-bit value from the specified register, in little\n endian byte order.\"\"\"\n return self.readU16(register, little_endian=True)\n\n def readU16BE(self, register):\n \"\"\"Read an unsigned 16-bit value from the specified register, in big\n endian byte order.\"\"\"\n return self.readU16(register, little_endian=False)\n\n def readS16LE(self, register):\n \"\"\"Read a signed 16-bit value from the specified register, in little\n endian byte order.\"\"\"\n return self.readS16(register, little_endian=True)\n\n def readS16BE(self, register):\n \"\"\"Read a signed 16-bit value from the specified register, in big\n endian byte order.\"\"\"\n return self.readS16(register, little_endian=False)" }, { "alpha_fraction": 0.6483126282691956, "alphanum_fraction": 0.7300177812576294, "avg_line_length": 30.33333396911621, "blob_id": "e313a3005866cbcec1a1cd65df31e3f42b1ec280", "content_id": "57b4dceedf248a4b8a1704f6dea7236e251a536d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 563, "license_type": "permissive", "max_line_length": 59, "num_lines": 18, "path": "/bme280_test.py", "repo_name": "Kuzj/Adafruit_Python_BME280", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom Adafruit_BME280 import BME280\nfrom time import sleep\n\nDELAY_BETWEEN_SENSORS = 0.5\nSPI_BUS = 0\nfor i in [1,2,3,4,5]:\n\tbme280SensorInstance = BME280(spi_bus=SPI_BUS,spi_dev=i)\n\tif bme280SensorInstance.sample_ok:\n\t\tprint(f'sensor {SPI_BUS}.{i}')\n\t\tprint(f't = {round(bme280SensorInstance.temperature,1)}')\n\t\tprint(f'h = {round(bme280SensorInstance.humidity,1)}')\n\t\tprint(f'p = {round(bme280SensorInstance.pressure,1)}')\n\t\t#bme280SensorInstance.max_speed_hz = 10\n\t\t#bme280SensorInstance.mode = 3\n\tsleep(DELAY_BETWEEN_SENSORS)\nprint('-'*30)" } ]
2
arvindb95/Mass_model_grid_codes
https://github.com/arvindb95/Mass_model_grid_codes
722a277c0b070365a576ee0b3f21048da6d581fa
1e1efca97a91ea7a8e8268ed468ed7ef6b61528b
6838a407eeb6bed0b275b33015c56ced138c18f8
refs/heads/master
2021-09-03T22:00:33.884627
2018-01-12T10:12:34
2018-01-12T10:12:34
117,224,980
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5338245034217834, "alphanum_fraction": 0.6242464780807495, "avg_line_length": 26.648147583007812, "blob_id": "73b3d9c46dc3e361f53a48a92836f71097bf1696", "content_id": "a85eb807c2baae13d77b033e0cda6fb47fd080ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1493, "license_type": "no_license", "max_line_length": 89, "num_lines": 54, "path": "/plot_basemap.py", "repo_name": "arvindb95/Mass_model_grid_codes", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport esutil as es\nfrom astropy.table import Table\nfrom mpl_toolkits.basemap import Basemap\nimport astropy.coordinates as coo\n\nhtm_grid = es.htm.HTM(4)\n\ncentres_tab = Table.read(\"level4_grid.txt\",format=\"ascii\")\ntheta = centres_tab[\"theta\"]\nphi = centres_tab[\"phi\"]\n\nplot_theta = 90 - theta\n\nnew_map = Basemap(projection=\"moll\",resolution=\"l\", lat_0=45, lon_0=0)\n\npoints_done = []\n\nfor i in range(2048,2048*2):\n v1, v2, v3 = htm_grid.get_vertices(i)\n\n theta_1 = np.rad2deg(np.arccos(v1[2]))\n phi_1 = np.rad2deg(np.arctan2(v1[0],v1[1]))\n theta_2 = np.rad2deg(np.arccos(v2[2]))\n phi_2 = np.rad2deg(np.arctan2(v2[0],v2[1]))\n theta_3 = np.rad2deg(np.arccos(v3[2]))\n phi_3 = np.rad2deg(np.arctan2(v3[0],v3[1]))\n\n if (phi_1 < 0):\n phi_1 = 360.0 + phi_1\n if (phi_2 < 0):\n phi_2 = 360.0 + phi_2\n if (phi_3 < 0):\n phi_3 = 360.0 + phi_3\n\n\n xpt1, ypt1 = new_map(phi_1, 90 - theta_1)\n xpt2, ypt2 = new_map(phi_2, 90 - theta_2)\n xpt3, ypt3 = new_map(phi_3, 90 - theta_3)\n\n new_map.plot(xpt1, ypt1, \"bo\", ms=1)\n new_map.plot(xpt2, ypt2, \"bo\", ms=1)\n new_map.plot(xpt3, ypt3, \"bo\", ms=1)\n\n \n\n new_map.drawgreatcircle(phi_1,90-theta_1,phi_2,90-theta_2,linewidth=0.7,color=\"gray\")\n new_map.drawgreatcircle(phi_2,90-theta_2,phi_3,90-theta_3,linewidth=0.7,color=\"gray\")\n new_map.drawgreatcircle(phi_1,90-theta_1,phi_3,90-theta_3,linewidth=0.7,color=\"gray\")\n \n \n\nplt.show()\n" }, { "alpha_fraction": 0.5455272793769836, "alphanum_fraction": 0.5956538915634155, "avg_line_length": 33.39908218383789, "blob_id": "53c0007cddac0f33196745a30acbcead443a6589", "content_id": "3bf22b0a10da9eee87141d47c44867219fa8db6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7501, "license_type": "no_license", "max_line_length": 195, "num_lines": 218, "path": "/gps_gen.py", "repo_name": "arvindb95/Mass_model_grid_codes", "src_encoding": "UTF-8", "text": "\"\"\"\n gps_gen.py\n\n Aim : Generate gps.mac and other accessory files to be used for executing by GEANT4 on a cluster\n\n\n\"\"\"\nimport numpy as np\nimport esutil as es\nfrom astropy.table import Table\nimport os\nimport astropy.coordinates as coo\nimport matplotlib.pyplot as plt\n\ndef gen_gps(theta,phi,energy,nevt=6.97e6,satIllum=1,R=500.0,path=''):\n \"\"\"\n Returns a string which should go into the gps file\n\n Required inputs:\n theta = theta of the point (deg)\n phi = phi of the point (deg)\n energy = energy to be run (keV) \n Optional inputs:\n nevt = No. of photons to be shined \n satIllum = Boolean to decide wheteher we need to illuminate only czti(0) or whole satellite(1), default=1\n R = radius of the celestial sphere (a large number), default = 500.0\n path = path where the gps file needs to be saved\n\n Output:\n gps output file Tddd.dd_Pddd.dd_Edddd.d_gps.mac\n \"\"\"\n \n # Store energy in E, theta and phi\n E = energy\n th = np.deg2rad(theta)\n ph = np.deg2rad(phi)\n\n # Calculating the vector from source plane to czti (minus sign because of opposite direction)\n vx = -np.sin(th)*np.sin(ph)\n vy = -np.cos(th)\n vz = -np.sin(th)*np.cos(ph)\n \n # Calculating the position of the source plane\n if (satIllum == 0):\n posx = -R*vx\n posy = -R*vy\n posz = -R*vz\n radius = 50.0\n else :\n posx = -R*vx + 50.0\n posy = -R*vy\n posz = -R*vz + 60.0\n radius = 200.0\n \n\n # Calculating the rotation of the source plane\n rot1 = np.zeros(3)\n rot2 = np.zeros(3)\n\n rot1[0] = -vz/np.sqrt(1.0 - vy**2.0)\n rot1[1] = 0\n rot1[2] = vx/np.sqrt(1.0 - vy**2.0)\n\n rot2[0] = vy*vx/np.sqrt(1.0 - vy**2.0)\n rot2[1] = -np.sqrt(vx**2.0 + vz**2.0)\n rot2[2] = vy*vz/(1.0 - vy**2)\n\n # Writing to a file\n \n gps_file = open(path+\"/T{th:06.2f}_P{ph:06.2f}_E{e:07.2f}_gps.mac\".format(th=theta,ph=phi,e=energy),\"w\")\n \n gps_file.write(\"\"\"/gps/particle gamma\n/gps/ene/type Mono\n/gps/ene/mono {} keV\n/gps/pos/type Plane\n/gps/pos/shape Circle\n/gps/pos/centre {} {} {} cm\n/gps/direction {} {} {}\n/gps/pos/rot1 {} {} {}\n/gps/pos/rot2 {} {} {}\n/gps/pos/radius {} cm\n/tracking/verbose {}\n/gps/verbose {}\n/run/beamOn {}\n \"\"\".format(energy,posx,posy,posz,vx,vy,vz,rot1[0],rot1[1],rot1[2],rot2[0],rot2[1],rot2[2],radius,0,0,int(nevt)))\n gps_file.close()\n\n gps_filename = \"T{th:06.2f}_P{ph:06.2f}_E{e:07.2f}_gps.mac\".format(th=theta,ph=phi,e=energy)\n return gps_filename\n\n\ndef get_centers(depth,theta_filename=\"theta.txt\",phi_filename=\"phi.txt\",R=500.0):\n \"\"\"\n Returns the coordinates of the centers of the trixel of given depth\n\n Required inputs:\n depth = level of the HTM grid (int from 0 to 12)\n Optional inputs:\n theta_file = Name of file in which calculated theta values are to be put\n phi_file = Name of file in which calculated values of phi are to be put\n R = Radius of the celestial sphere (a large value), default = 500.0\n\n Returns:\n Arrays of theta and phi values of the centers of the trixels\n \"\"\"\n htm_map = es.htm.HTM(depth)\n no_of_trixels = 8*4**(depth)\n \n # To get a list of all possible number of trixels for all depths from 0 to 13\n n_of_t = np.zeros(10)\n for i in range(0,len(n_of_t)):\n n_of_t[i] = 4**(i)*8\n\n n_id_arr = np.zeros(len(n_of_t)+1)\n n_id_arr[0] = 1\n n_id_arr[1:] = n_of_t\n n_id_range = np.cumsum(n_id_arr)\n \n n_id_low = no_of_trixels#int(n_id_range[depth]) # The lower limit of the number id for the given depth\n n_id_high = no_of_trixels*2#int(n_id_range[depth+1]) # The higher limit of the number id for the given depth\n \n\n print \"N_id low :\",n_id_low \n print \"N_id high : \",n_id_high\n\n theta_arr = []\n phi_arr = []\n\n for nid in range(n_id_low,n_id_high):\n v1,v2,v3 = htm_map.get_vertices(nid)\n center = (v1+v2+v3)/3.0\n center = center/np.sqrt(center[0]**2.0 + + center[1]**2.0 + center[2]**2.0)\n theta = np.rad2deg(np.arccos(center[2]))\n phi = np.rad2deg(np.arctan2(center[0],center[1]))\n if (phi < 0):\n phi = 360.0 + phi\n\n theta_arr.append(theta)\n phi_arr.append(phi)\n \n theta_file = open(theta_filename,\"w\")\n phi_file = open(phi_filename,\"w\")\n theta_table = Table([np.array(theta_arr)],names=['theta'])\n theta_table.write(theta_filename,format='ascii',overwrite=True)\n \n phi_table = Table([np.array(phi_arr)],names=['phi'])\n phi_table.write(phi_filename,format='ascii',overwrite=True)\n\n theta_file.close()\n phi_file.close()\n return theta_arr,phi_arr\n\n# Main function begins\n\nif __name__=='__main__':\n \n # Calling get_centers to write the theta and phi values for the centers of the trixels\n depth = 5\n\n #get_centers(depth)\n \n\n lvl5_minus_lvl4_file = Table.read(\"lvl5_minus_lvl4_grid.txt\",format='ascii')\n full_theta = lvl5_minus_lvl4_file['theta'].data\n full_phi = lvl5_minus_lvl4_file['phi'].data\n\n grb_theta = np.array([60.83,106.11,116.86,0.66,105.66,138.85,140.52,10.15,52.95,156.18,65.32,55.30,65.53])\n grb_phi = np.array([67.57,255.69,184.86,159.48,85.52,315.78,118.09,95.08,273.18,59.18,332.32,35.19,16.19])\n grb_names = np.array(['GRB151006A','GRB160106A','GRB160131A','GRB160325A','GRB160509A','GRB160607A','GRB160623A','GRB160703','GRB160802A','GRB160821A','GRB160910A','GRB171010A','GRB171103A'])\n\n# for i in range(len(grb_theta)):\n# print \"Start %s\"%i\n# trans_theta = grb_theta[i]\n# trans_phi = grb_phi[i]\n# trans_pos = coo.SkyCoord(trans_phi,trans_theta-90,unit=\"deg\")\n# neigh_theta_lst = []\n# neigh_phi_lst = []\n# for j in range(len(full_theta)):\n# point_pos = coo.SkyCoord(full_phi[j],full_theta[j]-90,unit=\"deg\")\n# sep = abs(trans_pos.separation(point_pos).value)\n# if (sep <= 10):\n# neigh_theta_lst.append(full_theta[j])\n# neigh_phi_lst.append(full_phi[j])\n# sel_theta_arr = np.array(neigh_theta_lst)\n# sel_phi_arr = np.array(neigh_phi_lst)\n# print \"Neighbour theta : \",sel_theta_arr\n# print \"Neighbour phi : \",sel_phi_arr\n#\n# neigh_file = open(grb_names[i]+\"_neigh_grid.txt\",\"w\")\n# neigh_table = Table([sel_theta_arr,sel_phi_arr],names=[\"theta\",\"phi\"])\n# neigh_table.write(neigh_file,format='ascii')\n# neigh_file.close()\n# print \"=============================\"+grb_names[i]+\"_neigh_grid.txt created ================================\"\n\n final_tab = Table.read(\"final_finer_grid.txt\",format=\"ascii\")\n theta_arr = final_tab[\"theta\"].data\n phi_arr = final_tab[\"phi\"].data\n\n # Open a file to note down the location of the gps files\n gps_file_list = open(\"gps_file_list.txt\",\"w\")\n \n path_file = open(\"path.txt\",\"r\")\n master_path = path_file.read()[:-1]\n\n no_of_files = 0\n \n for i in range(len(theta_arr)):\n path = master_path+\"/T{th:06.2f}_P{ph:06.2f}\".format(th=theta_arr[i],ph=phi_arr[i])\n if not os.path.exists(path):\n os.makedirs(path)\n energy_table = Table.read(\"grid_energy.txt\",format='ascii')\n energy = energy_table['energy'].data\n for ene in energy:\n gps_filename = gen_gps(theta_arr[i],phi_arr[i],ene,path=path)\n gps_file_list.write(path+\"/\"+gps_filename+\"\\n\")\n no_of_files += 1\n gps_file_list.close()\n print no_of_files,\" gps.mac files created !!!\"\n\n\n" }, { "alpha_fraction": 0.7816411852836609, "alphanum_fraction": 0.7830320000648499, "avg_line_length": 64.36363983154297, "blob_id": "30343dac624865e971996cec2268d589086b281d", "content_id": "d9f04478016bdf1f9908de343b455abbd763441b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 719, "license_type": "no_license", "max_line_length": 117, "num_lines": 11, "path": "/README.md", "repo_name": "arvindb95/Mass_model_grid_codes", "src_encoding": "UTF-8", "text": "# Mass_model_grid_codes\n\ngps_gen.py is a code to generate the gps mac file to be used to run the Geant4 simulation.\nIt creates the mac files with the name Tddd.dd_Pddd.dd_Edddd.dd_gps.mac in the directories \nTddd.dd_Pddd.dd where T, P and E refer to theta, phi and energy for the particular run.\nCopy over these directories to where you want the outputs to be written. The final fits files,\nTddd.dd_Pddd.dd_Edddd.dd_SingeEventFile.fits will be written in the respective Tddd.dd_Pddd.dd directory.\n\nMAKE SURE THESE DIRECTORIES ARE COPIED TO THE RIGHT PLACE. OTHERWISE, NO PRODUCT WILL BE WRITTEN EVEN AFTER THE RUN!!\n\nplot_basemap.py is still being developed so that we can visualise HTM pixels. Will be updated soon ;D\n" } ]
3
chinni2003/CSEC_20
https://github.com/chinni2003/CSEC_20
026a78340f259084f6e63cff66610e96107762c9
ad5dcf37f0ce97fe67d2ab00ec2dcb19e77f335b
ceaddad42c7595b115e72e0b1738accc5e2ca367
refs/heads/main
2023-04-26T17:11:39.542045
2021-05-21T06:51:29
2021-05-21T06:51:29
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6158192157745361, "alphanum_fraction": 0.6384180784225464, "avg_line_length": 18.875, "blob_id": "08bc9792ac7e40413d0d3d5523eeffe824206ed0", "content_id": "81b4b02ca814a7159f00b32f16a2cada6f0ae0d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 354, "license_type": "no_license", "max_line_length": 75, "num_lines": 16, "path": "/IFDEMO1.PY", "repo_name": "chinni2003/CSEC_20", "src_encoding": "UTF-8", "text": "#Control Structures\r\n'''\r\nCS determines the flow of exection\r\n'''\r\n''' why?The statements are executed in the sequential\r\nvarious types-multiline comment\r\n'''\r\n#if\r\na=10 #READ INPUT FROM USER\r\nif a<20: #if condition is true then the statements of if block is executed\r\n print('a is <20')\r\n print('HI')\r\n\r\n'''OUTPUT\r\na is <20\r\nHI'''\r\n \r\n \r\n \r\n" } ]
1
Deeptradingfx/Trapyng
https://github.com/Deeptradingfx/Trapyng
951032dd5b39daf0ae8329792dfc30ca20bbe1c7
4cc7bed7b7571c01925d37ff8cf90e3202ffd4bd
942db34c29930483f6e88e26f197083d1557ef4a
refs/heads/master
2020-05-09T22:17:29.198861
2019-02-15T10:18:27
2019-02-15T10:18:27
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.634358286857605, "alphanum_fraction": 0.6480615139007568, "avg_line_length": 35.938270568847656, "blob_id": "ed8e34bbc4189c46678fdffc5ded44d76b685a2b", "content_id": "00c00b999717f0337d60720120258e39eebc5f59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2992, "license_type": "no_license", "max_line_length": 88, "num_lines": 81, "path": "/Examples/1.1 Trading Information Classes/intraday_plotting.py", "repo_name": "Deeptradingfx/Trapyng", "src_encoding": "UTF-8", "text": "\"\"\" BASIC USAGE OF THE CLASS SYMBOL\"\"\"\n# Change main directory to the main folder and import folders\n### THIS CLASS DOES NOT DO MUCH, A QUICK WAY TO AFFECT ALL THE TIMESERIES\n## OF THE SYMBOL IN A CERTAIN MANNER, like loading, or interval.\n## It also contains info about the Symbol Itself that might be relevant.\n\nimport os\nos.chdir(\"../../\")\nimport import_folders\n# Classical Libraries\nimport datetime as dt\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport copy as copy\n# Own graphical library\nfrom graph_lib import gl\n# Data Structures Data\nimport CTimeData as CTD\nimport CSymbol as CSy\n# Import functions independent of DataStructure\nimport utilities_lib as ul\nplt.close(\"all\") # Close all previous Windows\n######## SELECT DATASET, SYMBOLS AND PERIODS ########\ndataSource = \"Hanseatic\" # Hanseatic FxPro GCI Yahoo\n[storage_folder, info_folder, \n updates_folder] = ul.get_foldersData(source = dataSource)\n#### Load the info about the available symbols #####\nSymbol_info = CSy.load_symbols_info(info_folder)\nSymbol_names = Symbol_info[\"Symbol_name\"].tolist()\nNsym = len(Symbol_names)\n\n############################### OUR SYMBOL ############################\nperiods = [5,15,60,1440] # Periods to load\nsymbols = [\"Mad.ITX\", \"XAUUSD\", \"XAGUSD\", \"USA.IBM\"] # Symbols to load\nmySymbol = CSy.CSymbol(symbols[0],periods) # Set the specified things. Symbol + periods\n\n################ OPERATIONS THAT AFFECT ALL Periods #####################\n## Load all the timeSeries and info of the Symbol\nmySymbol.set_csv(storage_folder)\nmySymbol.load_info(info_folder)\nprint mySymbol.info # print information about the symbol\n\n# Set time limits to all the TD of the object\nsdate_str = \"01-04-2016\"; edate_str = \"01-05-2016\"\nsdate = dt.datetime.strptime(sdate_str, \"%d-%m-%Y\")\nedate = dt.datetime.strptime(edate_str, \"%d-%m-%Y\")\nmySymbol.set_interval(sdate,edate) # Set the interval period to be analysed\n\n#### Filling of data !!!\n#mySymbol.fill_data()\n\n# Set the timeSeries to operate with.\nmySymbol.set_seriesNames([\"Close\"])\n\n############################################################\n###### NOW WE OPERATE DIRECTLY ON THE TIMEDATAs ############\n############################################################\n\nperiods = mySymbol.get_periods()\n\ngl.set_subplots(4,1, sharex = True)\n# TODO: Be able to automatize the shareX thing\nfor period in periods:\n myTimeData = mySymbol.get_timeDataObject(period)\n price = myTimeData.get_timeSeries([\"Close\"])\n volume = myTimeData.get_timeSeries([\"Volume\"])\n dates = myTimeData.get_dates()\n \n gl.plot(dates, price, labels = [\"\", \"\", mySymbol.symbol],\n legend = [str(period)])\n \n gl.stem(dates, volume,\n legend = [str(period)], na = 1, nf = 0)\n \ngl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.20, hspace=0)\n\n# TODO: We can also use the library of indicators especifing the period. \n# If no period specified, we use the dayly or the bigges one.\n\n\n#######################\n" }, { "alpha_fraction": 0.636566698551178, "alphanum_fraction": 0.6617740988731384, "avg_line_length": 36.77108383178711, "blob_id": "bfb480b674b8d15e80df487fe44d202e31349cf2", "content_id": "562c993c19b860cdaf8b2ebebd5d95b5ade9958c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3134, "license_type": "no_license", "max_line_length": 136, "num_lines": 83, "path": "/Examples/1.1 Trading Information Classes/1.0.main_Load_TD.py", "repo_name": "Deeptradingfx/Trapyng", "src_encoding": "UTF-8", "text": "\"\"\" BASIC USAGE OF THE timeData Class AND SOME PLOTTINGS\"\"\"\n# Change main directory to the main folder and import folders\nimport os\nos.chdir(\"../../\")\nimport import_folders\n# Classical Libraries\nimport datetime as dt\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport copy as copy\n# Own graphical library\nfrom graph_lib import gl\n# Data Structures Data\nimport CTimeData as CTD\n# Import functions independent of DataStructure\nimport utilities_lib as ul\nimport DDBB_lib as DBl\nimport get_data_lib as gdl\nimport DDBB_lib as DBl\nplt.close(\"all\") # Close all previous Windows\n# Options !\nbasic_plotting = 1\n\n\n######## SELECT SOURCE ########\ndataSource = \"GCI\" # Hanseatic FxPro GCI Yahoo\n[storage_folder, info_folder, \n updates_folder] = ul.get_foldersData(source = dataSource)\nfolder_images = \"../pics/gl/\"\n######## SELECT SYMBOLS AND PERIODS ########\nsymbols = [\"Amazon\", \"Alcoa_Inc\"]\nperiods = [15]\n\n######## SELECT DATE LIMITS ###########\nsdate = dt.datetime.strptime(\"21-11-2016\", \"%d-%m-%Y\")\n#edate = dt.datetime.strptime(\"25-11-2016\", \"%d-%m-%Y\")\nedate = dt.datetime.now()\n######## CREATE THE OBJECT AND LOAD THE DATA ##########\n# Tell which company and which period we want\ntimeData = CTD.CTimeData(symbols[0],periods[0])\nTD = DBl.load_TD_from_csv(storage_folder, symbols[1],periods[0])\ntimeData.set_csv(storage_folder) # Load the data into the model\ntimeData.set_TD(TD)\n\ncmplist = DBl.read_NASDAQ_companies(whole_path = \"../storage/Google/companylist.csv\")\ncmplist.sort_values(by = ['MarketCap'], ascending=[0],inplace = True)\nsymbolIDs = cmplist.iloc[0:30][\"Symbol\"].tolist()\n\n\nif (0):\n \"\"\"\n Shitty example to download data that do not work anymore because Yahoo and Google\n are cunts and they change their interfaces and remove services\n \"\"\"\n\n # Download the data from website maybe:\n TD2 = gdl.get_data_yahoo2(symbol = \"AAPL\", precision = \"m\", \n start_date = \"01-12-2011\", end_date = \"01-12-2015\")\n \n TD_yahoo = gdl.download_D1_TD_yahoo(\"AAPL\", sdate,edate)\n TD_yahoo2 = gdl.download_D1_TD_yahoo_prev(\"AAPL\", sdate,edate)\n TD_yahoo3 = gdl.download_TD_yahoo(symbol = \"AAPL\", precision = \"m\", \n start_date = dt.datetime(2016,1,1), end_date = dt.datetime(2017,1,1))\n \n TD_google = gdl.download_TD_google (\"AAPL\", period_seconds = 60 * 1440 * 7, timeInterval = \"15d\")\n TD_google = gdl.download_D1_TD_google (\"AAPL\", sdate,edate)\n timeData.set_TD(TD_google)\n \n timeData.set_TD_from_google(\"ONT\",5,\"10d\")\n \n#####################################################################3\ntimeData.set_interval(sdate, edate)\nopentime, closetime = timeData.guess_openMarketTime()\nperiod = timeData.guess_period()\nprint \"Period: %f\"%period\nprint \"Market Hours \" + str(opentime) +\" - \" + str(closetime)\ndataTransform = [\"intraday\", opentime, closetime]\n#dataTransform = None\ndataHLOC = timeData.get_timeSeries([\"High\",\"Low\",\"Open\",\"Close\"])\ndates = timeData.get_dates()\n\ngl.barchart(dates, dataHLOC, lw = 2, dataTransform = dataTransform, color = \"k\", labels = [symbols[0],\"\",\"Price\"], legend= [symbols[0]],\n AxesStyle = \"Normal\")" }, { "alpha_fraction": 0.6015669703483582, "alphanum_fraction": 0.6288935542106628, "avg_line_length": 36.371429443359375, "blob_id": "bc3fdadf03ff6f6402fde6c294cd031e26a95b59", "content_id": "8d9b140b3436623c43b8cc3459047aef616b48c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5233, "license_type": "no_license", "max_line_length": 97, "num_lines": 140, "path": "/Examples/1.2 Trading Indicators/1.1. main_singletimeDataGraphs.py", "repo_name": "Deeptradingfx/Trapyng", "src_encoding": "UTF-8", "text": "\"\"\" \nThis file plots the Price and Volume of charts in 3 different modalities:\n - Line: Just the close price\n - Barchart: With OCHL\n - CandleStick: With OCHL\n\nProperties:\n - It guesses form the data the open times of the market.\n - It does not need all data \n - It also saves the image to disk.\n\"\"\"\n# Change main directory to the main folder and import folders\nimport os\nos.chdir(\"../../\")\nimport import_folders\n# Classical Libraries\nimport datetime as dt\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport copy as copy\n# Own graphical library\nfrom graph_lib import gl\n# Data Structures Data\nimport CTimeData as CTD\n# Import functions independent of DataStructure\nimport utilities_lib as ul\nimport pandas as pd\nplt.close(\"all\") # Close all previous Windows\n\n\"\"\"\n$$$$$$$$$$$$$$$$$$$$$$$ OPTIONS $$$$$$$$$$$$$$$$$$$$$$$$$\n\"\"\"\n\nfolder_images = \"../pics/gl/\"\n# Using the library of function built in using the dataFrames in pandas\ntypeChart = \"Bar\" # Line, Bar, CandleStick\ntranformIntraday = 1\n\n######## SELECT DATASET, SYMBOLS AND PERIODS ########\ndataSource = \"GCI\" # Hanseatic FxPro GCI Yahoo\n[storage_folder, info_folder, \n updates_folder] = ul.get_foldersData(source = dataSource)\n\nsymbols = [\"Amazon\"]\nperiods = [15] # 1440 15\n\n######## SELECT DATE LIMITS ###########\n## We set one or other as a function of the timeSpan\n\nif (periods[0] >= 1440):\n sdate_str = \"01-09-2016\"\n edate_str = \"2-2-2017\"\nelse:\n sdate_str = \"6-09-2016\"\n edate_str = \"12-09-2016\"\n \nsdate = dt.datetime.strptime(sdate_str, \"%d-%m-%Y\")\nedate = dt.datetime.strptime(edate_str, \"%d-%m-%Y\")\n######## CREATE THE OBJECT AND LOAD THE DATA ##########\n# Tell which company and which period we want\ntimeData = CTD.CTimeData(symbols[0],periods[0])\ntimeData.set_csv(storage_folder) # Load the data into the model\ntimeData.set_interval(sdate,edate) # Set the interval period to be analysed\n\n\n# Open and close hours !\nopentime = dt.datetime.strptime('2016-09-06 09:30:00', \"%Y-%m-%d %H:%M:%S\")\nclosetime = dt.datetime.strptime('2016-09-06 16:00:00', \"%Y-%m-%d %H:%M:%S\")\n\nif(tranformIntraday):\n dataTransform = [\"intraday\", opentime, closetime]\nelse:\n dataTransform = None \n## If the timspan is daily or bigger do not transform time.\nif (periods[0] >= 1440):\n dataTransform = None \n# This is how we would obtain the info if we did not use tradingPlot functions\nprice = timeData.get_timeSeries([\"Close\"]);\nvolume = timeData.get_timeSeries([\"Volume\"]);\ndates = timeData.get_dates()\n\n\nif (0):\n## Try out time mapping func\n caca = ul.transformDatesOpenHours(dates,opentime, closetime )\n semen = ul.detransformDatesOpenHours(caca,opentime, closetime )\n semen = pd.to_datetime(semen)\n for i in range(semen.size):\n diff_sec = (semen[i] - dates[i]).total_seconds()\n print (semen[i], dates[i])\n if (diff_sec != 0):\n print (diff_sec/3600)\n \n# Get indicators for the price and volume\nnMA1 = 15\nEMA_price = timeData.EMA(seriesNames = [\"Close\"], n = nMA1)\nSMA_volume = timeData.EMA(seriesNames = [\"Volume\"], n = nMA1)\n\nax1 = gl.subplot2grid((4,1), (0,0), rowspan=3, colspan=1)\nif (typeChart == \"Line\"):\n title = \"Line Chart. \" + str(symbols[0]) + \"(\" + ul.period_dic[timeData.period]+ \")\" \n gl.tradingLineChart(timeData, seriesName = \"Close\", ax = ax1, \n legend = [\"Close price\"],labels = [title,\"\",r\"Price ($\\$$)\"], \n AxesStyle = \"Normal - No xaxis\", dataTransform = dataTransform)\n \nelif(typeChart == \"Bar\"):\n title = \"Bar Chart. \" + str(symbols[0]) + \"(\" + ul.period_dic[timeData.period]+ \")\" \n gl.tradingBarChart(timeData, ax = ax1, legend = [\"Close price\"], color = \"k\",\n labels = [title,\"\",r\"Price ($\\$$)\"], AxesStyle = \"Normal - No xaxis\", \n dataTransform = dataTransform)\n\nelif(typeChart == \"CandleStick\"):\n title = \"CandleStick Chart. \" + str(symbols[0]) + \"(\" + ul.period_dic[timeData.period]+ \")\" \n gl.tradingCandleStickChart(timeData, ax = ax1, legend = [\"Close price\"], color = \"k\",\n colorup = \"r\", colordown = \"k\", alpha = 0.5, lw = 3,\n labels = [title,\"\",r\"Price ($\\$$)\"], AxesStyle = \"Normal - No xaxis\",\n dataTransform = dataTransform)\n\ngl.plot(dates, EMA_price, ax = ax1,legend = [\"EMA(%i)\"%nMA1], dataTransform = dataTransform,\n AxesStyle = \"Normal\")\n\n# ax2: Plot the Volume with the EMA\nax2 = gl.subplot2grid((4,1), (3,0), rowspan=1, colspan=1, sharex = ax1)\ngl.tradingVolume(timeData, ax = ax2,legend = [\"Volume(%i)\"%nMA1], \n AxesStyle = \"Normal\", labels = [\"\",\"\",\"Volume\"],\n dataTransform = dataTransform)\n\ngl.plot(dates, SMA_volume, ax = ax2,legend = [\"SMA(%i)\"%nMA1], dataTransform = dataTransform,\n AxesStyle = \"Normal - Ny:5\")\n\n# Set final properties and save figure\ngl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.05, hspace=0.05)\n\nif(type(dataTransform) == type(None)):\n image_name = \"intraDay\" + typeChart +'ChartGraph.png'\nelse:\n image_name = \"TransformedX\" + typeChart +'ChartGraph.png'\n \ngl.savefig(folder_images + image_name, \n dpi = 100, sizeInches = [20, 6])\n\n" }, { "alpha_fraction": 0.5882806181907654, "alphanum_fraction": 0.6019660830497742, "avg_line_length": 37.8576774597168, "blob_id": "f50ceb7b4b885027a0f332702d6efbaca6ac7782", "content_id": "1d7fdcf4a18231eace6f634621ac480dfe751d29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10376, "license_type": "no_license", "max_line_length": 120, "num_lines": 267, "path": "/Examples/1.1 Trading Information Classes/1.1. main_Basic.py", "repo_name": "Deeptradingfx/Trapyng", "src_encoding": "UTF-8", "text": "\"\"\" BASIC USAGE OF THE timeData Class AND SOME PLOTTINGS\"\"\"\n# Change main directory to the main folder and import folders\nimport os\nos.chdir(\"../../\")\nimport import_folders\n\n# Classical Libraries\nimport datetime as dt\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport copy as copy\n# Own graphical library\nfrom graph_lib import gl\n# Data Structures Data\nimport CTimeData as CTD\n# Import functions independent of DataStructure\nimport utilities_lib as ul\nimport DDBB_lib as DBl\nimport get_data_lib as gdl\nplt.close(\"all\") # Close all previous Windows\n\n\n#### print options ####\nstorage_f = 0\nshow_data_shape = 0\nguessing_markerhours = 0\nbasic_timeSeries_functions = 0\n# Plotting Options !\nbasic_plotting = 1 # Basic chart with signal, volume, return\nintrabydays_f = 0 # We divide the intraday data into its dayly components and plot all days on top of each other\nCandlestick_f = 0 # Plot the CandleStick charts.\n\n\nplot_trials_f = 0 # Some stupid trial I cannot remember.\n\nown_plotting_func_f = 0 # Plotting function from timeData class, not supported anymore\nplot_gaps_scattering = 0\ndayly_data_f = 0\n\n\n######## SELECT SOURCE ########\ndataSource = \"GCI\" # Hanseatic FxPro GCI Yahoo\n[storage_folder, info_folder, \n updates_folder] = ul.get_foldersData(source = dataSource)\nfolder_images = \"../pics/gl/\"\n######## SELECT SYMBOLS AND PERIODS ########\nsymbols = [\"Amazon\", \"Alcoa_Inc\"]\nperiods = [15]\n\n######## SELECT DATE LIMITS ###########\nsdate = dt.datetime.strptime(\"21-11-2016\", \"%d-%m-%Y\")\nedate = dt.datetime.strptime(\"25-11-2016\", \"%d-%m-%Y\")\n\n######## CREATE THE OBJECT AND LOAD THE DATA ##########\n# Tell which company and which period we want\ntimeData = CTD.CTimeData(symbols[0],periods[0])\nTD = DBl.load_TD_from_csv(storage_folder, symbols[1],periods[0])\ntimeData.set_csv(storage_folder) # Load the data into the model\ntimeData.set_TD(TD)\ntimeData.set_interval(sdate,edate, trim = True) # Set the interval period to be analysed\n\n\nopentime, closetime = timeData.guess_openMarketTime()\ndataTransform = [\"intraday\", opentime, closetime]\n################# STORAGE FUNCTIONS ##############\nif (storage_f == 1):\n timeData.add_csv(updates_folder) # Add more data to the tables\n timeData.save_to_csv(storage_folder)\n\n############## Data filling #################################\n# TODO: call data filling functions\n\n############## OBTAIN TIME SERIES #################################\n# We can obtain some basic preprocessed time series\nprice = timeData.get_timeSeries([\"Open\",\"Close\",\"Average\"]);\ndates = timeData.get_dates() ## The dates of the selected data\n\nif (show_data_shape):\n \"\"\"\n Show the shape of different data structures\n \"\"\"\n print (price.shape) # np.array(Nsamples, Nseries)\n print (dates.shape) # np.array(Nsamples, ) of selected Dates\n print (timeData.time_mask.shape) # # np.array(Nsamples, ) of indices of dates\n\nif(guessing_markerhours):\n \"\"\"\n Guess the time in which the market is open\n \"\"\"\n# dates = timeData.get_dates()\n# print dates\n period = timeData.guess_period()\n print (period) # 15.0\n openTime, closeTime = timeData.guess_openMarketTime()\n print (openTime, closeTime) # 09:30:00 15:45:00\n \n############## OWN BASIC PLOTING FUNC #########################################\nif (basic_timeSeries_functions == 1):\n \"\"\"\n Functions to obtain the basic timeSeries data from the object.\n \"\"\"\n # If we do not specify new time series, we use the last ones, default = close.\n price = timeData.get_timeSeries([\"RangeHL\",\"RangeCO\"]);\n price = timeData.get_timeSeries([\"magicDelta\"]);\n\n returns = timeData.get_timeSeriesReturn([\"Close\",\"Average\"])\n cumReturns = timeData.get_timeSeriesCumReturn()\n SortinoRatio = timeData.get_SortinoR()\n get_SharpR = timeData.get_SharpR()\n \n\n################# BASIC PLOTTING MIXTURES ############################\nif (basic_plotting):\n \"\"\" \n We aim to plot the price, volume, return and cummulative return for the selected security \n in the selected time frame.\n \"\"\"\n gl.set_subplots(4,1)\n ############# 1: Basic Time Series and Volume\n seriesNames = [\"Average\", \"High\"]\n dataHLOC = timeData.get_timeSeries([\"High\",\"Low\",\"Open\",\"Close\"])\n prices = timeData.get_timeSeries(seriesNames);\n dates = timeData.get_dates()\n volume = timeData.get_timeSeries([\"Volume\"]);\n Returns = timeData.get_timeSeriesReturn(seriesNames = [\"Close\"]);\n CumReturns = timeData.get_timeSeriesCumReturn(seriesNames = [\"Close\"]);\n nSMA = 10\n SMA = timeData.SMA(n = nSMA)\n ax1 = gl.plot(dates, SMA, labels = [timeData.symbolID + str(timeData.period), \"Time\", \"Price\"],\n legend = [\"SMA(%i)\" % nSMA], nf = 1, dataTransform = dataTransform,\n AxesStyle = \"Normal - No xaxis\", color = \"cobalt blue\") \n \n gl.barchart(dates, dataHLOC, lw = 2, dataTransform = dataTransform, color = \"k\",\n AxesStyle = \"Normal - No xaxis\")\n # Notice the Weekends and the displacement between bars and step\n \n ############# 2: Volume\n gl.stem(dates, volume, sharex = ax1, labels = [timeData.symbolID + str(timeData.period), \"Time\", \"Volume\"],\n legend = [\"Volume\"], nf = 1, alpha = 0.5, dataTransform = dataTransform,\n AxesStyle = \"Normal - No xaxis\")\n\n ############# 3: Returns\n gl.stem(dates, Returns, sharex = ax1, labels = [timeData.symbolID + str(timeData.period), \"Time\", \"Return\"],\n legend = [\"Return\"], nf = 1, dataTransform = dataTransform,\n AxesStyle = \"Normal - No xaxis\")\n\n ############# 4: Commulative Returns \n seriesNames = [\"Close\"]\n\n gl.plot(dates, CumReturns, sharex = ax1,labels = [timeData.symbolID + str(timeData.period), \"Time\", \"Cum Return\"],\n legend = [\"Cum Return\"], nf = 1, dataTransform = dataTransform,\n AxesStyle = \"Normal\")\n \n gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.20, hspace=0)\n image_name = \"timeDataExample.png\"\n gl.savefig(folder_images + image_name, \n dpi = 100, sizeInches = [30, 12])\n # TODO: Plot reconstruction to show that it is not the same.\n\n\nif(intrabydays_f == 1):\n \"\"\" \n We aim to plot the intraday price and volume for different days on top of each other.\n For this purpose, we first divide the entire timeseries into its corresponding days and\n then we plot day by day\n \"\"\"\n \n TD = timeData.get_TD()\n #caca = TD.groupby(TD.index.map(lambda x: x.date))\n caca = TD.groupby(TD.index.date)\n groups_of_index_dict = caca.groups # This is a dictionary with the dates as keys and the indexes of the TD as values\n days_dict = caca.indices # This is a dictionary with the dates as keys and the indexes of the TD as valu\n keys = days_dict.keys()# list of datetime.date objects\n keys.sort() \n set_indexes = days_dict[keys[0]]\n \n gl.set_subplots(2,1)\n ax1 = gl.plot([],[], nf = 1)\n ax2 = gl.plot([],[], nf = 1, sharex = ax1)\n \n for key in keys:\n set_indexes = days_dict[key]\n set_indexes.sort()\n set_indexes = timeData.time_mask[set_indexes] # Since it changed.\n \n times = timeData.get_dates(set_indexes).time\n values = timeData.get_timeSeriesCumReturn([\"Close\"],set_indexes)\n \n gl.scatter(times, values, ax = ax1)\n volume = timeData.get_timeSeries([\"Volume\"],set_indexes)\n gl.scatter(times, volume, ax = ax2)\n\n\"\"\"\n$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n$$$$$$$$$$$$$$$$$$$$ Outdated shit $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n\"\"\"\n\n############## OWN BASIC PLOTING FUNC #########################################\nif (own_plotting_func_f):\n # There is a small set of functions to plot the time series and some more\n # complex stuff but it is very underdeveloped and it is better to use the graph library\n price = timeData.get_timeSeries([\"RangeHL\",\"RangeCO\"]);\n timeData.plot_timeSeries(nf = 1)\n\n price = timeData.get_timeSeries([\"Close\",\"Average\"]);\n timeData.plot_timeSeriesReturn(nf = 1)\n timeData.plot_timeSeriesCumReturn(nf = 0)\n\n\nif (plot_trials_f == 1):\n \"\"\" \n I dont remember, just a test to plot stuff\n \"\"\"\n \n olmo = 33\n X = [\"uno\",\"dos\",\"ocho\",\"cinco\"]; X = np.array(X)\n dataHLOC = timeData.get_timeSeries([\"High\",\"Low\"])\n Y4 = dataHLOC[:X.size,:]\n Y1 = dataHLOC[:X.size,1]\n \n dates = timeData.get_dates()\n \n gl.plot (X,Y4, labels = [r\"Curca $y={2}x + {%i}\\alpha \\pi $\"%56, r\"$\\alpha \\pi$\", \"Pene\"], legend = [\"retarded\"])\n# gl.plot (dates,dataHLOC, labels = [r\"Curca $y={2}x + {%i}\\alpha \\pi $\"%56, r\"$\\alpha \\pi$\", \"Pene\"], \n# legend = [\"retarded\"], xaxis_mode = \"dayly\")\n \n gl.set_fontSizes(title = 40, xlabel = 30, ylabel = 30, \n xticks = 20, yticks = 20, legend = 40)\n \n############## Other graphical Properties #################################\n\nif (plot_gaps_scattering == 1):\n \"\"\"\n Very old trial to plot the gaps to try to see some patterns\n \"\"\"\n gl.set_subplots(1,2)\n timeData.scatter_deltaDailyMagic()\n\n############## Velero Graphs #################################\nif (Candlestick_f == 1):\n \"\"\"\n Plot the Candlestick charts\n \"\"\"\n gl.Velero_graph(timeData.get_TD(), nf = 1)\n gl.Heiken_Ashi_graph(timeData.get_TD(), nf = 1)\n \n############## Dayly things obtaining ####################################\n# We separate the data into a list of days in order to be able to analyze it easier\n\nif (dayly_data_f == 1):\n prices_day, dates_day = timeData.get_intra_by_days()\n \n plot_flag = 1\n for day in range (len(prices_day)):\n # type(dates_day[1]) <class 'pandas.tseries.index.DatetimeIndex'>\n # I could not find a fucking way to modify it inline TODO\n # This is done this way becasue we cannot asume that we have all the data\n # for all the days\n list_time = []\n for i in range(len(dates_day[day])):\n # datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])\n dateless = dates_day[day][i].replace(year = 2000, month = 1, day = 1)\n list_time.append(dateless)\n gl.plot(list_time, prices_day[day],\n nf = plot_flag)\n plot_flag = 0\n\n" } ]
4
ipbrennan90/flask-graphene-sqlalchemy-react-starter
https://github.com/ipbrennan90/flask-graphene-sqlalchemy-react-starter
eca8ce5c841fc4a4080e12e72f7263fc9b3e1319
409aa8f0a741f52700589aa8189f8123587f94d8
7683f0b10121c14f0d8024a3eb6c7f51838a6626
refs/heads/master
2020-03-07T12:30:56.890139
2018-04-03T00:15:01
2018-04-03T00:15:01
127,479,663
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6315120458602905, "alphanum_fraction": 0.6315120458602905, "avg_line_length": 34.772727966308594, "blob_id": "a73f3517a56d48053eb2f50758c52b8c96684f8d", "content_id": "ada4b97784f0ff8718313acbf67f28602100095d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 787, "license_type": "no_license", "max_line_length": 74, "num_lines": 22, "path": "/server/models/teacher.py", "repo_name": "ipbrennan90/flask-graphene-sqlalchemy-react-starter", "src_encoding": "UTF-8", "text": "from models.foundation import Base\nfrom models.department import Department\nfrom models.subject import Subject\nfrom sqlalchemy import Column, Integer, String, DateTime, ForeignKey, func\nfrom sqlalchemy.orm import (relationship, backref)\n\n\nclass Teacher(Base):\n __tablename__ = 'teacher'\n id = Column(Integer, primary_key=True)\n name = Column(String)\n hired_on = Column(DateTime, default=func.now())\n department_id = Column(Integer, ForeignKey('department.id'))\n department = relationship(\n Department,\n backref=backref('teachers',\n uselist=True,\n cascade='delete,all')\n )\n subjects = relationship(Subject,\n secondary='session',\n backref='teachers')\n" }, { "alpha_fraction": 0.5777592062950134, "alphanum_fraction": 0.6095317602157593, "avg_line_length": 25, "blob_id": "13389b854b7ca6571658cddb49e7006b262a9f0a", "content_id": "6c6ffe13427edbd35acd4be8bf1a0874e10518e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1196, "license_type": "no_license", "max_line_length": 61, "num_lines": 46, "path": "/server/alembic/versions/a94f56f25597_classes.py", "repo_name": "ipbrennan90/flask-graphene-sqlalchemy-react-starter", "src_encoding": "UTF-8", "text": "\"\"\"classes\n\nRevision ID: a94f56f25597\nRevises: 0fafd71644fc\nCreate Date: 2018-04-02 12:12:24.249422\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a94f56f25597'\ndown_revision = '0fafd71644fc'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.create_table(\n 'subject',\n sa.Column('id', sa.Integer, primary_key=True),\n sa.Column('name', sa.String),\n sa.Column('department_id', sa.Integer, sa.ForeignKey(\n 'department.id', ondelete=\"CASCADE\")),\n\n )\n op.create_table(\n 'session',\n sa.Column('id', sa.Integer, primary_key=True),\n sa.Column('name', sa.String),\n sa.Column('room', sa.Integer),\n sa.Column('department_id', sa.Integer, sa.ForeignKey(\n 'department.id', ondelete=\"CASCADE\")),\n sa.Column('subject_id', sa.Integer, sa.ForeignKey(\n 'subject.id', ondelete=\"CASCADE\")),\n sa.Column('teacher_id', sa.Integer, sa.ForeignKey(\n 'teacher.id', ondelete=\"CASCADE\"\n )),\n sa.Column('total_students', sa.Integer)\n )\n\n\ndef downgrade():\n op.drop_table('session')\n op.drop_table('subject')\n" }, { "alpha_fraction": 0.6979950070381165, "alphanum_fraction": 0.6979950070381165, "avg_line_length": 30.920000076293945, "blob_id": "135bd97677a9b4636924d92498ef6533d17fbdcd", "content_id": "5162f73c7f152ee3daa5100223338584148a000d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 798, "license_type": "no_license", "max_line_length": 91, "num_lines": 25, "path": "/server/graph/schema.py", "repo_name": "ipbrennan90/flask-graphene-sqlalchemy-react-starter", "src_encoding": "UTF-8", "text": "from graphene import Schema, ObjectType\nfrom department import Department, Mutation as DepartmentMutation, Query as DepartmentQuery\nfrom session import Session, Mutation as SessionMutation, Query as SessionQuery\nfrom teacher import Teacher, Mutation as TeacherMutation, Query as TeacherQuery\nfrom subject import Subject, Mutation as SubjectMutation, Query as SubjectQuery\n\n\nclass Query(DepartmentQuery,\n TeacherQuery,\n SessionQuery,\n SubjectQuery,\n ObjectType):\n pass\n\n\nclass Mutation(DepartmentMutation,\n TeacherMutation,\n SessionMutation,\n SubjectMutation,\n ObjectType):\n pass\n\n\nschema = Schema(query=Query, mutation=Mutation,\n types=[Teacher, Department, Session, Subject])\n" }, { "alpha_fraction": 0.5317460298538208, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 17, "blob_id": "bdd5e3b63fd4c38aff19f6bb48a1728fde34f48e", "content_id": "3c6bc0fee919a19e0ce972586fe1c700db99cdb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 126, "license_type": "no_license", "max_line_length": 24, "num_lines": 7, "path": "/server/requirements.txt", "repo_name": "ipbrennan90/flask-graphene-sqlalchemy-react-starter", "src_encoding": "UTF-8", "text": "Flask==0.12.2\nrequests==2.18.4\nSQLAlchemy==1.2.5\ngraphene_sqlalchemy>=2.0\nFlask-GraphQl==1.4.1\npsycopg2==2.7.4\nalembic==0.9.9\n" }, { "alpha_fraction": 0.6581818461418152, "alphanum_fraction": 0.6581818461418152, "avg_line_length": 31.352941513061523, "blob_id": "3bd2ebb343aae6bd50e28ac8a4274e449ec37660", "content_id": "b66fc2bb57af52fe8dac4913251f7403d650d460", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 550, "license_type": "no_license", "max_line_length": 64, "num_lines": 17, "path": "/server/models/subject.py", "repo_name": "ipbrennan90/flask-graphene-sqlalchemy-react-starter", "src_encoding": "UTF-8", "text": "from models.foundation import Base\nfrom models.department import Department\nfrom sqlalchemy import Column, Integer, String, ForeignKey\nfrom sqlalchemy.orm import (relationship, backref)\n\n\nclass Subject(Base):\n __tablename__ = 'subject'\n id = Column(Integer, primary_key=True)\n name = Column(String)\n department_id = Column(Integer, ForeignKey('department.id'))\n department = relationship(\n Department,\n backref=backref('subjects',\n uselist=True,\n cascade='delete,all')\n )\n" }, { "alpha_fraction": 0.7147215604782104, "alphanum_fraction": 0.7147215604782104, "avg_line_length": 28.795454025268555, "blob_id": "59a6acdc44d452849b4218bdfa60fc711c54f2f0", "content_id": "ce66c3d513a188714dfadc385bbdcde7898ae4fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1311, "license_type": "no_license", "max_line_length": 105, "num_lines": 44, "path": "/server/graph/subject.py", "repo_name": "ipbrennan90/flask-graphene-sqlalchemy-react-starter", "src_encoding": "UTF-8", "text": "import graphene\nfrom graphene import relay\nfrom graphene_sqlalchemy import SQLAlchemyObjectType, SQLAlchemyConnectionField\nfrom models.subject import Subject as SubjectModel\nfrom models.foundation import db_session\nfrom department import Department\n\n\nclass Subject(SQLAlchemyObjectType):\n class Meta:\n model = SubjectModel\n interfaces = (relay.Node, )\n\n\nclass CreateSubject(graphene.Mutation):\n id = graphene.Int()\n name = graphene.String()\n department = graphene.Field(Department)\n\n class Arguments:\n department = graphene.Int()\n name = graphene.String()\n\n def mutate(self, info, name, department):\n q = Department.get_query(info)\n subject_department = q.filter_by(id=department).one()\n new_subject = SubjectModel(name=name, department=subject_department)\n db_session.add(new_subject)\n db_session.commit()\n\n return CreateSubject(id=new_subject.id, name=new_subject.name, department=new_subject.department)\n\n\nclass Query(graphene.ObjectType):\n all_subjects = SQLAlchemyConnectionField(Subject)\n subjects = graphene.List(Subject)\n\n def resolve_subjects(self, info, **args):\n q = Subject.get_query(info)\n return q.all()\n\n\nclass Mutation(graphene.ObjectType):\n create_subject = CreateSubject.Field()\n" }, { "alpha_fraction": 0.6633906364440918, "alphanum_fraction": 0.6633906364440918, "avg_line_length": 29.308509826660156, "blob_id": "40e6ac78f8f4efd2d325f139aed804831dd37859", "content_id": "5ffa51dc0ed13a8eb9436016e7b8db59a92938d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2849, "license_type": "no_license", "max_line_length": 101, "num_lines": 94, "path": "/server/graph/teacher.py", "repo_name": "ipbrennan90/flask-graphene-sqlalchemy-react-starter", "src_encoding": "UTF-8", "text": "import graphene\nfrom graphene import relay\nfrom graphene_sqlalchemy import SQLAlchemyObjectType, SQLAlchemyConnectionField\nfrom models.teacher import Teacher as TeacherModel\nfrom models.foundation import db_session\nfrom department import Department\n\n\nclass Teacher(SQLAlchemyObjectType):\n class Meta:\n model = TeacherModel\n interfaces = (relay.Node, )\n\n\nclass CreateTeacher(graphene.Mutation):\n id = graphene.Int()\n name = graphene.String()\n department = graphene.Field(Department)\n\n class Arguments:\n department = graphene.Int()\n name = graphene.String()\n\n def mutate(self, info, name, department):\n q = Department.get_query(info)\n teacher_department = q.filter_by(id=department).first()\n new_teacher = TeacherModel(name=name, department=teacher_department)\n db_session.add(new_teacher)\n db_session.commit()\n\n return CreateTeacher(id=new_teacher.id, name=new_teacher.name, department=teacher_department)\n\n\nclass UpdateTeacher(graphene.Mutation):\n id = graphene.Int()\n name = graphene.String()\n department = graphene.Field(Department)\n\n class Arguments:\n id = graphene.Int()\n department = graphene.Int()\n name = graphene.String()\n\n def mutate(self, info, id, name=None, department=None):\n q = Teacher.get_query(info)\n teacher = q.filter_by(id=id).one()\n update_data = {}\n if name:\n update_data.update({'name': name})\n if department:\n update_data.update({'department_id': department})\n for key, value in update_data.iteritems():\n setattr(teacher, key, value)\n db_session.commit()\n\n return UpdateTeacher(id=teacher.id, name=teacher.name, department=teacher.department)\n\n\nclass DestroyTeacher(graphene.Mutation):\n id = graphene.Int()\n name = graphene.String()\n\n class Arguments:\n id = graphene.Int()\n\n def mutate(self, info, id):\n q = Teacher.get_query(info)\n teacher = q.filter_by(id=id).one()\n db_session.delete(teacher)\n db_session.commit()\n\n return DestroyTeacher(id=teacher.id, name=teacher.name)\n\n\nclass Query(graphene.ObjectType):\n all_teachers = SQLAlchemyConnectionField(Teacher)\n teacher = graphene.Field(Teacher, name=graphene.String())\n teachers = graphene.List(Teacher)\n\n def resolve_teacher(self, info, **args):\n q = Teacher.get_query(info)\n teacher_result = q.filter(\n TeacherModel.name.contains(args.get('name'))).first()\n return teacher_result\n\n def resolve_teachers(self, info, **args):\n q = Teacher.get_query(info)\n return q.all()\n\n\nclass Mutation(graphene.ObjectType):\n create_teacher = CreateTeacher.Field()\n update_teacher = UpdateTeacher.Field()\n destroy_teacher = DestroyTeacher.Field()\n" }, { "alpha_fraction": 0.6230329275131226, "alphanum_fraction": 0.6230329275131226, "avg_line_length": 34.846153259277344, "blob_id": "0bd1c42e1263f41994505a6bb0ca9622b9aa6503", "content_id": "254a1987a5da2e01da81f79ec6b1501518162c87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1398, "license_type": "no_license", "max_line_length": 74, "num_lines": 39, "path": "/server/models/session.py", "repo_name": "ipbrennan90/flask-graphene-sqlalchemy-react-starter", "src_encoding": "UTF-8", "text": "from models.foundation import Base\nfrom models.department import Department\nfrom models.teacher import Teacher\nfrom models.subject import Subject\nfrom sqlalchemy import Column, ForeignKey, Integer, String, DateTime, func\nfrom sqlalchemy.orm import (relationship, backref)\n\n\nclass Session(Base):\n __tablename__ = 'session'\n id = Column(Integer, primary_key=True)\n name = Column(String)\n # registration_open = Column(DateTime, default=func.now())\n # registration_closed = Column(DateTime, default=func.now())\n # start_date = Column(DateTime, default=func.now())\n # end_date = Column(DateTime, default=func.now())\n room = Column(Integer)\n department_id = Column(Integer, ForeignKey('department.id'))\n department = relationship(\n Department,\n backref=backref('sessions',\n uselist=True,\n cascade='delete,all')\n )\n subject_id = Column(Integer, ForeignKey('subject.id'))\n subject = relationship(\n Subject,\n backref=backref('sessions',\n uselist=True,\n cascade='delete,all')\n )\n teacher_id = Column(Integer, ForeignKey('teacher.id'))\n teacher = relationship(\n Teacher,\n backref=backref('sessions',\n uselist=True,\n cascade='delete,all')\n )\n total_students = Column(Integer)\n" }, { "alpha_fraction": 0.5874316692352295, "alphanum_fraction": 0.6038251519203186, "avg_line_length": 39.66666793823242, "blob_id": "e6b806340d2780ff299b791af7409f9e9883548a", "content_id": "7f2a8cdf6f98444e30f267866da97029803b1cde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 732, "license_type": "no_license", "max_line_length": 73, "num_lines": 18, "path": "/server/models/foundation.py", "repo_name": "ipbrennan90/flask-graphene-sqlalchemy-react-starter", "src_encoding": "UTF-8", "text": "from sqlalchemy import *\nfrom sqlalchemy.orm import (\n scoped_session, sessionmaker, relationship, backref)\n\nfrom sqlalchemy.ext.declarative import declarative_base\n\n# engine = create_engine('postgresql://iam:developer@db:5432/school')\n# db_session = scoped_session(sessionmaker(autocommit=False,\n# autoflush=False,\n# bind=engine))\n\nengine = create_engine('postgresql://iam:ceme0530@localhost:5432/school')\ndb_session = scoped_session(sessionmaker(autocommit=False,\n autoflush=False,\n bind=engine))\nBase = declarative_base()\n\nBase.query = db_session.query_property()\n" }, { "alpha_fraction": 0.6481927633285522, "alphanum_fraction": 0.6481927633285522, "avg_line_length": 34, "blob_id": "3bf593a0e4009e4d04d6df8f2545901a8b874f56", "content_id": "0369fd56d6a27f8ecc85314c4eb35161f1b9d8b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2905, "license_type": "no_license", "max_line_length": 103, "num_lines": 83, "path": "/server/graph/session.py", "repo_name": "ipbrennan90/flask-graphene-sqlalchemy-react-starter", "src_encoding": "UTF-8", "text": "import graphene\nfrom graphene import relay\nfrom graphene_sqlalchemy import SQLAlchemyObjectType, SQLAlchemyConnectionField\nfrom models.teacher import Teacher as TeacherModel\nfrom models.subject import Subject as SubjectModel\nfrom models.session import Session as SessionModel\nfrom models.department import Department as DepartmentModel\nfrom models.foundation import db_session\nfrom department import Department\nfrom subject import Subject\nfrom teacher import Teacher\n\nfrom sqlalchemy import exists\n\n\nclass Session(SQLAlchemyObjectType):\n class Meta:\n model = SessionModel\n interfaces = (relay.Node, )\n\n\nclass CreateSession(graphene.Mutation):\n id = graphene.Int()\n name = graphene.String()\n department = graphene.Field(Department)\n subject = graphene.Field(Subject)\n teacher = graphene.Field(Teacher)\n room = graphene.String()\n\n class Arguments:\n department = graphene.Int()\n teacher = graphene.Int()\n subject = graphene.Int()\n name = graphene.String()\n room = graphene.Int()\n\n def mutate(self, info, name, department, subject, teacher, room):\n dept_exists = db_session.query(exists().where(\n DepartmentModel.id == department)).scalar()\n teacher_exists = db_session.query(\n exists().where(TeacherModel.id == teacher)).scalar()\n subject_exists = db_session.query(\n exists().where(SubjectModel.id == subject)).scalar()\n if dept_exists and teacher_exists and subject_exists:\n new_session = SessionModel(\n name=name, department_id=department, subject_id=subject, teacher_id=teacher, room=room)\n db_session.add(new_session)\n db_session.commit()\n else:\n exception_string = 'Error! '\n if not dept_exists:\n exception_string = exception_string + \\\n 'department with id {} was not found '.format(department)\n if not teacher_exists:\n exception_string = exception_string + \\\n 'teacher with id {} was not found '.format(teacher)\n if not subject_exists:\n exception_string = exception_string + \\\n 'subject with id {} was not found '.format(subject)\n\n raise Exception(exception_string)\n\n return CreateSession(\n id=new_session.id,\n name=new_session.name,\n department=new_session.department,\n subject=new_session.subject,\n teacher=new_session.teacher,\n room=new_session.room\n )\n\n\nclass Query(graphene.ObjectType):\n all_sessions = SQLAlchemyConnectionField(Session)\n sessions = graphene.List(Session)\n\n def resolve_sessions(self, info, **args):\n q = Session.get_query(info)\n return q.all()\n\n\nclass Mutation(graphene.ObjectType):\n create_session = CreateSession.Field()\n" }, { "alpha_fraction": 0.6431853175163269, "alphanum_fraction": 0.6554364562034607, "avg_line_length": 18.205883026123047, "blob_id": "98387344fb9f00ad93fe66c4bfd3e033447acdec", "content_id": "f9a4b088fd99b6c0980fc1461fa3baac095f51de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 653, "license_type": "no_license", "max_line_length": 53, "num_lines": 34, "path": "/server/server.py", "repo_name": "ipbrennan90/flask-graphene-sqlalchemy-react-starter", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template\nfrom flask_graphql import GraphQLView\n\nfrom models.foundation import db_session\nfrom graph.schema import schema\n\nimport logging\n\napp = Flask(__name__, static_folder=\"../static/dist\",\n template_folder=\"../static\")\napp.debug = True\n\napp.add_url_rule(\n '/graphql',\n view_func=GraphQLView.as_view(\n 'graphql',\n schema=schema,\n graphiql=True\n )\n)\n\n\[email protected]('/')\ndef index():\n return render_template(\"index.html\")\n\n\[email protected]_appcontext\ndef shutdown_session(exception=None):\n db_session.remove()\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=3000)\n" }, { "alpha_fraction": 0.5353535413742065, "alphanum_fraction": 0.5625485777854919, "avg_line_length": 21.98214340209961, "blob_id": "7fac3467e8361fb2eb6918739a4738dfee034f00", "content_id": "97f657e274bff3db708fa9214647b32ce8beb418", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1287, "license_type": "no_license", "max_line_length": 66, "num_lines": 56, "path": "/server/alembic/versions/0fafd71644fc_baseline.py", "repo_name": "ipbrennan90/flask-graphene-sqlalchemy-react-starter", "src_encoding": "UTF-8", "text": "\"\"\"baseline\n\nRevision ID: 0fafd71644fc\nRevises: \nCreate Date: 2018-04-01 13:43:32.634826\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '0fafd71644fc'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n department_type_table = op.create_table(\n 'department',\n sa.Column('id', sa.Integer, primary_key=True),\n sa.Column('name', sa.String)\n )\n\n teacher_type_table = op.create_table(\n 'teacher',\n sa.Column('id', sa.Integer, primary_key=True),\n sa.Column('name', sa.String),\n sa.Column('hired_on', sa.DateTime, default=sa.func.now()),\n sa.Column('department_id', sa.Integer, sa.ForeignKey(\n 'department.id', ondelete=\"CASCADE\"))\n )\n\n op.bulk_insert(\n department_type_table,\n [\n {'name': 'Dat Boi'},\n {'name': 'Computer Science'},\n {'name': 'Engineering'}\n ]\n )\n\n op.bulk_insert(\n teacher_type_table,\n [\n {'name': 'poot', 'department_id': 1},\n {'name': 'david', 'department_id': 2},\n {'name': 'justin', 'department_id': 3}\n ]\n )\n\n\ndef downgrade():\n op.drop_table('department')\n op.drop_table('teacher')\n" }, { "alpha_fraction": 0.720032811164856, "alphanum_fraction": 0.720032811164856, "avg_line_length": 28.707317352294922, "blob_id": "b0d24c4c58890a7ccc0a14a6f6ab13b866baa92e", "content_id": "e11997515ed230aba506fb43e69751d5a2beccbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1218, "license_type": "no_license", "max_line_length": 79, "num_lines": 41, "path": "/server/graph/department.py", "repo_name": "ipbrennan90/flask-graphene-sqlalchemy-react-starter", "src_encoding": "UTF-8", "text": "from graphene_sqlalchemy import SQLAlchemyObjectType, SQLAlchemyConnectionField\nimport graphene\nfrom graphene import relay\nfrom models.department import Department as DepartmentModel\nfrom models.foundation import db_session\n\n\nclass Department(SQLAlchemyObjectType):\n class Meta:\n model = DepartmentModel\n interfaces = (relay.Node, )\n\n\nclass CreateDepartment(graphene.Mutation):\n id = graphene.Int()\n name = graphene.String()\n\n class Arguments:\n name = graphene.String()\n\n def mutate(self, info, name):\n new_department = DepartmentModel(name=name)\n db_session.add(new_department)\n db_session.commit()\n\n return CreateDepartment(id=new_department.id, name=new_department.name)\n\n\nclass Mutation(graphene.ObjectType):\n create_department = CreateDepartment.Field()\n\n\nclass Query(graphene.ObjectType):\n all_departments = SQLAlchemyConnectionField(Department)\n department = graphene.Field(Department, name=graphene.String())\n\n def resolve_department(self, info, **args):\n q = Department.get_query(info)\n department_result = q.filter(\n DepartmentModel.name.contains(args.get('name'))).first()\n return department_result\n" }, { "alpha_fraction": 0.5103734731674194, "alphanum_fraction": 0.5117565989494324, "avg_line_length": 19.657142639160156, "blob_id": "22807ca0a0a0ef942e556b1212d453fcb5ca4c68", "content_id": "4904c647d6fff9efeb0d46957630b6a65107c87a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 723, "license_type": "no_license", "max_line_length": 65, "num_lines": 35, "path": "/static/js/containers/App/index.jsx", "repo_name": "ipbrennan90/flask-graphene-sqlalchemy-react-starter", "src_encoding": "UTF-8", "text": "import React, { Component } from 'react'\nimport { gql } from 'apollo-boost'\nimport { Query } from 'react-apollo'\nimport './style.css'\n\nconst GET_TEACHERS = gql`\n query {\n allTeachers {\n edges {\n node {\n name\n hiredOn\n department {\n name\n }\n }\n }\n }\n }\n`\n\nexport default class App extends Component {\n render() {\n return (\n <Query query={GET_TEACHERS}>\n {({ loading, error, data }) => {\n if (loading) return <div>Loading...</div>\n if (error) return <div>THERE WAS AN ERROR</div>\n console.log(data)\n return <div>{data.allTeachers.edges[0].node.name}</div>\n }}\n </Query>\n )\n }\n}\n" }, { "alpha_fraction": 0.7574257254600525, "alphanum_fraction": 0.7623762488365173, "avg_line_length": 24.375, "blob_id": "1975a9e079eb27d415ed09caebef419f5a55eb51", "content_id": "0a7eaaa893fe4449aacdc3434328c402f8e11463", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 202, "license_type": "no_license", "max_line_length": 80, "num_lines": 8, "path": "/docker-entrypoint-initdb.d/init-school-db.sh", "repo_name": "ipbrennan90/flask-graphene-sqlalchemy-react-starter", "src_encoding": "UTF-8", "text": "#!/bin/bash\nset -e\n\necho \"IM RUNNING CONFIGURATION NOW $POSTGRES_PASSWORD $POSTGRES_USER\"\n\nPGPASSWORD=$POSTGRES_PASSWORD psql -v ON_ERROR_STOP=1 -U $POSTGRES_USER <<-EOSQL\n\tCREATE DATABASE school;\nEOSQL" }, { "alpha_fraction": 0.7741617560386658, "alphanum_fraction": 0.7781065106391907, "avg_line_length": 52.3684196472168, "blob_id": "837946f21078e1e020e35e8ff2d3d66948c8c5a7", "content_id": "739f8ffacfae8896eb86a4e2f9dddd6e3be8cc93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1014, "license_type": "no_license", "max_line_length": 196, "num_lines": 19, "path": "/README.md", "repo_name": "ipbrennan90/flask-graphene-sqlalchemy-react-starter", "src_encoding": "UTF-8", "text": "# flask-graphene-sqlalchemy-react-starter\n\nsimple flask setup to serve a react app\n\nThis is a work in progress, it is certainly not production ready but I am hoping to be working on this regularly.\n\n# Getting Started\n\n* check out the package.json in static for more handy scripts but these will get you started\n* `npm run docker-build` will get the app built and served on localhost:3000\n* `npm run start` will start up the app without a build\n* `npm run docker-down` this takes all volumes down and removes them, this is handy if you are seeing any weirdness that isn't solved just from rebuilding\n* `npm run docker-newdep-js` this runs the docker-down script and then runs a docker-build, I run this everytime I add a new dependency to make sure everything is synced\n\n# Additional Notes\n\n* please don't hesitate to open an issue, I am learning more every day and I'm sure there are some rookie mistakes. I would be glad to have as much constructive criticism as you have time to give.\n\nThanks and happy hacking!\n" } ]
16
guptajay/differential-privacy-website
https://github.com/guptajay/differential-privacy-website
a98d6b9cd673aae7cdcc04a4a0be9d3e70409444
3549bffb6dd35ad8becf5ef0cac15f03031f4264
53bf74d1b983d1abf60ef26147665556cce3452b
refs/heads/master
2022-07-12T09:42:37.078347
2021-05-08T17:04:16
2021-05-08T17:04:16
240,564,504
0
1
null
2020-02-14T17:34:35
2021-05-08T17:08:52
2022-06-22T01:10:36
HTML
[ { "alpha_fraction": 0.8237547874450684, "alphanum_fraction": 0.8295019268989563, "avg_line_length": 103.4000015258789, "blob_id": "c02b8bc03aa63ad478804c2566a99154fbaaee81", "content_id": "16823389af22ac77b25af74fce291c7370093607", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1049, "license_type": "no_license", "max_line_length": 291, "num_lines": 10, "path": "/README.md", "repo_name": "guptajay/differential-privacy-website", "src_encoding": "UTF-8", "text": "# Differential Privacy in Machine Learning\n> This was a research project under NTU’s URECA (Undergraduate Research Experience on Campus) programme. I was presented URECA Undergraduate Research Excellence Award in recognition of outstanding research accomplishments with Distinction in URECA Undergraduate Research Programme AY2019-20.\n\nDifferential privacy makes it possible for tech companies to collect and share aggregate information about user habits, while maintaining the privacy of individual users.\n\nIn this project, we studied existing research developments in ε-differentially private algorithms on structured data using Google’s Differential Privacy Library and refine it so it can be used in real world production data.\n\n![Screenshot](screenshot.png)\n\nThis was a year long project, with a lot of unique experiences. In the beginning, we started with reading reseeach papers on Differential Privacy. In the development of the website shown above, I learnt how to operate Ubuntu Servers, use PostgreSQL and build websites with Flask.\n" }, { "alpha_fraction": 0.4838709533214569, "alphanum_fraction": 0.6950146555900574, "avg_line_length": 15.2380952835083, "blob_id": "eb51c7b2d301d1d03af4c2afb4649071cd98af23", "content_id": "475c84b7756b1ef9bf7c98f816462fda8a49ced2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 341, "license_type": "no_license", "max_line_length": 22, "num_lines": 21, "path": "/requirements.txt", "repo_name": "guptajay/differential-privacy-website", "src_encoding": "UTF-8", "text": "autopep8==1.5\nClick==7.0\ncycler==0.10.0\nFlask==1.1.1\nitsdangerous==1.1.0\nJinja2==2.11.1\nkiwisolver==1.1.0\nMarkupSafe==1.1.1\nmatplotlib==3.1.3\nnumpy==1.18.1\npandas==1.0.1\npsycopg2-binary==2.8.4\npycodestyle==2.5.0\npyparsing==2.4.6\npython-dateutil==2.8.1\npytz==2019.3\nscipy==1.4.1\nseaborn==0.10.0\nsix==1.14.0\nSQLAlchemy==1.3.13\nWerkzeug==1.0.0\n" }, { "alpha_fraction": 0.6426092982292175, "alphanum_fraction": 0.6613463163375854, "avg_line_length": 35.025001525878906, "blob_id": "f5c48fa71fd9958ad56dd00ff95eb6a70c3468d3", "content_id": "bbf806c144bb03ad4bd1ea5cb8f522fdb622885f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5764, "license_type": "no_license", "max_line_length": 135, "num_lines": 160, "path": "/project.py", "repo_name": "guptajay/differential-privacy-website", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nfrom flask import Flask, render_template, redirect, request\nfrom urllib import parse\nfrom sqlalchemy import create_engine\nimport psycopg2\nimport numpy as np\nimport pandas as pd\nimport seaborn as sb\nimport matplotlib.pyplot as plt\nimport io\nimport base64\nfrom flask import Response\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\n# Postgres Login Credentials\nPOSTGRES_ADDRESS = '157.230.253.111'\nPOSTGRES_PORT = '5432'\nPOSTGRES_USERNAME = 'postgres'\nPOSTGRES_PASSWORD = ''\nPOSTGRES_DBNAME = 'test'\n\n# Postgres Connection String\nconn_str = ('postgresql://{username}:{password}@{ipaddress}:{port}/{dbname}'\n .format(username=POSTGRES_USERNAME,\n password=POSTGRES_PASSWORD,\n ipaddress=POSTGRES_ADDRESS,\n port=POSTGRES_PORT,\n dbname=POSTGRES_DBNAME))\n\n# Create the connection\npsqlconn = create_engine(conn_str)\n\n# Global Variables\nstdQuery = ''\nadvQuery = ''\n\napp = Flask(__name__)\n\n\[email protected]('/')\ndef index():\n query = '''SELECT * FROM census_new LIMIT 10;'''\n queryResult = pd.read_sql_query(query, psqlconn)\n columns = list(queryResult)\n return render_template('index.html', dbPreview=queryResult.to_html(), dataset_name=\"census_new\", flag=0, columns=columns)\n\n\[email protected]('/change_dataset', methods=['POST'])\ndef change_dataset():\n dataset_name = request.form['dataset']\n query = '''SELECT * FROM ''' + dataset_name + ''' LIMIT 10;'''\n queryResult = pd.read_sql_query(query, psqlconn)\n columns = list(queryResult)\n return render_template('index.html', dbPreview=queryResult.to_html(), dataset_name=dataset_name, flag=1, columns=list(queryResult))\n\n\[email protected]('/generate_graphs', methods=['POST'])\ndef generate_graphs():\n\n dataset = request.form['dataset']\n col1 = request.form['stdQueryCol1']\n col2 = request.form['stdQueryCol2']\n whereClause = request.form['advQueryWhere']\n func = request.form['stdQueryFunc']\n column = func.lower()\n\n # To handle\n stdQuery = 'SELECT '+col1+','+func + \\\n '('+col2+') FROM '+dataset+' GROUP BY '+col1\n\n stdQueryResult = pd.read_sql_query(stdQuery, psqlconn)\n \n fig = ''\n advQuery = 'Not Applicable'\n\n if(request.form.get('anotherQuery')):\n advQuery = 'SELECT '+col1+','+func+'('+col2+') FROM '+dataset+' WHERE ' + \\\n whereClause+'!='+\"'\"+request.form['advQueryCondition']+\"'\"+' GROUP BY '+col1\n advQueryResult = pd.read_sql_query(advQuery, psqlconn)\n\n fig, axs = plt.subplots(3, 1, figsize=(15, 15))\n axs[0].bar(stdQueryResult[col1], stdQueryResult[column])\n axs[0].set_title('Standard Query')\n axs[1].bar(advQueryResult[col1], advQueryResult[column])\n axs[1].set_title('Adversarial Query')\n\n # Join the two Dataframes on `salary` and check the distributions\n jointData = pd.merge(stdQueryResult, advQueryResult, on=col1)\n\n # Join the two Dataframes on `salary` and check the difference\n jointData[\"difference\"] = jointData[column+\"_x\"] - jointData[column+\"_y\"]\n axs[2].bar(jointData[col1], jointData['difference'])\n axs[2].set_title('Difference')\n else:\n fig, axs = plt.subplots(1, 1, figsize=(8, 8))\n axs.bar(stdQueryResult[col1], stdQueryResult[column])\n axs.set_title('Standard Query')\n\n fig.tight_layout()\n output = io.BytesIO()\n FigureCanvas(fig).print_png(output)\n pngImageB64String = \"data:image/png;base64,\"\n pngImageB64String += base64.b64encode(output.getvalue()).decode('utf8')\n\n return render_template('plots.html', plot_url=pngImageB64String, stdQuery=stdQuery, advQuery=advQuery)\n\n\[email protected]('/handle_submit', methods=['POST'])\ndef handle_submit():\n # To handle standard query\n stdQuery = request.form['stdQuery']\n\n # To handle adversarial query\n advQuery = request.form['advQuery']\n\n # If only advQuery\n if(len(stdQuery) <= 1 and len(advQuery) > 1):\n advQueryResult = pd.read_sql_query(advQuery, psqlconn)\n fig, axs = plt.subplots(1, 1, figsize=(15, 5))\n axs.bar(advQueryResult['salary'], advQueryResult['count'])\n axs.set_title('Adversarial Query')\n\n # If both are present\n elif(len(stdQuery) > 1 and len(advQuery) > 1):\n stdQueryResult = pd.read_sql_query(stdQuery, psqlconn)\n advQueryResult = pd.read_sql_query(advQuery, psqlconn)\n\n fig, axs = plt.subplots(3, 1, figsize=(15, 15))\n axs[0].bar(stdQueryResult['salary'], stdQueryResult['count'])\n axs[0].set_title('Standard Query')\n axs[1].bar(advQueryResult['salary'], advQueryResult['count'])\n axs[1].set_title('Adversarial Query')\n\n # Join the two Dataframes on `salary` and check the distributions\n jointData = pd.merge(stdQueryResult, advQueryResult, on='salary')\n\n # Join the two Dataframes on `salary` and check the difference\n jointData[\"difference\"] = jointData[\"count_x\"] - jointData[\"count_y\"]\n axs[2].bar(jointData['salary'], jointData['difference'])\n axs[2].set_title('Difference')\n\n # If only standard query\n else:\n stdQueryResult = pd.read_sql_query(stdQuery, psqlconn)\n fig, axs = plt.subplots(1, 1, figsize=(15, 5))\n axs.bar(stdQueryResult['salary'], stdQueryResult['count'])\n axs.set_title('Standard Query')\n\n fig.tight_layout()\n output = io.BytesIO()\n FigureCanvas(fig).print_png(output)\n pngImageB64String = \"data:image/png;base64,\"\n pngImageB64String += base64.b64encode(output.getvalue()).decode('utf8')\n\n return render_template('plots.html', plot_url=pngImageB64String, stdQuery=stdQuery, advQuery=advQuery)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n" } ]
3
hodgyj/SSE_Python
https://github.com/hodgyj/SSE_Python
6a07794d19d6e95302201716299a2f045e6eb07f
1b9178557537a647ecc4e4d61194b2f8d1b5f0b6
588cd82e05e23c15d133c097c78028010ccb38d4
refs/heads/master
2021-01-12T14:32:19.905008
2017-01-12T15:31:55
2017-01-12T15:31:55
71,998,838
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.5662696957588196, "alphanum_fraction": 0.569343090057373, "avg_line_length": 28.919540405273438, "blob_id": "a0c6af0ba77c26aa19711c3df879b20c9031aabe", "content_id": "07b2b11c0a1d60a837a75dcc31baf4121575a71f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2603, "license_type": "no_license", "max_line_length": 148, "num_lines": 87, "path": "/sse_python.py", "repo_name": "hodgyj/SSE_Python", "src_encoding": "UTF-8", "text": "import os\nimport json\nimport requests\n\nsse_running = False\nsse_address = \"\"\ngame_name = \"\"\ngame_friendly_name = \"\"\n\ndef json_post(url, data):\n if not sse_running:\n sse_status()\n if sse_running:\n r = requests.post(url, json=data)\n if r.status_code != 200:\n print(\"Error sending data to SteelSeries Engine. Error Code: \" + r.status_code)\n\ndef register_game(icon_id):\n if sse_running:\n game_metadata = {\n \"game\": game_name,\n \"game_display_name\": game_friendly_name,\n \"icon_color_id\": icon_id\n }\n json_post(sse_address + \"/game_metadata\", game_metadata)\n\ndef remove_game():\n if sse_running:\n game_metadata = {\n \"game\": game_name\n }\n json_post(sse_address + \"/remove_game\", game_metadata)\n\ndef register_event(event, minimum, maximum, icon_id=0, handlers=[]):\n if sse_running:\n event_data = {\n \"game\": game_name,\n \"event\": event,\n \"min_value\": minimum,\n \"max_value\": maximum,\n \"icon_id\": icon_id,\n \"handlers\": handlers # See https://github.com/SteelSeries/gamesense-sdk/blob/master/doc/api/writing-handlers-in-json.md#binding-an-event\n }\n json_post(sse_address + \"/register_game_event\", event_data)\n\ndef remove_event(event):\n if sse_running:\n event_data = {\n \"game\": game_name,\n \"event\": event\n }\n json_post(sse_address + \"/remove_game_event\", event_data)\n\ndef heartbeat():\n # Sends a heartbeat event to SSE3 so that colours stay there!\n if sse_running:\n sse_data = {\n \"game\": game_name\n }\n json_post(sse_address + \"/game_heartbeat\", sse_data)\n\ndef send_event(event, value):\n # This function sends a game event and value to SteelSeries\n # Engine 3 so that pretty colours are a thing\n if sse_running:\n sse_data = {\n \"game\": game_name,\n \"event\": event,\n \"data\": {\n \"value\": value\n }\n }\n json_post(sse_address + \"/game_event\", sse_data)\n\ndef sse_status():\n global sse_running\n global sse_address\n # coreProps file exists when SSE3 is running\n file_name = \"C:/ProgramData/SteelSeries/SteelSeries Engine 3/coreProps.json\"\n if os.path.isfile(file_name):\n sse_running = True\n with open(file_name) as sse_data_file:\n sse_data = json.load(sse_data_file)\n sse_address = \"http://\" + sse_data[\"address\"]\n else:\n sse_running = False\n return sse_running\n" }, { "alpha_fraction": 0.7952755689620972, "alphanum_fraction": 0.8031495809555054, "avg_line_length": 30.75, "blob_id": "c97d9094a279445b12e2a968e53c83ab9ac2cc0c", "content_id": "0f5fa566bf3221131085046b5929991089781bc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 127, "license_type": "no_license", "max_line_length": 57, "num_lines": 4, "path": "/README.md", "repo_name": "hodgyj/SSE_Python", "src_encoding": "UTF-8", "text": "# SSE_Python\nIntegration of SteelSeries Engine 3 GameSense into Python\n\n(Uses requests module from http://python-requests.org)\n" } ]
2
morbikdon/CutLang
https://github.com/morbikdon/CutLang
4b695ec96a4b210e52c910255a90105daaa19b8a
c9465e87ba5cae42c043ee445c8fa3aa72f749a1
a4dec05a44da729c088b1269dd43f83f064438bc
refs/heads/master
2023-06-15T12:58:40.631978
2021-07-14T15:33:54
2021-07-14T15:33:54
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7138833999633789, "alphanum_fraction": 0.7181075811386108, "avg_line_length": 34.5099983215332, "blob_id": "67f1c4233862628466f145998eda42cccf954382", "content_id": "3a1fb88b5d74ae6f29950806a141a7d1ae80b947", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3552, "license_type": "no_license", "max_line_length": 136, "num_lines": 100, "path": "/analysis_core/FuncNode.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// FuncNode.h\n// mm -=-=-=-=\n//\n// Created by Anna-Monica on 8/2/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n\n#ifndef FuncNode_h\n#define FuncNode_h\n#include <vector>\n#include \"myParticle.h\"\n#include \"Node.h\"\n#include \"ObjectNode.hpp\"\n\nusing namespace std;\n//takes care of functions with arguments\nclass FuncNode : public Node{\nprivate:\n double (*f)(dbxParticle* apart);\n float v_eta;\n TLorentzVector ametlv;\n Node* userObjectA;\n Node* userObjectB;\n Node* userObjectC;\n Node* userObjectD;\n\n friend class HistoNode1D;\n friend class HistoNode2D;\n friend class LoopNode;\n friend class TableNode;\nprotected:\n std::vector<myParticle*> inputParticles;\n std::vector<myParticle> originalParticles;\n dbxParticle myPart;\n\n virtual void ResetParticles();\n void partConstruct(AnalysisObjects *ao, std::vector<myParticle*> *input, dbxParticle* inputPart);\n virtual void setParticleIndex(int order, int newIndex);\n virtual void setParticleType(int order, int newType);\n virtual void setParticleCollection(int order, string newName);\n\npublic:\n FuncNode(double (*func)(dbxParticle* apart ),std::vector<myParticle*> input, std::string s, \n Node *objectNodea = NULL, std::string as=\"\", Node *objectNodeb = NULL, Node *objectNodec = NULL, Node *objectNoded = NULL);\n virtual void Reset() override;\n virtual void getParticles(std::vector<myParticle *>* particles) override;\n virtual void getParticlesAt(std::vector<myParticle *>* particles, int index) override;\n virtual void setUserObjects(Node *objectNodea = NULL, Node *objectNodeb = NULL, Node *objectNodec = NULL, Node *objectNoded = NULL);\n virtual double evaluate(AnalysisObjects* ao) override;\n virtual ~FuncNode();\n};\n\n\ndouble Qof( dbxParticle* apart);\ndouble Mof( dbxParticle* apart);\ndouble Eof( dbxParticle* apart);\ndouble Pof( dbxParticle* apart);\ndouble Pzof( dbxParticle* apart);\ndouble Ptof( dbxParticle* apart);\ndouble PtConeof( dbxParticle* apart);\ndouble EtConeof( dbxParticle* apart);\ndouble AbsEtaof( dbxParticle* apart);\ndouble Etaof( dbxParticle* apart);\ndouble Rapof( dbxParticle* apart);\ndouble Phiof( dbxParticle* apart);\ndouble \tpdgIDof( dbxParticle* apart);\ndouble MsoftDof( dbxParticle* apart);\ndouble DeepBof( dbxParticle* apart);\ndouble isBTag( dbxParticle* apart);\ndouble isTauTag( dbxParticle* apart);\ndouble tau1of( dbxParticle* apart);\ndouble tau2of( dbxParticle* apart);\ndouble tau3of( dbxParticle* apart);\ndouble dxyof( dbxParticle* apart);\ndouble dzof( dbxParticle* apart);\ndouble vxof( dbxParticle* apart);\ndouble vyof( dbxParticle* apart);\ndouble vzof( dbxParticle* apart);\ndouble vtof( dbxParticle* apart);\ndouble vtrof( dbxParticle* apart);\ndouble sieieof( dbxParticle* apart);\ndouble relisoof( dbxParticle* apart);\ndouble relisoallof( dbxParticle* apart);\ndouble pfreliso03allof( dbxParticle* apart);\ndouble iddecaymodeof( dbxParticle* apart);\ndouble idisotightof( dbxParticle* apart);\ndouble idantieletightof( dbxParticle* apart);\ndouble idantimutightof( dbxParticle* apart);\ndouble tightidof( dbxParticle* apart);\ndouble puidof( dbxParticle* apart);\ndouble genpartidxof( dbxParticle* apart);\ndouble decaymodeof( dbxParticle* apart);\ndouble tauisoof( dbxParticle* apart);\ndouble softIdof( dbxParticle* apart);\ndouble CCountof( dbxParticle* apart);\ndouble nbfof( dbxParticle* apart);\n\n//other functions to be added\n#endif /* FuncNode_h */\n" }, { "alpha_fraction": 0.5882353186607361, "alphanum_fraction": 0.5980392098426819, "avg_line_length": 13.428571701049805, "blob_id": "b9ecc1e7db8613ea17c14c0b9e227ec2dec43f14", "content_id": "f4be0f418b72cbd33ccf1ce3393403688999c89f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 102, "license_type": "no_license", "max_line_length": 52, "num_lines": 7, "path": "/binder/postBuild", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncd CLA\nmake DJUPY=1 \ncd ../runs\nfor f in ../analysis_core/*.pcm; do ln -s $f .; done\nls\n\n" }, { "alpha_fraction": 0.5824345350265503, "alphanum_fraction": 0.5963020324707031, "avg_line_length": 17.02777862548828, "blob_id": "5deaa20a95645ab80d1b75b04d7cb0a336fc8d4e", "content_id": "fc32b3347fdc6b8dbd004a040cd9b91d12602e7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 650, "license_type": "no_license", "max_line_length": 54, "num_lines": 36, "path": "/parser_test/SFuncNode.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// SFuncNode.h\n// mm\n//\n// Created by Anna-Monica on 8/2/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n\n#ifndef SFuncNode_h\n#define SFuncNode_h\n#include \"Node.h\"\nusing namespace std;\n//takes care of functions with arguments\nclass SFuncNode : public Node{\nprivate:\n //should add something related to trigger types\n double (*f)();\npublic:\n SFuncNode(double (*func)(), std::string s ){\n f=func;\n symbol=s;\n left=NULL;\n right=NULL;\n }\n \n virtual double evaluate() {\n return (*f)();\n }\n virtual ~SFuncNode() {}\n};\n\ndouble all(){\n return 1;\n}\n\n#endif /* SFuncNode_h */\n" }, { "alpha_fraction": 0.5259179472923279, "alphanum_fraction": 0.5388768911361694, "avg_line_length": 27.9375, "blob_id": "6099c7729dee37d861b0f56ef1bafc92734383a2", "content_id": "cb99fa48847added0726b4bee8625ff6b6460279", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "Shell", "length_bytes": 926, "license_type": "no_license", "max_line_length": 82, "num_lines": 32, "path": "/.github/workflows/mail_body.sh", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncd $HOME/work/CutLang/CutLang/.github/workflows/artifacts\n\n. $HOME/work/CutLang/CutLang/build/bin/thisroot.sh\nroot --version 2>&1 | tee ./temp2.txt\necho \"\" | tee -a temp2.txt\ncat raw_output.txt | grep -e error -e WARNING -e syntax -e CLA.sh | tee ./temp.txt\n\na=''\nwhile IFS='' read -r i || [ -n \"$i\" ]; do\n if echo $i | grep -q -e \"Check the input file\"; then\n echo $a | tee -a temp2.txt\n echo $i | tee -a temp2.txt\n echo \"\" | tee -a temp2.txt\n\telif echo $i | grep -q Aborted; then\n\t\tif echo $a | grep -q \"Check the input file\"; then\n\t\t\ta=$i\n\t\t\tcontinue\n\t\telse\n\t echo $a | tee -a temp2.txt\n \t echo $i | tee -a temp2.txt\n \techo \"\" | tee -a temp2.txt\n\t\tfi\n elif echo $i | grep -q error; then\n echo $a | tee -a temp2.txt\n fi\n a=$i\ndone < ./temp.txt\n\nrm temp.txt\nmv temp2.txt temp.txt\n" }, { "alpha_fraction": 0.582564115524292, "alphanum_fraction": 0.5917948484420776, "avg_line_length": 21.674419403076172, "blob_id": "36bf077710da79b34a47513c75da332a867060c0", "content_id": "880f59b4994be0bb97b6b27117f380218f16150f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 976, "license_type": "no_license", "max_line_length": 84, "num_lines": 43, "path": "/parser_test/IfNode.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// IfNode.h\n// mm\n//\n// Created by Anna-Monica on 8/14/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n\n#ifndef IfNode_h\n#define IfNode_h\n#include \"Node.h\"\nusing namespace std;\n//takes care of If statements\nclass IfNode : public Node{\nprivate:\n Node * condition;\npublic:\n IfNode(Node* c,Node* l, Node* r, std::string s ){\n \n symbol=s;\n condition=c;\n left=l;\n right=r;\n \n }\n \n virtual void getParticles(std::vector<myParticle *>* particles) override{\n cout<<\"Calling getParticles on an IfNode------doing nothing to input\\n\"; \n }\n\n virtual void Reset() override{\n cout<<\"Calling Rest on an IfNode------doing nothing\\n\"; \n }\n \n virtual double evaluate() override{\n double testResult=condition->evaluate();\n if((bool) testResult) return left->evaluate();\n else return right->evaluate();\n }\n virtual ~IfNode() {}\n};\n\n#endif /* IfNode_h */\n" }, { "alpha_fraction": 0.6295585632324219, "alphanum_fraction": 0.6380038261413574, "avg_line_length": 28.269662857055664, "blob_id": "d43693c40e718ae01d7fc19474d61700c3256005", "content_id": "fd571d9990b7e76ea8c80889be1811805c2c7760", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2605, "license_type": "no_license", "max_line_length": 188, "num_lines": 89, "path": "/analysis_core/HistoNode.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#ifndef HistoNode_h\n#define HistoNode_h\n\n#include \"Node.h\"\n#include <string>\n#include \"TH1F.h\"\n#include \"TH2F.h\"\n\nusing namespace std;\n\nclass HistoNode1D : public Node{\nprivate:\n std::string id;\n std::string Desciption;\n float lowerLimitx;\n float upperLimitx;\n int binsx;\n TH1D *ahisto1;\n std::vector<myParticle*> inputParticles;\n\npublic:\n HistoNode1D( std::string id,std::string desc,int n, float l1, float l2,Node* l){\n this->id=id;\n Desciption=desc;\n lowerLimitx=l1;\n upperLimitx=l2;\n binsx=n;\n symbol=\"histo \"+id+\",\"+Desciption+\",\"+std::to_string(l1)+\",\"+std::to_string(l2)+\",\"+std::to_string(n);\n ahisto1 = new TH1D(id.data(), Desciption.data(), binsx, lowerLimitx, upperLimitx);\n left=l;\n right=NULL;\n }\nvirtual void Reset() override{ left->Reset(); } \n\nvirtual void getParticles(std::vector<myParticle *>* particles) override{\n left->getParticles(particles);\n }\nvirtual void getParticlesAt(std::vector<myParticle *>* particles, int index) override{}\ndouble evaluate(AnalysisObjects* ao) override;\nvirtual ~HistoNode1D(){\n if (left!=NULL) delete left;\n\tif (right!=NULL) delete right;\n}\n\n};\n//----------------------------------------------------------------\nclass HistoNode2D : public Node{\nprivate:\n std::string id;\n std::string Desciption;\n float lowerLimitx;\n float upperLimitx;\n float lowerLimity;\n float upperLimity;\n int binsx;\n int binsy;\n TH2D *ahisto2;\n std::vector<myParticle*> inputParticles;\n\npublic:\n HistoNode2D( std::string id,std::string desc,int nx, float xmin, float xmax, int ny, float ymin, float ymax, Node* l, Node* r){\n this->id=id;\n Desciption=desc;\n lowerLimitx=xmin;\n upperLimitx=xmax;\n\tlowerLimity=ymin;\n\tupperLimity=ymax;\n binsx=nx;\n\tbinsy=ny;\n symbol=\"histo \"+id+\",\"+Desciption+\",\"+std::to_string(xmin)+\",\"+std::to_string(xmax)+\",\"+std::to_string(nx)+\",\"+std::to_string(ymin)+\",\"+std::to_string(ymax)+\",\"+std::to_string(ny);\n ahisto2 = new TH2D(id.data(), Desciption.data(), binsx, lowerLimitx, upperLimitx, binsy, lowerLimity, upperLimity);\n left=l;\n right=r;\n }\nvirtual void Reset() override{ left->Reset(); } \n\nvirtual void getParticles(std::vector<myParticle *>* particles) override{\n left->getParticles(particles);\n }\nvirtual void getParticlesAt(std::vector<myParticle *>* particles, int index) override{}\ndouble evaluate(AnalysisObjects* ao) override;\nvirtual ~HistoNode2D(){\n if (left!=NULL) delete left;\n\tif (right!=NULL) delete right;\n}\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.6212121248245239, "alphanum_fraction": 0.6515151262283325, "avg_line_length": 16.600000381469727, "blob_id": "a46ffcf979cebe3cce5213f0c2351a763a6794c0", "content_id": "e3aed4dcb751156b395795957e29523f8b188290", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 265, "license_type": "no_license", "max_line_length": 54, "num_lines": 15, "path": "/parser_test/myParticle.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// myParticle.h\n// mm\n//\n// Created by Anna-Monica on 8/2/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n#include <string>\n#ifndef myParticle_h\n#define myParticle_h\nstruct myParticle{\n int type;\n int index;\n};\n#endif /* myParticle_h */\n" }, { "alpha_fraction": 0.6481835842132568, "alphanum_fraction": 0.6522200703620911, "avg_line_length": 35.765625, "blob_id": "39578f4732a425dada274b271ff0d8adc12fdec0", "content_id": "9e736ebb17db1899479013559454d63d5224f542", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 4707, "license_type": "no_license", "max_line_length": 185, "num_lines": 128, "path": "/CLA/Makefile", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "MACHINE = $(shell uname -s)\nLINUX = Linux\nMAC = Darwin\nROOTCFLAGS = $(shell root-config --cflags)\nROOTLIBS = $(shell root-config --libs)\nROOTGLIBS = $(shell root-config --glibs)\nTODAYDATE = $(shell date)\t\n\n# we try to identify where the various subdirs (like CorrectionMethods) are\nSUBDIRLOC = $(shell test -d ../CLA && echo ../ || echo ./)\n\n# now we have the include directories defined, possibly using the SUBDIRLOC variable as the root\nINCLUDES = -I$(ROOTSYS)/include -I. -I$(SUBDIRLOC)analysis_core/ -I$(SUBDIRLOC)BP/ -I$(SUBDIRLOC)Dump/\n\n# allow Make to use the same include directories as locations of the sources of various files\nVPATH = $(subst -I,:,$(INCLUDES))\n\nJUPY\t = $(shell uname -n | grep -c 'jupyter')\n\nBISONV = $(shell which bison)\nYACCV = $(shell which yacc)\nFLEXV = $(shell which flex)\nLEXEV = $(shell which lex)\n\nCXX = $(shell root-config --cxx) -g -O2 -D__GRID__ -D__STANDALONE__ \n#-D_CLV_\n#-D__DEBUG__\nCXXFLAGS =$(INCLUDES) -Wall -fPIC\nLD = $(shell root-config --ld) -stdlib=libstdc++\n#LDFLAGS = -g\nSOFLAGS = -shared\n\nCXXFLAGS += $(ROOTCFLAGS)\nLIBS = $(ROOTLIBS) -lMinuit -L. -lDBXNtuple_cpp -ldbx_electron_h -ldbx_tau_h -ldbx_muon_h -ldbx_photon_h -ldbx_jet_h -ldbxParticle_cpp -ldbx_truth_h -ldelphesParticles_h -lz \nGLIBS = $(ROOTGLIBS)\n\n#LIBS += -lzstd -lCling -lpng -ltbb -lssl -lcrypto\n\nBISEXE = 1\nLEXEXE = 1\n\nifneq ($(YACCV),)\nBISEXE = yacc\nendif\n\nifneq ($(BISONV),)\nBISEXE = bison\nendif\n\nifneq ($(LEXV),)\nLEXEXE = lex\nendif\n\nifneq ($(FLEXV),)\nLEXEXE = flex\nendif\n\n\nifeq (1, ${DJUPY})\n\t LIBS += -lCling -lpng -ltbb -lssl -lcrypto\nendif\n\nifneq (0, ${JUPY})\n\t LIBS += -lCling -lpng -ltbb -lssl -lcrypto\nendif\n\nANLOBJS = bp_a.o dump_a.o \nOBJS_1 = $(ANLOBJS) lhco.o lvl0.o fcc.o delphes.o atlasopen.o atlasopenR2.o cmsod.o AtlMin.o VLLMin.o CMSnanoAOD.o VLLBG3.o VLLMinSignal.o\nOBJS_2 = b.o l.o\n\nifneq ($(MACHINE), $(MAC))\n\tcpargs = -pHr\nelse\n\tcpargs = -pr\n\tLDFLAGS = -undefined dynamic_lookup\nendif\n\n.PHONY: clean cleanall auxiliaries softlinks\n\nCLA.exe : checks auxiliaries $(OBJS_1) $(OBJS_2) softlinks\n\tsed \"s/XXXXYYYYZZZZ/$(TODAYDATE)/g\" CLA.Q > CLA.C ; $(CXX) $(CXXFLAGS) $(INCLUDES) -c CLA.C\n\t$(CXX) $(LDFLAGS) -o $@ $(OBJS_1) $(OBJS_2) CLA.o $(SUBDIRLOC)analysis_core/*.o $(CXXFLAGS) $(LIBS)\n\nchecks:\nifeq (${BISEXE},1)\n\t@echo no yacc or bison. Can NOT Continue. Please install bison\n\texit 1\nendif\nifeq (${LEXEXE},1)\n\t@echo no lex or flex. Can NOT Continue. Please install flex\n\texit 1\nendif\n\t@echo yacc:$(YACCV) bison:$(BISONV) executable:$(BISEXE)\n\t@echo lex:$(LEXV) flex:$(FLEXV) executable:$(LEXEXE)\n\n\nb.o : parse.y\n\t$(BISEXE) -d -v -o b.cpp parse.y; $(CXX) $(CXXFLAGS) $(INCLUDES) -c b.cpp\n\nl.o : parse.l\n\t$(LEXEXE) -s -o l.cpp parse.l ; $(CXX) $(INCLUDES) -c l.cpp\n\nauxiliaries:\n\t$(MAKE) -C $(SUBDIRLOC)analysis_core\n\n# it might be good to handle the creation of all the necessary softlinks here\nsoftlinks: auxiliaries\n\ttest -r libdbx_muon_h.so || ( ln -s $(SUBDIRLOC)analysis_core/dbx_muon_h.so libdbx_muon_h.so ; ln -s libdbx_muon_h.so dbx_muon_h.so )\n\ttest -r libdbx_tau_h.so || ( ln -s $(SUBDIRLOC)analysis_core/dbx_tau_h.so libdbx_tau_h.so ; ln -s libdbx_tau_h.so dbx_tau_h.so )\n\ttest -r libdbx_electron_h.so || ( ln -s $(SUBDIRLOC)analysis_core/dbx_electron_h.so libdbx_electron_h.so ; ln -s libdbx_electron_h.so dbx_electron_h.so )\n\ttest -r libdbx_photon_h.so || ( ln -s $(SUBDIRLOC)analysis_core/dbx_photon_h.so libdbx_photon_h.so ; ln -s libdbx_photon_h.so dbx_photon_h.so )\n\ttest -r libdbx_jet_h.so || ( ln -s $(SUBDIRLOC)analysis_core/dbx_jet_h.so libdbx_jet_h.so ; ln -s libdbx_jet_h.so dbx_jet_h.so )\n\ttest -r libdbx_truth_h.so || ( ln -s $(SUBDIRLOC)analysis_core/dbx_truth_h.so libdbx_truth_h.so ; ln -s libdbx_truth_h.so dbx_truth_h.so )\n\ttest -r libdbxParticle_cpp.so || ( ln -s $(SUBDIRLOC)analysis_core/dbxParticle_cpp.so libdbxParticle_cpp.so; ln -s libdbxParticle_cpp.so dbxParticle_cpp.so )\n\ttest -r libDBXNtuple_cpp.so || ( ln -s $(SUBDIRLOC)analysis_core/DBXNtuple_cpp.so libDBXNtuple_cpp.so ; ln -s libDBXNtuple_cpp.so DBXNtuple_cpp.so )\n\ttest -r libdelphesParticles_h.so || ( ln -s $(SUBDIRLOC)analysis_core/delphesParticles_h.so libdelphesParticles_h.so ; ln -s libdelphesParticles_h.so delphesParticles.so )\n\n$(ANLOBJS): %.o : %.cxx\n\t$(CXX) -c $< -o $@ $(CXXFLAGS)\n\n# clean\nclean:\n\trm -f *~ *.o *.so *.o~ *.d core DBX2analysis a.out CLA.exe _* b.* l.cpp \n\t$(MAKE) -C $(SUBDIRLOC)analysis_core clean\n\n# clean everything including the auxiliaries we depend on\ncleanall: clean\n\t$(MAKE) -C $(SUBDIRLOC)analysis_core clean\n\n" }, { "alpha_fraction": 0.5896670818328857, "alphanum_fraction": 0.6100031137466431, "avg_line_length": 43.00353240966797, "blob_id": "6aad380d9587d10d4589bdd4e18049d4ba5c5bc4", "content_id": "9ef30601930f25a6b3eb4cf7991424a01b17c858", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12736, "license_type": "no_license", "max_line_length": 165, "num_lines": 283, "path": "/CLA/AtlMin.C", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#define AtlMin_cxx\r\n#include \"AtlMin.h\"\r\n#include <TH2.h>\r\n#include <TStyle.h>\r\n#include <TCanvas.h>\r\n#include <signal.h>\r\n\r\n#include \"dbx_electron.h\"\r\n#include \"dbx_muon.h\"\r\n#include \"dbx_jet.h\"\r\n#include \"dbx_tau.h\"\r\n#include \"dbx_a.h\"\r\n#include \"DBXNtuple.h\"\r\n#include \"analysis_core.h\"\r\n#include \"AnalysisController.h\"\r\n\r\n//#define __DEBUG__\r\n//extern void _fsig_handler (int) ;\r\n//extern bool fctrlc;\r\n\r\n\r\nvoid AtlMin::GetPhysicsObjects( Long64_t j, AnalysisObjects *a0 )\r\n{\r\n\r\n fChain->GetEntry(j);\r\n\r\n vector<dbxMuon> muons;\r\n vector<dbxElectron> electrons;\r\n vector<dbxTau> taus;\r\n vector<dbxPhoton> photons;\r\n vector<dbxJet> jets;\r\n vector<dbxJet> ljets;\r\n vector<dbxTruth> truth;\r\n vector<dbxParticle> combos;\r\n vector<dbxParticle> constis;\r\n\r\n\r\n map<string, vector<dbxMuon> > muos_map;\r\n map<string, vector<dbxElectron> > eles_map;\r\n map<string, vector<dbxTau> > taus_map;\r\n map<string, vector<dbxPhoton> > gams_map;\r\n map<string, vector<dbxJet> > jets_map;\r\n map<string, vector<dbxJet> >ljets_map;\r\n map<string, vector<dbxTruth> >truth_map;\r\n map<string, vector<dbxParticle> >combo_map;\r\n map<string, vector<dbxParticle> >constits_map;\r\n map<string, TVector2 > met_map;\r\n\r\n evt_data anevt;\r\n int extra_analysis_count=1;\r\n int year=2015;\r\n int prev_RunNumber=-1;\r\n\r\n//temporary variables\r\n TLorentzVector alv;\r\n TLorentzVector dummyTlv(0.,0.,0.,0.);\r\n TVector2 met;\r\n dbxJet *adbxj;\r\n dbxElectron *adbxe;\r\n dbxMuon *adbxm;\r\n //dbxTau *adbxt;\r\n dbxPhoton *adbxp;\r\n\r\n#ifdef __DEBUG__\r\nstd::cout << \"Begin Filling\"<<std::endl;\r\n#endif\r\n\r\n// PHOTONS -------- // now truth info\r\n for (unsigned int i=0; i<truth_pt->size(); i++) {\r\n alv.SetPtEtaPhiE( truth_pt->at(i)*0.001, truth_eta->at(i), truth_phi->at(i), truth_e->at(i)*0.001 ); // all in GeV\r\n adbxp= new dbxPhoton(alv);\r\n adbxp->setCharge(truth_charge->at(i) );\r\n adbxp->setParticleIndx( truth_pdgID->at(i) );\r\n adbxp->setElTriggerMatch( truth_parentIndex->at(i) );\r\n photons.push_back(*adbxp);\r\n delete adbxp;\r\n }\r\n#ifdef __DEBUG__\r\nstd::cout << \"Photons OK:\"<< truth_pt->size()<<std::endl;\r\n#endif\r\n\r\n//MUONS\r\n for (unsigned int i=0; i<mu_pt->size(); i++) {\r\n alv.SetPtEtaPhiE( mu_pt->at(i)*0.001, mu_eta->at(i), mu_phi->at(i), mu_e->at(i)*0.001 ); // all in GeV\r\n adbxm= new dbxMuon(alv);\r\n adbxm->setCharge(mu_charge->at(i) );\r\n\t\tadbxm->setPdgID(-13*mu_charge->at(i) );\r\n adbxm->setEtCone(mu_topoetcone20->at(i) );\r\n adbxm->setPtCone(mu_ptvarcone30->at(i) );\r\n adbxm->setParticleIndx(i);\r\n adbxm->setisZCand(mu_isZCand->at(i) );\r\n adbxm->settrigMatch_HLT_mu26_ivarmedium(mu_trigMatch_HLT_mu26_ivarmedium->at(i));\r\n adbxm->settrigMatch_HLT_mu50(mu_trigMatch_HLT_mu50->at(i));\r\n adbxm->settrigMatch_HLT_mu20_iloose_L1MU15(mu_trigMatch_HLT_mu20_iloose_L1MU15->at(i));\r\n muons.push_back(*adbxm);\r\n delete adbxm;\r\n }\r\n#ifdef __DEBUG__\r\nstd::cout << \"Muons OK:\"<< mu_pt->size()<<std::endl;\r\n#endif\r\n\r\n//ELECTRONS\r\n for (unsigned int i=0; i<el_e->size(); i++) {\r\n alv.SetPtEtaPhiE( el_pt->at(i)*0.001, el_eta->at(i), el_phi->at(i), el_e->at(i)*0.001 ); // all in GeV\r\n adbxe= new dbxElectron(alv);\r\n adbxe->setCharge(el_charge->at(i) );\r\n\t\tadbxe->setPdgID(-11*el_charge->at(i) );\r\n adbxe->setPtCone(el_ptvarcone20->at(i));// 30 has 20 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n adbxe->setEtCone20(el_ptvarcone20->at(i) );\r\n adbxe->settrue_origin(el_true_origin->at(i));\r\n adbxe->settrue_type(el_true_type->at(i));\r\n adbxe->setParticleIndx(i);\r\n adbxe->setClusterEta(el_cl_eta->at(i) );\r\n adbxe->setd0sig(el_d0sig->at(i) );\r\n adbxe->setdelta_z0_sintheta(el_delta_z0_sintheta->at(i) );\r\n adbxe->setisZCand(el_isZCand->at(i) );\r\n adbxe->settrigMatch_HLT_e60_lhmedium_nod0(el_trigMatch_HLT_e60_lhmedium_nod0->at(i));\r\n adbxe->settrigMatch_HLT_e26_lhtight_nod0_ivarloose(el_trigMatch_HLT_e26_lhtight_nod0_ivarloose->at(i));\r\n adbxe->settrigMatch_HLT_e140_lhloose_nod0(el_trigMatch_HLT_e140_lhloose_nod0->at(i));\r\n adbxe->settrigMatch_HLT_e60_lhmedium(el_trigMatch_HLT_e60_lhmedium->at(i));\r\n adbxe->settrigMatch_HLT_e24_lhmedium_L1EM20VH(el_trigMatch_HLT_e24_lhmedium_L1EM20VH->at(i));\r\n adbxe->settrigMatch_HLT_e120_lhloose(el_trigMatch_HLT_e120_lhloose->at(i));\r\n\r\n electrons.push_back(*adbxe);\r\n delete adbxe;\r\n }\r\n\r\n#ifdef __DEBUG__\r\nstd::cout << \"Electrons OK:\"<< el_e->size() <<std::endl;\r\n#endif\r\n\r\n//JETS\r\n for (unsigned int i=0; i<jet_pt->size(); i++) {\r\n alv.SetPtEtaPhiE( jet_pt->at(i)*0.001, jet_eta->at(i), jet_phi->at(i), jet_e->at(i)*0.001 ); // all in GeV\r\n adbxj= new dbxJet(alv);\r\n adbxj->setCharge(-99);\r\n adbxj->setjvt(jet_jvt->at(i));\r\n adbxj->setParticleIndx(i);\r\n adbxj->setFlavor(jet_truthflav->at(i) );\r\n adbxj->set_isbtagged_77(bool(jet_isbtagged_MV2c10_77->at(i)));\r\n// if (jet_isbtagged_MV2c10_77->at(i)>0) std::cout << bool(jet_isbtagged_MV2c10_77->at(i)) <<\"\\n\";\r\n adbxj->setmv2c00(jet_mv2c00->at(i));\r\n adbxj->setmv2c10(jet_mv2c10->at(i));\r\n adbxj->setmv2c20(jet_mv2c20->at(i));\r\n adbxj->setip3dsv1(jet_ip3dsv1->at(i));\r\n\r\n jets.push_back(*adbxj);\r\n delete adbxj;\r\n }\r\n#ifdef __DEBUG__\r\nstd::cout << \"Jets OK:\"<< jet_pt->size() <<std::endl;\r\n#endif\r\n//MET\r\n met.SetMagPhi( met_met*0.001, met_phi); //mev-->gev\r\n#ifdef __DEBUG__\r\nstd::cout << \"MET OK\"<<std::endl;\r\n#endif\r\n\r\n\r\n anevt.run_no=runNumber;\r\n anevt.user_evt_weight=1;\r\n anevt.event_no=eventNumber;\r\n anevt.lumiblk_no=1;\r\n anevt.top_hfor_type=0;\r\n anevt.TRG_e= 1;\r\n anevt.TRG_m= 0;\r\n anevt.TRG_j= 0;\r\n anevt.vxp_maxtrk_no= 1;\r\n anevt.badjet=0;\r\n\r\n anevt.weight_mc=weight_mc;\r\n anevt.weight_pileup=weight_pileup;\r\n anevt.weight_leptonSF=weight_leptonSF;\r\n anevt.weight_bTagSF_77=weight_bTagSF_MV2c10_77;\r\n anevt.weight_jvt=weight_jvt;\r\n\r\n/*\r\n anevt.weight_pileup_UP=weight_pileup_UP;\r\n anevt.weight_pileup_DOWN=weight_pileup_DOWN;\r\n anevt.weight_leptonSF_EL_SF_Trigger_UP=weight_leptonSF_EL_SF_Trigger_UP;\r\n anevt.weight_leptonSF_EL_SF_Trigger_DOWN=weight_leptonSF_EL_SF_Trigger_DOWN;\r\n anevt.weight_leptonSF_EL_SF_Reco_UP=weight_leptonSF_EL_SF_Reco_UP;\r\n anevt.weight_leptonSF_EL_SF_Reco_DOWN=weight_leptonSF_EL_SF_Reco_DOWN;\r\n anevt.weight_leptonSF_EL_SF_ID_UP=weight_leptonSF_EL_SF_ID_UP;\r\n anevt.weight_leptonSF_EL_SF_ID_DOWN=weight_leptonSF_EL_SF_ID_DOWN;\r\n anevt.weight_leptonSF_EL_SF_Isol_UP=weight_leptonSF_EL_SF_Isol_UP;\r\n anevt.weight_leptonSF_EL_SF_Isol_DOWN=weight_leptonSF_EL_SF_Isol_DOWN;\r\n anevt.weight_leptonSF_MU_SF_Trigger_STAT_UP=weight_leptonSF_MU_SF_Trigger_STAT_UP;\r\n anevt.weight_leptonSF_MU_SF_Trigger_STAT_DOWN=weight_leptonSF_MU_SF_Trigger_STAT_DOWN;\r\n anevt.weight_leptonSF_MU_SF_Trigger_SYST_UP=weight_leptonSF_MU_SF_Trigger_SYST_UP;\r\n anevt.weight_leptonSF_MU_SF_Trigger_SYST_DOWN=weight_leptonSF_MU_SF_Trigger_SYST_DOWN;\r\n anevt.weight_leptonSF_MU_SF_ID_STAT_UP=weight_leptonSF_MU_SF_ID_STAT_UP;\r\n anevt.weight_leptonSF_MU_SF_ID_STAT_DOWN=weight_leptonSF_MU_SF_ID_STAT_DOWN;\r\n anevt.weight_leptonSF_MU_SF_ID_SYST_UP=weight_leptonSF_MU_SF_ID_SYST_UP;\r\n anevt.weight_leptonSF_MU_SF_ID_SYST_DOWN=weight_leptonSF_MU_SF_ID_SYST_DOWN;\r\n anevt.weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP=weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP;\r\n anevt.weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN=weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN;\r\n anevt.weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP=weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP;\r\n anevt.weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN=weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN;\r\n anevt.weight_leptonSF_MU_SF_Isol_STAT_UP=weight_leptonSF_MU_SF_Isol_STAT_UP;\r\n anevt.weight_leptonSF_MU_SF_Isol_STAT_DOWN=weight_leptonSF_MU_SF_Isol_STAT_DOWN;\r\n anevt.weight_leptonSF_MU_SF_Isol_SYST_UP=weight_leptonSF_MU_SF_Isol_SYST_UP;\r\n anevt.weight_leptonSF_MU_SF_Isol_SYST_DOWN=weight_leptonSF_MU_SF_Isol_SYST_DOWN;\r\n anevt.weight_leptonSF_MU_SF_TTVA_STAT_UP=weight_leptonSF_MU_SF_TTVA_STAT_UP;\r\n anevt.weight_leptonSF_MU_SF_TTVA_STAT_DOWN=weight_leptonSF_MU_SF_TTVA_STAT_DOWN;\r\n anevt.weight_leptonSF_MU_SF_TTVA_SYST_UP=weight_leptonSF_MU_SF_TTVA_SYST_UP;\r\n anevt.weight_leptonSF_MU_SF_TTVA_SYST_DOWN=weight_leptonSF_MU_SF_TTVA_SYST_DOWN;\r\n anevt.weight_jvt_UP=weight_jvt_UP;\r\n anevt.weight_jvt_DOWN=weight_jvt_DOWN;\r\n anevt.weight_bTagSF_77_extrapolation_up=weight_bTagSF_77_extrapolation_up;\r\n anevt.weight_bTagSF_77_extrapolation_down=weight_bTagSF_77_extrapolation_down;\r\n anevt.weight_bTagSF_77_extrapolation_from_charm_up=weight_bTagSF_77_extrapolation_from_charm_up;\r\n anevt.weight_bTagSF_77_extrapolation_from_charm_down=weight_bTagSF_77_extrapolation_from_charm_down;\r\n// anevt.mc_generator_weights=*mc_generator_weights;\r\n anevt.weight_bTagSF_77_eigenvars_B_up=*weight_bTagSF_77_eigenvars_B_up;\r\n anevt.weight_bTagSF_77_eigenvars_C_up=*weight_bTagSF_77_eigenvars_C_up;\r\n anevt.weight_bTagSF_77_eigenvars_Light_up=*weight_bTagSF_77_eigenvars_Light_up;\r\n anevt.weight_bTagSF_77_eigenvars_B_down=*weight_bTagSF_77_eigenvars_B_down;\r\n anevt.weight_bTagSF_77_eigenvars_C_down=*weight_bTagSF_77_eigenvars_C_down;\r\n anevt.weight_bTagSF_77_eigenvars_Light_down=*weight_bTagSF_77_eigenvars_Light_down;\r\n*/\r\n#ifdef __DEBUG__\r\nstd::cout << \"Filling finished\"<<std::endl;\r\n#endif\r\n\r\n muos_map.insert( pair <string,vector<dbxMuon> > (\"MUO\", muons) );\r\n eles_map.insert( pair <string,vector<dbxElectron> > (\"ELE\", electrons) );\r\n taus_map.insert( pair <string,vector<dbxTau> > (\"TAU\", taus) );\r\n gams_map.insert( pair <string,vector<dbxPhoton> > (\"PHO\", photons) );\r\n jets_map.insert( pair <string,vector<dbxJet> > (\"JET\", jets) );\r\n ljets_map.insert( pair <string,vector<dbxJet> > (\"FJET\", ljets) );\r\n truth_map.insert( pair <string,vector<dbxTruth> > (\"Truth\", truth) );\r\n combo_map.insert( pair <string,vector<dbxParticle> > (\"Combo\", combos) );\r\n constits_map.insert( pair <string,vector<dbxParticle> > (\"Constits\", constis) );\r\n met_map.insert( pair <string,TVector2> (\"MET\", met) );\r\n\r\n *a0={muos_map, eles_map, taus_map, gams_map, jets_map, ljets_map, truth_map, combo_map, constits_map, met_map, anevt};\r\n}\r\n\r\n//--------------------------------------------------------LOOP\r\nvoid AtlMin::Loop( analy_struct aselect, char *extname)\r\n{\r\n// Signal HANDLER\r\n// signal (SIGINT, _fsig_handler); // signal handler has issues with CINT\r\n\r\n if (fChain == 0) {\r\n cout <<\"Error opening the data file\"<<endl; return;\r\n }\r\n int verboseFreq(aselect.verbfreq);\r\n\r\n map < string, int > syst_names;\r\n syst_names[\"01_jes\"] = 2;\r\n\r\n AnalysisController aCtrl(&aselect, syst_names);\r\n aCtrl.Initialize(extname);\r\n cout << \"End of analysis initialization\"<<endl;\r\n\r\n Long64_t nentries = fChain->GetEntriesFast();\r\n if (aselect.maxEvents>0 ) nentries=aselect.maxEvents;\r\n cout << \"number of entries \" << nentries << endl;\r\n Long64_t startevent = 0;\r\n if (aselect.startpt>0 ) startevent=aselect.startpt;\r\n cout << \"starting entry \" << startevent << endl;\r\n Long64_t lastevent = startevent + nentries;\r\n if (lastevent > fChain->GetEntriesFast() ) { lastevent=fChain->GetEntriesFast();\r\n cout << \"Interval exceeds tree. Analysis is done on max available events starting from event : \" << startevent << endl;\r\n }\r\n\r\n Long64_t nbytes = 0, nb = 0;\r\n for (Long64_t j=startevent; j<lastevent; ++j) {\r\n\r\n // if ( fctrlc ) { cout << \"Processed \" << j << \" events\\n\"; break; }\r\n if (0 > LoadTree (j)) break;\r\n if ( j%verboseFreq == 0 ) cout << \"Processing event \" << j << endl;\r\n\r\n AnalysisObjects a0;\r\n GetPhysicsObjects(j, &a0);\r\n aCtrl.RunTasks(a0);\r\n\r\n }// event loop ends.\r\n aCtrl.Finalize();\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6072485446929932, "alphanum_fraction": 0.6072485446929932, "avg_line_length": 29.727272033691406, "blob_id": "3060678348e856a2b1f3253cfe89d9e07210dcf9", "content_id": "a1feb27efa2bd92e3956139661205dc1ef79244d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1352, "license_type": "no_license", "max_line_length": 84, "num_lines": 44, "path": "/analysis_core/AnalysisController.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#ifndef _AnalysisController_h\n#define _AnalysisController_h\n\n#include <vector>\n#include <unordered_set>\n#include <map>\n#include <string>\n#include \"dbx_electron.h\"\n#include \"dbx_photon.h\"\n#include \"dbx_muon.h\"\n#include \"dbx_jet.h\"\n\n// analysis related headers\n#include \"DBXNtuple.h\"\n#include \"../BP/bp_a.h\"\n#include \"../Dump/dump_a.h\"\n#include \"analysis_core.h\"\n\nclass AnalysisController {\n public : \n AnalysisController ( analy_struct *, std::map <std::string, int> syst_names ) ;\n AnalysisController ( analy_struct *as ) { AnalysisController(as, snull); }\n ~AnalysisController ( ) {};\n void Initialize ( char*);\n void SetJetUncs( vector<double> );\n void RunTasks (AnalysisObjects, std::map <std::string, AnalysisObjects>);\n void RunTasks (AnalysisObjects aos) {RunTasks (aos, anull); }\n void Finalize();\n void MakePlots();\n\n private:\n analy_struct aselect;\n vector<double> m_quad_unc;\n std::map <std::string, int> syst_names;\n int extra_analysis_count;\n std::vector<dbxA*> dbxAnalyses;\n std::map <string, int> snull;\n std::map <std::string, AnalysisObjects> anull;\n int mainAnalysis;\n std::unordered_set<int> depAnalyses;\n bool do_deps;\n};\n\n#endif\n" }, { "alpha_fraction": 0.527293860912323, "alphanum_fraction": 0.5311653017997742, "avg_line_length": 34.88888931274414, "blob_id": "63dc5b59b1f132c3b743be6e47ecc02863c7a188", "content_id": "7b047440ff1ec9242a3b4a5bc548232284c633a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2583, "license_type": "no_license", "max_line_length": 135, "num_lines": 72, "path": "/parser_test/main.cpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//include these and only compile main.cpp OR compile together\n// #include \"l.cpp\"\n// #include \"b.cpp\"\n#include <iostream>\n#include <map>\n#include <list>\n#include <vector>\n#include <iterator>\n#include \"myParticle.h\"\n#include \"Node.h\"\nusing namespace std;\nextern int yyparse(list<string> *parts,map<string,Node*>* NodeVars,map<string,vector<myParticle> >* ListParts,map<int,Node*>* NodeCuts,\n vector<double>* Initializations , vector<double>* DataFormats\n );\nextern FILE* yyin;\nint main(void){\n\n list<string> parts; //for def of particles as given by user\n map<string,Node*> NodeVars;//for variable defintion\n map<string,vector<myParticle> > ListParts;//for particle definition\n map<int,Node*> NodeCuts;//cuts and histos\n vector<double> Initializations=vector<double>(11);\n vector<double> DataFormats=vector<double>(6);\n yyin=fopen(\"ini.txt\",\"r\");\n yyparse(&parts,&NodeVars,&ListParts,&NodeCuts,&Initializations,&DataFormats);\n cout<<\"\\n Initializing : \\n\";\n for (vector<double>::iterator a = Initializations.begin(); a != Initializations.end(); a++){\n cout<<*a<<endl;\n }\n\n cout<<\"\\n Particle Lists: \\n\";\n \n for (map<string,vector<myParticle> >::iterator it1 = ListParts.begin(); it1 != ListParts.end(); it1++)\n {\n cout << it1->first << \": \";\n for (vector<myParticle>::iterator lit = it1->second.begin(); lit != it1->second.end(); lit++)\n cout << lit->type << \"_\" << lit->index << \" \";\n cout << \"\\n\";\n }\n \n \n cout<<\"\\n Particles defintions as given by user: \\n\";\n\n std::list<std::string>::iterator it = parts.begin();\n while(it != parts.end())\n {\n std::cout<<(*it)<<std::endl;\n it++;\n }\n\n cout<<\"\\n Variables results: \\n\";\n map<string,Node* >::iterator itv = NodeVars.begin();\n while(itv != NodeVars.end())\n {\n std::cout<<\"**************************** \"<<itv->first<<\" :: \"<<itv->second->evaluate()<<endl;\n itv->second->display();\n std::cout<<std::endl;\n itv++;\n }\n\n cout<<\"\\n CUTS : \\n\";\n std::map<int, Node*>::iterator iter = NodeCuts.begin();\n while(iter != NodeCuts.end())\n {\n cout<<\"**************************** CUT \"<<iter->first<<\" :: \"<<(bool)iter->second->evaluate()<<endl;\n iter->second->display();\n std::cout<<endl;\n iter++;\n }\t\t\n return 0;\n \n}" }, { "alpha_fraction": 0.5787348747253418, "alphanum_fraction": 0.5921937823295593, "avg_line_length": 20.22857093811035, "blob_id": "a930a191c7778da2b87757cf6a21b9bfb60355e3", "content_id": "30a7f06d1728925dae36a3d3fd5241c2257bb043", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 744, "license_type": "no_license", "max_line_length": 69, "num_lines": 35, "path": "/parser_test/Node.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// Node.h\n// mm\n//\n// Created by Anna-Monica on 7/31/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n\n#ifndef Node_h\n#define Node_h\n#include <string>\n#include <iostream>\n//generic node interface\nclass Node{\nprotected:\n Node* left;\n Node* right;\n std::string symbol;\n void display(std::string indent){\n if(left!=NULL) left->display(indent+\" \");\n std::cout<<indent+symbol<<std::endl;\n if(right!=NULL) right->display(\"\\n\"+indent+\" \");\n }\npublic:\n void display(){\n this->display(\"\");\n }\n virtual double evaluate()=0;\n virtual void Reset(){}\n virtual void getParticles(std::vector<myParticle *>* particles){}\n virtual ~ Node(){\n }\n};\n\n#endif /* Node_h */\n" }, { "alpha_fraction": 0.6057692170143127, "alphanum_fraction": 0.6057692170143127, "avg_line_length": 16.5, "blob_id": "1493e92f44b187a8a82aab878dd8663545432274", "content_id": "5894148821424610b8aa3e78b713c49e536a11d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 104, "license_type": "no_license", "max_line_length": 23, "num_lines": 6, "path": "/parser_test/compil.sh", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#!/bin/bash\nflex parse.l\nyacc -d parse.y\ng++ -c lex.yy.c y.tab.c\ng++ y.tab.o lex.yy.o\n./a.out<./ini.txt" }, { "alpha_fraction": 0.536878228187561, "alphanum_fraction": 0.5540308952331543, "avg_line_length": 17.80645179748535, "blob_id": "411162a307e397cfdd8f474de7aa72a887b1895d", "content_id": "a1971f404ab90af30fb498ca1695683645aa2a10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 584, "license_type": "no_license", "max_line_length": 54, "num_lines": 31, "path": "/parser_test/ValueNode.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// ValueNode.h\n// mm\n//\n// Created by Anna-Monica on 7/31/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n\n#ifndef ValueNode_h\n#define ValueNode_h\n#include \"Node.h\"\n//takes care of integers and real values\nclass ValueNode :public Node{\nprivate:\n double value;\npublic:\n ValueNode(double v=0){\n value=v;\n left=NULL;\n right=NULL;\n symbol=std::to_string(v);\n }\n \n virtual double evaluate() {\n return value;\n }\n \n virtual ~ValueNode() {}\n};\n\n#endif /* ValueNode_h */\n" }, { "alpha_fraction": 0.46170786023139954, "alphanum_fraction": 0.4685996174812317, "avg_line_length": 44.160221099853516, "blob_id": "d715daf726bb96ac0016c7f2dee5bf9923a5a943", "content_id": "b972e19637ea156294fcbda322746fa22270ccd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 24522, "license_type": "no_license", "max_line_length": 165, "num_lines": 543, "path": "/analysis_core/FuncNode.cpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#include \"FuncNode.h\"\n\n//#define _CLV_\n#ifdef _CLV_\n#define DEBUG(a) std::cout<<a\n#else\n#define DEBUG(a)\n#endif\n\nvoid FuncNode::ResetParticles(){\n for(int i=0;i<originalParticles.size();i++){\n/*\n cout <<\"O Collection:\"<<originalParticles[i].collection<<\" type:\"<< originalParticles[i].type<<\" index:\"<<originalParticles[i].index<<\"\\n\";\n cout <<\"R Collection:\"<<inputParticles[i]->collection<<\" type:\"<< inputParticles[i]->type<<\" index:\"<<inputParticles[i]->index<<\"\\n\";\n*/\n DEBUG(\"Recall orig i:\"<<originalParticles[i].index);\n *(inputParticles[i])=originalParticles[i];\n }\n}\n \nvoid FuncNode::partConstruct(AnalysisObjects *ao, std::vector<myParticle*> *input, dbxParticle* inputPart){\n inputPart->Reset();\n DEBUG(\"\\n\");\n for(vector<myParticle*>::iterator i=input->begin();i!=input->end();i++){\n DEBUG(\"CONSTRUCT type:\"<<(*i)->type<<\" index:\"<< (*i)->index<< \" addr:\"<<*i<< \"\\t name:\"<< (*i)->collection<<\"\\n\");\n if (((*i)->collection).size() < 1 && abs((*i)->type)!=7 ) cerr << \"Object name SHOULD NOT be empty. type:\"<<(*i)->type\n << \" size:\"<< ((*i)->collection).size()<< \" idx:\"<<(*i)->index <<\"\\n\"; \n }\n int ka;\n DEBUG(\"inputPart q:\"<<inputPart->q()<<\" pdgID:\"<<inputPart->pdgID()<<\"\\n\");\n for(vector<myParticle*>::iterator i=input->begin();i!=input->end();i++){\n int atype=abs((*i)->type);\n short int sgn=atype/(*i)->type;\n int ai=(*i)->index;\n string ac=(*i)->collection;\n if (ai >= 10000) continue; // skip the loop particles\n if (atype==7) ac=\"MET\";\n DEBUG(\"adding:\"<<ac<<\" idx:\"<<ai<<\" type:\"<<atype<<\"\\n\");\n switch (atype) { //----burada STR ile mapda find ediliyor\n\t\t case truth_t: DEBUG(\"truth:\"<< (*i)->index <<\" \");\n\t\t inputPart->setTlv( inputPart->lv()+sgn*ao->truth[ac].at(ai).lv()); \n\t\t inputPart->setCharge(inputPart->q()+ao->truth[ac].at(ai).q() );\n\t\t inputPart->setPdgID(inputPart->pdgID() + ao->truth[ac].at(ai).pdgID() );\n ka=ao->truth[ac].at(ai).nAttribute();\n DEBUG(\"Gen Nattr:\"<<ka<<\"\\n\");\n for (int anat=0; anat<ka; anat++) {\n // cout << \"GenAttr:\"<<anat<< \" :\"<<ao->truth[ac].at(ai).Attribute(anat)<<\"\\n\";\n inputPart->addAttribute(ao->truth[ac].at(ai).Attribute(anat) );\n }\n// cout <<\"----------------done----------------------\\n\";\n\t\t break;\n case muon_t: //ao->muons_map-->find...\n inputPart->setTlv( inputPart->lv()+sgn*ao->muos[ac].at(ai).lv() ); \n inputPart->setCharge(inputPart->q()+ao->muos[ac].at(ai).q() );\n\t\t\t\t\t\t\tinputPart->setPdgID(inputPart->pdgID() + ao->muos[ac].at(ai).pdgID() );\n inputPart->setIsTight(ao->muos[ac].at(ai).isZCand()); // i am overloading the isTight\n ka=ao->muos[ac].at(ai).nAttribute();\n for (int anat=0; anat<ka; anat++) inputPart->addAttribute(ao->muos[ac].at(ai).Attribute(anat) );\n DEBUG(\"muon:\"<<(*i)->index <<\" q:\"<<ao->muos[ac].at(ai).q()<<\" Pt:\" <<ao->muos[ac].at(ai).lv().Pt()<<\" \");\n break;\n case electron_t: inputPart->setTlv( inputPart->lv()+sgn*ao->eles[ac].at(ai).lv() ); \n inputPart->setCharge(inputPart->q()+ao->eles[ac].at(ai).q() );\n\t\t\t\t\t\t\tinputPart->setPdgID(inputPart->pdgID() + ao->eles[ac].at(ai).pdgID() );\n inputPart->setIsTight(ao->eles[ac].at(ai).isZCand()); // i am overloading the isTight\n ka=ao->eles[ac].at(ai).nAttribute();\n DEBUG(\"e- Nattr:\"<<ka<<\"\\n\");\n for (int anat=0; anat<ka; anat++) inputPart->addAttribute(ao->eles[ac].at(ai).Attribute(anat) );\n DEBUG(\"electron:\"<<(*i)->index<<\" \");\n break;\n case tau_t: inputPart->setTlv( inputPart->lv()+sgn*ao->taus[ac].at(ai).lv() ); \n inputPart->setCharge(inputPart->q()+ao->taus[ac].at(ai).q() );\n\t\t\t\t\t\t\tinputPart->setPdgID(inputPart->pdgID() + ao->taus[ac].at(ai).pdgID() );\n // inputPart->setIsTight(ao->eles[ac].at(ai).isZCand()); // i am overloading the isTight\n ka=ao->taus[ac].at(ai).nAttribute();\n for (int anat=0; anat<ka; anat++) inputPart->addAttribute(ao->taus[ac].at(ai).Attribute(anat) );\n DEBUG(\"TAU:\"<<ai<<\" \");\n break;\n case jet_t: DEBUG(\"jet:\"<<ai<<\" \");\n inputPart->setTlv(inputPart->lv()+sgn*ao->jets[ac].at(ai).lv() ); // any jet\n inputPart->setFlavor( ao->jets[ac].at(ai).Flavor() );\n inputPart->setIsTight( ao->jets[ac].at(ai).isbtagged_77()+2* ao->jets[ac].at(ai).isTautagged() );\n ka=ao->jets[ac].at(ai).nAttribute();\n for (int anat=0; anat<ka; anat++) inputPart->addAttribute(ao->jets[ac].at(ai).Attribute(anat) );\n break;\n case bjet_t: inputPart->setTlv(inputPart->lv()+sgn*tagJets(ao, 1, ac)[ ai ].lv() ); // b jet\n inputPart->setIsTight( tagJets(ao,1, ac)[ai].isbtagged_77() );\n DEBUG(\"b-jet:\"<<ai<<\" \");\n break;\n case lightjet_t: inputPart->setTlv(inputPart->lv()+sgn*tagJets(ao, 0, ac)[ ai ].lv()); \n inputPart->setIsTight( tagJets(ao,0, ac)[ai].isbtagged_77() );\n DEBUG(\"qgjet:\"<<ai<<\" \");\n break;\n case muonlikeV_t: v_eta=ao->muos[ac].at(ai).lv().Eta();\n ametlv.SetPtEtaPhiM(ao->met[ac].Mod(), v_eta,ao->met[ac].Phi(),0);\n inputPart->setTlv(inputPart->lv()+sgn*ametlv); // met4v is v from MET using same eta approx.\n DEBUG(\"muMET \");\n break;\n case electronlikeV_t: v_eta=ao->eles[ac].at(ai).lv().Eta();\n ametlv.SetPtEtaPhiM(ao->met[ac].Mod(), v_eta,ao->met[ac].Phi(),0);\n inputPart->setTlv(inputPart->lv()+sgn*ametlv); // v from MET using same eta approx.\n DEBUG(\"eleMET \");\n break;\n case pureV_t: DEBUG(\"MET LV\\n \");\n ametlv.SetPxPyPzE(ao->met[ac].Px(), ao->met[ac].Py(), 0, ao->met[ac].Mod());\n inputPart->setTlv(inputPart->lv()+sgn*ametlv); \n break;\n case photon_t: DEBUG(\"gamma:\"<< (*i)->index <<\" \");\n inputPart->setTlv(inputPart->lv()+sgn*ao->gams[ac].at(ai).lv()); \n ka=ao->gams[ac].at(ai).nAttribute();\n for (int anat=0; anat<ka; anat++) inputPart->addAttribute(ao->gams[ac].at(ai).Attribute(anat) );\n break;\n case fjet_t: DEBUG(\"FatJet:\"<< (*i)->index <<\" \");\n inputPart->setTlv(inputPart->lv()+sgn*ao->ljets[ac].at(ai).lv());\n inputPart->setFlavor( ao->ljets[ac].at(ai).Flavor() );\n ka=ao->ljets[ac].at(ai).nAttribute();\n for (int anat=0; anat<ka; anat++) inputPart->addAttribute(ao->ljets[ac].at(ai).Attribute(anat) );\n break;\n case combo_t: DEBUG(\"combo:\"<< (*i)->index <<\" \");\n inputPart->setTlv( inputPart->lv()+sgn*ao->combos[ac].at(ai).lv()); \n inputPart->setCharge(inputPart->q()+ao->combos[ac].at(ai).q() );\n DEBUG(\"initial pdgID:\"<< inputPart->pdgID() <<\" add pdgID:\"<<ao->combos[ac].at(ai).pdgID()<<\"\\n\");\n\t\t\t\t\t\t\tinputPart->setPdgID(inputPart->pdgID()+ao->combos[ac].at(ai).pdgID() );\n break;\n\n case consti_t: DEBUG(\"consti:\"<< (*i)->index <<\" \");\n inputPart->setTlv( inputPart->lv()+sgn*ao->constits[ac].at(ai).lv()); \n inputPart->setCharge(inputPart->q()+ao->constits[ac].at(ai).q() );\n DEBUG(\"initial pdgID:\"<< inputPart->pdgID() <<\" add pdgID:\"<<ao->constits[ac].at(ai).pdgID()<<\"\\n\");\n\t\t\t\t\t\t\tinputPart->setPdgID(inputPart->pdgID()+ao->constits[ac].at(ai).pdgID() );\n break;\n\n default: std::cout<<\"FN. No such object of type \"<<atype<<\" collection:\"<<ac<<\" idx:\"<<ai<<\" ERROR!\\n\";\n exit(1);\n break;\n } // end of case\n }// end of for\n\t\n}\n\nvoid FuncNode::setParticleIndex(int order, int newIndex){\n inputParticles.at(order)->index=newIndex;\n}\nvoid FuncNode::setParticleType(int order, int newType){\n inputParticles.at(order)->type=newType;\n}\nvoid FuncNode::setParticleCollection(int order, string newName){\n inputParticles.at(order)->collection=newName;\n}\n\nvoid FuncNode::setUserObjects(Node *objectNodea, Node *objectNodeb, Node *objectNodec, Node *objectNoded){\n userObjectA=objectNodea;\n userObjectB=objectNodeb;\n userObjectC=objectNodec;\n userObjectD=objectNoded;\n}\n\nFuncNode::FuncNode(double (*func)(dbxParticle* apart ), std::vector<myParticle*> input, std::string s, \n Node *objectNodea, std::string as, Node *objectNodeb, Node *objectNodec, Node *objectNoded ){\n f=func;\n symbol=s;\n inputParticles=input; // type, index, string=ELE, crELE, ELEsr... and/or Node*objectNode\n myParticle apart;\n userObjectA=objectNodea;\n userObjectB=objectNodeb;\n userObjectC=objectNodec;\n userObjectD=objectNoded;\n DEBUG(\" Received:\"<<input.size() <<\" particles for \"<<s<<\"\\n\");\n\n for (int i=0; i<input.size(); i++){\n// cout <<\" Collection:\"<<inputParticles[i]->collection<<\" type:\"<< inputParticles[i]->type<<\" index:\"<<inputParticles[i]->index<<\"\\n\";\n DEBUG(\" orig i:\"<<input[i]->index);\n apart.index=input[i]->index;\n apart.type=input[i]->type;\n apart.collection=input[i]->collection;\n originalParticles.push_back(apart);\n // cout <<\"O Collection:\"<<originalParticles[i].collection<<\" type:\"<< originalParticles[i].type<<\" index:\"<<originalParticles[i].index<<\"\\n\";\n }\n left=NULL;\n right=NULL;\n}\n \nvoid FuncNode::Reset() {\n this->ResetParticles();\n}\n\nvoid FuncNode::getParticles(std::vector<myParticle *>* particles) {\n int size=particles->size();\n for (int i=0; i<inputParticles.size(); i++){\n \n bool found=false;\n for(int j=0;j<size;j++){\n if (inputParticles[i]->index==particles->at(j)->index)\n {\n found=true;break;\n }\n }\n\n if(!found){\n particles->push_back(inputParticles[i]);\n }\n\n } \n}\n\nvoid FuncNode::getParticlesAt(std::vector<myParticle *>* particles, int index){\n DEBUG(\"function particleAt giver, size: \"<< inputParticles.size()<<\" idx:\"<<index<<\"\\n\");\n particles->push_back(inputParticles[index]);\n}\n\ndouble FuncNode::evaluate(AnalysisObjects* ao) {\n DEBUG(\"\\nIn function Node evaluate, #particles:\"<< inputParticles.size() <<\"\\n\");\n// all objects in *ao are as they were read from the file // returns 1, hardcoded. see ObjectNode.cpp \n if(userObjectA) { double retval=userObjectA->evaluate(ao); \n DEBUG(\"RetVal:\"<< retval <<\"\\n\");\n int thistype=((ObjectNode*)userObjectA)->type;\n string realname=((ObjectNode*)userObjectA)->name;\n DEBUG(\"A t,n:\"<<thistype<<\" , \"<< realname <<\"\\n\");\n for (int ipa=0; ipa<inputParticles.size(); ipa++){\n DEBUG(\"T:\"<<inputParticles[ipa]->type<<\" idx:\"<<inputParticles[ipa]->index<<\"\\n\");\n if (inputParticles[ipa]->type == thistype) inputParticles[ipa]->collection=realname;\n }\n } // replace collection if needed\n if(userObjectB) { userObjectB->evaluate(ao);\n int thistype=((ObjectNode*)userObjectB)->type;\n string realname=((ObjectNode*)userObjectB)->name;\n DEBUG(\"B t,n:\"<<thistype<<\" , \"<< realname <<\"\\n\");\n for (int ipa=0; ipa<inputParticles.size(); ipa++){\n if (inputParticles[ipa]->type == thistype) inputParticles[ipa]->collection=realname;\n }\n } \n if(userObjectC) userObjectC->evaluate(ao); \n if(userObjectD) userObjectD->evaluate(ao); \n if ( userObjectA || userObjectB || userObjectC || userObjectD ) DEBUG(\"UOs EVALUATED:\"<< getStr() <<\"\\n\");\n\n DEBUG(\"P_0 Type:\"<<inputParticles[0]->type<<\" collection:\"\n << inputParticles[0]->collection << \" index:\"<<inputParticles[0]->index<<\"\\n\");\n\n\n if (inputParticles[0]->index == 6213) {\n string base_collection2=inputParticles[0]->collection;\n int base_type2=inputParticles[0]->type;\n int ipart2_max=-1;\n try {\n switch(abs(inputParticles[0]->type) ){ \n case 12: ipart2_max=(ao->muos).at(base_collection2).size(); break;\n case 10: ipart2_max=(ao->truth).at(base_collection2).size(); break;\n case 1: ipart2_max=(ao->eles).at(base_collection2).size(); break;\n case 2: ipart2_max=(ao->jets).at(base_collection2).size(); break;\n case 7: ipart2_max=1; break;\n case 8: ipart2_max=(ao->gams).at(base_collection2).size(); break;\n case 9: ipart2_max=(ao->ljets).at(base_collection2).size(); break;\n case 11: ipart2_max=(ao->taus).at(base_collection2).size(); break;\n case 20: ipart2_max=(ao->combos)[base_collection2].size(); break;\n\n default:\n std::cerr << \"WRONG PARTICLE TYPE:\"<<inputParticles[0]->type << std::endl; break;\n }\n } catch(...) {\n// is it an object we can create?\n// userObjectA->evaluate(ao); // returns 1, hardcoded. see ObjectNode.cpp\n std::cerr << \"YOU WANT A PARTICLE TYPE YOU DIDN'T CREATE:\"<<base_collection2 <<\" !\\n\";\n _Exit(-1);\n }\n // now we know how many we want\n DEBUG (\"loop over \"<< ipart2_max<<\" particles\\t\");\n std::vector<myParticle*> inputParticles1;\n std::vector<myParticle> inputParticles0;\n for (int ip2=0; ip2 < ipart2_max; ip2++){\n myParticle * aparticle = new myParticle;\n aparticle->type= base_type2;\n aparticle->collection= base_collection2;\n aparticle->index=ip2;\n DEBUG( \"index=\"<<ip2<<\" \");\n inputParticles0.push_back(*aparticle);\n delete aparticle;\n }\n DEBUG(\"\\n\");\n double total=0;\n for (int ji=0; ji<inputParticles0.size(); ji++){\n inputParticles1.push_back( &inputParticles0[ji]);\n partConstruct(ao, &inputParticles1,&myPart);\n DEBUG(\"a particle constructed \\t\");\n double retval=(*f)(&myPart );\n DEBUG(\"yielded:\" << retval<<\"\\n\"); \n total+=retval;\n inputParticles1.clear();\n }\n inputParticles0.clear();\n DEBUG(\"FuncNode Sum:\"<<total<<\"\\n\");\n return total;\n } else {\n//------------simply execute\n partConstruct(ao, &inputParticles, &myPart);\n }\n DEBUG(\"Particle constructed \\t\");\n return (*f)(&myPart );\n DEBUG(\"\\n\");\n}\n\nFuncNode::~FuncNode() {}\n\ndouble Qof( dbxParticle* apart){\n double charge=apart->q();\n DEBUG(\" q:\"<<charge<<\"\\t\");\n return charge;\n}\n\ndouble pdgIDof( dbxParticle* apart){\n double pdgID = apart->pdgID();\n DEBUG(\" pdgIDof:\"<<pdgID<<\"\\t\");\n return pdgID;\n}\n\n\ndouble Mof( dbxParticle* apart){\n double mass=(apart->lv()).M();\n DEBUG(\" m:\"<<mass<<\"\\t\");\n return mass;\n}\n\ndouble Eof( dbxParticle* apart){\n double energy=(apart->lv()).E();\n DEBUG(\" E:\"<<energy<<\"\\t\");\n return energy;\n}\n\ndouble Pof( dbxParticle* apart){\n double p=(apart->lv()).P();\n DEBUG(\" P:\"<<p<<\"\\t\");\n return p;\n}\n\ndouble Pzof( dbxParticle* apart){\n double pz=(apart->lv()).Pz();\n DEBUG(\" Pz:\"<<pz<<\"\\t\");\n return pz;\n}\ndouble Ptof( dbxParticle* apart){\n double pt=(apart->lv()).Pt();\n DEBUG(\" Pt:\"<<pt<<\"\\t\");\n return pt;\n}\n\ndouble AbsEtaof( dbxParticle* apart){\n double aeta=fabs((apart->lv()).Eta() );\n DEBUG(\" AEta:\"<<aeta<<\"\\t\");\n return aeta;\n}\n\ndouble Etaof( dbxParticle* apart){\n double eta=(apart->lv()).Eta();\n DEBUG(\" Eta:\"<<eta<<\"\\t\");\n return eta;\n}\n\ndouble Rapof( dbxParticle* apart){\n double rap=(apart->lv()).Rapidity();\n DEBUG(\" Rap:\"<<rap<<\"\\t\");\n return rap;\n}\n\ndouble Phiof( dbxParticle* apart){\n double phi=(apart->lv()).Phi();\n DEBUG(\" phi:\"<<phi<<\"\\t\");\n return phi;\n}\n\ndouble MsoftDof( dbxParticle* apart){\n double MsoftD=apart->Attribute(0) ;\n DEBUG(\" MsoftD:\"<<MsoftD<<\"\\t\");\n return MsoftD;\n}\ndouble DeepBof( dbxParticle* apart){\n double DeepB=apart->Flavor();\n DEBUG(\" DeepB:\"<<DeepB<<\"\\t\");\n return DeepB;\n}\ndouble PtConeof( dbxParticle* apart){\n double ptc=apart->PtCone();\n DEBUG(\" PTC:\"<<ptc<<\"\\t\");\n return ptc;\n}\ndouble EtConeof( dbxParticle* apart){\n double etc=apart->EtCone();\n DEBUG(\" ETC:\"<<etc<<\"\\t\");\n return etc;\n}\n\ndouble isBTag( dbxParticle* apart){\n bool Bval=((apart)->isTight())&1;\n DEBUG(\" BTAG:\"<<Bval<<\"\\t\");\n return Bval;\n}\ndouble isTauTag( dbxParticle* apart){\n bool Tval=((apart)->isTight())&2;\n DEBUG(\" BTAG:\"<<Tval<<\"\\t\");\n return Tval;\n}\n\ndouble tau1of( dbxParticle* apart){\n double tau1=apart->Attribute(1) ;\n DEBUG(\" tau1:\"<<tau1<<\"\\t\");\n return tau1;\n}\ndouble tau2of( dbxParticle* apart){\n double tau2=apart->Attribute(2) ;\n DEBUG(\" tau2:\"<<tau2<<\"\\t\");\n return tau2;\n}\ndouble tau3of( dbxParticle* apart){\n double tau3=apart->Attribute(3) ;\n DEBUG(\" tau3:\"<<tau3<<\"\\t\");\n return tau3;\n}\n//----------for electron and muons\ndouble dzof( dbxParticle* apart){\n double dz=999;\n int ka=apart->nAttribute();\n if (ka>0) dz=apart->Attribute(0) ;\n DEBUG(\" dz:\"<<dz<<\"\\t\");\n return dz;\n}\ndouble dxyof( dbxParticle* apart){\n double dxy=999;\n int ka=apart->nAttribute();\n if (ka>1) dxy=apart->Attribute(1) ;\n DEBUG(\" dxy:\"<<dxy<<\"\\t\");\n return dxy;\n}\ndouble relisoof( dbxParticle* apart){\n double v=apart->Attribute(2);\n DEBUG(\" relisoof:\"<<v<<\"\\t\");\n return v;\n}\ndouble softIdof( dbxParticle* apart){\n double v=apart->Attribute(3);\n DEBUG(\" softidof:\"<<v<<\"\\t\");\n return v;\n}\ndouble vzof( dbxParticle* apart){ \n double v=apart->Attribute(4);\n DEBUG(\" vert z of:\"<<v<<\"\\t\");\n return v;\n}\ndouble vyof( dbxParticle* apart){ \n double v=apart->Attribute(5);\n DEBUG(\" vert y of:\"<<v<<\"\\t\");\n return v;\n}\ndouble vxof( dbxParticle* apart){ \n double v=apart->Attribute(6);\n DEBUG(\" vert x of:\"<<v<<\"\\t\");\n return v;\n}\ndouble vtof( dbxParticle* apart){ \n double v=apart->Attribute(7);\n DEBUG(\" vert t of:\"<<v<<\"\\t\");\n return v;\n}\ndouble vtrof( dbxParticle* apart){ \n double vx=apart->Attribute(6);\n double vy=apart->Attribute(5);\n double v=sqrt(vx*vx+vy*vy);\n DEBUG(\" vert tr of:\"<<v<<\"\\t\");\n return v;\n}\ndouble tauisoof( dbxParticle* apart){\n double v=apart->Attribute(0); // tau attri0\n DEBUG(\" Tau iso of:\"<<v<<\"\\t\");\n return v;\n}\ndouble CCountof( dbxParticle* apart){\n double v=apart->Attribute(9) - apart->Attribute(8)+1;\n DEBUG(\"# Children :\"<<v<<\"\\n\");\n return v;\n}\n//---------for tau's added by SS\ndouble iddecaymodeof( dbxParticle* apart){\n double v=apart->Attribute(1);\n DEBUG(\" iddecaymode:\"<<v<<\"\\t\");\n return v;\n}\ndouble idisotightof( dbxParticle* apart){\n double v=apart->Attribute(2);\n DEBUG(\" idisotight:\"<<v<<\"\\t\");\n return v;\n}\ndouble idantieletightof( dbxParticle* apart){\n double v=apart->Attribute(3);\n DEBUG(\" idantieletight:\"<<v<<\"\\t\");\n return v;\n}\ndouble idantimutightof( dbxParticle* apart){\n double v=apart->Attribute(4);\n DEBUG(\" idantimutight:\"<<v<<\"\\t\");\n return v;\n}\ndouble tightidof( dbxParticle* apart){\n double v=apart->Attribute(4);\n DEBUG(\" tightID for mus:\"<<v<<\"\\t\");\n return v;\n}\ndouble puidof( dbxParticle* apart){\n double v=apart->Attribute(0);\n DEBUG(\" PU ID for jets:\"<<v<<\"\\t\");\n return v;\n}\ndouble genpartidxof( dbxParticle* apart){\n double v=apart->Attribute(5);\n DEBUG(\" genPartIdx:\"<<v<<\"\\t\");\n return v;\n}\ndouble relisoallof( dbxParticle* apart){\n double v=apart->Attribute(6);\n DEBUG(\" tau reliso_all:\"<<v<<\"\\t\");\n return v;\n}\n\ndouble sieieof( dbxParticle* apart){\n double v=apart->Attribute(0);\n DEBUG(\" Photon sieie:\"<<v<<\"\\t\");\n return v;\n}\n\n\ndouble decaymodeof( dbxParticle* apart){\n double v=apart->Attribute(7);\n DEBUG(\" tau decay mode:\"<<v<<\"\\t\");\n return v;\n}\ndouble pfreliso03allof( dbxParticle* apart){\n double v=apart->Attribute(6);\n DEBUG(\" muon pfRelIso03_all:\"<<v<<\"\\t\");\n return v;\n}\n\n//------------------------------\ndouble nbfof( dbxParticle* apart){\n double phi=(apart->lv()).Phi();\n DEBUG(\" CORRECT ME NBF:\"<<phi<<\"\\t\");\n cout <<\"--This is wrong--\\n\";\n return phi;\n}\n" }, { "alpha_fraction": 0.6028131246566772, "alphanum_fraction": 0.6496986150741577, "avg_line_length": 48.766666412353516, "blob_id": "a32dfe43ca4f143757997df56294ef685f3f2165", "content_id": "91afdd264477d2eed86b7c3c1e3734505128b5e3", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "Shell", "length_bytes": 1493, "license_type": "no_license", "max_line_length": 114, "num_lines": 30, "path": "/.github/workflows/deploy.sh", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncd $HOME/work/CutLang/CutLang/runs\nwget http://www.hepforge.org/archive/cutlang/cms_opendata_ttbar.root\nwget http://www.hepforge.org/archive/cutlang/atla_opendata_had_ttbar.root\nwget -O delphes_events_ttbar.root https://docs.google.com/uc?export=download\\&id=1P8Pv2hmV4QcMfNWmQTsuAkqIYcEzsuxt\n\nfor i in $(ls |grep .adl); do\n echo \"Testing $i:\"\n echo \"Using Bash Scripts\"\n echo \"With CMSOD\"\n echo \"./CLA.sh ./cms_opendata_ttbar.root CMSOD -i $i -e 10000\"\n ./CLA.sh ./cms_opendata_ttbar.root CMSOD -i $i -e 10000\n echo \"With ATLASOD\"\n echo \"./CLA.sh ./atla_opendata_had_ttbar.root ATLASOD -i $i -e 10000\"\n ./CLA.sh ./atla_opendata_had_ttbar.root ATLASOD -i $i -e 10000\n echo \"With DELPHES\"\n echo \"./CLA.sh ./delphes_events_ttbar.root DELPHES -i $i -e 10000\"\n ./CLA.sh ./delphes_events_ttbar.root DELPHES -i $i -e 10000\n echo \"Using Python Scripts\"\n echo \"With CMSOD\"\n echo \"python3 CLA.py ./cms_opendata_ttbar.root CMSOD -i $i -e 10000\"\n python3 CLA.py ./cms_opendata_ttbar.root CMSOD -i $i -e 10000\n echo \"With ATLASOD\"\n echo \"python3 CLA.py ./atla_opendata_had_ttbar.root ATLASOD -i $i -e 10000\"\n python3 CLA.py ./atla_opendata_had_ttbar.root ATLASOD -i $i -e 10000\n echo \"With DELPHES\"\n echo \"python3 CLA.py ./delphes_events_ttbar.root DELPHES -i $i -e 10000\"\n python3 CLA.py ./delphes_events_ttbar.root DELPHES -i $i -e 10000\ndone\n" }, { "alpha_fraction": 0.5998085141181946, "alphanum_fraction": 0.6335567235946655, "avg_line_length": 20.536083221435547, "blob_id": "2af1db2bf7c2c63364fe2adcca6fc22c35a49899", "content_id": "e4e0ffc1b200edb7fe182a0787dd8962d51908fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4178, "license_type": "no_license", "max_line_length": 177, "num_lines": 194, "path": "/analysis_core/dbxParticle.cpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#include \"dbxParticle.h\"\n\n#include <iostream>\n#include <cmath>\n#include <iomanip>\n#include <fstream>\n\n#ifndef __DBX_PARTICLE_C__\nClassImp(dbxParticle)\n\ndbxParticle:: dbxParticle() : TObject() {\n/*\n p_et_cone = -999;\n p_pt_cone = -999;\n p_flavor = -999;\n p_istight = -999;\n p_particleindx = -999;\n p_scalefactor=1.;\n p_escalefactor=999.;\n*/\n p_charge=0; // not initialized\n p_pdgID= 0.;\n p_lvector.SetPtEtaPhiM(0, 0, 0, 0);\n}\ndbxParticle:: dbxParticle (TLorentzVector lv){\n p_et_cone = -999;\n p_pt_cone = -999;\n p_flavor = -999;\n p_istight = -999;\n p_particleindx = -999;\n p_charge=-999; // not initialized\n p_lvector=lv;\n p_scalefactor=1.;\n p_scalefactorreco=1.;\n p_scalefactorid=1.;\n p_scalefactortrig=1.;\n p_escalefactor=999.;\n p_z0 = -999;\n}\n\ndbxParticle:: ~dbxParticle() {}\n\ndbxParticle:: dbxParticle (TLorentzVector lv, int q){\n p_pdgID = 0.;\n p_et_cone = -999;\n p_pt_cone = -999;\n p_flavor = -999;\n p_istight = -999;\n p_particleindx = -999;\n p_charge=q; // initalized\n p_lvector=lv;\n p_scalefactor=1.;\n p_escalefactor=999.;\n p_z0=-999;\n\n}\ndbxParticle dbxParticle::operator+ (dbxParticle& p)\n{\n dbxParticle result (this->lv()+p.lv(), this->q()+p.q() );\n// dbxParticle result ;\n// result.setTlv(this->lv()+p.lv());\n// result.setCharge(this->q()+p.q());\n return result;\n}\n\nint dbxParticle::setPdgID(int pdgID)\n{\n\tp_pdgID = pdgID;\n\treturn 0;\n}\n\ndouble dbxParticle::deltaR(dbxParticle p1,dbxParticle p2){\n \n return p1.lv().DeltaR(p2.lv());\n}\n\n\ndouble dbxParticle::deltaPhi(dbxParticle p1,dbxParticle p2){\n \n return p1.lv().DeltaPhi(p2.lv());\n}\n\nint dbxParticle:: setCharge (int q){\n p_charge=q;\n return 0;\n}\n\nint dbxParticle:: setFlavor (double fla){\n p_flavor=fla;\n return 0;\n}\n\nint dbxParticle:: setEtCone (double iso){\n p_et_cone=iso;\n return 0;\n}\n\nint dbxParticle:: setPtCone (double iso){\n p_pt_cone=iso;\n return 0;\n}\n\nint dbxParticle:: setIsTight (int indx){\n p_istight=indx;\n return 0;\n}\n\nint dbxParticle:: setParticleIndx (int indx){\n p_particleindx=indx;\n return 0;\n}\n\nint dbxParticle:: setTlv (TLorentzVector lv){\n p_lvector=lv;\n return 0;\n}\n\n\nint dbxParticle:: setScaleFactor (double sf){\n p_scalefactor=sf;\n return 0;\n}\n\nint dbxParticle:: setScaleFactorReco (double sf){\n p_scalefactorreco=sf;\n return 0;\n}\nint dbxParticle:: setScaleFactorId (double sf){\n p_scalefactorid=sf;\n return 0;\n}\nint dbxParticle:: setScaleFactorTrig (double sf){\n p_scalefactortrig=sf;\n return 0;\n}\nint dbxParticle:: setScaleFactorTrigMcEff (double sf){\n p_scalefactortrig_mceff=sf;\n return 0;\n}\nint dbxParticle:: setScaleFactorIso(double sf){\n p_scalefactoriso=sf;\n return 0;\n}\n\n////////////////////////////////////////////////////////////////////////////\n//These don't make sense now, we keep them for historical reasons 26.02.2014\nint dbxParticle:: setScaleFactorUncertainty (double sf){\n p_escalefactor=sf;\n return 0;\n}\n\nint dbxParticle:: setScaleFactorUncertaintyUp (double sf){\n p_scalefactorup=sf;\n return 0;\n}\n\nint dbxParticle:: setScaleFactorUncertaintyDown (double sf){\n p_scalefactordown= sf;\n return 0;\n}\n\n//////////////////////////////////////////////////////////////////////////\nint dbxParticle:: scaleLorentzVector ( double scale ){\n p_lvector*=scale;\n return 0;\n}\n\nint dbxParticle:: setZ0(double q){\n p_z0=q;\n return 0;\n}\n\nvoid dbxParticle:: dump (){\n std::cout << \"Px=\"<<p_lvector.Px()<< \" Py=\"<<p_lvector.Py()<< \" Pz=\"<<p_lvector.Pz()<< \" E=\"<<p_lvector.E()<<std::endl;\n}\n\n\nvoid dbxParticle:: dump_b (){\n std::cout << \"PT=\"<<p_lvector.Pt()<< \" Eta=\"<<p_lvector.Eta()<< \" Phi=\"<<p_lvector.Phi()<< \" M=\"<<p_lvector.M()<<std::endl;\n}\n\nvoid dbxParticle:: dumpLHCO (std::ofstream& fn){\n using namespace std;\n// # typ eta phi pt jmas ntrk btag had/em sv0 dum2\n fn << fixed <<setprecision(1)<<p_lvector.Eta()<< setw(9)<<setprecision(1)<<p_lvector.Phi()<< setw(9)<<setprecision(1)<<p_lvector.Pt()<< setw(9)<<setprecision(1)<<p_lvector.M();\n fn << fixed<<setw(9)<<setprecision(1)<<p_charge<< setw(9)<<0.0<< setw(9)<<setprecision(1)<< 0.0 << setw(9)<<setprecision(2);\n if (fabs(p_charge)==1) fn << 0.0;\n else fn<<p_flavor;\n fn<<setw(9)<<0.0<<std::endl;\n}\n\n\n#define __DBX_PARTICLE_C__\n#endif\n" }, { "alpha_fraction": 0.7478991746902466, "alphanum_fraction": 0.7899159789085388, "avg_line_length": 16, "blob_id": "6d835b66a8fe442c86fce7d90f3fc461e7960c01", "content_id": "d15ca9ee49b5e5d82e2d1b82a3324cd03dfc376c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 119, "license_type": "no_license", "max_line_length": 34, "num_lines": 7, "path": "/analysis_core/ExternFunctions.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#ifndef externFunctions_h\n#define externFunctions_h\n\n#include \"Razorfunc.h\"\n#include \"CMSSUS16048_functions.h\"\n\n#endif\n" }, { "alpha_fraction": 0.6384040117263794, "alphanum_fraction": 0.6483790278434753, "avg_line_length": 22.58823585510254, "blob_id": "02f4048f0fae2a185f887ad458957f420d0db034", "content_id": "2540c4bbf302ab7ab470f028742eabab443bc7f4", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "Shell", "length_bytes": 401, "license_type": "no_license", "max_line_length": 70, "num_lines": 17, "path": "/.github/workflows/commit.sh", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ntarget_date=`date \"+%Y-%m-%d\" -d \"6 day ago\"`\ncur_date=`git log -1 --pretty=\"format:%cs\" ../previous/raw_output.txt`\ntar_date_int=$(date -d $target_date +%s)\ncur_date_int=$(date -d $cur_date +%s)\n\nif [ $tar_date_int -le $cur_date_int ]; then\n\texit 0\nfi\n\ngit config user.email \"[email protected]\"\ngit config user.name \"bot\"\n\ngit add ../previous/\ngit commit -m \"automated update\" \ngit push origin $1\n" }, { "alpha_fraction": 0.4580935835838318, "alphanum_fraction": 0.482361763715744, "avg_line_length": 36.00925827026367, "blob_id": "14fd32530e996ec280e371b5c0c3a5d3610c1bd0", "content_id": "8034a138369840486908130f4da368023ba882b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3998, "license_type": "no_license", "max_line_length": 128, "num_lines": 108, "path": "/analysis_core/TableNode.cpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// TableNode.cpp\n// takes care of Table Operations\n//\n// Created by ngu on Oct19.\n// Copyright © 2019 . All rights reserved.\n//\n\n#ifndef TableNode_cpp\n#define TableNode_cpp\n\n#include <stdio.h>\n#include <math.h>\n#include \"TableNode.h\"\n#include \"FuncNode.h\"\n#include <TF1.h>\n//#define _CLV_\n#ifdef _CLV_\n#define DEBUG(a) std::cout<<a\n#else\n#define DEBUG(a)\n#endif\n\n\n//---------EVALUATE---------\ndouble TableNode::evaluate(AnalysisObjects* ao) {\n double aval=left->evaluate(ao);\n double bval, tval; \n bool range_found=false;\n int it;\n\n if (left2==NULL){ // 1D\n DEBUG(\"aval:\"<<aval<<\"\\t\");\n for (it=0; it<atable.size(); it+=3){ // 3 is for 1D only. value, min, max.\n if ( aval>=atable[it+1] && aval<atable[it+2]){\n range_found=true;\n tval=atable[it];\n DEBUG(\" tval:\"<<tval<<\"\\n\");\n it=(it/3);\n break;\n } \n }\n if (!range_found) {std::cerr << \"Specified 1st value \"<< aval <<\" is out of table range! Setting coeff to ZERO.\\n\"; \n tval=0;}\n }else{ //2D\n DEBUG(\"\\nTABLE evaluating second function\\n\");\n std::vector<myParticle*> inputParts1;\n std::vector<myParticle*> inputParts2;\n left->getParticles(&inputParts1);\n left2->getParticles(&inputParts2);\n DEBUG(\"1 Size:\"<<inputParts1.size()<<\" 0th:\"<<inputParts1[0]->index<<\"\\n\");\n DEBUG(\"2 Size:\"<<inputParts2.size()<<\" 0th:\"<<inputParts2[0]->index<<\"\\n\");\n FuncNode *pippo;\n if (inputParts2[0]->index == 6213) {\n if (pippo=dynamic_cast< FuncNode*>(left2) ) {\n DEBUG(\"TABLE 2nd func downcast OK\\n\");\n pippo->setParticleIndex(0, inputParts1[0]->index);\n pippo->setParticleCollection(0, inputParts1[0]->collection);\n DEBUG(\"TABLE 2nd func param set OK\\n\");\n } else {\n std::cerr<<\"TABLE 2nd function parmeters can not be set. ERROR\\n\"; exit (15);\n }\n bval=left2->evaluate(ao);\n pippo->setParticleIndex(0, 6213);\n } else bval=left2->evaluate(ao);\n \n DEBUG(\"\\naval:\"<<aval<< \" bval:\"<<bval<<\"\\t\");\n for (it=0; it<atable.size(); it+=5){ // 5 is for 2D only. value, min, max, min2, max2.\n if (aval>=atable[it+1] && aval<atable[it+2] && bval>=atable[it+3] && bval<atable[it+4]){\n range_found=true;\n tval=atable[it];\n DEBUG(\" tval:\"<<tval<<\"\\n\");\n it=(it/5);\n break;\n } \n }\n \n if (!range_found) {std::cerr << \"Specified 1st:\"<< aval << \" or 2nd:\"<< bval\n <<\" value is out of table range! Setting coeff to ZERO.\\n\";\n tval=0;}\n }// 1D & 2D ends.\n DEBUG(\" Error condition:\"<<errors<< \" it:\"<<it<<\"\\n\");\n if (errors && it<errtable.size() ){\n double sigleft=errtable[it];\n double sigright=errtable[it+1];\n double Area=sqrt(2/3.14159265)/(sigright+sigleft);\n TString hesap=\"x>\";\n hesap+=tval;\n hesap+=\"?gaus(0):gaus(3)\";\n TF1 *f4 = new TF1(\"f4\",hesap,0,1);\n f4->SetParameters(Area,tval,sigleft,Area,tval,sigright);\n DEBUG(\"err range:\"<<sigleft<<\",\"<< sigright<<\" modified tval:\"<<f4->GetRandom()<<\"\\n\"); \n }\n\n return (*f)(tval, ao);\n }\n\n\ndouble tweight(double value, AnalysisObjects* ao ) {\n ao->evt.user_evt_weight *= value;\n return 1;\n}\ndouble thitmiss(double value, AnalysisObjects* ao ) {\n DEBUG( \"table hitmiss retval:\"<<value<<\"\\n\");\n return value;\n}\n\n#endif /* TableNode */\n" }, { "alpha_fraction": 0.5586994290351868, "alphanum_fraction": 0.5677917003631592, "avg_line_length": 37.72676086425781, "blob_id": "3e85a338163e49f7330d3ddd53b61781fbbe7aad", "content_id": "2b61653b3a0416030cb4bd139030d136277876eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13748, "license_type": "no_license", "max_line_length": 142, "num_lines": 355, "path": "/CLA/delphes.C", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#define delphes_cxx\n#include \"delphes.h\"\n#include <TH2.h>\n#include <TStyle.h>\n#include <TCanvas.h>\n#include <signal.h>\n#include <TObject.h>\n#include <TBranchElement.h>\n\n#include \"dbx_electron.h\"\n#include \"dbx_muon.h\"\n#include \"dbx_jet.h\"\n#include \"dbx_tau.h\"\n#include \"dbx_a.h\"\n#include \"DBXNtuple.h\"\n#include \"analysis_core.h\"\n#include \"AnalysisController.h\"\n\n//#define _CLV_\n#ifdef _CLV_\n#define DEBUG(a) std::cout<<a\n#else\n#define DEBUG(a)\n#endif\n\n\nextern void _fsig_handler (int) ;\nextern bool fctrlc;\n\n\nTClonesArray* delphes::UseBranch(const char *branchName, TTree *fChain){\n TClonesArray *array = 0;\n TBranchMap::iterator itBranchMap = fBranchMap.find(branchName);\n if(itBranchMap != fBranchMap.end()) {\n cout << \"** WARNING: branch '\" << branchName << \"' is already in use\" << endl;\n array = itBranchMap->second.second;\n } else { \n TBranch *branch = fChain->GetBranch(branchName);\n if(branch) {\n if(branch->IsA() == TBranchElement::Class()) {\n TBranchElement *element = static_cast<TBranchElement *>(branch);\n const char *className = element->GetClonesName();\n Int_t size = element->GetMaximum();\n TClass *cl = gROOT->GetClass(className);\n if(cl) {\n array = new TClonesArray(cl, size);\n array->SetName(branchName);\n fBranchMap.insert(make_pair(branchName, make_pair(branch, array)));\n branch->SetAddress(&array);\n }\n }\n }\n }\n\n if(!array) {\n cout << \"** WARNING: cannot access branch '\" << branchName << \"', return NULL pointer\" << endl;\n }\n return array;\n};\n\n\nvoid delphes::Loop(analy_struct aselect, char *extname)\n{\n\n// Signal HANDLER\n signal (SIGINT, _fsig_handler); // signal handler has issues with CINT\n\n if (fChain == 0) {\n cout <<\"Error opening the data file\"<<endl; return;\n }\n\n int verboseFreq(aselect.verbfreq);\n evt_data anevt;\n int prev_RunNumber=-1;\n\n map < string, int > syst_names;\n syst_names[\"01_jes\"] = 2;\n AnalysisController aCtrl(&aselect, syst_names);\n aCtrl.Initialize(extname);\n cout << \"End of analysis initialization\"<<endl;\n\n TClonesArray *branchParticle = UseBranch(\"Particle\", fChain);\n TClonesArray *branchJet = UseBranch(\"Jet\", fChain);\n TClonesArray *branchPhoton = UseBranch(\"Photon\", fChain);\n TClonesArray *branchElectron = UseBranch(\"Electron\", fChain);\n TClonesArray *branchMuon = UseBranch(\"Muon\", fChain);\n TClonesArray *branchMET = UseBranch(\"MissingET\", fChain);\n//-----------------------------------------------------------min and max nb events\n Long64_t nentries = fChain->GetEntriesFast();\n Long64_t nentinfile=nentries;\n cout << \"number of entries \" << nentries << endl;\n if (aselect.maxEvents>0 ) nentries=aselect.maxEvents;\n cout << \"Forced number of entries \" << nentries << endl;\n Long64_t startevent = 0;\n if (aselect.startpt>0 ) startevent=aselect.startpt;\n cout << \"starting entry \" << startevent << endl;\n Long64_t lastevent = startevent + nentries;\n if (lastevent > nentinfile ) { lastevent=nentinfile;\n cout << \"Interval exceeds tree. Analysis is done on max available events starting from event : \" << startevent << endl;\n }\n//--------------------------------------------------------------generic variables\n GenParticle *particle;\n Jet *jet;\n Photon *photon;\n Electron *electron;\n Muon *muon;\n MissingET *metd;\n Int_t i, j;\n TObject *object;\n TLorentzVector momentum;\n//--------------------------------------------------------------event loop\n for (Long64_t je=startevent; je<lastevent; ++je) {\n\n if ( fctrlc ) { cout << \"Processed \" << je << \" events\\n\"; break; }\n if ( je%verboseFreq == 0 ) cout << \"Processing event \" << je << endl;\n DEBUG(\"Read Event\"<<std::endl);\n int RunNumber=137;\n/*\n if (int(RunNumber)!=prev_RunNumber) {\n cout << \"Working on Run #:\"<<RunNumber<<endl;\n prev_RunNumber=RunNumber;\n }\n*/\n \n// Load selected branches with data from specified event\n fChain->LoadTree(je);\n TBranchMap::iterator itBranchMap;\n TBranch *branch;\n for(itBranchMap = fBranchMap.begin(); itBranchMap != fBranchMap.end(); ++itBranchMap) {\n branch = itBranchMap->second.first;\n if(branch) {\n branch->GetEntry(je);\n }\n }\n DEBUG(\"Branch Entries retrieved\\n\");\n\n vector<dbxMuon> muons;\n vector<dbxElectron> electrons;\n vector<dbxTau> taus;\n vector<dbxPhoton> photons;\n vector<dbxJet> jets;\n vector<dbxJet> ljets;\n vector<dbxTruth> truth;\n vector<dbxParticle> combos;\n vector<dbxParticle> constis;\n\n map<string, vector<dbxMuon> > muos_map;\n map<string, vector<dbxElectron> > eles_map;\n map<string, vector<dbxTau> > taus_map;\n map<string, vector<dbxPhoton> > gams_map;\n map<string, vector<dbxJet> > jets_map;\n map<string, vector<dbxJet> >ljets_map;\n map<string, vector<dbxTruth> >truth_map;\n map<string, vector<dbxParticle> >combo_map;\n map<string, vector<dbxParticle> >constits_map;\n map<string, TVector2 > met_map;\n\n\n//temporary variables\n TLorentzVector alv, alv_up, alv_down, slv;\n TLorentzVector alv_msdown, alv_msup, alv_iddown, alv_idup, alv_ptsup,alv_ptsdown;\n TLorentzVector dummyTlv(0.,0.,0.,0.);\n TVector2 met;\n dbxJet *adbxj;\n dbxElectron *adbxe;\n dbxMuon *adbxm;\n //dbxTau *adbxt;\n dbxPhoton *adbxp;\n dbxTruth *adbxgen;\n\n DEBUG(\"Begin Filling\"<<std::endl);\n if (branchMuon != NULL)\n for(i = 0; i < branchMuon->GetEntriesFast(); ++i) {\n muon= (Muon*) branchMuon->At(i);\n alv.SetPtEtaPhiM( muon->PT, muon->Eta, muon->Phi, (105.658/1E3) ); // all in GeV\n adbxm= new dbxMuon(alv);\n adbxm->setCharge(muon->Charge );\n \t adbxm->setPdgID(-13*muon->Charge );\n adbxm->setEtCone(muon->IsolationVarRhoCorr);\n adbxm->setPtCone(muon->IsolationVar );\n adbxm->setParticleIndx(i);\n adbxm->addAttribute( muon->DZ);\n adbxm->addAttribute( muon->D0);\n adbxm->addAttribute( muon->IsolationVar );\n muons.push_back(*adbxm);\n delete adbxm;\n }\n DEBUG(\"Muons OK:\"<< std::endl);\n\n//ELECTRONS\n if (branchElectron != NULL)\n for(i = 0; i < branchElectron->GetEntriesFast(); ++i) {\n electron= (Electron*) branchElectron->At(i);\n alv.SetPtEtaPhiM( electron->PT, electron->Eta, electron->Phi, (0.511/1E3) ); // all in GeV\n adbxe= new dbxElectron(alv);\n adbxe->setCharge(electron->Charge );\n \t adbxe->setPdgID(-11*electron->Charge );\n adbxe->setParticleIndx(i);\n adbxe->setClusterE(electron->EhadOverEem );\n adbxe->addAttribute( electron->DZ);\n adbxe->addAttribute( electron->D0 );\n adbxe->addAttribute( electron->IsolationVar );\n electrons.push_back(*adbxe);\n delete adbxe;\n }\n DEBUG(\"Electrons OK:\"<< i <<std::endl);\n//PHOTONS\n if (branchPhoton != NULL)\n for(i = 0; i < branchPhoton->GetEntriesFast(); ++i) {\n photon= (Photon*) branchPhoton->At(i);\n alv.SetPtEtaPhiM( photon->PT, photon->Eta, photon->Phi, 0 ); // all in GeV\n adbxp= new dbxPhoton(alv);\n adbxp->setCharge(0);\n adbxp->setParticleIndx(i);\n adbxp->setClusterE(photon->EhadOverEem );\n photons.push_back(*adbxp);\n delete adbxp;\n }\n DEBUG(\"Photons OK:\"<<i<<std::endl);\n\n // Loop over all jets in event\n if (branchJet != NULL)\n for(i = 0; i < branchJet->GetEntriesFast(); ++i) { \n jet = (Jet*) branchJet->At(i);\n alv.SetPtEtaPhiM( jet->PT, jet->Eta, jet->Phi, jet->Mass ); // all in GeV\n// cout<<\"This Jet pt: \"<<jet->PT<<\", eta: \"<<jet->Eta<<\", phi: \"<<jet->Phi <<\" T:\"<<jet->T<<endl;\n adbxj= new dbxJet(alv);\n adbxj->setCharge(jet->Charge);\n adbxj->setParticleIndx(i);\n adbxj->setFlavor(jet->BTag);\n adbxj->set_isbtagged_77( (bool)jet->BTag ); // btag\n adbxj->set_isTautagged( (bool)jet->TauTag); // tau tag\n\n// Loop over all jet's constituents\n for(j = 0; j < jet->Particles.GetEntriesFast(); ++j) {\n object = jet->Particles.At(j);\n// Check if the constituent is accessible\n if(object == 0) continue;\n if(object->IsA() == GenParticle::Class()) {\n particle = (GenParticle*) object;\n// cout << \" GenPart pt: \" << particle->PT << \", eta: \" << particle->Eta << \", phi: \" << particle->Phi << endl;\n alv.SetPtEtaPhiM( particle->PT, particle->Eta, particle->Phi, particle->Mass ); \n adbxgen= new dbxTruth(alv);\n adbxgen->setCharge( particle->Charge );\n adbxgen->setPdgID( particle->PID );\n adbxgen->setParticleIndx(j);\n adbxgen->addAttribute( particle->DZ); //0\n adbxgen->addAttribute( particle->D0); \n adbxgen->addAttribute( 0 ); // this is dummy, as we dont have isolation variable for GEN particles(unlike e,m,photon)\n adbxgen->addAttribute( particle->Status ); //3\n adbxgen->addAttribute( particle->Z ); //4\n adbxgen->addAttribute( particle->Y ); //5\n adbxgen->addAttribute( particle->X ); //6\n adbxgen->addAttribute( particle->T ); //7\n constis.push_back(*adbxgen);\n delete adbxgen;\n }\n }// end of loop over jets constits.\n\n jets.push_back(*adbxj);\n delete adbxj;\n if (constis.size() > 0){\n TString cname =\"JET_\";\n cname+=i; // jet index\n cname+=\"c\"; // c for constituents\n constits_map.insert( pair <string,vector<dbxParticle> > (cname.Data(), constis) );\n DEBUG(\"Inserting \"<<cname<<\" :\"<<constis.size()<<\"\\n\");\n constis.clear();\n }\n }// end of loop over jets\n DEBUG(\"Jets:\"<<i<<std::endl);\n\n\n\n//GEN LEVEL particles\n if (branchParticle != NULL)\n for(i = 0; i < branchParticle->GetEntriesFast(); ++i) { \n particle = (GenParticle*) branchParticle->At(i);\n alv.SetPtEtaPhiM( particle->PT, particle->Eta, particle->Phi, particle->Mass ); // all in GeV\n adbxgen= new dbxTruth(alv);\n adbxgen->setCharge( particle->Charge );\n adbxgen->setPdgID( particle->PID );\n adbxgen->setParticleIndx(i);\n adbxgen->addAttribute( particle->DZ); // 0\n adbxgen->addAttribute( particle->D0); // 1 \n adbxgen->addAttribute( 0 ); // this is dummy, as we dont have isolation variable for GEN particles(unlike e,m,photon)\n adbxgen->addAttribute( particle->Status ); // 3\n adbxgen->addAttribute( particle->Z ); //4\n adbxgen->addAttribute( particle->Y ); //5\n adbxgen->addAttribute( particle->X ); //6\n adbxgen->addAttribute( particle->T ); //7\n adbxgen->addAttribute( particle->D1 ); //8\n adbxgen->addAttribute( particle->D2 ); //9\n unsigned int nkids=particle->D2-particle->D1 +1;\n truth.push_back(*adbxgen);\n/*\n if (abs( particle->PID ) == 1000021 && nkids>1 ){\n cout << \"Gen:\"<<i<<\" Status:\"<< particle->Status << \" pdgID:\"<< particle->PID\n <<\" has \"<<nkids<<\" kids.\" << \" from:\"<<particle->D1<<\" to:\"<<particle->D2<< \"\\n\"; \n cout <<\"vtx:\"<<particle->X <<\" y:\"<<particle->Y<<\"\\n\";\n }\n*/\n delete adbxgen;\n }\n DEBUG(\"GENs:\"<<i<<std::endl);\n\n//MET\n metd = (MissingET*) branchMET->At(0);\n met.SetMagPhi( metd->MET, metd->Phi);\n DEBUG(\"MET OK\"<<std::endl);\n\n\n//------------ auxiliary information -------\n anevt.run_no=RunNumber;\n anevt.lumiblk_no=1;\n anevt.user_evt_weight=1;\n anevt.top_hfor_type=0;\n// anevt.event_no=Event_Number[0];\n anevt.TRG_e= 1;\n anevt.TRG_m= 0;\n anevt.TRG_j= 0;\n anevt.vxp_maxtrk_no= 9;\n anevt.badjet=0;\n anevt.mcevt_weight=1.0;\n anevt.pileup_weight=1.0;\n anevt.z_vtx_weight = 1.0;\n anevt.weight_bTagSF_77 = 1.0;\n anevt.weight_leptonSF = 1.0;\n anevt.vxpType=0;\n anevt.lar_Error=0;\n anevt.core_Flags=0;\n\tanevt.maxEvents=nentries;\n\n DEBUG(\"Filling finished\"<<std::endl);\n muos_map.insert( pair <string,vector<dbxMuon> > (\"MUO\", muons) );\n eles_map.insert( pair <string,vector<dbxElectron> > (\"ELE\", electrons) );\n taus_map.insert( pair <string,vector<dbxTau> > (\"TAU\", taus) );\n gams_map.insert( pair <string,vector<dbxPhoton> > (\"PHO\", photons) );\n jets_map.insert( pair <string,vector<dbxJet> > (\"JET\", jets) );\n ljets_map.insert( pair <string,vector<dbxJet> > (\"FJET\", ljets) );\n truth_map.insert( pair <string,vector<dbxTruth> > (\"Truth\", truth) );\n combo_map.insert( pair <string,vector<dbxParticle> > (\"Combo\", combos) );\n met_map.insert( pair <string,TVector2> (\"MET\", met) );\n if (constits_map.size() < 1) // we only add this if it was previously empty...\n constits_map.insert( pair <string,vector<dbxParticle> > (\"Constits\", constis) );\n\n AnalysisObjects a0={muos_map, eles_map, taus_map, gams_map, jets_map, ljets_map, truth_map, combo_map, constits_map, met_map, anevt};\n\n aCtrl.RunTasks(a0);\n\n }// event loop ends.\n\n aCtrl.Finalize();\n\n}\n" }, { "alpha_fraction": 0.6903353333473206, "alphanum_fraction": 0.7061144113540649, "avg_line_length": 20.125, "blob_id": "9045f79e99da0d16ac68f08523bd9ef27093a128", "content_id": "2f6e492c644afdf10764e51adfd473543f20fba4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 508, "license_type": "no_license", "max_line_length": 54, "num_lines": 24, "path": "/parser_test/NodeTree.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// NodeTree.h\n// mm\n//\n// Created by Anna-Monica on 8/2/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n\n#ifndef NodeTree_h\n#define NodeTree_h\n//include all header files needed in parser\n#include \"myParticle.h\"\n#include \"Node.h\"\n#include \"ValueNode.h\"\n#include \"BinaryNode.hpp\"\n#include \"UnaryAONode.h\"\n#include \"FuncNode.h\"\n#include \"LFuncNode.h\"\n#include \"SFuncNode.h\"\n#include \"HistoNode.h\"\n#include \"IfNode.h\"\n//Delete Nodes\n//Print Nodes As Defined by User\n#endif /* NodeTree_h */\n" }, { "alpha_fraction": 0.49984976649284363, "alphanum_fraction": 0.514321506023407, "avg_line_length": 35.77532196044922, "blob_id": "8e6c8a40ce9af26ed5216208b8049a305e483b4c", "content_id": "d9e3227eff38bc58cc7b71bc71bc4a0dc2c0ae51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 19970, "license_type": "no_license", "max_line_length": 149, "num_lines": 543, "path": "/BP/bp_a.cxx", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#include \"TParameter.h\"\n#include <TRandom.h>\n#include \"TText.h\"\n#include <iostream>\n#include <sstream> // std::istringstream\n#include <string>\n#include <map>\n#include <iterator>\n#include <vector>\n#include \"SearchNode.h\"\n\n#include \"bp_a.h\"\n#include \"analysis_core.h\"\n#include \"dbx_a.h\"\n\n//#define __SEZEN__\n//#define _CLV_\n\n#ifdef _CLV_\n#define DEBUG(a) std::cout<<a\n#else\n#define DEBUG(a)\n#endif\n\nextern int yyparse(list<string> *parts,map<string,Node*>* NodeVars,map<string,vector<myParticle*> >* ListParts,map<int,Node*>* NodeCuts,\n map<int,Node*>* BinCuts, map<string,Node*>* ObjectCuts, vector<string>* Initializations, \n vector<int>* TRGValues, map<string,pair<vector<float>, bool> >* ListTables,\n map<string, vector<cntHisto> >*cntHistos);\n\nextern FILE* yyin;\nextern int cutcount;\nextern int bincount;\nextern int yylineno;\nextern char * yytext;\n\n\nbool is_number(const std::string& s)\n{\n return( strspn( s.c_str(), \"-.0123456789\" ) == s.size() );\n}\n\nint BPdbxA::getInputs(std::string aname) {\n int retval=0;\n return retval;\n}\n\nint BPdbxA::plotVariables(int sel) {\n return 0; \n}\n\n//--------------------------\nint BPdbxA:: readAnalysisParams() {\n int retval=0;\n\n// dbxA::ChangeDir(cname);\n TString CardName=cname;\n CardName+=\"-card.ini\";\n\n ifstream cardfile(CardName);\n if ( ! cardfile.good()) {\n cerr << \"The cardfile \" << CardName << \" file has problems... \" << endl;\n return -1;\n }\n\n// ---------------------------DBX style defs, objects and cuts\n string tempLine;\n string tempS1, tempS2;\n string hashdelimiter = \"#\";\n size_t found, foundp, foundr, foundw, founds, foundsave;\n TString DefList2file=\"\\n\";\n TString CutList2file=\"\\n\";\n TString ObjList2file=\"\\n\";\n\n bool algorithmnow=false;\n\n while ( ! cardfile.eof() ) {\n getline( cardfile, tempLine );\n if ( tempLine[0] == '#' ) continue; // skip comment lines starting with #\n if (tempLine.find_first_of(\"#\") != std::string::npos ){ // skip anything after #\n tempLine.erase(tempLine.find_first_of(\"#\"));\n }\n// cout << tempLine<<\"\\n\";\n if (tempLine.size() < 3) continue; // remove the junk\n\n//-------------tokenize with space or tab \n std::istringstream iss(tempLine);\n std::vector<std::string> resultstr((std::istream_iterator<std::string>(iss)), std::istream_iterator<std::string>());\n if (resultstr.size() < 1) continue;\n string firstword=resultstr[0];\n for(auto& c : firstword) { c = tolower(c); } // convert to lowercase\n string toplam;\n if (resultstr.size() >1) for(int ic=1; ic<resultstr.size(); ic++) {\n// cout << resultstr[ic] <<\".\\n\";\n toplam+=resultstr[ic];\n if (ic<resultstr.size()-1) toplam+=\" \";\n } \n\n//---------obj\n if ((firstword == \"obj\") || (firstword == \"object\") ) {\n ObjList2file+=tempLine;\n ObjList2file+=\"\\n\";\n continue;\n }\n\n//---------algo / region etc.\n if ((firstword == \"algo\") || (firstword==\"region\")) {\n cout <<\"\\t REGION/ALGO:\"<< resultstr[1] <<\"\\n\";\n algorithmnow=true;\n sprintf (algoname,\"%s\",resultstr[1].c_str());\n continue;\n }\n//---------defs\n if ((firstword == \"def\") || (firstword==\"define\")) {\n DefList2file+=tempLine;\n DefList2file+=\"\\n\";\n continue;\n }\n//---------bins\n if (firstword == \"bin\") {\n// cout << toplam <<\"\\n\";\n if (is_number(resultstr[2]) ){ // MHT 0 300 400, do magic\n// cout <<\"magic needed \\n\"; // 1 2 3 4\n TString con1 =resultstr[1];\n con1+=\" <= \";\n con1+=resultstr[2];\n binCL.push_back(con1.Data());\n for(int ic=3; ic<resultstr.size(); ic++) {\n con1 =resultstr[1];\n con1+=\" [] \";\n con1+=resultstr[ic-1];\n con1+=\" \";\n con1+=resultstr[ic];\n binCL.push_back(con1.Data());\n }\n con1 =resultstr[1];\n con1+=\" >= \";\n con1+=resultstr[resultstr.size()-1];\n binCL.push_back(con1.Data());\n \n } else binCL.push_back(toplam); // no magic\n continue;\n }\n\n//---------other cmds\n if ( (firstword==\"cmd\") || (firstword==\"sort\") || (firstword==\"reject\")\n || (firstword==\"save\") || (firstword==\"weight\") || (firstword==\"select\")\n ) {\n if (algorithmnow) {\n CutList2file+=tempLine;\n CutList2file+=\"\\n\";\n if (firstword==\"save\"){\n tempS2 = \"[Save] \";\n tempS2 += toplam;\n effCL.push_back(tempS2);\n } else effCL.push_back(toplam);\n// cout <<toplam<<\"\\n\";\n } else {\n ObjList2file+=tempLine;\n ObjList2file+=\"\\n\";\n }\n continue;\n }\n//---------histos\n if (firstword==\"histo\") {\n CutList2file+=tempLine;\n CutList2file+=\"\\n\";\n size_t apos=toplam.find_first_of('\"');\n size_t bpos=toplam.find_last_of('\"');\n tempS1 = toplam.substr(apos+1, bpos-apos-1); // without the quotation marks\n tempS2 = \"[Histo] \";\n tempS2 += tempS1;\n// cout <<tempS2<<\"\\n\";\n if (algorithmnow) {\n effCL.push_back(tempS2);\n CutList2file+=tempLine;\n CutList2file+=\"\\n\";\n } else {\n ObjList2file+=tempLine;\n ObjList2file+=\"\\n\";\n }\n\n continue;\n }\n\n } // end of first look over ADL file\n\n//-----create the relevant output directory\n if (!algorithmnow) {\n int r=dbxA::setDir(cname); // make the relevant root directory\n if (r) std::cout <<\"Root Directory Set Failure in:\"<<cname<<std::endl;\n dbxA::ChangeDir(cname);\n } else {\n int r=dbxA::setDir(algoname); // make the relevant root directory\n if (r) std::cout <<\"Root Directory Set Failure in:\"<<cname<<std::endl;\n dbxA::ChangeDir(algoname);\n }\n\n\n\n// ---------------------------read CutLang style cuts using lex/yacc\n NameInitializations={\" \",\" \"};\n TRGValues={1,0,0,0,0};\n yyin=fopen(CardName,\"r\");\n if (yyin==NULL) { cout << \"Cardfile \"<<CardName<<\" has problems, please check\\n\";}\n cutcount=0;\n bincount=0;\n cout <<\"==Parsing started:\\t\";\n retval=yyparse(&parts,&NodeVars,&ListParts,&NodeCuts, &BinCuts, &ObjectCuts, &NameInitializations, &TRGValues, &ListTables, &cntHistos);\n cout <<\"\\t Parsing finished.==\\n\";\n if (retval){\n cout << \"\\nyyParse returns SYNTAX error in the input file.\\n\";\n cout << \"Offending text is: \"<< yytext<<\"\\n\";\n exit (99); \n }\n cout << \"We have \"<<NodeCuts.size() << \" CutLang Cuts, \"<<ObjectCuts.size() <<\" CutLang objects and \";\n cout << BinCuts.size() << \" Bins\\n\";\n TRGe = TRGValues[0];\n TRGm = TRGValues[1];\n skip_effs = (bool) TRGValues[2];\n skip_histos = (bool) TRGValues[3];\n systematics_bci = TRGValues[4];\n cout << \"Systematics:\"<<systematics_bci<<\"\\n\";\n// ------------------------------------4 is reserved for systematics use.\n\n//---------save in the dir.\n unsigned int effsize=NodeCuts.size()+1; // all is always there \n \n//-----create the eff histograms\n int r=dbxA::defHistos( effsize); // enough room\n\n//----------put into output file as text\n TText cinfo(0,0,CutList2file.Data());\n cinfo.SetName(\"CLA2cuts\");\n cinfo.Write();\n\n TText info(0,0,DefList2file.Data());\n info.SetName(\"CLA2defs\");\n info.Write();\n\n TText oinfo(0,0,ObjList2file.Data());\n oinfo.SetName(\"CLA2Objs\");\n oinfo.Write();\n\n\n std::map<int, Node*>::iterator iter = NodeCuts.begin();\n while(iter != NodeCuts.end()) {\n// cout << \"**-- BP sees:\"<<iter->second->getStr().Data()<<\".\\n\";\n if (iter->second->getStr().CompareTo(\" save\") == 0 ) {\n\t\t save.push_back(iter->first);\n// cout <<\"Saving at \"<<iter->first<<\"\\n\";\n\t\t iter->second->createFile();\n\t\t}\n if (iter->second->getStr().Contains(\"~=\") ) {\n\t optimize.insert(iter->first);\n// cout <<\"Optimize at \"<<iter->first<<\"\\n\";\n\t\t}\n iter++;\n }\n#ifdef _CLV_\n// check if the user injects cuts or not.\n for (int jt=0; jt<TRGValues.size(); jt++){\n cout <<\"Cut @:\"<<jt<<\" value:\"<<TRGValues.at(jt)<<\"\\n\";\n }\n for (int jt=0; jt<effCL.size(); jt++){\n cout << \"Eff @:\"<<jt<<\" val:\"<<effCL.at(jt)<<\"\\n\";\n }\n#endif\n \n unsigned int binsize=BinCuts.size(); // bins \n if (binsize>0) hbincounts= new TH1D(\"bincounts\",\"event counts in bins \",binsize,0.5,binsize+0.5);\n if (binsize==binCL.size() ) {\n for (int jbin=0; jbin<binsize; jbin++){\n DEBUG(\"Bin from User C++:\"<<binCL[jbin]<<\"\\n\");\n hbincounts->GetXaxis()->SetBinLabel(1+jbin,binCL[jbin].c_str() );\n }\n } else {\n std::map<int, Node*>::iterator biter = BinCuts.begin();\n while(biter != BinCuts.end()) { \n DEBUG(\"Bin from Auto yacc:\"<<biter->second->getStr()<<\"\\n\");\n hbincounts->GetXaxis()->SetBinLabel(biter->first, biter->second->getStr().Data() );\n biter++;\n }\n }\n//--------effciency names and debugs \n eff->GetXaxis()->SetBinLabel(1,\"all Events\"); // this is hard coded.\n cout << \"TRGe:\"<<TRGe<<\" TRGm:\"<<TRGm<<\"\\n\";\n DEBUG(\"CL CUTS:\"<< NodeCuts.size()<< \" eff:\"<<effCL.size() <<\"\\n\");\n iter = NodeCuts.begin();\n int labelSkip=0;\n bool usecpp=true;\n int inserted=TRGValues.size()-5;\n if (inserted>0) {\n std::cout<<\"Auto inserted cuts:\"<< inserted<<\"\\n\";\n }\n bool nextcpp=false;\n while(iter != NodeCuts.end())\n { \n DEBUG(\" CUT \"<<iter->first<<\" LabelSkip:\"<<labelSkip<< \" inserted:\"<<inserted << \" \");\n DEBUG(\" :\"<<iter->second->getStr()<<\"\\t\");\n string newNLabels=iter->second->getStr().Data();\n DEBUG(\"-->\"<<effCL[ iter->first -1-labelSkip]<<\"\\t\");\n TString ELabels=effCL[ iter->first -1-labelSkip];\n if (inserted>0 && !nextcpp) { //5-0 yacc, 6-1: c++,\n if ( iter->first == TRGValues.at(labelSkip+5) ) { usecpp=false; inserted-=1; } \n } else usecpp=true;\n \n if (usecpp) {\n DEBUG(\"From C++:\"<<ELabels<<\"\\n\");\n eff->GetXaxis()->SetBinLabel(iter->first+1,ELabels.Data()); // labels\n nextcpp=false;\n } else {\n DEBUG(\"from yacc:\"<<newNLabels<<\"\\n\");\n string newlabels=\"Size \"+newNLabels; \n eff->GetXaxis()->SetBinLabel(iter->first+1,newlabels.c_str()); // labels\n labelSkip++;\n nextcpp=true;\n } \n \n iter++; \n }\n DEBUG(\"BIN CUTS: \\n\");\n iter = BinCuts.begin();\n while(iter != BinCuts.end())\n { bincounts.push_back(0);\n DEBUG(\"+++++ Binning: \"<<iter->first<<\" |\"<< iter->second->getStr()<<\"\\n\");\n iter++;\n }\n//---------------------- count histos\nfor (map<string,vector<cntHisto> >::iterator ichi = cntHistos.begin(); ichi != cntHistos.end(); ichi++){\n // cout << ichi->first << \" \\n ------- \\n \";\n for (vector<cntHisto>::iterator ih=ichi->second.begin(); ih!=ichi->second.end(); ih++){\n // cout<< ih->cH_name<< \" \"<< ih->cH_title<<\":\"<< ih->cH_means.size()<<\"\\n\";\n TH1D* chistoM= new TH1D(ih->cH_name.c_str(), ih->cH_title.c_str(), ih->cH_means.size(), 0.5, 0.5+ih->cH_means.size());\n string upname=ih->cH_name; upname+=\"_up\";\n string downname=ih->cH_name; downname+=\"_down\";\n TH1D* chistoU= new TH1D( upname.c_str(), ih->cH_title.c_str(), ih->cH_means.size(), 0.5, 0.5+ih->cH_means.size());\n TH1D* chistoD= new TH1D(downname.c_str(), ih->cH_title.c_str(), ih->cH_means.size(), 0.5, 0.5+ih->cH_means.size());\n for (int iv=0; iv<ih->cH_means.size(); iv++){\n // cout<< ih->cH_means[iv] << \" stat +\" << ih->cH_StatErr_p[iv] << \" -\"<<ih->cH_StatErr_n[iv] \n // << \" sys +\" << ih->cH_SystErr_p[iv] << \" -\"<<ih->cH_SystErr_n[iv] <<\"\\n\"; \n chistoM->SetBinContent(1+iv, ih->cH_means[iv]);\n chistoU->SetBinContent(1+iv, sqrt(ih->cH_StatErr_p[iv]*ih->cH_StatErr_p[iv] + ih->cH_SystErr_p[iv]*ih->cH_SystErr_p[iv]));\n chistoD->SetBinContent(1+iv, sqrt(ih->cH_StatErr_n[iv]*ih->cH_StatErr_n[iv] + ih->cH_SystErr_n[iv]*ih->cH_SystErr_n[iv]));\n }\n }\n}\n\n#ifdef _CLV__\n cout<<\"\\n Parsed Particle Lists: \\n\";\n\n for (map<string,vector<myParticle*> >::iterator it1 = ListParts.begin(); it1 != ListParts.end(); it1++)\n {\n cout << it1->first << \": \";\n for (vector<myParticle*>::iterator lit = it1->second.begin(); lit != it1->second.end(); lit++)\n cout << (*lit)->type << \"_\" << (*lit)->index << \" \";\n cout << \"\\n\";\n }\n\n cout<<\"\\n UNParsed Particles Lists: \\n\";\n\n std::list<std::string>::iterator it = parts.begin();\n while(it != parts.end())\n {\n std::cout<<(*it)<<std::endl;\n it++;\n }\n\n cout<<\"\\n Variables results: \\n\";\n map<string,Node* >::iterator itv = NodeVars.begin();\n while(itv != NodeVars.end())\n {\n std::cout<<\"**************************** \"<<itv->first<<endl;\n itv->second->display();\n std::cout<<std::endl;\n itv++;\n }\n\n#endif\n\n return retval;\n}\n\nint BPdbxA::printEfficiencies() {\n if (skip_effs) return 0;\n cout <<\"Efficiencies for analysis : \"<< cname <<endl;\n cout <<\"\\t\\t\\t\\t\\t\\t\"<<algoname<<\"\\t\";\n PrintEfficiencies(eff, skip_histos);\n cout <<\"Bins for analysis : \"<< cname <<endl;\n cout <<setprecision(6);\n for (int ii=0; ii<bincounts.size(); ii++) std::cout<<\"\\t\\t\\t\\t\\t\\tBin:\"<<ii<<\" has:\"<<bincounts[ii]<<\" events\\n\";\n return 0;\n}\n\nint BPdbxA:: initGRL() {\n int retval=0;\n grl_cut=true;\n return retval;\n}\n\nint BPdbxA::bookAdditionalHistos() {\n int retval=0;\n// dbxA::ChangeDir(cname);\n\n#ifdef __SEZEN__\n\t// Sezen's handmade histograms\n\tmWHh1 = new TH1D(\"mWHh1\", \"Hadronic W best combi (GeV)\", 50, 50, 150);\n\tmWHh2 = new TH1D(\"mHWh2\", \"Hadronic W best combi (GeV)\", 50, 50, 150);\n\tmTopHh1 = new TH1D(\"mTopHh1\", \"Hadronic top combi (GeV)\", 70, 0, 700);\n\tmTopHh2 = new TH1D(\"mTopHh2\", \"Hadronic top combi (GeV)\", 70, 0, 700);\n\tWHbRh1 = new TH1D(\"WHbRh1\", \"Angular distance between W1 and bjet\", 70, 0, 7);\n\tWHbRh2 = new TH1D(\"WHbRh2\", \"Angular distance between W2 and bjet\", 70, 0, 7);\n\txWHbRh1 = new TH1D(\"xWHbRh1\", \"Hadronic top combi (GeV) after angular cut\", 70, 0, 700);\n\txWHbRh2 = new TH1D(\"xWHbRh2\", \"Hadronic top combi (GeV) after angular cut\", 70, 0, 700);\n#endif\n\n// ---------------------------DBX style defs from the main file\n\n return retval;\n}\n//------------------------\nint BPdbxA::Finalize(){ \n std::cout <<\"finalize.\\n\";\n return 1;\n}\n\n/////////////////////////\nint BPdbxA::makeAnalysis( AnalysisObjects *ao, int controlword, int lastCutPass){\n\n evt_data anevt = ao->evt; // event information\n\n DEBUG(\"-----------------------------------------------\"<<cname<<\" ctrl:\"<< controlword<< \" lastC:\"<<lastCutPass<< \"\\n\");\n double evt_weight = ao->evt.user_evt_weight; // FROM file or previous calculation \n if (controlword == 0){\n if(TRGe>1 || TRGm> 1) evt_weight = anevt.weight_mc*anevt.weight_pileup*anevt.weight_jvt;\n ao->evt.user_evt_weight*=evt_weight;\n }else { // this is a dependent region, with pre-selection that failed at some point\n// no need to calculate something that we know will fail.\n if (!lastCutPass) return 0;\n } \n\n// --------- INITIAL # events ====> C0\n eff->Fill(1, 1);\nDEBUG(\"------------------------------------------------- Event ID:\"<<anevt.event_no<<\" \\n\");\n\n// *************************************\n/// CutLang execution starts-------here*\n// *************************************\n\n std::map<int, Node*>::iterator iter = NodeCuts.begin();\n//----------------------reset \n\n if (controlword == 0){\n DEBUG(\"Start resetting cuts:\"<< NodeCuts.size() <<\"\\n\");\n while(iter != NodeCuts.end())\n { \n iter->second->Reset();\n iter++;\n }\n particleBank.clear();\n DEBUG(\"Done resetting cuts.\\n\");\n iter = NodeCuts.begin();\n } else {\n for (int in:optimize){\n DEBUG(\"Get Optimals from:\"<< in<<\"\\t\");\n DEBUG(\"names:\"<< NodeCuts[ in ]->getStr()<<\"\\n\");\n for (int ip=0; ip<particleBank[in].size(); ip++){\n DEBUG(\"Bank-> Coll:\"<<particleBank[in].at(ip)->collection<<\" type:\"<< particleBank[in].at(ip)->type\n <<\" index:\"<<particleBank[in].at(ip)->index<<\"\\n\");\n }\n ((SearchNode *)NodeCuts[in])->setParticles(&particleBank[in]);\n }\n for (int aa=0; aa<controlword; aa++) iter++;\n\n }\n\n//----------------------execute\n while(iter != NodeCuts.end())\n { \n double d;\n DEBUG(\"**********Selecting: \"<<iter->first<<\" | \");\n if ( iter->first < controlword ) {\n// controlword 5 means 1 1 1 1 0, first 4 cuts passed.\n DEBUG (\"preset\");\n d=1;\n// if only 5cuts were there, and all 5 passed, we get a 10000+4\n } else if (iter->first == controlword ){\n DEBUG (\"preset\");\n d=lastCutPass;\n }\n else d=iter->second->evaluate(ao); // execute the selection cut\n \n DEBUG(\"\\t***Result : \" << d << std::endl);\n evt_weight = ao->evt.user_evt_weight;\n if (d==0) {\n\t\tif (ao->evt.event_no == (ao->evt.maxEvents - 1)) {\t// to close\n\t\t\tstd::map<int, Node*>::iterator jter = NodeCuts.begin();\n\t for (std::vector<int>::iterator it = save.begin() ; it != save.end(); ++it) {\n \t int diff = *it - jter->first;\n for(int i = 0; i < diff; i++) jter++;\n \tjter->second->saveFile();\n \t }\n\t\t}\n DEBUG(\"Return:\"<<iter->first<<\"\\n\");\n\t\treturn iter->first; // quits the event.\n\t}\n DEBUG(\"W:\"<<evt_weight<<\"\\n\");\n eff->Fill(iter->first+1, evt_weight); // filling starts from 1 which is already filled.\n if ((controlword == 0) && (optimize.size()>0)) {\n if (optimize.find(iter->first) != optimize.end()){\n DEBUG(\"This optimized results are to be saved.\\n\");\n vector<myParticle *> theseParticles;\n iter->second->getParticles(&theseParticles);\n DEBUG(\"#particles:\"<< theseParticles.size()<<\".\\n\");\n for (int ip=0; ip<theseParticles.size(); ip++){\n DEBUG(\"Bank] Coll:\"<<theseParticles[ip]->collection<<\" type:\"<< theseParticles[ip]->type<<\" index:\"<<theseParticles[ip]->index<<\"\\n\");\n }\n particleBank.insert(make_pair(iter->first, theseParticles) );\n }\n }\n iter++; //moves on to the next cut\n } // loop over all cutlang cuts\n DEBUG(\" EOE\\n \");\n\n iter = BinCuts.begin();\n DEBUG(\"Binning now ..\\n\");\n while(iter != BinCuts.end())\n {\n DEBUG(\"+++++ Binning: \"<<iter->first<<\" |\"<<\"\\t\");\n double d=iter->second->evaluate(ao); // execute the selection cut\n DEBUG(\"\\t****Result : \" << d << std::endl);\n evt_weight = ao->evt.user_evt_weight;\n if (d==1) { // inside a bin\n DEBUG(iter->first<<\" Passed\\n\"); // do something\n bincounts[iter->first -1]++;\n hbincounts->Fill(iter->first , evt_weight);\n break;\n }\n iter++; //moves on to the next cut\n }// loop over all binnings \n\n// les cuts sont finis ici.\n return 10000+NodeCuts.size();\n}\n\n" }, { "alpha_fraction": 0.609000027179718, "alphanum_fraction": 0.6179999709129333, "avg_line_length": 21.727272033691406, "blob_id": "eb00b03f4bd61390958cbf23099fa5ad8e0d53c2", "content_id": "68f01436ef8ef0d63dd83dc89ee5c46e203a772e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1001, "license_type": "no_license", "max_line_length": 102, "num_lines": 44, "path": "/parser_test/FuncNode.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// FuncNode.h\n// mm\n//\n// Created by Anna-Monica on 8/2/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n\n#ifndef FuncNode_h\n#define FuncNode_h\n#include <vector>\n#include \"myParticle.h\"\n#include \"Node.h\"\nusing namespace std;\n//takes care of functions with arguments\nclass FuncNode : public Node{\nprivate:\n double (*f)(std::vector<myParticle>);\n std::vector<myParticle> inputParticles;\npublic:\n FuncNode(double (*func)(std::vector<myParticle> ),std::vector<myParticle> input, std::string s ){\n f=func;\n symbol=s;\n inputParticles=input;\n left=NULL;\n right=NULL;\n }\n \n virtual double evaluate() {\n return (*f)(inputParticles);\n }\n virtual ~FuncNode() {}\n};\n\ndouble MASS(vector<myParticle> v){\n double mass=0;\n for(vector<myParticle>::iterator i=v.begin();i!=v.end();i++){\n mass+=i->index;\n }\n std::cout <<\" m:\"<<mass<<\"\\t\";\n return mass;\n}\n//other functions to be added\n#endif /* FuncNode_h */\n" }, { "alpha_fraction": 0.5603174567222595, "alphanum_fraction": 0.5702381134033203, "avg_line_length": 25.25, "blob_id": "46d14c006b840450bee45fe13c500ed2a519b946", "content_id": "10d63f136f9eb24151c8ef1eacfde98cbd0012b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2521, "license_type": "no_license", "max_line_length": 90, "num_lines": 96, "path": "/analysis_core/TableNode.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// TableNode.h\n// mm\n//\n// Created by ngu on Oct19.\n// Copyright © 2019 . All rights reserved.\n//\n\n#ifndef TableNode_h\n#define TableNode_h\n\n#include <stdio.h>\n#include <math.h>\n#include \"Node.h\"\n//takes care of Table Operations\n//#define _CLV_\n#ifdef _CLV_\n#define DEBUG(a) std::cout<<a\n#else\n#define DEBUG(a)\n#endif\n\n\nclass TableNode : public Node{\nprivate:\n double (*f)(double, AnalysisObjects* );\n std::vector<float> atable;\n std::vector<float> errtable;\n Node* left2;\n bool errors; \n\npublic:\n TableNode(double (*func)(double, AnalysisObjects*), \n Node* l, std::pair<std::vector<float>, bool> tabe, std::string s){\n f=func;\n symbol=s;\n left=l;\n left2=NULL;\n errors=tabe.second;\n right=NULL;\n if (errors){\n for (int ii=0; ii<tabe.first.size(); ii+=5){\n atable.push_back( tabe.first[ii]);\n errtable.push_back( tabe.first[ii+1]);\n errtable.push_back( tabe.first[ii+2]);\n atable.push_back( tabe.first[ii+3]);\n atable.push_back( tabe.first[ii+4]);\n }\n } else {\n atable=tabe.first;\n }\n }\n TableNode(double (*func)(double, AnalysisObjects*), \n Node* l, Node* l2, std::pair<std::vector<float>, bool> tabe, std::string s){\n f=func;\n symbol=s;\n left=l;\n left2=l2;\n errors=tabe.second;\n right=NULL;\n if (errors){\n for (int ii=0; ii<tabe.first.size(); ii+=7){\n atable.push_back( tabe.first[ii]);\n errtable.push_back( tabe.first[ii+1]);\n errtable.push_back( tabe.first[ii+2]);\n atable.push_back( tabe.first[ii+3]);\n atable.push_back( tabe.first[ii+4]);\n atable.push_back( tabe.first[ii+5]);\n atable.push_back( tabe.first[ii+6]);\n }\n } else {\n atable=tabe.first;\n }\n }\n\n virtual double evaluate(AnalysisObjects* ao) override;\n\n virtual void getParticles(std::vector<myParticle *>* particles) override{\n left->getParticles(particles);\n }\n\n virtual void getParticlesAt(std::vector<myParticle *>* particles,int index) override{\n left->getParticlesAt(particles,index);\n }\n virtual void Reset() override{\n left->Reset();\n }\n virtual ~TableNode() {\n if (left!=NULL) delete left;\n }\n};\n\ndouble tweight(double value, AnalysisObjects* ao ) ;\ndouble thitmiss(double value, AnalysisObjects* ao ) ;\n\n#endif /* TableNode */\n" }, { "alpha_fraction": 0.6309055089950562, "alphanum_fraction": 0.6433727145195007, "avg_line_length": 27.22222137451172, "blob_id": "295eae5e02a48db260c66fe4b26a4730be3a47d5", "content_id": "62649b28904ff3d5e9091bdb3f43ac7f13c67bb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3049, "license_type": "no_license", "max_line_length": 168, "num_lines": 108, "path": "/analysis_core/Node.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// Node.h\n// mm\n//\n// Created by Anna-Monica on 7/31/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n\n#ifndef Node_h\n#define Node_h\n#include <string>\n#include <iostream>\n#include <map>\n\n#include \"dbxParticle.h\"\n#include \"dbx_electron.h\"\n#include \"dbx_photon.h\"\n#include \"dbx_muon.h\"\n#include \"dbx_tau.h\"\n#include \"dbx_jet.h\"\n#include \"dbx_truth.h\"\n#include \"analysis_core.h\"\n#include \"myParticle.h\"\n\n\n struct indicesA{\n std::vector< std::vector <int> > tableA;\n int max_col;\n int max_row;\n };\n\nstruct AnalysisObjects {\n std::map<std::string, std::vector<dbxMuon> > muos;\n std::map<std::string, std::vector<dbxElectron> > eles;\n std::map<std::string, std::vector<dbxTau> > taus;\n std::map<std::string, std::vector<dbxPhoton> > gams;\n std::map<std::string, std::vector<dbxJet> > jets;\n std::map<std::string, std::vector<dbxJet> >ljets;\n std::map<std::string, std::vector<dbxTruth> >truth;\n std::map<std::string, std::vector<dbxParticle> >combos;\n std::map<std::string, std::vector<dbxParticle> >constits;\n std::map<std::string, TVector2 > met;\n evt_data evt;\n std::map<std::string, indicesA > combosA;\n};\n\nenum particleType{\n none_t=0,\n electron_t=1,\n jet_t=2,\n bjet_t=3,\n lightjet_t=4,\n muonlikeV_t=5,\n electronlikeV_t=6,\n pureV_t=7,\n photon_t=8,\n fjet_t=9,\n truth_t=10,\n tau_t=11,\n muon_t=12,\n combo_t=20,\n consti_t=21\n};\n\n\n//generic node interface\nclass Node{\nprotected:\n Node* userObjectA;\n Node* userObjectB;\n Node* userObjectC;\n Node* userObjectD;\n std::string symbol;\n void getStr(TString *ss);\n void display(std::string indent);\npublic:\n\n Node* right;\n Node* left;\n virtual void Reset()=0;\n virtual void getParticles(std::vector<myParticle *>* particles)=0;\n virtual void getParticlesAt(std::vector<myParticle *>* particles,int index)=0;\n void display();\n virtual TString getStr();\n virtual void saveFile();\n virtual void createFile();\n virtual void setUserObjects(Node *objectNodea = NULL, Node *objectNodeb = NULL, Node *objectNodec = NULL, Node *objectNoded = NULL){std::cout<<\"Mother adds UOs.\\n\";\n userObjectA=objectNodea;\n userObjectB=objectNodeb;\n userObjectC=objectNodec;\n userObjectD=objectNoded;\n };\n\n virtual double evaluate(AnalysisObjects* ao){\n if(userObjectA) userObjectA->evaluate(ao); // returns 1, hardcoded. see ObjectNode.cpp\n if(userObjectB) userObjectB->evaluate(ao); // returns 1, hardcoded. see ObjectNode.cpp\n if(userObjectC) userObjectC->evaluate(ao); // returns 1, hardcoded. see ObjectNode.cpp\n if(userObjectD) userObjectD->evaluate(ao); // returns 1, hardcoded. see ObjectNode.cpp\n if( userObjectA || userObjectB || userObjectC || userObjectD ) std::cout<<\"UOs EVALUATED:\"<< getStr() <<\"\\n\";\n\n return 0;\n }\n virtual ~ Node();\n std::vector<dbxJet> tagJets(AnalysisObjects *ao, int jtype, std::string cn) ;\n\n};\n\n#endif /* Node_h */\n" }, { "alpha_fraction": 0.7346278429031372, "alphanum_fraction": 0.7346278429031372, "avg_line_length": 37.625, "blob_id": "5ce117adf2a8c4c519bd73e5838567e38eab54f1", "content_id": "9fb35702162c89244557b9cad283e931ef3eb25e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1545, "license_type": "no_license", "max_line_length": 167, "num_lines": 40, "path": "/analysis_core/SearchNode.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#ifndef SearchNode_h\n#define SearchNode_h\n\n#include <stdio.h>\n#include <math.h>\n#include <list>\n#include <unordered_set>\n#include \"myParticle.h\"\n#include \"Node.h\"\n\n\nusing namespace std;\n\n//takes care of Minimizing/Maximizing\nclass SearchNode : public Node{\nprivate:\n static std::map< std::string, unordered_set<int> > FORBIDDEN_INDEX_LIST;\n double (*f)(double, double);\n vector<int> bestIndices;\n std::vector<myParticle *> particles;//pointers to particles in all nodes that have to be changed\n void performInnerOperation(vector<int> *v,vector<int> *indices, double *current_difference,AnalysisObjects* ao);\n void runNestedLoopBarb( int start, int N, int level, int maxDepth, vector<int> *v,vector<int> *indices,double *curr_diff,AnalysisObjects* ao, int type, string ac);\n void runNestedLoopRec ( int start, int N, int level, int maxDepth, vector<int> *v,vector<int> *indices,double *curr_diff,AnalysisObjects* ao, int type, string ac);\n\n\npublic:\n SearchNode(double (*func)(double, double), Node* l, Node* r, std::string s);\n virtual double evaluate(AnalysisObjects* ao) override;\n virtual void Reset() override;\n virtual void setParticles(std::vector<myParticle *>* particles);\n virtual void getParticles(std::vector<myParticle *>* particles) override;\n virtual void getParticlesAt(std::vector<myParticle *>* particles, int index) override;\n virtual ~SearchNode() ;\n\n};\n\ndouble maxim( double difference, double current_difference);\ndouble minim( double difference, double current_difference);\n\n#endif\n" }, { "alpha_fraction": 0.6970198750495911, "alphanum_fraction": 0.7094370722770691, "avg_line_length": 27.42352867126465, "blob_id": "98d0632b9d5cc1ebd28f27e4026996343bbc6e30", "content_id": "abf2260a985c4a769fce1456ae15dbaf36737bfc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2416, "license_type": "no_license", "max_line_length": 121, "num_lines": 85, "path": "/analysis_core/dbx_a.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#ifndef DBX_A_H\n#define DBX_A_H\n\n#include <vector>\n#include <cmath>\n#include \"TLorentzVector.h\"\n#include \"TFile.h\"\n#include \"TNtuple.h\"\n#include \"TH1F.h\"\n#include \"TH2F.h\"\n#include <iostream>\n#include \"TCanvas.h\"\n\n#include \"dbx_electron.h\"\n#include \"dbx_photon.h\"\n#include \"dbx_muon.h\"\n#include \"dbx_jet.h\"\n#include \"Node.h\"\n\nusing namespace std;\n\n#define NPERIOD 11\n\n\n\nclass dbxA {\n\npublic:\n\tdbxA( char*);\n\t~dbxA();\n\n virtual int makeAnalysis(AnalysisObjects *ao, int, int);\n virtual int makeAnalysis(AnalysisObjects *ao, int);\n virtual int makeAnalysis(AnalysisObjects *ao) { return makeAnalysis(ao,0); } // execute default\n virtual int makeAnalysis(AnalysisObjects *ao, map <int, TVector2>, vector <double>){std::cout<<\"3RR0Rg!\\n\"; return 0;}\n\n virtual int saveHistos();\n virtual int defHistos(unsigned int);\n string getName() { return cname;}\n virtual int initGRL() { return 0;}\n virtual int readAnalysisParams() { return 0;}\n virtual int bookAdditionalHistos() { return 0;}\n virtual int setQCD() { return 0;}\n virtual int printEfficiencies() { return 0;}\n virtual int setDir(char *); // to have multiple directories\n virtual int ChangeDir(char *); // to be able to cd later on\n virtual int addRunLumiInfo(int rn, int lbn); // to have list of run and lumi block numbers\n static const string perName[NPERIOD];\n\n void setDataCardPrefix(string dcp) { dataCardPrefix = dcp; }\n string getDataCardPrefix() { return dataCardPrefix; }\n\n char cname[128];\n TH1D *eff, *hbincounts;\n// list the analysis parameters here.\n float minpte, minptm, minptg, maxmet;\n float maxetae,maxetam,maxetag, minmetmu,minmwte,minmwtmu; // leptons\n float minmete,minmwtmete; // met and mwt related\n float minmetm,minmwtmetm; // met and mwt related\n float minptj, maxetaj; // basic jet definitions \n float mindrjm, mindrje; // isolation related\n float minptj1, minptj2, minEj2, minetaj2, mindrjj, minetajj;\n float mqhxmin, mqhxmax,maxdeltam;//related to reconstructed quark mass\n float maxMuPtCone, maxMuEtCone, maxElPtCone, maxElEtCone;\n float jetVtxf2011,jetVtxf2012,jetVtxf;\n int HFtype;\n int TRGe, TRGm;\n\n\n// mass values that could be used in the analysis\n Double_t GEV;\n\nprivate:\n// file to output histogtrams\n TFile *histoOut;\n \n// run and lumi block information\n int p_runno;\n int p_lumino;\n string dataCardPrefix;\n TNtuple *rntuple;\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.6345034837722778, "alphanum_fraction": 0.6801201701164246, "avg_line_length": 36.251747131347656, "blob_id": "dbe48e9b578304da410e1fbce331da963f796901", "content_id": "b53ac65057172d70b03ff734069005e3602d53bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5327, "license_type": "no_license", "max_line_length": 145, "num_lines": 143, "path": "/runs/plotting/ROOTintroCpp.C", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "{\n // Let's start with setting some ROOT style parameters:\n // You do not need to know what they mean, but can directly use these settings\n \n gStyle->SetOptStat(kFALSE);\n gStyle->SetPalette(1);\n \n gStyle->SetTextFont(42);\n \n gStyle->SetTitleStyle(0000);\n gStyle->SetTitleBorderSize(0);\n gStyle->SetTitleFont(42);\n gStyle->SetTitleFontSize(0.055);\n \n gStyle->SetTitleFont(42, \"xyz\");\n gStyle->SetTitleSize(0.5, \"xyz\");\n gStyle->SetLabelFont(42, \"xyz\");\n gStyle->SetLabelSize(0.45, \"xyz\");\n\n // We are currently in the CutLang/binder directory. Let's move to the CutLang/runs directory:\n gSystem->cd(\"../runs/\");\n // Let's open the histoOut-exHistos.root file \n TFile f(\"histoOut-exHistos.root\");\n // Let's see what is in there\n f.ls();\n\n // There is a ROOT directory (TDirectory) called presel.\n // Let's go inside\n f.cd(\"presel\");\n // ... and// There is a ROOT directory (TDirectory) called presel.\n // Let's go inside\n f.cd(\"presel\");\n // ... and check what is there\n f.ls();\n \n /* \n There are lots of histograms in the presel directory. \n Some of them are 1-dimensional (TH1D), which have only one variable.\n Here, the histograms hjet1pt, hjet2pt, hjet3pt, hjet4pt are plotting the transverse moementa of the 1st, 2nd, 3rd and 4th jet in the events.\n We will plot these histograms on top of each other.\n Those histograms can be accessed with their names. In C++, they are pointer.\n There is also a 2-dimensional histogram hmetjet1pt. We will get to that one shortly. \n */\n \n // We start with setting the style of the histograms.\n // Let's increase the line width of the histograms.\n hjet1pt->SetLineWidth(2);\n hjet2pt->SetLineWidth(2);\n hjet3pt->SetLineWidth(2);\n hjet4pt->SetLineWidth(2);\n \n // Now let's set the colors.\n // Information about ROOT colors: https://root.cern.ch/doc/master/classTColor.html\n // Set the histogram line color:\n hjet1pt->SetLineColor(616+1); // kMagenta + 1\n hjet2pt->SetLineColor(600); // kBlue\n hjet3pt->SetLineColor(632+1); // kRed + 1\n hjet4pt->SetLineColor(416+2); // kGreen + 2\n\n // Set the histogram fill color:\n hjet1pt->SetFillColor(616+1); // kMagenta + 1\n hjet2pt->SetFillColor(600); // kBlue\n hjet3pt->SetFillColor(632+1); // kRed + 1\n hjet4pt->SetFillColor(416+2); // kGreen + 2\n \n // Let's get even more fancy and fill \"in style\"\n // https://root.cern.ch/root/html528/TMarker.html\n hjet1pt->SetFillStyle(3003);\n hjet2pt->SetFillStyle(3003);\n hjet3pt->SetFillStyle(3003);\n hjet4pt->SetFillStyle(3003);\n \n // One can also plot markers with different styles, but we won't do it here.\n // https://root.cern.ch/root/html528/TMarker.html\n \n // Set the histogram title\n hjet4pt->SetTitle(\"Jet p_{T}\");\n // Set the x-axis title and font properties\n hjet4pt->GetXaxis()->SetTitle(\"p_{T} (GeV)\");\n hjet4pt->GetXaxis()->SetTitleOffset(1.25);\n hjet4pt->GetXaxis()->SetTitleSize(0.05);\n hjet4pt->GetXaxis()->SetLabelSize(0.045);\n hjet4pt->GetXaxis()->SetNdivisions(8, 5, 0);\n // Set the y-axis title and font properties\n hjet4pt->GetYaxis()->SetTitle(\"number of events\");\n hjet4pt->GetYaxis()->SetTitleOffset(1.4);\n hjet4pt->GetYaxis()->SetTitleSize(0.05);\n hjet4pt->GetYaxis()->SetLabelSize(0.045);\n\n // To plot our histogram, we first need a canvas.\n TCanvas c1(\"c1\", \"c1\", 620, 500);\n // ... and we need to make wide margins for all the axis titles to fit in:\n c1.SetBottomMargin(0.15);\n c1.SetLeftMargin(0.15);\n c1.SetRightMargin(0.15);\n\n // Now we can plot the histograms. We start with the distribution which has the highest y-axis value, so everything can fit into the frame.\n // If you want to understand this better, you can start with drawing hjet1pt, then the others\n hjet4pt->Draw();\n hjet3pt->Draw(\"same\");\n hjet2pt->Draw(\"same\");\n hjet1pt->Draw(\"same\");\n // The histogram will be drawn on the TCanvas c1. Now we can draw the canvas:\n c1.Draw();\n \n // In order the see which histogram corresponds to which distribution, we need a legend.\n // This is how we make one:\n TLegend l1(0.65, 0.67, 0.88, 0.87);\n l1.SetBorderSize(0);\n l1.SetFillStyle(0000);\n l1.AddEntry(hjet1pt,\"jet 1 p_{T}\", \"f\");\n l1.AddEntry(hjet2pt,\"jet 2 p_{T}\", \"f\");\n l1.AddEntry(hjet3pt,\"jet 3 p_{T}\", \"f\");\n l1.AddEntry(hjet4pt,\"jet 4 p_{T}\", \"f\");\n l1.Draw(\"same\");\n\n // We re-draw the canvas c1 in order to see the legend:\n c1.Draw();\n // Let's save c1 as a pdf file\n c1.Print(\"hjetpt.pdf\");\n\n // Now let's take the 2D histogram hmetjet1pt. It shows missing transverse energy versus the 1st jet pT.\n // Let's set the axis titles.\n hmetjet1pt->GetXaxis()->SetTitle(\"MET (GeV)\");\n hmetjet1pt->GetYaxis()->SetTitle(\"jet 1 p_{T} (GeV)\");\n hmetjet1pt->GetZaxis()->SetTitle(\"number of events\");\n\n // We need a different canvas for the new histogram\n TCanvas c2(\"c2\", \"c2\", 620, 500);\n c2.SetBottomMargin(0.15);\n c2.SetLeftMargin(0.15);\n c2.SetRightMargin(0.15);\n \n // Let's draw the histogram. The colz option draws the histogram with the nice colors and the z-axis bar.\n // You can learn about drawing options from https://root.cern/doc/master/classTHistPainter.html\n // and perhaps try a few for fun\n hmetjet1pt->Draw(\"colz\");\n // As usual, we need to draw the canvas separately\n c2.Draw();\n // Let's save c2 as a pdf file\n c2.Print(\"hmetjet1pt.pdf\");\n\n}\n" }, { "alpha_fraction": 0.5174857378005981, "alphanum_fraction": 0.5283747315406799, "avg_line_length": 40.523921966552734, "blob_id": "dafcabdd2ea685439126ab230ae6a89130a559e1", "content_id": "7e76480cbd3417b6cedbe64cf304f262916ba4c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 17359, "license_type": "no_license", "max_line_length": 149, "num_lines": 418, "path": "/analysis_core/SFuncNode.cpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// SFuncNode.cpp\n// mm\n//\n// Created by Anna-Monica on 8/2/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n// Copyright © 2020 Gokhan Unel. All rights reserved.\n//\n#include \"SFuncNode.h\"\n#include \"ValueNode.h\"\n\n//#define _CLV_\n#ifdef _CLV_\n#define DEBUG(a) std::cout<<a\n#else\n#define DEBUG(a)\n#endif\n \ndouble SFuncNode::evaluate(AnalysisObjects* ao) {\n\n DEBUG(\"*******In SF, Extern True/False:\"<< ext <<\"\\n\"); \n if(userObjectA && !ext) {\n DEBUG(\"\\t start user obj A\\n\"); \n userObjectA->evaluate(ao); // returns 1, hardcoded. see ObjectNode.cpp\n DEBUG(\"user obj A done.\\n\"); \n }\n if(userObjectB && !ext) {\n DEBUG(\"\\t B user obj\\n\"); \n userObjectB->evaluate(ao); // returns 1, hardcoded. see ObjectNode.cpp\n DEBUG(\"user obj B done.\\n\"); \n }\n dbxParticle *aPart= new dbxParticle;\n dbxParticle *bPart= new dbxParticle;\n dbxParticle *cPart= new dbxParticle;\n\n TString unikID=\"_\";\n\n if ( inputParticlesA.size()>0 ){\n aPart->Reset();\n TLorentzVector ametlv;\n DEBUG(\"\\n input particles A \"); \n for(vector<myParticle*>::iterator i=inputParticlesA.begin();i!=inputParticlesA.end();i++){\n DEBUG(\"type:\"<<(*i)->type<<\" index:\"<< (*i)->index<< \" addr:\"<<*i<< \"\\t name:\"<< (*i)->collection<<\"\\n\");\n int atype=(*i)->type;\n int ai=(*i)->index;\n string ac=(*i)->collection;\n\n if (atype==7) ac=\"MET\";\n unikID+=ac; \n unikID+=ai; \n\n switch (atype) { \n\t\t case 10: aPart->setTlv( aPart->lv()+ao->truth[ac].at(ai).lv() ); break;\n case 12: aPart->setTlv( aPart->lv()+ao->muos[ac].at(ai).lv() ); break;\n case 1: aPart->setTlv( aPart->lv()+ao->eles[ac].at(ai).lv() ); break;\n case 11: aPart->setTlv( aPart->lv()+ao->taus[ac].at(ai).lv() ); break;\n case 2: aPart->setTlv( aPart->lv()+ao->jets[ac].at(ai).lv() ); break;\n case 20: aPart->setTlv( aPart->lv()+ao->combos[ac].at(ai).lv() ); break;\n case 9: aPart->setTlv( aPart->lv()+ao->ljets[ac].at(ai).lv() ); break;\n case 8: aPart->setTlv( aPart->lv()+ao->gams[ac].at(ai).lv() ); break;\n case 7: DEBUG(\"MET LV\\n \");\n ametlv.SetPxPyPzE(ao->met[ac].Px(), ao->met[ac].Py(), 0, ao->met[ac].Mod());\n aPart->setTlv(aPart->lv()+ametlv); // v from MET using same eta approx.\n break;\n default: std::cout<<\"SFN No such object! ERROR\\n\";\n break;\n\n } // end of switch\n }// end of for\n\n DEBUG(\"aPart constructed \\t\");\n }\n if ( inputParticlesB.size()>0 ){\n bPart->Reset();\n TLorentzVector ametlv;\n DEBUG(\"\\n input particles B \"); \n for(vector<myParticle*>::iterator i=inputParticlesB.begin();i!=inputParticlesB.end();i++){\n DEBUG(\"type:\"<<(*i)->type<<\" index:\"<< (*i)->index<< \" addr:\"<<*i<< \"\\t name:\"<< (*i)->collection<<\"\\n\");\n int atype=(*i)->type;\n int ai=(*i)->index;\n string ac=(*i)->collection;\n if (atype==7) ac=\"MET\";\n unikID+=ac; \n unikID+=ai; \n\n switch (atype) { \n\t\t case 10: bPart->setTlv( bPart->lv()+ao->truth[ac].at(ai).lv() ); break;\n case 12: bPart->setTlv( bPart->lv()+ao->muos[ac].at(ai).lv() ); break;\n case 1: bPart->setTlv( bPart->lv()+ao->eles[ac].at(ai).lv() ); break;\n case 11: bPart->setTlv( bPart->lv()+ao->taus[ac].at(ai).lv() ); break;\n case 2: bPart->setTlv( bPart->lv()+ao->jets[ac].at(ai).lv() ); break;\n case 20: aPart->setTlv( bPart->lv()+ao->combos[ac].at(ai).lv() ); break;\n case 9: bPart->setTlv( bPart->lv()+ao->ljets[ac].at(ai).lv() ); break;\n case 8: bPart->setTlv( bPart->lv()+ao->gams[ac].at(ai).lv() ); break;\n case 7: DEBUG(\"MET LV\\n \");\n ametlv.SetPxPyPzE(ao->met[ac].Px(), ao->met[ac].Py(), 0, ao->met[ac].Mod());\n bPart->setTlv(bPart->lv()+ametlv); // v from MET using same eta approx.\n break;\n default: std::cout<<\"SFN No such object! ERROR\\n\";\n break;\n\n } // end of switch\n }// end of for\n\n DEBUG(\"bPart constructed \\t\");\n }\n if ( inputParticlesC.size()>0 ){\n cPart->Reset();\n TLorentzVector ametlv;\n DEBUG(\"\\n input particles C \"); \n for(vector<myParticle*>::iterator i=inputParticlesC.begin();i!=inputParticlesC.end();i++){\n DEBUG(\"type:\"<<(*i)->type<<\" index:\"<< (*i)->index<< \" addr:\"<<*i<< \"\\t name:\"<< (*i)->collection<<\"\\n\");\n int atype=(*i)->type;\n int ai=(*i)->index;\n string ac=(*i)->collection;\n if (atype==7) ac=\"MET\";\n unikID+=ac; \n unikID+=ai; \n\n switch (atype) { \n\t\t case 10: cPart->setTlv( cPart->lv()+ao->truth[ac].at(ai).lv() ); break;\n case 12: cPart->setTlv( cPart->lv()+ao->muos[ac].at(ai).lv() ); break;\n case 1: cPart->setTlv( cPart->lv()+ao->eles[ac].at(ai).lv() ); break;\n case 11: cPart->setTlv( cPart->lv()+ao->taus[ac].at(ai).lv() ); break;\n case 2: cPart->setTlv( cPart->lv()+ao->jets[ac].at(ai).lv() ); break;\n case 20: cPart->setTlv( cPart->lv()+ao->combos[ac].at(ai).lv() ); break;\n case 9: cPart->setTlv( cPart->lv()+ao->ljets[ac].at(ai).lv() ); break;\n case 8: cPart->setTlv( cPart->lv()+ao->gams[ac].at(ai).lv() ); break;\n case 7: DEBUG(\"MET LV\\n \");\n ametlv.SetPxPyPzE(ao->met[ac].Px(), ao->met[ac].Py(), 0, ao->met[ac].Mod());\n cPart->setTlv(cPart->lv()+ametlv); // v from MET using same eta approx.\n break;\n default: std::cout<<\"SFN No such object! ERROR\\n\";\n break;\n\n } // end of switch\n }// end of for\n\n DEBUG(\"cPart constructed \\t\");\n }\n if (left != NULL) {\n value =left->evaluate(ao);\n }\n\n DEBUG (\"Before Symbol:\"<<symbol<<\" Value:\"<<value<< \" Type:\"<<type<<\"\\n\");\n if(ext) {\n TString extkey =symbol;\n extkey+=\"_\";\n extkey+=value;\n extkey+=\"_\";\n extkey+=type;\n extkey+=unikID;\n\n std::map< std::string, double >::iterator keyit; \n\n DEBUG(\"external user function evaluation. initial Key:\"<< extkey<<\"\\n\");\n if (g1 != NULL) return (*g1)(ao, symbol, type, h1 ); // A\n if (g2 != NULL) return (*g2)(ao, symbol, type, h2 ); // B\n if (g3 != NULL) return (*g3)(ao, symbol, type, h3 ); // C\n if (g4 != NULL) return (*g4)(ao, symbol, type, aPart->lv(), h4); // D\n if (g5 != NULL) { // E\n if ( BUFFERED_VALUES.find(extkey.Data()) !=BUFFERED_VALUES.end() ){\n DEBUG(\"Returning buffered value:\"<<(BUFFERED_VALUES[extkey.Data()]) << \"\\n\");\n return (BUFFERED_VALUES[extkey.Data()]);\n } else { \n double g5retval=(*g5)(ao, symbol, type, aPart->lv(), bPart->lv(), cPart->lv(), h5);\n BUFFERED_VALUES.insert(std::pair<string, double >(extkey.Data(), g5retval));\n return g5retval;\n }\n }\n }\n double arv=(*f)(ao, symbol, value); \n DEBUG(\"ARV=\"<<arv<<\"\\n\");\n return arv;\n// return (*f)(ao, symbol, value);\n}\n\nvoid SFuncNode::Reset() {\n DEBUG (\" Resetting cache \\n\");\n BUFFERED_VALUES.clear();\n }\n\ndouble getIndex(AnalysisObjects* ao, string s, float id){ // new internal function\n particleType pid = (particleType)id;\n DEBUG(\"GETINDEX function\\n\");\n DEBUG(\"STR:\"<<s<<\" Type:\"<<pid<<\" #Combos types:\"<<ao->combos.size() << \" #Table types:\"<<ao->combosA.size()<<\"\\n\");\n map <string, indicesA >::iterator itp;\n for (itp=ao->combosA.begin();itp!=ao->combosA.end();itp++){\n DEBUG(\"#Combo typename:\"<<itp->first<<\" Table size:\"<<itp->second.tableA.size() <<\" maxRow:\" \n <<itp->second.max_row<< \" maxCol:\"<< itp->second.max_col <<\"\\n\");\n std::vector< std::vector <int> > mytable= itp->second.tableA;\n for (int anidx=0; anidx < mytable.size(); anidx++) {\n DEBUG(mytable[anidx][0] <<\" \"<< mytable[anidx][1]); // asume 2 cols\n DEBUG(\"\\n\");\n if (pid==muon_t) return mytable[anidx][0];\n if (pid==tau_t ) return mytable[anidx][1];\n }\n }\n return (123); // never here\n}\n\ndouble count(AnalysisObjects* ao, string s, float id) {\n particleType pid = (particleType)id;\n\n DEBUG(\"STR:\"<<s<<\" Type:\"<<pid<<\" #J types:\"<<ao->jets.size() << \" #M types:\"<<ao->muos.size()<<\"\\n\");\n map <string, std::vector<dbxJet> >::iterator it;\n for (it=ao->jets.begin();it!=ao->jets.end();it++){\n DEBUG(\"\\t #Jtypename:\"<<it->first<<\" size:\"<<it->second.size() <<\"\\n\");\n }\n\n DEBUG(\"\\n\");\n map <string, indicesA >::iterator itp;\n for (itp=ao->combosA.begin();itp!=ao->combosA.end();itp++){\n DEBUG(\"#C typename:\"<<itp->first<<\" size:\"<<itp->second.tableA.size() <<\"\\n\");\n }\n\n ValueNode abc=ValueNode();\n switch (pid) {\n// case consti_t: return (ao->truth.at(s).size()); break;\n case truth_t: return (ao->truth.at(s).size()); break;\n case muon_t: return (ao->muos.at(s).size()); break;\n case electron_t: return (ao->eles.at(s).size()); break;\n case tau_t: return (ao->taus.at(s).size()); break;\n case jet_t: return (ao->jets.at(s).size()); break;\n case bjet_t: return ( (abc.tagJets(ao, 1, s) ).size()); break;\n case lightjet_t: return ( (abc.tagJets(ao, 0, s) ).size()); break;\n case fjet_t: return (ao->ljets.at(s).size()); break;\n case photon_t: return (ao->gams.at(s).size()); break;\n case combo_t: if (ao->combosA.find(s)!=ao->combosA.end() ){\n DEBUG(s<<\" tableA max r,c:\"<<ao->combosA.at(s).max_row <<\" \"<< ao->combosA.at(s).max_col<<\"\\n\");\n return (ao->combosA.at(s).max_row);\n } else { \n DEBUG(s<<\" Normal\\n\"); // to be continued \n return (ao->combos.at(s).size() );\n }\n break;\n default: std::cerr<<\"No such Particle Type:\\n\"; return (-1); break;\n }\n return (-1);\n}\n\ndouble met(AnalysisObjects* ao, string s, float id){\n DEBUG(\"MET:\" << ao->met[\"MET\"].Mod() <<\"\\n\");\n return ( ao->met[\"MET\"].Mod() );\n}\n\ndouble hlt_iso_mu(AnalysisObjects* ao, string s, float id){\n bool retval=ao->evt.HLT_IsoMu17_eta2p1_LooseIsoPFTau20;\n DEBUG(\"HLT_ISO_MU:\" << retval <<\"\\n\");\n return ( (double)retval );\n}\n\n\ndouble ht(AnalysisObjects* ao, string s, float id){\n double sum_htjet=0;\n for (UInt_t i=0; i<ao->jets.at(s).size(); i++) sum_htjet+=ao->jets.at(s).at(i).lv().Pt();\n return (sum_htjet );\n}\n\ndouble userfuncA(AnalysisObjects* ao, string s, int id, std::vector<TLorentzVector> (*func)(std::vector<TLorentzVector> jets, int p1) ){\n// string contains what to send\n// id contains the particle type ASSUME ID=JET TYPE,\n\n DEBUG(\"UserfunctionA, s:\"<<s<<\" id: \"<<id<<\"\\n\");\n\n std::vector<TLorentzVector> myjets;\n for (UInt_t i=0; i<ao->jets.at(s).size(); i++) myjets.push_back(ao->jets.at(s).at(i).lv() );\n\n DEBUG(\"evaluating external function on jets: :\"<<s<<\"\\n\");\n std::vector<TLorentzVector> retjets= (*func)(myjets, id);\n DEBUG(\"external function Done. size:\"<<retjets.size()<<\"\\n\");\n for (int ipart=ao->jets.at(s).size()-1; ipart>=0; ipart--){ // I have all particles, jets, in an event.\n if (ipart > (retjets.size()-1) ) {\n (ao->jets).find(s)->second.erase( (ao->jets).find(s)->second.begin()+ipart);\n } else {\n ao->jets.at(s).at(ipart).setTlv( retjets[ipart] );\n }\n }\n return (1);\n}\n\ndouble userfuncB(AnalysisObjects* ao, string s, int id, double (*func)(std::vector<TLorentzVector> jets ) ){\n// string contains what to send\n// id contains the particle type ASSUME ID=JET TYPE,\n\n DEBUG(\"UserfunctionB :\"<<s<<\"\\n\");\n\n std::vector<TLorentzVector> myjets;\n for (UInt_t i=0; i<ao->jets.at(s).size(); i++) myjets.push_back(ao->jets.at(s).at(i).lv() );\n DEBUG(\"evaluating external function :\"<<s<<\"\\n\");\n double retvalue= (*func)(myjets);\n return (retvalue);\n}\n\ndouble userfuncC(AnalysisObjects* ao, string s, int id, double (*func)(std::vector<TLorentzVector> jets, TVector2 amet ) ){\n// string contains what to send\n// id contains the particle type ASSUME ID=JET TYPE,\n\n DEBUG(\"UserfunctionC :\"<<s<<\"\\n\");\n\n std::vector<TLorentzVector> myjets;\n TVector2 mymet=ao->met[\"MET\"];\n for (UInt_t i=0; i<ao->jets.at(s).size(); i++) myjets.push_back(ao->jets.at(s).at(i).lv() );\n DEBUG(\"evaluating external function :\"<<s<<\"\\n\");\n double retvalue= (*func)(myjets, mymet);\n return (retvalue);\n}\n\ndouble userfuncD(AnalysisObjects* ao, string s, int id, TLorentzVector alv, double (*func)(std::vector<TLorentzVector> jets, TLorentzVector amet ) ){\n// string contains what to send\n// id contains the particle type ASSUME ID=JET TYPE,\n\n DEBUG(\"UserfunctionD :\"<<s<<\"\\n\");\n\n std::vector<TLorentzVector> myjets;\n for (UInt_t i=0; i<ao->jets.at(s).size(); i++) myjets.push_back(ao->jets.at(s).at(i).lv() );\n DEBUG(\"evaluating external function :\"<<s<<\"\\n\");\n double retvalue= (*func)(myjets, alv);\n return (retvalue);\n}\n\ndouble userfuncE(AnalysisObjects* ao, string s, int id, TLorentzVector l1, TLorentzVector l2, TLorentzVector m1,\n double (*func)(TLorentzVector la, TLorentzVector lb, TLorentzVector amet ) ){\n// string contains what to send\n// id contains the particle type ASSUME ID=JET TYPE,\n\n DEBUG(\"UserfunctionE :\"<<s<<\"\\n\");\n DEBUG(\"evaluating external function :\"<<s<<\"\\n\");\n double retvalue= (*func)(l1, l2, m1);\n return (retvalue);\n}\n\nstd::vector<TLorentzVector> sumobj(std::vector<TLorentzVector> myjets, int p1) {\n TLorentzVector h1;\n for (int i=0; i<myjets.size(); i++) {\n h1+=myjets[i];\n }\n std::vector<TLorentzVector> retval;\n retval.push_back(h1);\n return (retval);\n}\n\nstd::vector<TLorentzVector> fhemisphere(std::vector<TLorentzVector> myjets, int p1) {\n// int p1=100*seed+assoc;\n int seed=int(p1/100);\n int assoc=int(p1%10);\n // Convert\n std::vector<float> px;\n std::vector<float> py;\n std::vector<float> pz;\n std::vector<float> E;\n for (int i=0; i<myjets.size(); i++) {\n px.push_back(myjets[i].Px());\n py.push_back(myjets[i].Py());\n pz.push_back(myjets[i].Pz());\n E.push_back(myjets[i].E());\n }\n // Run the hemisphere algorithm\n Hemisphere hemis(px, py, pz, E, seed, assoc);\n // Get the vector that gives int values for group number assigned to each jet\n std::vector<int> hemisgroup = hemis.getGrouping();\n // Combine jets in each group into one object\n std::vector<TLorentzVector> myhemispheres;\n TLorentzVector h1, h2;\n for (int i=0; i<myjets.size(); i++) {\n int hg = hemisgroup[i];\n if (hg == 1) h1 += myjets[i];\n if (hg == 2) h2 += myjets[i];\n }\n myhemispheres.push_back(h1);\n myhemispheres.push_back(h2);\n return myhemispheres;\n\n}\n\ndouble fMT2(TLorentzVector lep1, TLorentzVector lep2, TLorentzVector amet){\n double retval;\n DEBUG(\"MT2 function wrapper\\n\");\n mt2_bisect::mt2 mt2_event;\n// Set momenta and the mass of the invisible particle, mn:\n// where array pa[0..2], pb[0..2], pmiss[0..2] contains (mass,px,py)\n double pa[3], pb[3], pmiss[3];\n pa[0]=lep1.M(); pb[0]=lep2.M(); pmiss[0]=amet.M();\n pa[1]=lep1.Px(); pb[1]=lep2.Px(); pmiss[1]=amet.Px();\n pa[2]=lep1.Py(); pb[2]=lep2.Py(); pmiss[2]=amet.Py();\n double mn=0.0;\n\n mt2_event.set_momenta( pa, pb, pmiss );\n mt2_event.set_mn( mn );\n retval=mt2_event.get_mt2();\n return (retval);\n}\n\ndouble all(AnalysisObjects* ao, string s, float id){\n return 1;\n}\n\ndouble uweight(AnalysisObjects* ao, string s, float value){\n ao->evt.user_evt_weight *= value;\n return 1;\n}\n\ndouble lepsf(AnalysisObjects* ao, string s, float value){\n ao->evt.user_evt_weight *= ao->evt.weight_leptonSF;\n return 1;\n}\n\ndouble btagsf(AnalysisObjects* ao, string s, float value){\n ao->evt.user_evt_weight *= ao->evt.weight_bTagSF_77;\n return 1;\n}\n\ndouble xslumicorrsf(AnalysisObjects* ao, string s, float value){\n\tao->evt.user_evt_weight *= ao->evt.correction_weight;\n\tao->evt.user_evt_weight *= ao->evt.luminosity_weight;\n\tao->evt.user_evt_weight *= ao->evt.weight_xsec;\n\treturn 1;\n}\n" }, { "alpha_fraction": 0.5625, "alphanum_fraction": 0.5775862336158752, "avg_line_length": 20.581396102905273, "blob_id": "fb2546adaf6b1591f6b7dbcc7f3f165f382daa8b", "content_id": "4f60f29cabe11554d81b33269b3aa4d91cee23a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 929, "license_type": "no_license", "max_line_length": 110, "num_lines": 43, "path": "/parser_test/HistoNode.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// HistoNode.h\n// mm\n//\n// Created by Anna-Monica on 8/6/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n\n#ifndef HistoNode_h\n#define HistoNode_h\n#include \"Node.h\"\n#include <string>\nclass HistoNode : public Node{\nprivate:\n std::string id;\n std::string Desciption;\n int lowerLimit;\n int upperLimit;\n int bins;\npublic:\n HistoNode( std::string id,std::string desc,int l1,int l2,int n,Node* l){\n this->id=id;\n Desciption=desc;\n lowerLimit=l1;\n upperLimit=l2;\n bins=n;\n symbol=\"histo \"+id+\",\"+Desciption+\",\"+std::to_string(l1)+\",\"+std::to_string(l2)+\",\"+std::to_string(n);\n left=l;\n right=NULL;\n }\n \n virtual double evaluate() {\n std::cout<<\"\\nHisto should evaluate and fill \";\n return left->evaluate();\n\n }\n virtual ~HistoNode() {\n if (left!=NULL) delete left;\n }\n \n};\n\n#endif /* HistoNode_h */\n" }, { "alpha_fraction": 0.6525506973266602, "alphanum_fraction": 0.6617069840431213, "avg_line_length": 41.47222137451172, "blob_id": "c3b98fd71e572e1a13969a71dcf1381466c6f0ac", "content_id": "a17d5d1d985068fcda2f9c21f823e1f7f13aaaba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12232, "license_type": "no_license", "max_line_length": 169, "num_lines": 288, "path": "/analysis_core/dbxParticle.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#ifndef DBX_PARTICLE_H\n#define DBX_PARTICLE_H\n\n#include \"TLorentzVector.h\"\n#include <iostream>\n#include <vector>\n#define CHMAX 256\n\n\n#ifndef USE_MEMCOPY\n#define USE_MEMCOPY 0\n#endif\n\n\nstruct analy_struct { // Declare analysis types\n\tint BPcount;\n\tint Dumpcount;\n\tint maxEvents;\n\tint startpt;\n\tint verbfreq;\n\tbool dosystematics;\n\tbool doQCD;\n\tbool doHF;\n std::string dependencies;\n};\n\ntypedef struct evt_data\n{\n\tevt_data()\n\t{\n\t}\n\n\tvoid operator=( const evt_data &right)\n\t{\n\n#if USE_MEMCOPY\n\n\t\tmemcpy(this,right,sizeof(evt_data));\n#else\n\n\t\trun_no =right.run_no;\n\t\tlumiblk_no =right.lumiblk_no;\n\t\tevent_no =right.event_no;\n\t\tTRG_e =right.TRG_e;\n\t\tTRG_m =right.TRG_m;\n\t\tTRG_j =right.TRG_j;\n\t\tbadjet =right.badjet;\n\t\ttop_hfor_type=right.top_hfor_type;\n\t\tmcevt_weight =right.mcevt_weight;\n\t\tuser_evt_weight =right.user_evt_weight;\n\t\tisemuoverlap =right.isemuoverlap;\n\t\tvxp_maxtrk_no=right.vxp_maxtrk_no;\n\t\tvxpType =right.vxpType;\n\t\tlar_Error =right.lar_Error;\n\t\tpileup_weight=right.pileup_weight;\n\t\tbad_lar_feb =right.bad_lar_feb;\n\t\tmet_loose =right.met_loose;\n\t\tmaxEvents =right.maxEvents;\n\t\tHLT_IsoMu17_eta2p1_LooseIsoPFTau20 =right.HLT_IsoMu17_eta2p1_LooseIsoPFTau20;\n\t\tcore_Flags =right.core_Flags;\n\t\tz_vtx_weight =right.z_vtx_weight;\n\n weight_mc =right.weight_mc;\n weight_pileup=right.weight_pileup;\n weight_leptonSF=right.weight_leptonSF;\n weight_bTagSF_77=right.weight_bTagSF_77;\n \t correction_weight=right.correction_weight;\n \t luminosity_weight=right.luminosity_weight;\n\t\t weight_xsec =right.weight_xsec; \n weight_jvt =right.weight_jvt;\n weight_sherpa_22_vjets=right.weight_sherpa_22_vjets;\n weight_pileup_UP=right.weight_pileup_UP;\n weight_pileup_DOWN=right.weight_pileup_DOWN;\n weight_leptonSF_EL_SF_Trigger_UP = right.weight_leptonSF_EL_SF_Trigger_UP;\n weight_leptonSF_EL_SF_Trigger_DOWN = right.weight_leptonSF_EL_SF_Trigger_DOWN;\n weight_leptonSF_EL_SF_Reco_UP = right.weight_leptonSF_EL_SF_Reco_UP;\n weight_leptonSF_EL_SF_Reco_DOWN = right.weight_leptonSF_EL_SF_Reco_DOWN;\n weight_leptonSF_EL_SF_ID_UP = right.weight_leptonSF_EL_SF_ID_UP;\n weight_leptonSF_EL_SF_ID_DOWN = right.weight_leptonSF_EL_SF_ID_DOWN;\n weight_leptonSF_EL_SF_Isol_UP = right.weight_leptonSF_EL_SF_Isol_UP;\n weight_leptonSF_EL_SF_Isol_DOWN = right.weight_leptonSF_EL_SF_Isol_DOWN;\n weight_leptonSF_MU_SF_Trigger_STAT_UP = right.weight_leptonSF_MU_SF_Trigger_STAT_UP;\n weight_leptonSF_MU_SF_Trigger_STAT_DOWN = right.weight_leptonSF_MU_SF_Trigger_STAT_DOWN;\n weight_leptonSF_MU_SF_Trigger_SYST_UP = right.weight_leptonSF_MU_SF_Trigger_SYST_UP;\n weight_leptonSF_MU_SF_Trigger_SYST_DOWN = right.weight_leptonSF_MU_SF_Trigger_SYST_DOWN;\n weight_leptonSF_MU_SF_ID_STAT_UP = right.weight_leptonSF_MU_SF_ID_STAT_UP;\n weight_leptonSF_MU_SF_ID_STAT_DOWN = right.weight_leptonSF_MU_SF_ID_STAT_DOWN;\n weight_leptonSF_MU_SF_ID_SYST_UP = right.weight_leptonSF_MU_SF_ID_SYST_UP;\n weight_leptonSF_MU_SF_ID_SYST_DOWN = right.weight_leptonSF_MU_SF_ID_SYST_DOWN;\n weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP = right.weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP;\n weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN = right.weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN;\n weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP = right.weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP;\n weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN = right.weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN;\n weight_leptonSF_MU_SF_Isol_STAT_UP = right.weight_leptonSF_MU_SF_Isol_STAT_UP;\n weight_leptonSF_MU_SF_Isol_STAT_DOWN = right.weight_leptonSF_MU_SF_Isol_STAT_DOWN;\n weight_leptonSF_MU_SF_Isol_SYST_UP = right.weight_leptonSF_MU_SF_Isol_SYST_UP;\n weight_leptonSF_MU_SF_Isol_SYST_DOWN = right.weight_leptonSF_MU_SF_Isol_SYST_DOWN;\n weight_leptonSF_MU_SF_TTVA_STAT_UP = right.weight_leptonSF_MU_SF_TTVA_STAT_UP;\n weight_leptonSF_MU_SF_TTVA_STAT_DOWN = right.weight_leptonSF_MU_SF_TTVA_STAT_DOWN;\n weight_leptonSF_MU_SF_TTVA_SYST_UP = right.weight_leptonSF_MU_SF_TTVA_SYST_UP;\n weight_leptonSF_MU_SF_TTVA_SYST_DOWN = right.weight_leptonSF_MU_SF_TTVA_SYST_DOWN;\n weight_bTagSF_77_extrapolation_up = right.weight_bTagSF_77_extrapolation_up;\n weight_bTagSF_77_extrapolation_down = right.weight_bTagSF_77_extrapolation_down;\n weight_bTagSF_77_extrapolation_from_charm_up = right.weight_bTagSF_77_extrapolation_from_charm_up;\n weight_bTagSF_77_extrapolation_from_charm_down = right.weight_bTagSF_77_extrapolation_from_charm_down;\n weight_jvt_UP = right.weight_jvt_UP;\n weight_jvt_DOWN = right.weight_jvt_DOWN;\n weight_bTagSF_77_eigenvars_B_up=right.weight_bTagSF_77_eigenvars_B_up;\n weight_bTagSF_77_eigenvars_C_up=right.weight_bTagSF_77_eigenvars_C_up;\n weight_bTagSF_77_eigenvars_Light_up=right.weight_bTagSF_77_eigenvars_Light_up;\n weight_bTagSF_77_eigenvars_B_down=right.weight_bTagSF_77_eigenvars_B_down;\n weight_bTagSF_77_eigenvars_C_down=right.weight_bTagSF_77_eigenvars_C_down;\n weight_bTagSF_77_eigenvars_Light_down=right.weight_bTagSF_77_eigenvars_Light_down;\n#endif\n\t}\n\tunsigned int run_no;\n\tunsigned int lumiblk_no;\n\tunsigned int event_no;\n\tbool TRG_e, TRG_m, TRG_j;\n\tbool badjet;\n\tint top_hfor_type;\n\tfloat mcevt_weight;\n\tbool isemuoverlap;\n\tunsigned int vxp_maxtrk_no;\n\tint vxpType;\n\tunsigned int lar_Error;\n\tfloat pileup_weight;\n\tbool bad_lar_feb;\n\tTVector2 met_loose;\n\tunsigned int maxEvents;\n\tbool HLT_IsoMu17_eta2p1_LooseIsoPFTau20;\n\tunsigned int core_Flags;\n\tfloat z_vtx_weight;\n double user_evt_weight;\n\n//S.I\n Float_t weight_mc;\n Float_t weight_pileup;\n Float_t weight_leptonSF;\n Float_t weight_bTagSF_77;\n Float_t correction_weight;\n Float_t luminosity_weight;\n Float_t weight_xsec;\n Float_t weight_jvt;\n Float_t weight_sherpa_22_vjets;\n Float_t weight_pileup_UP;\n Float_t weight_pileup_DOWN;\n Float_t weight_leptonSF_EL_SF_Trigger_UP;\n Float_t weight_leptonSF_EL_SF_Trigger_DOWN;\n Float_t weight_leptonSF_EL_SF_Reco_UP;\n Float_t weight_leptonSF_EL_SF_Reco_DOWN;\n Float_t weight_leptonSF_EL_SF_ID_UP;\n Float_t weight_leptonSF_EL_SF_ID_DOWN;\n Float_t weight_leptonSF_EL_SF_Isol_UP;\n Float_t weight_leptonSF_EL_SF_Isol_DOWN;\n Float_t weight_leptonSF_MU_SF_Trigger_STAT_UP;\n Float_t weight_leptonSF_MU_SF_Trigger_STAT_DOWN;\n Float_t weight_leptonSF_MU_SF_Trigger_SYST_UP;\n Float_t weight_leptonSF_MU_SF_Trigger_SYST_DOWN;\n Float_t weight_leptonSF_MU_SF_ID_STAT_UP;\n Float_t weight_leptonSF_MU_SF_ID_STAT_DOWN;\n Float_t weight_leptonSF_MU_SF_ID_SYST_UP;\n Float_t weight_leptonSF_MU_SF_ID_SYST_DOWN;\n Float_t weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP;\n Float_t weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN;\n Float_t weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP;\n Float_t weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN;\n Float_t weight_leptonSF_MU_SF_Isol_STAT_UP;\n Float_t weight_leptonSF_MU_SF_Isol_STAT_DOWN;\n Float_t weight_leptonSF_MU_SF_Isol_SYST_UP;\n Float_t weight_leptonSF_MU_SF_Isol_SYST_DOWN;\n Float_t weight_leptonSF_MU_SF_TTVA_STAT_UP;\n Float_t weight_leptonSF_MU_SF_TTVA_STAT_DOWN;\n Float_t weight_leptonSF_MU_SF_TTVA_SYST_UP;\n Float_t weight_leptonSF_MU_SF_TTVA_SYST_DOWN;\n Float_t weight_bTagSF_77_extrapolation_up;\n Float_t weight_bTagSF_77_extrapolation_down;\n Float_t weight_bTagSF_77_extrapolation_from_charm_up;\n Float_t weight_bTagSF_77_extrapolation_from_charm_down;\n Float_t weight_jvt_UP;\n Float_t weight_jvt_DOWN;\n\n std::vector<float> weight_bTagSF_77_eigenvars_B_up;\n std::vector<float> weight_bTagSF_77_eigenvars_C_up;\n std::vector<float> weight_bTagSF_77_eigenvars_Light_up;\n std::vector<float> weight_bTagSF_77_eigenvars_B_down;\n std::vector<float> weight_bTagSF_77_eigenvars_C_down;\n std::vector<float> weight_bTagSF_77_eigenvars_Light_down;\n\n//E S.I.\n\n}evt_data;\n\n\nclass dbxParticle : public TObject {\n\npublic:\n\tdbxParticle();\n\tdbxParticle(TLorentzVector);\n\tdbxParticle(TLorentzVector, int);\n\t~dbxParticle();\n\tdbxParticle operator+ (dbxParticle& c);\n\tstatic double deltaR(dbxParticle,dbxParticle);\n\tstatic double deltaPhi(dbxParticle,dbxParticle);\n\t//dbxParticle operator-() const;\n\tstatic bool comparePt(dbxParticle lhs, dbxParticle rhs) { return (lhs.lv().Pt() > rhs.lv().Pt()); }\n\tvoid Reset(){ p_charge=0; p_pdgID=0; p_lvector.SetPtEtaPhiM(0, 0, 0, 0); p_attribute.clear(); }\n\tvoid dump();\n\tvoid dump_b ();\n\tvoid dumpLHCO(std::ofstream& );\n\n\tint setCharge( int);\n\tint setPdgID( int);\n\tint setEtCone( double );\n\tint setPtCone( double );\n\tint setFlavor ( double );\n\tint setIsTight ( int );\n\n\tint setParticleIndx ( int );\n\tint setTlv( TLorentzVector );\n void setPPPE(float px, float py, float pz, float Ee ){p_lvector.SetPxPyPzE(px, py, pz, Ee ); }\n void addTlv(TLorentzVector *alv){p_lvector.SetPxPyPzE( p_lvector.Px()+alv->Px(), p_lvector.Py()+alv->Py(), p_lvector.Pz()+alv->Pz(), p_lvector.E()+alv->E()); }\n void addTlv(TLorentzVector alv){p_lvector.SetPxPyPzE( p_lvector.Px()+alv.Px(), p_lvector.Py()+alv.Py(), p_lvector.Pz()+alv.Pz(), p_lvector.E()+alv.E()); }\n\tint setScaleFactor ( double );\n\tint setScaleFactorReco ( double );\n\tint setScaleFactorId ( double );\n\tint setScaleFactorTrig ( double );\n\tint setScaleFactorTrigMcEff(double);\n\tint setScaleFactorIso (double );\n\tint setScaleFactorUncertainty ( double );\n\tint setScaleFactorUncertaintyUp ( double );\n\tint setScaleFactorUncertaintyDown ( double );\n\tint scaleLorentzVector ( double );\n\tint setZ0 (double );\n\tvoid setAttribute(int k, double v) {\n if (k>(int)p_attribute.size()) { std::cerr<<\"NO Such Attribute! Use addAttribute first.\\n\";\n } else { p_attribute[k]=v; }\n }\n\tvoid addAttribute(double v) {p_attribute.push_back(v);}\n\n\tint q() { return p_charge; }\n\tint pdgID() {return p_pdgID; }\n\tdouble Attribute(int k) { if (k>(int)p_attribute.size()){\n std::cerr<<\"NO Such Attribute! ID:\"<<k<<\"\\n\";return -999999;} else {return p_attribute.at(k);} }\n\tint nAttribute() { return p_attribute.size(); }\n\tdouble EtCone() { return p_et_cone; }\n\tdouble PtCone() { return p_pt_cone; }\n\tdouble Flavor() { return p_flavor; }\n\tint isTight() { return p_istight; }\n\tint ParticleIndx() { return p_particleindx; }\n\tTLorentzVector lv() const{ return p_lvector; }\n\tdouble ScaleFactor() { return p_scalefactor; }\n\tdouble ScaleFactorReco() { return p_scalefactorreco; }\n\tdouble ScaleFactorId() { return p_scalefactorid; }\n\tdouble ScaleFactorTrig() { return p_scalefactortrig; }\n\tdouble ScaleFactorTrigMcEff() { return p_scalefactortrig_mceff; }\n\tdouble ScaleFactorIso() { return p_scalefactoriso; }\n\tdouble ScaleFactorUncertainty() { return p_escalefactor; }\n\tdouble ScaleFactorUncertaintyUp() { return p_scalefactorup; }\n\tdouble ScaleFactorUncertaintyDown() { return p_scalefactordown; }\n\tdouble Z0() {return p_z0;}\n\n\nprivate:\n std::vector<double> p_attribute;\n\tint p_charge;\n\tint p_pdgID;\n\tdouble p_et_cone;\n\tdouble p_pt_cone;\n\tdouble p_flavor;\n\tint p_particleindx;\n\tTLorentzVector p_lvector;\n\tdouble p_scalefactor;\n\tdouble p_scalefactorreco;\n\tdouble p_scalefactorid;\n\tdouble p_scalefactortrig;\n\tdouble p_scalefactortrig_mceff;\n\tdouble p_scalefactoriso;\n\tdouble p_escalefactor;\n\tdouble p_scalefactorup;\n\tdouble p_scalefactordown;\n\tint p_istight;\n\tdouble p_z0;\n\n\tClassDef(dbxParticle,2);\n};\n\n#endif\n" }, { "alpha_fraction": 0.5140718817710876, "alphanum_fraction": 0.5258982181549072, "avg_line_length": 35.298912048339844, "blob_id": "76422e8faa4e7140e3a8f6b2e4fdf271de4d6fa7", "content_id": "8d57b053e72d858f0e8186294b6a19e31f0c56f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6680, "license_type": "no_license", "max_line_length": 134, "num_lines": 184, "path": "/analysis_core/AnalysisController.cpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#include \"AnalysisController.h\"\n#include \"ReadCard.h\"\n#include <string>\n\n//#define _CLV_\n\n#ifdef _CLV_\n#define DEBUG(a) std::cout<<a\n#else\n#define DEBUG(a)\n#endif\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nAnalysisController::AnalysisController( analy_struct *iselect, std::map <string, int> systematics) \n{\n\textra_analysis_count=1;\n\t// ----- how many do we run in parallel ----\n\tif (iselect->dosystematics) {\n\t\tfor( map<string,int>::iterator it=systematics.begin(); it!=systematics.end(); ++it) {\n\t\t\tsyst_names.insert(*it);\n\t\t}\n\t}\n\taselect=*iselect;\n\tcout << \" #systematic included:\"<<syst_names.size() <<endl;\n\n do_deps=false;\n\tstring prereqs=aselect.dependencies;\n\tif (prereqs.length()>2 ){\n do_deps=true;\n\t size_t kol=prereqs.find_first_of(':',0);\n\t if (kol == std::string::npos){ cerr<<\"Wrong dependency list format. Use: m:i,j,k \\n\"; exit (14);}\n\t mainAnalysis= atoi(prereqs.substr(0,kol).c_str());\n\t cout<<\"Indep region ID:\"<<mainAnalysis<<\"\\n\";\n\t std::string depStr = prereqs.substr(kol+1, prereqs.length());\n\t for (size_t i=0,n; i <= depStr.length(); i=n+1) {\n\t n = depStr.find_first_of(',',i);\n\t if (n == std::string::npos) n = depStr.length();\n\t std::string tmp = depStr.substr(i,n-i);\n\t cout <<\"Dep region id:\"<<atoi(tmp.c_str() )<<\"\\n\";\n depAnalyses.insert(atoi(tmp.c_str()) );\n\t }\n\t} \n}\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nvoid AnalysisController::Initialize(char *extname) {\n\n\tint analyindex=0;\n int k=0;\n int last_a=0;\n\n/*\n * The BP analysis\n */\n\tfor (int i=0; i<aselect.BPcount; i++) {\n\t\tchar tmp[32];\n\t\tsprintf (tmp,\"BP_%i\",i+1);\n\t\tdbxAnalyses.push_back( new BPdbxA(tmp) ); // BP analysis with name\n\t}\n\tDEBUG(\"End of BP initialization\\n\");\n\n/*\n * Dump analysis\n */\n\tfor (int i=0; i<aselect.Dumpcount; i++) {\n\t\tchar tmp[32];\n\t\tsprintf (tmp,\"Dump_%i\",i+1);\n\t\tdbxAnalyses.push_back( new DumpdbxA(tmp) ); // Dump analysis with name\n\t}\n\tDEBUG(\"End of Dumper initialization\\n\");\n\n\n// common suff for all analyses\n// ----------------------------\n for (k=0; k<dbxAnalyses.size(); k++) {\n\t\tdbxAnalyses[k]->initGRL();\n\t\tdbxAnalyses[k]->readAnalysisParams();\n std::cout << \" => \" << k << \" \"<< dbxAnalyses[k]->getName() <<endl;\n\t\tdbxAnalyses[k]->bookAdditionalHistos();\n }\n}\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nvoid AnalysisController::RunTasks( AnalysisObjects a0, map <string, AnalysisObjects> analysis_objs_map){\n//-------------------------------------------------this is called for each event read from the ntuple file\n int evret=0; // return value of each analysis\n std::string delimiter = \"_\";\n std::string sysnam=\"\";\n AnalysisObjects refA0=a0;\n int controlword=0; // no dependency, all cuts executed.\n int mainAresults;\n\n for (int k=0; k<dbxAnalyses.size(); k++) \n {\n bool aDumper=false; \n int token_cnt=0;\n sysnam=\"\";\n string ana=dbxAnalyses[k]->getName();\n size_t pos = 0;\n std::string token;\n while ((pos = ana.find(delimiter)) != std::string::npos) {\n token = ana.substr(0, pos);\n ana.erase(0, pos + delimiter.length());\n token_cnt++;\n if (token==\"Dump\") { aDumper=true; break;}\n/*\n if (token_cnt>1) { // systematics or QCD or WHF\n if ((ana.find(\"WHF\") == std::string::npos) && (ana.find(\"qcd\") == std::string::npos ) ){\n sysnam=ana;\n break;\n }\n }\n*/\n }\n \n if (sysnam.size()< 1){ // not a systematics run condition\n if (!aDumper){ //not a dumper, i.e. BP run\n//-----------------------------assume initial analysis returns this:\n//2: 1,pass 0,fail\n//5: 1,pass 1,pass 1,pass 1,pass 0,fail\n//10005: 1,pass 1,pass 1,pass 1,pass 1,pass\n\n//-------------at this point we should know if anAnalysis depends on Another.\n DEBUG(dbxAnalyses[k]->getName()<<\" to be executed with defaults\"<<endl);\n int lastpass=0;\n if(do_deps) {\n if ( depAnalyses.find(k) != depAnalyses.end() ){ // if this is analysis 1, we are dependent, get info from 0.\n if (mainAresults < 10000) controlword=mainAresults; // means last cut fails.\n else {\n lastpass=1;\n controlword=(mainAresults-10000);\n }\n }\n } else {\n a0.evt.user_evt_weight=refA0.evt.user_evt_weight;\n }\n//----------------------------------------------\n\t evret=dbxAnalyses[k]->makeAnalysis(&a0, controlword, lastpass); //------------------------------ regular analysis\n//----------------------------------------------\n if(do_deps) {\n if (k==mainAnalysis) {\n mainAresults=evret; // save the results from main;\n DEBUG(\"Main at \"<<k<<\" has evret:\"<<evret<<\"\\n\");\n }\n }\n } else { // the below is a dumper\n DEBUG(dbxAnalyses[k]->getName()<<\" to be executed with Dumper specials\"<<endl);\n\t\tstd::map <int, TVector2> metsmap;\n\t\tint kmet=1;\n\t\tfor ( std::map<string, AnalysisObjects>::iterator anit=analysis_objs_map.begin(); anit!=analysis_objs_map.end(); ++anit){\n\t\t\tAnalysisObjects these_objs= anit->second;\n\t\t\tTVector2 a_met = these_objs.met.begin()->second ;\n\t\t\tmetsmap.insert ( std::pair<int, TVector2> (kmet, a_met));\n\t\t\tkmet++;\n\t\t}\n\t\tevret=dbxAnalyses[k]->makeAnalysis(&a0,metsmap, m_quad_unc);\n }\n } else { //systematics run\n map<string, AnalysisObjects>::iterator il=analysis_objs_map.find(sysnam);\n if (il==analysis_objs_map.end()) {cout<<\"Systematics name mismatch. \"<<sysnam<<\" not found, MAJOR error\\n\"; exit (888);};\n DEBUG( k<<\" \"<<dbxAnalyses[k]->getName()<<\" also known as \"<< il->first<<\" to be executed with systematics\"<<endl );\n\t\tAnalysisObjects these_objs=il->second;\n\t\tevret=dbxAnalyses[k]->makeAnalysis(&these_objs); // generic\n DEBUG(\"retval=:\"<<evret<<endl);\n }\n }\n\n\tDEBUG(\"An Event finished.\" <<std::endl);\n}\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nvoid AnalysisController::SetJetUncs(vector <double> uncs){\n\tm_quad_unc.clear();\n\tfor (unsigned int u=0; u<uncs.size(); u++) m_quad_unc.push_back( uncs.at(u) );\n}\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nvoid AnalysisController::Finalize(){\n\tfor ( int i=0; i<dbxAnalyses.size(); i++)\n\t{\n\t\tdbxAnalyses[i]->printEfficiencies();\n\t\tdbxAnalyses[i]->saveHistos();\n\t}\n\n}\n\n" }, { "alpha_fraction": 0.607464611530304, "alphanum_fraction": 0.6078935861587524, "avg_line_length": 30.5, "blob_id": "fac0aff436cd79468bc88ab845c669b338855b08", "content_id": "2b546e0335f0983a5ef298aaf9b6b5fed4fbe6b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2331, "license_type": "no_license", "max_line_length": 92, "num_lines": 74, "path": "/BP/bp_a.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#ifndef BP_A_H\n#define BP_A_H\n\n#include \"dbx_a.h\"\n#include \"ReadCard.h\"\n#include <iostream>\n#include \"analysis_core.h\"\n#include \"myParticle.h\"\n#include \"Node.h\"\n#include <list>\n#include \"DBXNtuple.h\"\n#include \"TFile.h\"\n#include \"TTree.h\"\n\n\nclass BPdbxA : public dbxA {\n public: \n BPdbxA(char *aname) : dbxA ( aname)\n {\n sprintf (cname,\"%s\",aname); // keep the current analysis name in the class variable\n// int r=dbxA::setDir(cname); // make the relevant root directory\n// if (r) std::cout <<\"Root Directory Set Failure in:\"<<cname<<std::endl;\n //grl_cut=false;\n }\n\n int getInputs(std::string);\n int initGRL();\n int readAnalysisParams();\n int plotVariables(int sel);\n int printEfficiencies();\n int bookAdditionalHistos();\n int makeAnalysis(AnalysisObjects *ao, int controlword, int preResults );\n int Finalize();\n int saveHistos() {\n int r = dbxA::saveHistos();\n std::map<int, Node*>::iterator jter = NodeCuts.begin();\n for (std::vector<int>::iterator it = save.begin() ; it != save.end(); ++it) {\n int diff = *it - jter->first;\n for(int i = 0; i < diff; i++) jter++;\n jter->second->saveFile();\n }\n return r;\n }\n \n private:\n bool grl_cut;\n char cname[CHMAX];\n char algoname[CHMAX];\n std::vector<TString> effCL;\n std::vector< string> binCL;\n\n unsigned short int TRGe, TRGm;\n unsigned int systematics_bci;\n bool skip_histos;\n bool skip_effs;\n vector<int> save;\n unordered_set<int> optimize;\n static map<int, vector<myParticle *> > particleBank;\n\n \n//relevant variables\n list<string> parts; //for def of particles as given by user\n map<string,Node*> NodeVars;//for variable defintion\n map<string,vector<myParticle*> > ListParts;//for particle definition\n map<string,pair<vector<float>,bool> > ListTables;//for table definition\n map<string, vector<cntHisto> > cntHistos;\n map<int,Node*> NodeCuts;//cuts and histos\n map<int,Node*> BinCuts;//binning\n map<string,Node*> ObjectCuts;//cuts for user defined objects\n std::vector<std::string> NameInitializations;\n vector<int> TRGValues;\n vector<double> bincounts;\n};\n#endif\n" }, { "alpha_fraction": 0.4992794990539551, "alphanum_fraction": 0.509095311164856, "avg_line_length": 46.51864242553711, "blob_id": "074e10352271757a91934866e58845c712303d69", "content_id": "3486eb1687dbad12e66320ea8928862ba106d61e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 70092, "license_type": "no_license", "max_line_length": 260, "num_lines": 1475, "path": "/analysis_core/ObjectNode.cpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// ObjectNode.cpp\n// mm\n//\n// Created by Anna-Monica on 8/16/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n#include \"ObjectNode.hpp\"\n#include \"ValueNode.h\"\n#include <set>\n\n#include \"Comb.h\"\n#include \"Denombrement.h\"\n\n//#define _CLV_\n#ifdef _CLV_\n#define DEBUG(a) std::cout<<a\n#else\n#define DEBUG(a)\n#endif\n\n\nObjectNode::ObjectNode(std::string id,\n Node* previous,\n void (* func) (AnalysisObjects* ao, vector<Node*>* criteria, std::vector<myParticle *>* particles, std::string name, std::string basename),\n vector<Node*> criteria,\n std::string s) {\n\n symbol=s; // e.g. \"obj Ele\"\n name=id;//this is useless because symbol already has name of the particle, e.g. \"ELE\"\n\n if(func==NULL) {\n createNewSet=((ObjectNode*)previous)->createNewSet;\n } else {\n createNewSet=func;\n }\n for(int i=0;i<criteria.size();i++){\n this->criteria.push_back(criteria[i]);\n }\n\n left=previous;\n right=NULL;\n\n ObjectNode* anode=(ObjectNode*)previous; \n if (anode != NULL){\n while (anode->left != NULL) { anode=(ObjectNode*)anode->left; }\n if (anode->name == \"MUO\" ) type=muon_t;\n if (anode->name == \"ELE\" ) type=electron_t;\n if (anode->name == \"JET\" ) type=jet_t;\n if (anode->name == \"PHO\" ) type=photon_t;\n if (anode->name == \"FJET\") type=fjet_t;\n if (anode->name == \"Truth\") type=truth_t;\n if (anode->name == \"TAU\" ) type=tau_t;\n if (anode->name == \"Combo\" ) type=combo_t;\n DEBUG(\" I found:\" << anode->name<<\" t:\"<<type<<\"\\n\");\n } else { // if null\n if (id == \"MUO\" ) type=muon_t;\n if (id == \"ELE\" ) type=electron_t;\n if (id == \"JET\" ) type=jet_t;\n if (id == \"PHO\" ) type=photon_t;\n if (id == \"FJET\") type=fjet_t;\n if (id == \"Truth\") type=truth_t;\n if (id == \"TAU\" ) type=tau_t;\n if (id == \"Combo\" ) type=combo_t;\n DEBUG(\" I have:\"<<id<<\" t:\"<<type<<\"\\n\");\n }\n}\n\nObjectNode::~ObjectNode(){}\n\nvoid ObjectNode::Reset(){\n if(left!=NULL) {\n left->Reset();\n }\n for(auto it=criteria.begin();it!=criteria.end();it++){\n (*it)->Reset();\n }\n}\n\nvoid ObjectNode::getParticles(std::vector<myParticle *>* particles){\n cout<<\"Calling get particles on ObjectNode-----doing nothing\\n\";\n}\n\nvoid ObjectNode::getParticlesAt(std::vector<myParticle *>* particles, int index){\n cout<<\"Calling get particlesAT on ObjectNode-----doing nothing\\n\";\n}\n\ndouble ObjectNode::evaluate(AnalysisObjects* ao){\n //test if the AO thing not null=> then avoid function call\n DEBUG(\" working for:\"<<name << \" type:\"<<type<<\"\\n\");\n this->Reset(); ///////NGU\n std::string basename=\"xxx\";\n bool keepworking=true;\n\n DEBUG(\"inital sets #types: J, FJ:\"<< ao->jets.size()<<\",\"<<ao->ljets.size()<<\" E,M,T:\"<< ao->eles.size()<<\",\"<<ao->muos.size()<<\",\"<<ao->taus.size() <<\" P:\"<<ao->gams.size() <<\"\\n\"); \n DEBUG(\"# iparticles:\"<< particles.size()<<\"\\n\");\n if (particles.size() >0) DEBUG(\"type:\"<< particles[0]->type<<\"\\t index:\"<<particles[0]->index <<\"name:\"<<particles[0]->collection<<\"\\n\" );\n\n if (type == 0) {cerr <<\"type 0 unknown\\n\"; exit(1);}\n while(left!=NULL && keepworking) {\n ObjectNode* anode=(ObjectNode*)left;\n basename=anode->name;\n DEBUG(\"previous:\"<< basename<< \" type:\"<<type<<\"\\n\"); // Combo, 20\n// is it in the map list?\n switch (type) {\n case muon_t: if (ao->muos.find(basename)==ao->muos.end() ){\n \t\t\tanode->evaluate(ao);\n DEBUG(\" Muos evaluated.\\n\");\n } else keepworking=false;\n break;\n\n\tcase truth_t: if (ao->truth.find(basename) == ao->truth.end() ){\n\t\t\t\tanode->evaluate(ao);\n\t\t\t\tDEBUG(\" Truth evaluated.\\n\");\n\t\t } else keepworking=false;\n\t\t break;\n\n case electron_t: if (ao->eles.find(basename)==ao->eles.end() ){\n \t\t\tanode->evaluate(ao);\n DEBUG(\" Eles evaluated.\\n\");\n } else keepworking=false;\n break;\n case tau_t: if (ao->taus.find(basename)==ao->taus.end() ){\n \t\t\tanode->evaluate(ao);\n DEBUG(\" Taus evaluated.\\n\");\n } else keepworking=false;\n break;\n\n case jet_t: if (ao->jets.find(basename)==ao->jets.end() ){\n \t\t\tanode->evaluate(ao);\n DEBUG(\" Jets evaluated.\\n\");\n \t } else keepworking=false;\n break;\n case photon_t: if (ao->gams.find(basename)==ao->gams.end() ){\n \t\t\tanode->evaluate(ao);\n DEBUG(\" *****Phos evaluated.\\n\");\n \t } else keepworking=false;\n break;\n case fjet_t: if (ao->ljets.find(basename)==ao->ljets.end() ){\n \t\t\tanode->evaluate(ao);\n DEBUG(\" *****FJETs evaluated.\\n\");\n \t } else keepworking=false;\n break;\n case combo_t: if (ao->combos.find(basename)==ao->combos.end() ){\n \t\t\tanode->evaluate(ao);\n DEBUG(\" *****COMBOs evaluated.\\n\");\n \t } else keepworking=false;\n break;\n\n default: break;\n }\n anode=(ObjectNode*)anode->left;\n DEBUG(\"~~~~~~~~~~~~~~MOVED LEFT\\n\");\n }\n DEBUG(\"#particles:\"<< particles.size()<<\"\\n\");\n map <string, std::vector<dbxJet> >::iterator itj;\n for (itj=ao->jets.begin();itj!=ao->jets.end();itj++){\n if (itj->first == name) return 1;\n }\n map <string, std::vector<dbxElectron> >::iterator ite;\n for (ite=ao->eles.begin();ite!=ao->eles.end();ite++){\n if (ite->first == name) return 1;\n }\n map <string, std::vector<dbxTruth> >::iterator ittr;\n for (ittr=ao->truth.begin();ittr!=ao->truth.end();ittr++){\n if (ittr->first == name) return 1;\n }\n map <string, std::vector<dbxMuon> >::iterator itm;\n for (itm=ao->muos.begin();itm!=ao->muos.end();itm++){\n if (itm->first == name) return 1;\n }\n map <string, std::vector<dbxTau> >::iterator itt;\n for (itt=ao->taus.begin();itt!=ao->taus.end();itt++){\n if (itt->first == name) return 1;\n }\n map <string, std::vector<dbxPhoton> >::iterator itp;\n for (itp=ao->gams.begin();itp!=ao->gams.end();itp++){\n if (itp->first == name) return 1;\n }\n map <string, std::vector<dbxJet> >::iterator itfj;\n for (itfj=ao->ljets.begin();itfj!=ao->ljets.end();itfj++){\n if (itfj->first == name) return 1;\n }\n map <string, std::vector<dbxParticle> >::iterator itc;\n for (itc=ao->combos.begin();itc!=ao->combos.end();itc++){\n if (itc->first == name) return 1;\n }\n DEBUG(\"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\\n\"); \n DEBUG(\"Before new set #types: J, FJ, E, M, T, P, Combo, Consti:\"<< ao->jets.size()<<\",\"<<ao->ljets.size()<<\",\"<< ao->eles.size()<<\",\"<<ao->muos.size()<<\",\"<<ao->taus.size() <<\",\"<<ao->gams.size()<<\",\"<<ao->combos.size()<<\",\"<<ao->constits.size() <<\"\\n\"); \n//---------------\n (*createNewSet)(ao,&criteria,&particles, name, basename);//modify analysis object based on criteria here\n//---------------\n DEBUG(\" After new set #types: J, FJ, E, M, T, P, Combo, Consti:\"<< ao->jets.size()<<\",\"<<ao->ljets.size()<<\",\"<< ao->eles.size()<<\",\"<<ao->muos.size()<<\",\"<<ao->taus.size() <<\",\"<<ao->gams.size()<<\",\"<<ao->combos.size()<<\",\"<< ao->constits.size() <<\"\\n\"); \n DEBUG(\"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\\n\"); \n\n for (itj=ao->jets.begin();itj!=ao->jets.end();itj++){\n DEBUG(\"\\t #Jet typename:\"<<itj->first<<\" size:\"<<itj->second.size() <<\"\\n\");\n }\n for (itp=ao->gams.begin();itp!=ao->gams.end();itp++){\n DEBUG(\"\\t #Pho typename:\"<<itp->first<<\" size:\"<<itp->second.size() <<\"\\n\");\n }\n for (itc=ao->combos.begin();itc!=ao->combos.end();itc++){\n DEBUG(\"\\t #Com typename:\"<<itc->first<<\" size:\"<<itc->second.size() <<\"\\n\");\n }\n //Save AO somewhere to return in next time\n return 1;\n}\n// ***********************************\n\nvoid createNewJet(AnalysisObjects* ao,vector<Node*> *criteria,std::vector<myParticle *>* particles, std::string name, std::string basename){\n DEBUG(\"Creating new JETtype named:\"<<name<<\" #Jtypes:\"<<ao->jets.size()<< \" Duplicating:\"<<basename<<\"\\n\");\n ao->jets.insert( std::pair<string, vector<dbxJet> >(name, (ao->jets)[basename]) );\n DEBUG(\"Before all constituents \"<< ao->constits.size() << \"\\n\");\n for (int ipart=(ao->jets)[name].size()-1; ipart>=0; ipart--){ //Loop over all jets in the event.\n TString consname=name; TString baseconsname=basename;\n consname+=\"_\"; baseconsname+=\"_\";\n consname+=ipart; baseconsname+=ipart;\n consname+=\"c\"; baseconsname+=\"c\";\n ao->constits.insert( std::pair<string, vector<dbxParticle> >(consname.Data(), (ao->constits)[(string)baseconsname]) );\n DEBUG(consname<<\" added.\\t\");\n }\n DEBUG(\"\\n ALL Constits now:\"<<ao->constits.size() <<\"\\n\");\n\n for(auto cutIterator=criteria->begin();cutIterator!=criteria->end();cutIterator++){\n particles->clear();\n (*cutIterator)->getParticlesAt(particles,0);\n int ipart_max = (ao->jets)[name].size();\n bool simpleloop=true;\n bool constiloop=false;\n \n DEBUG(\"Nb of particles in this cut:\"<<particles->size() <<\"\\n\");\n if ( particles->size()==0) {\n DEBUG(\"No particle CutIte:\"<<(*cutIterator)->getStr()<<\"\\n\");\n bool ppassed=(*cutIterator)->evaluate(ao);\n continue;\n }\n//---------this needs to be tested at PARSING TIME!!!!!!!!!! NGU TODO\n std::set<int> ptypeset; // set of types, same type twice doesn't exist.\n int t1=particles->at(0)->type;\n int t2;\n for ( int kp=0; kp<particles->size(); kp++ ) {\n ptypeset.insert( particles->at(kp)->type);\n if (particles->at(kp)->type == consti_t) constiloop=true;\n }\n//--------------------- if we have a LoopNode(max, min, sum) no constiloop.\n TString mycutstr=(*cutIterator)->getStr();\n if ( mycutstr.Contains(\"sum\") || mycutstr.Contains(\"max\") || mycutstr.Contains(\"min\")) constiloop=false;\n if ( ptypeset.size()>2 ) {cerr <<\" 3 particle selection is not allowed in this version!\\n\"; exit(1);}\n if ( ptypeset.size()==2) {simpleloop=false;}\n std::set<int>::iterator ptit; \n ptit=ptypeset.begin(); ptit++;\n t2=*ptit;\n/*\nobject goodjets take Jet\n select q(Jet constituents ) != 0 # remove neutral constituents\n select pT(decayVert(Jet constituents) ) < minPVdistance # remove far PrimaryVertex'ed constituents\n select Sum(pT(Jet constituents ) ) < maxjetchargedpT # PT from remaining constituents\n# example \"goodJet_0c\"\n*/\n//--------------------\n if (constiloop) { // basename: previous base object, name: new object\n for (int ipart=ipart_max-1; ipart>=0; ipart--){ // loop over all particles, jets, in an event.\n TString konsname=name;\n konsname+=\"_\";\n konsname+=ipart;\n konsname+=\"c\";\n string consname=(string)konsname;\n int constiCount =(ao->constits).find(consname)->second.size();\n DEBUG(\"for \"<<consname<<\" constituents size:\"<<constiCount<<\"\\n\");\n for (int ic=constiCount-1; ic>=0; ic--){\n//---------------these are the particles to be dealt with, like a loop!\n for (int jp=0; jp<particles->size(); jp++){//the particles in the cut, e.g. pT(JET_jp) > 10\n particles->at(jp)->index=ic;\n particles->at(jp)->collection=consname; // new name\n particles->at(jp)->type=consti_t;\n }\n DEBUG(\"For consti:\"<<ic<<\" CutIte:\"<<(*cutIterator)->getStr()<<\"\\n\"); // this is like qOf, applied on each constituent\n bool ppassed=(*cutIterator)->evaluate(ao); // check on constituents?\n DEBUG(\"Result:\"<<ppassed<<\"\\n\");\n if (!ppassed) { \n DEBUG(\"consti \"<< ic <<\" failed and will be removed.\\n\");\n (ao->constits).find(consname)->second.erase( (ao->constits).find(consname)->second.begin()+ic); // erase consti\n }\n }//end of loop over constituent\n if ( (ao->constits).find(consname)->second.size() < 1) {\n DEBUG(ipart<<\"th jet removed from \"<<name<<\" since all constituents were removed.\\n\");\n (ao->jets).find(name)->second.erase( (ao->jets).find(name)->second.begin()+ipart); // erase jets without constituents\n }\n }// end of loop over all particles (jets) in the event.\n continue; // will move to the next cut iterator\n } // done with constis\n//------------------------------just to see\n/*\n for ( int ipa = (ao->jets)[name].size()-1; ipa>=0; ipa--){\n DEBUG(name <<\" \"<<ipa<<\" has \");\n TString konsname=name;\n konsname+=\"_\";\n konsname+=ipa;\n konsname+=\"c\";\n string consname=(string)konsname;\n int ciCount =(ao->constits).find(consname)->second.size();\n DEBUG(ciCount<<\" constituents\\n\"); \n }\n*/\n\n if(simpleloop){\n for (int ipart=ipart_max-1; ipart>=0; ipart--){ // I have all particles, jets, in an event.\n for (int jp=0; jp<particles->size(); jp++){//the particles in the cut\n particles->at(jp)->index=ipart;\n particles->at(jp)->collection=name;\n }\n DEBUG(\"CutIte:\"<<(*cutIterator)->getStr()<<\"\\t\");\n bool ppassed=(*cutIterator)->evaluate(ao);\n DEBUG(ppassed<<\"\\n\");\n if (!ppassed) (ao->jets).find(name)->second.erase( (ao->jets).find(name)->second.begin()+ipart);\n }\n } else { // if not a simple loop\n ValueNode abc=ValueNode();\n for (int ipart=ipart_max-1; ipart>=0; ipart--){\n particles->at(0)->index=ipart; // 6213\n particles->at(0)->collection=name; \n int ipart2_max=-1;\n string base_collection2=particles->at(1)->collection;\n try {\n switch(particles->at(1)->type){\n case muon_t: ipart2_max=(ao->muos).at(base_collection2).size(); break;\n\t case truth_t: ipart2_max=(ao->truth).at(base_collection2).size(); break;\n case electron_t: ipart2_max=(ao->eles).at(base_collection2).size(); break;\n case jet_t: ipart2_max=(ao->jets).at(base_collection2).size(); break;\n// case 3: ipart2_max=abc.tagJets(ao, 1).size(); //b-jets\n// break;\n// case 4: ipart2_max=abc.tagJets(ao, 1).size(); //light jets\n// break;\n case pureV_t: ipart2_max=1; break;\n case photon_t: ipart2_max=(ao->gams).at(base_collection2).size(); break;\n case fjet_t: ipart2_max=(ao->ljets).at(base_collection2).size(); break;\n case tau_t: ipart2_max=(ao->taus).at(base_collection2).size(); break;\n case combo_t: ipart2_max=(ao->combos)[base_collection2].size(); break;\n\n default:\n std::cerr << \"WRONG PARTICLE JET TYPE:\"<<particles->at(1)->type << std::endl;\n break;\n }\n } catch(...) {\n std::cerr << \"YOU WANT A PARTICLE TYPE YOU DIDN'T CREATE:\"<<base_collection2 <<\" !\\n\"; \n _Exit(-1);\n }\n for (int kpart=ipart2_max-1; kpart>=0; kpart--){ \n particles->at(1)->index=kpart; \n particles->at(1)->collection=base_collection2; \n for (int jp=2; jp<particles->size(); jp++){\n if (particles->at(jp)->type == t1) particles->at(jp)->index=ipart;\n if (particles->at(jp)->type == t2) particles->at(jp)->index=kpart;\n }\n\n bool ppassed=(*cutIterator)->evaluate(ao);\n if (!ppassed) {\n (ao->jets).find(name)->second.erase( (ao->jets).find(name)->second.begin()+ipart);\n break; // we can quit at first mismatch.\n }\n } // end of loop over 2nd particle type\n } // loop over 1st particle type\n }\n } // end of cutIterator loop\n DEBUG(\"created\\n\");\n}\n\nvoid createNewEle(AnalysisObjects* ao, vector<Node*> *criteria, std::vector<myParticle *> * particles, std::string name, std::string basename) {\n DEBUG(\"Creating new ELEtype named:\"<<name<<\" #Etypes:\"<<ao->eles.size()<< \" Duplicating:\"<<basename<<\"\\n\");\n ao->eles.insert( std::pair<string, vector<dbxElectron> >(name, (ao->eles)[basename]) );\n for(auto cutIterator=criteria->begin();cutIterator!=criteria->end();cutIterator++) {\n particles->clear();\n (*cutIterator)->getParticlesAt(particles,0);\n int ipart_max = (ao->eles)[name].size();\n bool simpleloop=true;\n \n DEBUG(\"Psize:\"<<particles->size() <<\"\\n\");\n if ( particles->size()==0) {\n DEBUG(\"CutIte:\"<<(*cutIterator)->getStr()<<\"\\n\");\n bool ppassed=(*cutIterator)->evaluate(ao);\n continue;\n }\n//---------this needs to be tested at PARSING TIME!!!!!!!!!! NGU TODO\n std::set<int> ptypeset;\n int t1=particles->at(0)->type;\n int t2;\n for ( int kp=0; kp<particles->size(); kp++ ) {\n ptypeset.insert( particles->at(kp)->type);\n }\n if ( ptypeset.size()>2 ) {cerr <<\" 3 particle selection is not allowed in this version!\\n\"; exit(1);}\n if ( ptypeset.size()==2) {simpleloop=false; }\n std::set<int>::iterator ptit;\n ptit=ptypeset.begin(); ptit++;\n t2=*ptit;\n \n if(simpleloop){\n for (int ipart=ipart_max-1; ipart>=0; ipart--){\n for (int jp=0; jp<particles->size(); jp++){\n particles->at(jp)->index=ipart;\n particles->at(jp)->collection=name;\n }\n bool ppassed=(*cutIterator)->evaluate(ao);\n if (!ppassed) (ao->eles).find(name)->second.erase( (ao->eles).find(name)->second.begin()+ipart);\n }\n }\n else {\n//################################# I have >=2 particles which should have the same index\n ValueNode abc=ValueNode();\n for (int ipart=ipart_max-1; ipart>=0; ipart--){ // loop over ALL electrons of the base class\n particles->at(0)->index=ipart; // 6213\n particles->at(0)->collection=name;\n int ipart2_max;\n string base_collection2=particles->at(1)->collection;\n switch(particles->at(1)->type){\n case muon_t: ipart2_max=(ao->muos)[base_collection2].size(); break;\n\t case truth_t: ipart2_max=(ao->truth)[base_collection2].size(); break;\n case electron_t: ipart2_max=(ao->eles)[base_collection2].size(); break;\n case jet_t: ipart2_max=(ao->jets)[base_collection2].size(); break;\n// case 3: ipart2_max=abc.tagJets(ao, 1).size(); //b-jets\n// break;\n// case 4: ipart2_max=abc.tagJets(ao, 1).size(); //light jets\n// break;\n case photon_t: ipart2_max=(ao->gams)[base_collection2].size(); break;\n case fjet_t: ipart2_max=(ao->ljets)[base_collection2].size(); break;\n case tau_t: ipart2_max=(ao->taus)[base_collection2].size(); break;\n case combo_t: ipart2_max=(ao->combos)[base_collection2].size(); break;\n\n default:\n std::cerr << \"WRONG PARTICLE TYPE! Try ELE:\"<<particles->at(1)->type << std::endl;\n break;\n }\n for (int kpart=ipart2_max-1; kpart>=0; kpart--){\n particles->at(1)->index=kpart;\n particles->at(1)->collection=base_collection2;\n for (int jp=2; jp<particles->size(); jp++){\n if (particles->at(jp)->type == t1) particles->at(jp)->index=ipart;\n if (particles->at(jp)->type == t2) particles->at(jp)->index=kpart;\n }\n bool ppassed=(*cutIterator)->evaluate(ao);\n if (!ppassed) {\n (ao->eles).find(name)->second.erase( (ao->eles).find(name)->second.begin()+ipart);\n break;\n }\n }\n }\n }\n }\n}\n\nvoid createNewMuo(AnalysisObjects* ao, vector<Node*> *criteria, std::vector<myParticle *> * particles, std::string name, std::string basename) {\n DEBUG(\"Creating new MUOtype named:\"<<name<<\" #MUOtypes:\"<<ao->muos.size()<< \" Duplicating:\"<<basename<<\"\\t\");\n ao->muos.insert( std::pair<string, vector<dbxMuon> >(name, (ao->muos)[basename]) );\n DEBUG(\" #MUOtypes:\"<<ao->muos.size()<< \" Duplicated.\\n\");\n\n for(auto cutIterator=criteria->begin();cutIterator!=criteria->end();cutIterator++) {\n particles->clear();\n (*cutIterator)->getParticlesAt(particles,0);\n int ipart_max = (ao->muos)[name].size();\n bool simpleloop=true;\n \n DEBUG(\"Psize:\"<<particles->size() <<\"\\t\"<<\" ipart_max:\"<<ipart_max<<\"\\n\");\n if ( particles->size()==0) {\n DEBUG(\"CutIte:\"<<(*cutIterator)->getStr()<<\"\\n\");\n bool kill_all=false;\n TString mycutstr=(*cutIterator)->getStr();\n if ( mycutstr.Contains(\"kill\") ) kill_all=true;\n\n int retval=(*cutIterator)->evaluate(ao);\n DEBUG(\"RetVal:\"<<retval<<\"\\n\");\n if (kill_all) {\n for (int ipart=ipart_max-1; ipart>=0; ipart--){\n if (retval != ipart) { DEBUG(\"Killing muon:\"<<ipart);\n (ao->muos).find(name)->second.erase( (ao->muos).find(name)->second.begin()+ipart);\n }\n }\n }\n DEBUG(\"M---------------------------------\\n\");\n continue;\n }\n std::set<int> ptypeset;\n int t1=particles->at(0)->type;\n int t2;\n for ( int kp=0; kp<particles->size(); kp++ ) {\n ptypeset.insert( particles->at(kp)->type);\n }\n if ( ptypeset.size()>2 ) {cerr <<\" 3 particle selection is not allowed in this version!\\n\"; exit(1);}\n if ( ptypeset.size()==2) {simpleloop=false; }\n std::set<int>::iterator ptit;\n ptit=ptypeset.begin(); ptit++;\n t2=*ptit; \n\n if(simpleloop){\n DEBUG(\"ONE particle Muon Loop \\n\");\n for (int ipart=ipart_max-1; ipart>=0; ipart--){\n for (int jp=0; jp<particles->size(); jp++){\n particles->at(jp)->index=ipart;\n particles->at(jp)->collection=name;\n }\n bool ppassed=(*cutIterator)->evaluate(ao);\n if (!ppassed) { DEBUG(\"Killing muon:\"<<ipart);\n (ao->muos).find(name)->second.erase( (ao->muos).find(name)->second.begin()+ipart);\n }\n }\n }\n else {\n DEBUG(\"TWO particle Muon Loop\\n\");\n ValueNode abc=ValueNode();\n for (int ipart=ipart_max-1; ipart>=0; ipart--){\n particles->at(0)->index=ipart; // 6213\n int ipart2_max;\n string base_collection2=particles->at(1)->collection;\n switch(particles->at(1)->type){\n case 12: ipart2_max=(ao->muos)[base_collection2].size(); break;\n\t\t case 10: ipart2_max=(ao->truth)[base_collection2].size(); break;\n case 1: ipart2_max=(ao->eles)[base_collection2].size(); break;\n case 2: ipart2_max=(ao->jets)[base_collection2].size(); break;\n// case 3: ipart2_max=abc.tagJets(ao, 1).size(); //b-jets\n// break;\n// case 4: ipart2_max=abc.tagJets(ao, 1).size(); //light jets\n// break;\n case 8: ipart2_max=(ao->gams)[base_collection2].size(); break;\n case 9: ipart2_max=(ao->ljets)[base_collection2].size(); break;\n case 11: ipart2_max=(ao->taus)[base_collection2].size(); break;\n case 20: ipart2_max=(ao->combos)[base_collection2].size(); break;\n\n default:\n std::cerr << \"WRONG PARTICLE TYPE! Try MUO:\"<<particles->at(1)->type << std::endl;\n break;\n }\n for (int kpart=ipart2_max-1; kpart>=0; kpart--){\n particles->at(1)->index=kpart;\n\n for (int jp=2; jp<particles->size(); jp++){\n if (particles->at(jp)->type == t1) particles->at(jp)->index=ipart;\n if (particles->at(jp)->type == t2) particles->at(jp)->index=kpart;\n }\n\n bool ppassed=(*cutIterator)->evaluate(ao);\n if (!ppassed) {\n (ao->muos).find(name)->second.erase( (ao->muos).find(name)->second.begin()+ipart);\n break;\n }\n } // second particle set\n }// first particle set\n }// end of two particles\n }// end of cutIterator\n}\nvoid createNewPho(AnalysisObjects* ao, vector<Node*> *criteria, std::vector<myParticle *> * particles, std::string name, std::string basename) {\n DEBUG(\"Creating new PHOtype named:\"<<name<<\" #Ptypes:\"<<ao->gams.size()<< \" Duplicating:\"<<basename<<\"\\t\");\n ao->gams.insert( std::pair<string, vector<dbxPhoton> >(name, (ao->gams)[basename]) );\n DEBUG(\" #Ptypes:\"<<ao->gams.size()<< \" Duplicated.\\n\");\n\n for(auto cutIterator=criteria->begin();cutIterator!=criteria->end();cutIterator++) {\n particles->clear();\n (*cutIterator)->getParticlesAt(particles,0);\n int ipart_max = (ao->gams)[name].size();\n bool simpleloop=true;\n \n DEBUG(\"Psize:\"<<particles->size() <<\"\\n\");\n if ( particles->size()==0) {\n DEBUG(\"CutIte:\"<<(*cutIterator)->getStr()<<\"\\n\");\n bool ppassed=(*cutIterator)->evaluate(ao);\n continue;\n }\n std::set<int> ptypeset;\n int t1=particles->at(0)->type;\n int t2;\n for ( int kp=0; kp<particles->size(); kp++ ) {\n ptypeset.insert( particles->at(kp)->type);\n }\n if ( ptypeset.size()>2 ) {cerr <<\" 3 particle selection is not allowed in this version!\\n\"; exit(1);}\n if ( ptypeset.size()==2) {simpleloop=false; }\n std::set<int>::iterator ptit;\n ptit=ptypeset.begin(); ptit++;\n t2=*ptit;\n \n if(simpleloop){\n DEBUG(\"size=1\\n\");\n for (int ipart=ipart_max-1; ipart>=0; ipart--){\n for (int jp=0; jp<particles->size(); jp++){\n particles->at(jp)->index=ipart;\n particles->at(jp)->collection=name;\n }\n bool ppassed=(*cutIterator)->evaluate(ao);\n if (!ppassed) (ao->gams).find(name)->second.erase( (ao->gams).find(name)->second.begin()+ipart);\n }\n }\n else {\n DEBUG(\"size=2\\n\");\n ValueNode abc=ValueNode();\n for (int ipart=ipart_max-1; ipart>=0; ipart--){\n particles->at(0)->index=ipart; // 6213\n int ipart2_max;\n string base_collection2=particles->at(1)->collection;\n switch(particles->at(1)->type){\n case 12: ipart2_max=(ao->muos)[base_collection2].size(); break;\n\t\t case 10: ipart2_max=(ao->truth)[base_collection2].size(); break;\n case 1: ipart2_max=(ao->eles)[base_collection2].size(); break;\n case 2: ipart2_max=(ao->jets)[base_collection2].size(); break;\n// case 3: ipart2_max=abc.tagJets(ao, 1).size(); //b-jets\n// break;\n// case 4: ipart2_max=abc.tagJets(ao, 1).size(); //light jets\n// break;\n case 8: ipart2_max=(ao->gams)[base_collection2].size(); break;\n case 9: ipart2_max=(ao->ljets)[base_collection2].size(); break;\n case 11: ipart2_max=(ao->taus)[base_collection2].size(); break;\n case 20: ipart2_max=(ao->combos)[base_collection2].size();\n default:\n std::cerr << \"WRONG PARTICLE TYPE! Try PHO:\"<<particles->at(1)->type << std::endl;\n break;\n }\n for (int kpart=ipart2_max-1; kpart>=0; kpart--){\n particles->at(1)->index=kpart;\n for (int jp=2; jp<particles->size(); jp++){\n if (particles->at(jp)->type == t1) particles->at(jp)->index=ipart;\n if (particles->at(jp)->type == t2) particles->at(jp)->index=kpart;\n }\n bool ppassed=(*cutIterator)->evaluate(ao);\n if (!ppassed) {\n (ao->gams).find(name)->second.erase( (ao->gams).find(name)->second.begin()+ipart);\n break;\n }\n } // second particle set\n }// first particle set\n }// end of two particles\n }// end of cutIterator\n DEBUG(\"PHOTONS created\\n\");\n}\nvoid createNewFJet(AnalysisObjects* ao, vector<Node*> *criteria, std::vector<myParticle *> * particles, std::string name, std::string basename) {\n DEBUG(\"Creating new FATJETtype named:\"<<name<<\" #Ttypes:\"<<ao->ljets.size()<< \" Duplicating:\"<<basename<<\"\\t\");\n ao->ljets.insert( std::pair<string, vector<dbxJet> >(name, (ao->ljets)[basename]) );\n DEBUG(\" #Ttypes became:\"<<ao->ljets.size()<< \" \\n\");\n\n for(auto cutIterator=criteria->begin();cutIterator!=criteria->end();cutIterator++) {\n particles->clear();\n (*cutIterator)->getParticlesAt(particles,0);\n int ipart_max = (ao->ljets)[name].size();\n bool simpleloop=true;\n\n DEBUG(\"Psize:\"<<particles->size() <<\"\\n\");\n if ( particles->size()==0) {\n DEBUG(\"CutIte:\"<<(*cutIterator)->getStr()<<\"\\n\");\n bool ppassed=(*cutIterator)->evaluate(ao);\n continue;\n }\n std::set<int> ptypeset;\n int t1=particles->at(0)->type;\n int t2;\n for ( int kp=0; kp<particles->size(); kp++ ) {\n ptypeset.insert( particles->at(kp)->type);\n }\n if ( ptypeset.size()>2 ) {cerr <<\" 3 particle selection is not allowed in this version!\\n\"; exit(1);}\n if ( ptypeset.size()==2) {simpleloop=false; }\n std::set<int>::iterator ptit;\n ptit=ptypeset.begin(); ptit++;\n t2=*ptit;\n \n if(simpleloop){\n DEBUG(\"Simple Loop\\n\");\n for (int ipart=ipart_max-1; ipart>=0; ipart--){\n for (int jp=0; jp<particles->size(); jp++){\n particles->at(jp)->index=ipart;\n particles->at(jp)->collection=name;\n }\n bool ppassed=(*cutIterator)->evaluate(ao);\n if (!ppassed) (ao->ljets).find(name)->second.erase( (ao->ljets).find(name)->second.begin()+ipart);\n }\n }\n else {\n DEBUG(\"size=2\\n\");\n ValueNode abc=ValueNode();\n for (int ipart=ipart_max-1; ipart>=0; ipart--){\n particles->at(0)->index=ipart; // 6213\n int ipart2_max;\n string base_collection2=particles->at(1)->collection;\n switch(particles->at(1)->type){\n case 12: ipart2_max=(ao->muos)[base_collection2].size(); break;\n\t\t case 10: ipart2_max=(ao->truth)[base_collection2].size(); break;\n case 1: ipart2_max=(ao->eles)[base_collection2].size(); break;\n case 2: ipart2_max=(ao->jets)[base_collection2].size(); break;\n// case 3: ipart2_max=abc.tagJets(ao, 1).size(); //b-jets\n// break;\n// case 4: ipart2_max=abc.tagJets(ao, 1).size(); //light jets\n// break;\n case 8: ipart2_max=(ao->gams)[base_collection2].size(); break;\n case 9: ipart2_max=(ao->ljets)[base_collection2].size(); break;\n case 11: ipart2_max=(ao->taus)[base_collection2].size(); break;\n case 20: ipart2_max=(ao->combos)[base_collection2].size();\n default:\n std::cerr << \"WRONG PARTICLE TYPE! Try FJET:\"<<particles->at(1)->type << std::endl;\n break;\n }\n for (int kpart=ipart2_max-1; kpart>=0; kpart--){\n particles->at(1)->index=kpart;\n for (int jp=2; jp<particles->size(); jp++){\n if (particles->at(jp)->type == t1) particles->at(jp)->index=ipart;\n if (particles->at(jp)->type == t2) particles->at(jp)->index=kpart;\n }\n\n\n bool ppassed=(*cutIterator)->evaluate(ao);\n if (!ppassed) {\n (ao->ljets).find(name)->second.erase( (ao->ljets).find(name)->second.begin()+ipart);\n break;\n }\n } // second particle set\n }// first particle set\n }// end of two particles\n }// end of cutIterator\n DEBUG(\"FATJETs created\\n\");\n}\nvoid createNewTau(AnalysisObjects* ao, vector<Node*> *criteria, std::vector<myParticle *> * particles, std::string name, std::string basename) {\n DEBUG(\"Creating new TAUtype named:\"<<name<<\" #Ttypes:\"<<ao->taus.size()<< \" Duplicating:\"<<basename<<\"\\n\");\n ao->taus.insert( std::pair<string, vector<dbxTau> >(name, (ao->taus)[basename]) );\n DEBUG(\" #Ttypes:\"<<ao->taus.size()<< \" Duplicated.\\n\");\n\n for(auto cutIterator=criteria->begin();cutIterator!=criteria->end();cutIterator++) {\n particles->clear();\n (*cutIterator)->getParticlesAt(particles,0);\n int ipart_max = (ao->taus)[name].size();\n bool simpleloop=true;\n \n DEBUG(\"Psize:\"<<particles->size() <<\"\\n\");\n if ( particles->size()==0) {\n DEBUG(\"CutIte:\"<<(*cutIterator)->getStr()<<\"\\n\");\n bool kill_all=false;\n TString mycutstr=(*cutIterator)->getStr();\n if ( mycutstr.Contains(\"kill\") ) kill_all=true;\n\n int retval=(*cutIterator)->evaluate(ao);\n DEBUG(\"RetVal:\"<<retval<<\"\\n\");\n if (kill_all) {\n for (int ipart=ipart_max-1; ipart>=0; ipart--){\n if (retval != ipart) { DEBUG(\"Killing muon:\"<<ipart);\n (ao->taus).find(name)->second.erase( (ao->taus).find(name)->second.begin()+ipart);\n }\n }\n }\n DEBUG(\"T---------------------------------\\n\");\n continue;\n }\n std::set<int> ptypeset;\n int t1=particles->at(0)->type;\n int t2;\n for ( int kp=0; kp<particles->size(); kp++ ) {\n ptypeset.insert( particles->at(kp)->type);\n }\n if ( ptypeset.size()>2 ) {cerr <<\" 3 particle selection is not allowed in this version!\\n\"; exit(1);}\n if ( ptypeset.size()==2) {simpleloop=false; }\n std::set<int>::iterator ptit; \n ptit=ptypeset.begin(); ptit++;\n t2=*ptit; \n\n if(simpleloop){\n DEBUG(\"size=1\\n\");\n for (int ipart=ipart_max-1; ipart>=0; ipart--){\n particles->at(0)->index=ipart;\n particles->at(0)->collection=name;\n bool ppassed=(*cutIterator)->evaluate(ao);\n if (!ppassed) (ao->taus).find(name)->second.erase( (ao->taus).find(name)->second.begin()+ipart);\n }\n }\n else {\n DEBUG(\"size=2\\n\");\n ValueNode abc=ValueNode();\n for (int ipart=ipart_max-1; ipart>=0; ipart--){\n particles->at(0)->index=ipart; // 6213\n int ipart2_max;\n string base_collection2=particles->at(1)->collection;\n switch(particles->at(1)->type){\n case 12: ipart2_max=(ao->muos)[base_collection2].size(); break;\n\t case 10: ipart2_max=(ao->truth)[base_collection2].size(); break; \n case 1: ipart2_max=(ao->eles)[base_collection2].size(); break;\n case 2: ipart2_max=(ao->jets)[base_collection2].size(); break;\n// case 3: ipart2_max=abc.tagJets(ao, 1).size(); //b-jets\n// break;\n// case 4: ipart2_max=abc.tagJets(ao, 1).size(); //light jets\n// break;\n case 8: ipart2_max=(ao->gams)[base_collection2].size(); break;\n case 9: ipart2_max=(ao->ljets)[base_collection2].size(); break;\n case 11: ipart2_max=(ao->taus)[base_collection2].size(); break;\n case 20: ipart2_max=(ao->combos)[base_collection2].size();\n default:\n std::cerr << \"WRONG PARTICLE TYPE! Try Tau:\"<<particles->at(1)->type << std::endl;\n break;\n }\n for (int kpart=ipart2_max-1; kpart>=0; kpart--){\n particles->at(1)->index=kpart;\n for (int jp=2; jp<particles->size(); jp++){\n if (particles->at(jp)->type == t1) particles->at(jp)->index=ipart;\n if (particles->at(jp)->type == t2) particles->at(jp)->index=kpart;\n }\n\n\n bool ppassed=(*cutIterator)->evaluate(ao);\n if (!ppassed) {\n (ao->taus).find(name)->second.erase( (ao->taus).find(name)->second.begin()+ipart);\n break;\n }\n } // second particle set\n }// first particle set\n }// end of two particles\n }// end of cutIterator\n DEBUG(\"TAUS created\\n\");\n}\n//------------------------\nvoid createNewCombo(AnalysisObjects* ao, vector<Node*> *criteria, std::vector<myParticle *> * particles, std::string name, std::string basename) {\n DEBUG(\"Creating new COMBO type named:\"<<name<<\" previous Combo types #:\"<<ao->combos.size()<<\"\\n\"); //xxx\n\n vector<dbxParticle> combination;\n dbxParticle *adbxp;\n TLorentzVector alv;\n std::string collectionName;\n int ipart_max;\n\n for(auto cutIterator=criteria->begin();cutIterator!=criteria->end();cutIterator++){\n particles->clear();\n (*cutIterator)->getParticles(particles);\n\n DEBUG(\"Psize:\"<<particles->size() <<\"\\n\");\n for (int jj=0; jj<particles->size(); jj++){\n DEBUG(\"T:\"<<particles->at(jj)->type<< \" i:\"<<particles->at(jj)->index<<\" C:\"<< particles->at(jj)->collection<<\"\\n\");\n collectionName=particles->at(jj)->collection;\n\n switch(particles->at(jj)->type){\n case muon_t: \n if ( (ao->muos).find(collectionName) == ao->muos.end() ) {\n cout << \"ERROR: \"<<collectionName<<\" collection is not DEFINED\\n\"\n << \" Try adding: select Size(\"<<collectionName<<\") >= 0 to solve the problem.\";\n exit (1);\n }\n ipart_max=(ao->muos)[collectionName].size();\n for (int ipart=0; ipart<ipart_max; ipart++){\n alv=(ao->muos)[collectionName].at(ipart).lv();\n adbxp= new dbxParticle(alv);\n adbxp->setCharge((ao->muos)[collectionName].at(ipart).q() );\n adbxp->setPdgID( (ao->muos)[collectionName].at(ipart).pdgID() );\n combination.push_back(*adbxp);\n delete adbxp;\n }\n break;\n case electron_t: \n if ( (ao->eles).find(collectionName) == ao->eles.end() ) {\n cout << \"ERROR: \"<<collectionName<<\" is not previously used in Selection.\\n\"\n << \" Try adding: select Size(\"<<collectionName<<\") >= 0 to solve the problem.\";\n exit (1);\n }\n ipart_max=(ao->eles)[collectionName].size();\n for (int ipart=0; ipart<ipart_max; ipart++){\n alv=(ao->eles)[collectionName].at(ipart).lv();\n adbxp= new dbxParticle(alv);\n adbxp->setCharge((ao->eles)[collectionName].at(ipart).q() );\n adbxp->setPdgID( (ao->eles)[collectionName].at(ipart).pdgID() );\n combination.push_back(*adbxp);\n delete adbxp;\n }\n break;\n\t\t case 10: ipart_max=(ao->truth)[collectionName].size();\n break;\n case 2: ipart_max=(ao->jets)[collectionName].size();\n break;\n// case 3: ipart_max=abc.tagJets(ao, 1).size(); //b-jets\n// break;\n// case 4: ipart_max=abc.tagJets(ao, 1).size(); //light jets\n// break;\n case 8: ipart_max=(ao->gams)[collectionName].size(); break;\n case 9: ipart_max=(ao->ljets)[collectionName].size(); break;\n case 11: ipart_max=(ao->taus)[collectionName].size();\n for (int ipart=0; ipart<ipart_max; ipart++){\n alv=(ao->taus)[collectionName].at(ipart).lv();\n adbxp= new dbxParticle(alv);\n adbxp->setCharge((ao->taus)[collectionName].at(ipart).q() );\n adbxp->setPdgID( (ao->taus)[collectionName].at(ipart).pdgID() );\n combination.push_back(*adbxp);\n delete adbxp;\n }\n break;\n case 20: ipart_max=(ao->combos)[collectionName].size(); \n for (int ipart=0; ipart<ipart_max; ipart++){\n alv=(ao->combos)[collectionName].at(ipart).lv();\n adbxp= new dbxParticle(alv);\n adbxp->setCharge((ao->combos)[collectionName].at(ipart).q() );\n adbxp->setPdgID( (ao->combos)[collectionName].at(ipart).pdgID() );\n combination.push_back(*adbxp);\n delete adbxp;\n }\n break;\n default:\n std::cerr << \"WRONG PARTICLE COMBO TYPE! Type:\"<<particles->at(jj)->type << std::endl;\n break;\n }\n DEBUG(\"Adding # particles:\"<<ipart_max<<\"\\n\");\n\n } //end of particle loop\n }// end of cut iterator loop\n ao->combos.insert( pair <string,vector<dbxParticle> > (name, combination) );\n\n DEBUG(\"After addition, types #:\"<<ao->combos.size()<< \" \\t\");\n DEBUG(\" added particle#:\"<<(ao->combos)[name].size()<< \" \\n\");\n\n}\n\n//------------------------------------------------\nvoid createNewTruth(AnalysisObjects* ao, vector<Node*> *criteria, std::vector<myParticle *> * particles, std::string name, std::string basename) {\n DEBUG(\"Creating new GEN type named:\"<<name<<\" #Gtypes:\"<<ao->truth.size()<<\" #Gparticles:\"<< (ao->truth)[basename].size() <<\" Duplicating:\"<<basename<<\"\\n\"); \n ao->truth.insert( std::pair<string, vector<dbxTruth> >(name, (ao->truth)[basename]) );\n DEBUG(ao->constits.size()<< \" initial constits maps\\n\");\n map <string, std::vector<dbxParticle> >::iterator itpa;\n for (itpa=ao->constits.begin();itpa!=ao->constits.end();itpa++){\n DEBUG(itpa->first<<\" has \"<<itpa->second.size()<<\"\\n\" );\n }\n\n for(auto cutIterator=criteria->begin();cutIterator!=criteria->end();cutIterator++) {\n particles->clear();\n (*cutIterator)->getParticlesAt(particles,0);\n int ipart_max = (ao->truth)[name].size();\n bool simpleloop=true;\n bool constiloop=false;\n\n DEBUG(\"Number of particles in this cut:\"<<particles->size() <<\"\\n\");\n DEBUG(\"CutIte:\"<<(*cutIterator)->getStr()<<\"\\n\");\n if ( particles->size()==0) {\n bool ppassed=(*cutIterator)->evaluate(ao);\n continue;\n }\n//---------this needs to be tested at PARSING TIME!!!!!!!!!! NGU TODO\n std::set<int> ptypeset;\n int t1=particles->at(0)->type;\n int t2;\n for ( int kp=0; kp<particles->size(); kp++ ) {\n ptypeset.insert( particles->at(kp)->type);\n DEBUG(kp<<\" th particle ID is:\"<<particles->at(kp)->type<<\"\\n\");\n if (particles->at(kp)->type == consti_t) constiloop=true;\n }\n//--------------------- if we have a LoopNode(max, min, sum) no constiloop.\n TString mycutstr=(*cutIterator)->getStr();\n if ( mycutstr.Contains(\"sum\") || mycutstr.Contains(\"max\") || mycutstr.Contains(\"min\")) constiloop=false;\n if ( ptypeset.size()>2 ) {cerr <<\" 3 particle selection is not allowed in this version!\\n\"; exit(1);}\n if ( ptypeset.size()==2) {simpleloop=false; }\n std::set<int>::iterator ptit;\n ptit=ptypeset.begin(); ptit++;\n t2=*ptit; \n//----------------------------\n if (constiloop) { // basename: previous base object, name: new object\n DEBUG(\"--GEN daugther loop-- \"<< ipart_max<<\"\\n\");\n for (int ipart=ipart_max-1; ipart>=0; ipart--){ // loop over all particles, jets, in an event.\n//--------------the name is derived from particleID\n int pidx=(ao->truth)[name].at(ipart).ParticleIndx();\n TString colname=name + pidx;\n int constiCount = (ao->constits).find((string)colname)->second.size();\n DEBUG(\"for \"<<name<<\" children size:\"<<constiCount<<\"\\n\");\n for (int ic=constiCount-1; ic>=0; ic--){\n//---------------these are the particles to be dealt with, like a loop!\n for (int jp=0; jp<particles->size(); jp++){//the particles in the cut, e.g. pT(JET_jp) > 10\n particles->at(jp)->index=ic;\n particles->at(jp)->collection=(string)colname; // new name\n particles->at(jp)->type=consti_t;\n }\n DEBUG(\"For child:\"<<ic<<\" CutIte:\"<<(*cutIterator)->getStr()<<\"\\n\"); // this is like qOf, applied on each constituent\n bool ppassed=(*cutIterator)->evaluate(ao); // check on constituents?\n DEBUG(\"Result:\"<<ppassed<<\"\\n\");\n if (!ppassed) { \n DEBUG(\"child \"<< ic <<\" failed and will be removed.\\n\");\n (ao->constits).find((string)colname)->second.erase( (ao->constits).find((string)colname)->second.begin()+ic); // erase child\n }\n }//end of loop over constituent\n if ( (ao->constits).find((string)colname)->second.size() < 1) {\n DEBUG(ipart<<\"th gen removed from \"<<name<<\" since all constituents were removed.\\n\");\n (ao->truth).find(name)->second.erase( (ao->truth).find(name)->second.begin()+ipart); // erase particle without children\n }\n }// end of loop over all particles (truth) in the event.\n continue; // will move to the next cut iterator\n } // done with constis\n DEBUG(name <<\" has \" << (ao->truth)[name].size()<<\" particles left after constiloop.\\n\");\n map <string, std::vector<dbxParticle> >::iterator itpa;\n\n if(simpleloop){\n DEBUG(\"--GEN simple loop-- \"<< ipart_max<<\"\\n\");\n for (int ipart=ipart_max-1; ipart>=0; ipart--){\n int pidx=(ao->truth)[name].at(ipart).ParticleIndx();\n for (int jp=0; jp<particles->size(); jp++){\n particles->at(jp)->index=ipart;\n particles->at(jp)->collection=name;\n }\n bool ppassed=(*cutIterator)->evaluate(ao);\n DEBUG(name<<\" ID\"<< pidx<<\" Res:\"<<ppassed<<\"\\n\");\n if (!ppassed) {\n TString dname;\n dname = name + pidx;\n itpa=(ao->constits).find((string)dname);\n DEBUG(\"will delete:\"<<dname<<\"\\n\");\n if (itpa!=(ao->constits).end()) (ao->constits).erase(itpa);\n (ao->truth).find(name)->second.erase( (ao->truth).find(name)->second.begin()+ipart);\n } \n }\n DEBUG(name <<\" has \" << (ao->truth)[name].size()<<\" particles left after simpleloop.\\n\");\n//------------------------------------\n//put the children in a consti_t array\n//------------------------------------\n DEBUG(ao->constits.size()<< \" constits maps\\n\");\n for (itpa=ao->constits.begin();itpa!=ao->constits.end();itpa++){\n DEBUG(itpa->first<<\" has \"<<itpa->second.size()<<\"\\n\" );\n }\n DEBUG(\"===============\\n\");\n TString dname;\n for (int ipart=(ao->truth)[name].size()-1; ipart>=0; ipart--){\n int child1=(ao->truth)[name].at(ipart).Attribute(8);\n int child2=(ao->truth)[name].at(ipart).Attribute(9);\n int pidx=(ao->truth)[name].at(ipart).ParticleIndx();\n DEBUG(\"Id:\"<< pidx <<\" has children:\"<<child1<<\" to \"<<child2<<\"\\t\");\n vector<dbxParticle> children;\n string genname=\"Truth\";\n for (int ichild=child1; ichild<=child2; ichild++){\n children.push_back( (ao->truth)[genname].at(ichild) );\n }\n dname = name;\n dname+= pidx;\n (ao->constits).insert( std::pair<string, vector<dbxParticle> >((string)dname, children) );\n DEBUG(name <<\" has \" << (ao->constits).find((string)dname)->second.size()<<\" dauthers inserted.\\n\");\n }\n//------------DONE\n }\n else {\n ValueNode abc=ValueNode();\n for (int ipart=ipart_max-1; ipart>=0; ipart--){\n particles->at(0)->index=ipart; // 6213\n int ipart2_max;\n string base_collection2=particles->at(1)->collection;\n switch(particles->at(1)->type){\n case muon_t: ipart2_max=(ao->muos)[base_collection2].size();\n break;\n\t case truth_t: ipart2_max=(ao->truth)[base_collection2].size();\n break;\n case electron_t: ipart2_max=(ao->eles)[base_collection2].size();\n break;\n case jet_t: ipart2_max=(ao->jets)[base_collection2].size();\n break;\n case photon_t: ipart2_max=(ao->gams)[base_collection2].size();\n break;\n case fjet_t: ipart2_max=(ao->ljets)[base_collection2].size();\n break;\n case tau_t: ipart2_max=(ao->taus)[base_collection2].size();\n break;\n case combo_t: ipart2_max=(ao->combos)[base_collection2].size();\n break;\n default:\n std::cerr << \"WRONG PARTICLE TYPE! Try Truth:\"<<particles->at(1)->type << std::endl;\n break;\n }\n for (int kpart=ipart2_max-1; kpart>=0; kpart--){\n particles->at(1)->index=kpart;\n\n for (int jp=2; jp<particles->size(); jp++){\n if (particles->at(jp)->type == t1) particles->at(jp)->index=ipart;\n if (particles->at(jp)->type == t2) particles->at(jp)->index=kpart;\n }\n\n bool ppassed=(*cutIterator)->evaluate(ao);\n if (!ppassed) {\n (ao->truth).find(name)->second.erase( (ao->truth).find(name)->second.begin()+ipart);\n break;\n }\n } // second particle set\n }// first particle set\n }// end of two particles\n }// end of cutIterator\n}\n \nvoid step_add_a_comb(vector<int> output_ii, vector<int> tab_select_jj, vector<int>& table_B_ii, int index_jj, int n, int pas )\n{\n\tvector<int> temp(tab_select_jj.size()); \n\tfor(int i = 0; i<n; i++)\n\t{\n\t\tfor(int j = 0; j<pas; j++)\n\t\t\ttemp[j] = output_ii[j+i*pas];\n\n\t\tif(temp==tab_select_jj)\n\t\t\t{\n table_B_ii.push_back(index_jj);\n }\n\t}\n}\n\nvoid createNewParti(AnalysisObjects* ao, vector<Node*> *criteria, std::vector<myParticle *> * particles, std::string name, std::string basename) {\n DEBUG(\"Creating new PARTITION COMBO type named:\"<<name<<\" previous Combo types #:\"<<ao->combos.size()<<\"\\n\"); //xxx\n\n vector<dbxParticle> combination;\n dbxParticle *adbxp;\n std::string collectionName;\n int ipart_max;\n vector<int> available_parts;\n int requested_max;\n int requested_size;\n\n auto cutIterator=criteria->begin();\n particles->clear();\n (*cutIterator)->getParticles(particles);\n requested_size=particles->size();\n DEBUG(\"iCut: \"<<(*cutIterator)->getStr()<<\"\\n\");\n DEBUG(\"iPsize:\"<<particles->size() <<\"\\n\");\n\n// at this point I have the particles I will use to construct the combined object. like j1 and j2\n// now we find how many of those particles we have in each event\n for (int jj=0; jj<particles->size(); jj++){\n DEBUG(\"Type:\"<<particles->at(jj)->type<< \" index:\"<<particles->at(jj)->index<<\" Coll:\"<< particles->at(jj)->collection<<\"\\n\");\n collectionName=particles->at(jj)->collection;\n switch(particles->at(jj)->type){\n case muon_t: \n if ( (ao->muos).find(collectionName) == ao->muos.end() ) {\n cout << \"ERROR: \"<<collectionName<<\" collection is not DEFINED\\n\"\n << \" Try adding: select Size(\"<<collectionName<<\") >= 0 to solve the problem.\";\n exit (1);\n }\n ipart_max=(ao->muos)[collectionName].size();\n break;\n case electron_t: \n if ( (ao->eles).find(collectionName) == ao->eles.end() ) {\n cout << \"ERROR: \"<<collectionName<<\" is not previously used in Selection.\\n\"\n << \" Try adding: select Size(\"<<collectionName<<\") >= 0 to solve the problem.\";\n exit (1);\n }\n ipart_max=(ao->eles)[collectionName].size();\n break;\n\t\t case truth_t: ipart_max=(ao->truth)[collectionName].size();\n break;\n case jet_t: ipart_max=(ao->jets)[collectionName].size();\n break;\n case photon_t: ipart_max=(ao->gams)[collectionName].size();\n break;\n case fjet_t: ipart_max=(ao->ljets)[collectionName].size();\n break;\n case tau_t: ipart_max=(ao->taus)[collectionName].size();\n break;\n case combo_t: ipart_max=(ao->combos)[collectionName].size();\n break;\n default:\n std::cerr << \"WRONG PARTICLE TYPE in Parti! Type:\"<<particles->at(jj)->type << std::endl;\n break;\n }\n DEBUG(\"Max # particles:\"<<ipart_max<<\"\\n\");\n\n if ((jj>0) && (particles->at(jj)->type != particles->at(jj-1)->type) ) {\n available_parts.push_back(ipart_max);\n } \n if (jj==0){\n available_parts.push_back(ipart_max);\n requested_max=ipart_max;\n } \n } //end of particle loop\n\n vector<int> temp_index;\n vector<vector<int>> combi_out; \n \n\n if (available_parts.size() < 2) {\n//---- NANT's code to produce all the combined objetcs\n DEBUG (\"req max:\"<<requested_max <<\" req_size:\"<< requested_size <<\" \\n\");\n Comb combinations_part (requested_max, requested_size);\n\n#ifdef _CLV_\n combinations_part.affiche();\n#endif\n combi_out = combinations_part.output();// exemple: out = {{0,1} , {0,2}, {1,2}} si ipart_max = 3 et particles->size() = 2\n } else { // works for two particles for now\n for (int ipa1=0; ipa1<available_parts[0]; ipa1++) {\n for (int ipa2=0; ipa2<available_parts[1]; ipa2++) {\n DEBUG(ipa1 << \" , \" << ipa2<<\"\\n\");\n temp_index.push_back(ipa1); temp_index.push_back(ipa2);\n combi_out.push_back(temp_index);\n temp_index.clear();\n }\n }\n }\n\n TLorentzVector alv;\n int apq = 0;\n int apdgid=0;\n \n for(size_t k=0; k<combi_out.size(); ++k) {\n temp_index = combi_out[k]; // ex temp_index = {0,1} \n for(size_t i = 0; i<temp_index.size(); ++i){\n\tDEBUG (\"Now p index is:\"<< temp_index[i]<< \" type:\"<< particles->at(i)->type<< \" \\n\"); \n collectionName=particles->at(i)->collection;\n\tswitch(particles->at(i)->type){\n\t case muon_t: \n DEBUG (\"getting a muon \"<< collectionName <<\" \\n\");\n\t alv+=(ao->muos)[collectionName].at(temp_index[i]).lv();\n\t apq+=(ao->muos)[collectionName].at(temp_index[i]).q();\n\t apdgid+=(ao->muos)[collectionName].at(temp_index[i]).pdgID();\n\t break;\n\t case electron_t: \n\t alv+=(ao->eles)[collectionName].at(temp_index[i]).lv();\n\t apq+=(ao->eles)[collectionName].at(temp_index[i]).q();\n\t apdgid+=(ao->eles)[collectionName].at(temp_index[i]).pdgID();\n\t break;\n\t case truth_t:\n\t alv+=(ao->truth)[collectionName].at(temp_index[i]).lv();\n\t apq+=(ao->truth)[collectionName].at(temp_index[i]).q();\n\t apdgid+=(ao->truth)[collectionName].at(temp_index[i]).pdgID();\n\t break;\n\t case jet_t:\n\t alv+=(ao->jets)[collectionName].at(temp_index[i]).lv();\n\t apq+=(ao->jets)[collectionName].at(temp_index[i]).q();\n\t apdgid+=(ao->jets)[collectionName].at(temp_index[i]).pdgID();\n\t break;\n\t case photon_t: \n alv+=(ao->gams)[collectionName].at(temp_index[i]).lv();\n apdgid+=(ao->gams)[collectionName].at(temp_index[i]).pdgID();\n\t break;\n\t case fjet_t: \n alv+=(ao->ljets)[collectionName].at(temp_index[i]).lv();\n\t apq+=(ao->ljets)[collectionName].at(temp_index[i]).q();\n\t apdgid+=(ao->ljets)[collectionName].at(temp_index[i]).pdgID();\n\t break;\n\t case tau_t: \n DEBUG (\"getting a Tau \"<< collectionName <<\" \\n\");\n\t alv+=(ao->taus)[collectionName].at(temp_index[i]).lv();\n\t apq+=(ao->taus)[collectionName].at(temp_index[i]).q();\n\t apdgid+=(ao->taus)[collectionName].at(temp_index[i]).pdgID();\n\t break;\n\t case combo_t: \n\t alv+=(ao->combos)[collectionName].at(temp_index[i]).lv();\n\t apq+=(ao->combos)[collectionName].at(temp_index[i]).q();\n\t apdgid+=(ao->combos)[collectionName].at(temp_index[i]).pdgID();\n\t break;\n\t default:\n\t std::cerr << \"WRONG particle TYPE! Type:\"<<particles->at(i)->type << std::endl;\n\t break;\n\t }\n DEBUG(\"Added a particle\\n\");\n \n } \t \n DEBUG(\"all combis added\\n\");\n// we have the combined particle AND the indices of the parents\n\n\tadbxp= new dbxParticle(alv);\n\tadbxp->setCharge(apq); \n\tadbxp->setPdgID(apdgid); \n\tcombination.push_back(*adbxp);\n\tdelete adbxp;\n apq=0;\n apdgid=0;\n alv.SetPxPyPzE(0,0,0,0);\n DEBUG(\"\\n\");\n }\n ao->combos.insert( pair <string,vector<dbxParticle> > (name, combination) );\n\n vector<vector<int>> bad_combinations;\n set<vector<int>> good_combinations;\n\n//---------- \n ipart_max = (ao->combos)[name].size();\n cutIterator++; // now moving on to the real, first cut defining the new set.\n while ( cutIterator!=criteria->end() ){ // do the real cuts now.\n particles->clear();\n (*cutIterator)->getParticles(particles); // reset particles for each cut\n bool simpleloop=true;\n DEBUG(\"***** Cur Cut: \"<<(*cutIterator)->getStr()<<\"\\t Psize:\"<<particles->size() <<\" max_partices in event:\"<<ipart_max<<\"\\n\");\n if ( particles->size()==0) {\n DEBUG(\"CutIte:\"<<(*cutIterator)->getStr()<<\"\\n\");\n bool ppassed=(*cutIterator)->evaluate(ao);\n continue;\n }\n std::set<int> ptypeset;\n std::set<int> pindexset;\n std::vector<int> index_backup;\n int t1=particles->at(0)->type;\n int tidx1=particles->at(0)->index;\n int t2;\n int tidx2;\n for ( int kp=0; kp<particles->size(); kp++ ) { // to count particle types,\n if (particles->at(kp)->type == 6213) {simpleloop=false; }\n ptypeset.insert( particles->at(kp)->type);\n\t pindexset.insert( particles->at(kp)->index); \n index_backup.push_back(particles->at(kp)->index ); // to take a backup\n }\n if ( ptypeset.size()>2 ) {cerr <<\" 3 different particle type selection is not allowed in this version!\\n\"; exit(1);}\n std::set<int>::iterator ptit;\n std::set<int>::iterator pIit;\n ptit=ptypeset.begin(); ptit++;\n t2=*ptit;\n pIit=pindexset.begin(); pIit++;\n tidx2=*pIit;\n\n if(simpleloop){\n DEBUG(\"simpleloop, idx0:\"<<tidx1<<\"\\n\");\n for (int ipart=ipart_max-1; ipart>=0; ipart--){ //----------these are the combinations\n std::vector< vector<int> >::iterator itb; // bad list iterator\n DEBUG(\"\\n===> combi index:\"<<ipart<<\"\\n\");\n itb=find (bad_combinations.begin(), bad_combinations.end(), combi_out[ipart]);\n if ( itb!= bad_combinations.end() ) {\n DEBUG(\"SKIP aldeady bad combi\\n\");\n continue; // skip the bad indices\n }\n DEBUG(\"Going to evaluate \"<< combi_out[ipart][0] <<\" \" <<combi_out[ipart][1] <<\"\\n\");\n\n for (int jp=0; jp<particles->size(); jp++){ //\n tidx1=index_backup.at(jp);\n DEBUG(\" this particle:\"<<jp<<\" index:\"<< tidx1<<\" type:\"<< t1<<\" name:\"<<particles->at(jp)->collection<<\"\\n\");\n if (tidx1 < 0) { DEBUG(\"******Negative INDEX !!!\\t\");\n temp_index = combi_out[ ipart ];\n particles->at(jp)->index =temp_index[abs(1+tidx1)]; // means we respect order -1, -2 \n DEBUG(\"new index: \"<< particles->at(jp)->index <<\"\\n\");\n } else {\n// particles->at(jp)->index=ipart;\n// particles->at(jp)->collection=name;\n ;\n }\n }\n\n bool ppassed=(*cutIterator)->evaluate(ao);\n DEBUG(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ P or F: ~~~~~~ \"<<ppassed<<\"\\n\");\n if (!ppassed) {\n\t\t// \t\t\t(ao->combos).find(name)->second.erase( (ao->combos).find(name)->second.begin()+ipart);\n\t\t \t\t\tbad_combinations.push_back(combi_out[ipart]);\n\t\t \t\t\tgood_combinations.erase(combi_out[ipart]);\n\t \t\t } else good_combinations.insert(combi_out[ipart]);\n DEBUG(\"A cut finished.\\n\");\n\t }\n } else {\n\tDEBUG(\"TWO particle type loop\\n\");\n\tValueNode abc=ValueNode();\n\tfor (int ipart=ipart_max-1; ipart>=0; ipart--){ // loop over combis\n std::vector< vector<int> >::iterator itb; // bad list iterator\n itb=find (bad_combinations.begin(), bad_combinations.end(), combi_out[ipart]);\n if ( itb!= bad_combinations.end() ) {\n DEBUG(\"SKIP aldeady bad combi\\n\");\n continue; // skip the bad indices\n }\n DEBUG(\"combi index:\"<<ipart<<\"\\n\");\n for (int jp=0; jp<particles->size(); jp++){ //\n tidx1=index_backup.at(jp);\n DEBUG(\" this particle:\"<<jp<<\" index:\"<< tidx1<<\" type:\"<< t1<<\" name:\"<<name<<\"\\n\");\n if (tidx1 < 0) { DEBUG(\"******Negative INDEX !!!\\t\");\n temp_index = combi_out[ ipart ];\n particles->at(jp)->index =temp_index[abs(1+tidx1)]; // means we respect order -1, -2 \n DEBUG(\"new index: \"<< particles->at(jp)->index <<\"\\n\");\n } else if (tidx1 == 6213){ // this is a loop over the other particles\n\t\t\t int ipart2_max;\n\t\t\t string base_collection2=particles->at(jp)->collection;\n\t\t\t switch(particles->at(jp)->type){\n\t\t\t case muon_t: ipart2_max=(ao->muos)[base_collection2].size(); break;\n\t\t\t case truth_t: ipart2_max=(ao->truth)[base_collection2].size(); break;\n\t\t\t case electron_t: ipart2_max=(ao->eles)[base_collection2].size(); break;\n\t\t\t case jet_t: ipart2_max=(ao->jets)[base_collection2].size(); break;\n\t\t\t case photon_t: ipart2_max=(ao->gams)[base_collection2].size(); break;\n\t\t\t case fjet_t: ipart2_max=(ao->ljets)[base_collection2].size(); break;\n\t\t\t case tau_t: ipart2_max=(ao->taus)[base_collection2].size(); break;\n\t\t\t case combo_t: ipart2_max=(ao->combos)[base_collection2].size(); break;\n\t\t\t default:\n\t\t\t std::cerr << \"WRONG PARTICLE TYPE! type:\"<<particles->at(1)->type << std::endl;\n\t\t\t break;\n\t\t\t }\n DEBUG(\"Its Max: \"<< ipart2_max <<\"\\n\");\n\n\n } else { // normal particles\n particles->at(jp)->index=ipart;\n particles->at(jp)->collection=name;\n }\n }\n\t \n DEBUG(\"Going to evaluate \"<< combi_out[ipart][0] <<\" \" <<combi_out[ipart][1] <<\"\\n\");\n\t bool ppassed=(*cutIterator)->evaluate(ao);\n\t DEBUG(\"ooooooooooooooooooo P or F: ~~~ \"<<ppassed<<\"\\n\");\n\t if (!ppassed) {\n\t (ao->combos).find(name)->second.erase( (ao->combos).find(name)->second.begin()+ipart);\n\t bad_combinations.push_back(combi_out[ipart]);\n\t good_combinations.erase(combi_out[ipart]);\n\t }\n\t else good_combinations.insert(combi_out[ipart]);\n\n\t \n\t} // ipart loop\n } // two particle\n cutIterator++;\n }// end of cut iterator loop\n\n if (requested_max<=0) { //probably no particle available,never here\n vector<vector<int>> table_B;\n indicesA indexA={table_B, 0, 0};\n ao->combosA.insert( pair <string, indicesA > (name, indexA) );\n return;\n }\n\n//---------- we will clean the bad ones\n\n int new_req_max= requested_max-1;\n if (available_parts.size()>1 ) new_req_max = requested_size; \n\n DEBUG(\"Before denombre : \"<< requested_size<< \" max:\"<<new_req_max<<\"\\n\");\n vector<vector<int>> out_selection;\n\n\n if (available_parts.size() < 2) { // NANT\n Denombrement All_possibles_combinations = Denombrement(requested_size, new_req_max);\n DEBUG(\"Before selection : \\n\");\n#ifdef _CLV_\n All_possibles_combinations.affiche();\n#endif\n DEBUG(\"Number of bads:\"<< bad_combinations.size() <<\"\\n\");\n Denombrement All_possibilities_with_selection = Denombrement(requested_size, new_req_max, bad_combinations);\n DEBUG(endl <<\"After removing the bads : \" << endl);\n#ifdef _CLV_\n All_possibilities_with_selection.affiche();\n#endif\n out_selection = All_possibilities_with_selection.output();\n\n } else {\n DEBUG(\"Before my selection : \\n\");\n for (int ipa1=0; ipa1<combi_out.size(); ipa1++) {\n for (int ipa2=0; ipa2<combi_out[ipa1].size(); ipa2++) DEBUG( combi_out[ipa1][ipa2] << \" \");\n DEBUG(\"\\n\");\n }\n DEBUG(\"Number of bads:\"<< bad_combinations.size() <<\"\\n\");\n }// ngu\n \n DEBUG(\"After addition, types #:\"<<ao->combos.size()<< \" \\t\");\n DEBUG(\" remaining combo particle#:\"<<(ao->combos)[name].size()<< \" \\n\");\n\n vector<int> index_B;\n for(int i = 0; i<good_combinations.size(); i++) index_B.push_back(i);\n\n DEBUG(endl << \"We have \"<< index_B.size() << \" combined particles left\" << endl);\n set<vector<int>> :: iterator it;\n DEBUG(\"The surviving particles are :\\n\");\n\n for(it=good_combinations.begin(); it!=good_combinations.end(); it++)\n {\n out_selection.push_back(*it);\n for(int i = 0; i<particles->size(); i++) DEBUG((*it)[i] << \" \");\n DEBUG(\" -> \" << index_B[distance(good_combinations.begin(), it)] << endl);\n }\n DEBUG(endl <<\"After removing the bads : \" << endl);\n\n vector<vector<int>> table_B;\n for (int ipa1=0; ipa1<out_selection.size(); ipa1++) {\n vector<int> aRow;\n for (int ipa2=0; ipa2<out_selection[ipa1].size(); ipa2++) {\n DEBUG( out_selection[ipa1][ipa2] << \" \" );\n aRow.push_back(out_selection[ipa1][ipa2] );\n }\n table_B.push_back(aRow);\n DEBUG(\"\\n\");\n }\n \n/* \n vector<vector<int>> table_B(out_selection.size());\n\n for(int ii=0; ii<out_selection.size(); ii++)\n {\n \tfor(it=good_combinations.begin(); it!=good_combinations.end(); it++)\n \t{\n \t\tstep_add_a_comb(out_selection[ii], *it, table_B[ii], distance(good_combinations.begin(), it), out_selection[ii].size()/requested_size, requested_size);\n \t}\n }\n*/\n DEBUG( endl << \"Converting combinations to index:\" << endl);\n int amaxrow=0;\n for(int i = 0; i<table_B.size(); i++) {\n if (table_B[i].size() > amaxrow) amaxrow=table_B[i].size();\n \tfor(int j = 0; j<table_B[i].size(); j++) DEBUG(table_B[i][j] << \" \");\n \tDEBUG(\"\\n\"); \n }\n\n indicesA indexA={table_B, amaxrow, (int)table_B.size() };\n ao->combosA.insert( pair <string, indicesA > (name, indexA) );\n\n out_selection.clear();\n// NANT's code, to be commented in later\n// All_possibilities_with_selection.output(out_selection);\n// All_possibles_combinations.output(out_selection);\n \n DEBUG(\"--Create new Parti ends---\\n\");\n}\n\n" }, { "alpha_fraction": 0.6146632432937622, "alphanum_fraction": 0.6240409016609192, "avg_line_length": 20.72222137451172, "blob_id": "9e5e0e6e1bbe8aaccd3b2a56905dda3d82583c20", "content_id": "1350d4d46c3eca2446098a5b895ce1843817a575", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1174, "license_type": "no_license", "max_line_length": 90, "num_lines": 54, "path": "/analysis_core/UnaryAONode.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// UnaryAONode.h\n// mm\n//\n// Created by Anna-Monica on 8/1/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n\n#ifndef UnaryAONode_h\n#define UnaryAONode_h\n#include \"Node.h\"\n//takes care of Unary Minus and other Math.h functions\nclass UnaryAONode : public Node{\nprivate:\n double (*f)(double);\npublic:\n UnaryAONode(double (*func)(double), Node* l, std::string s){\n f=func;\n symbol=s;\n left=l;\n right=NULL;\n }\n \n virtual void getParticles(std::vector<myParticle *>* particles) override{\n left->getParticles(particles);\n }\n\n virtual void getParticlesAt(std::vector<myParticle *>* particles, int index) override{\n left->getParticlesAt(particles,index);\n }\n\n virtual void Reset() override{\n left->Reset();\n }\n\n virtual double evaluate(AnalysisObjects* ao) override {\n return (*f)(left->evaluate(ao));\n }\n \n virtual ~UnaryAONode() {\n if (left!=NULL) delete left;\n }\n \n};\ndouble unaryMinu(double left) {\n return -left;\n}\ndouble hstep(double x){\n\tif(x>=0) {return 1;}\n\telse return 0;\n}\n\n//double COS SIN TAN ALREADY EXIST\n#endif /* UnaryAONode_h */\n" }, { "alpha_fraction": 0.5743973255157471, "alphanum_fraction": 0.5914380550384521, "avg_line_length": 30.246753692626953, "blob_id": "0ef98a51d54f5edaa538957d864b4e3a8c6d2cf7", "content_id": "f536bfceaed2836189a18742ffd1d3b0307d7f1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2406, "license_type": "no_license", "max_line_length": 142, "num_lines": 77, "path": "/scripts/separate_algos.sh", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nINIFILE=CLA.ini\n\nif [ $# == 1 ]; then\n INIFILE=$1\nfi\n\ncat $INIFILE | grep -v '^ *#' > _inifile\n#-------remove all lines starting with a #\nINIFILE=_inifile\n\n# replace all region keyword with algo\nsed 's/region /algo /g' $INIFILE > pippo\nmv pippo _inifile \n\ninihead=`cat ${INIFILE} | grep -n -m 1 algo | cut -f1 -d\":\"`\ninitot=`wc -l ${INIFILE} | awk '{ print $1 }'` \n\nhead -n $inihead ${INIFILE} | grep -v algo > _head.ini\ntail -n $(( initot - $inihead +1 )) ${INIFILE} > _algos.ini\nrm -rf out1\n\nalgo_list=`cat _algos.ini | grep -n algo | cut -f1 -d\":\"`\n\niregion=0\nfor an_algo in $algo_list ; do\n iregion=$(( iregion + 1 ))\n algo1p=$(( an_algo + 1 ))\n thisline=`head -n $an_algo _algos.ini| tail -n 1`\n nextline=`head -n $algo1p _algos.ini| tail -n 1`\n depalgo=-1\n mainalgo=-1\n\n### echo $an_algo $thisline $nextline\n\n this_region_name=`echo $thisline | cut -f2 -d ' '`\n next_rline=`cat _algos.ini | grep -n -m $(( 1 + iregion )) algo | tail -1| cut -f1 -d\":\"`\n if [ $next_rline == $an_algo ]; then\n next_rline=`wc -l _algos.ini | awk '{ print $1+1 }'`\n fi\n printf 'A region, ID:%3s named:%20s \\t is defined in lines from %d to %d\\n' \"$((iregion -1 ))\" \"[$this_region_name]\" \"$an_algo\" \"$next_rline\"\n\n if [[ $nextline != *\"cmd \"* ]] && [[ $nextline != *\"select \"* ]] && [[ $nextline != *\"histo \"* ]] && [[ $nextline != *\"weight \"* ]]; then\n echo \" this region depends on:\" $nextline\n cat $nextline > $this_region_name\n awk -v lstart=$an_algo -v lfinish=$next_rline 'NR > lstart+1 && NR < lfinish' _algos.ini >> $this_region_name \n depalgo=$((iregion -1 ))\n else\n awk -v lstart=$an_algo -v lfinish=$next_rline 'NR > lstart && NR < lfinish' _algos.ini > $this_region_name \n mainalgo=$((iregion -1 ))\n fi\n cat _head.ini > BP_${iregion}-card.ini\n echo $thisline >> BP_${iregion}-card.ini\n cat $this_region_name >> BP_${iregion}-card.ini\n \n# echo $mainalgo \":\" $depalgo\n if [[ $mainalgo -gt -1 ]] && [[ $depalgo -eq -1 ]]; then\n echo -n ${mainalgo}\":\">> out1\n fi\n if [[ $mainalgo -eq -1 ]] && [[ $depalgo -gt -1 ]]; then\n echo -n $depalgo\",\">> out1\n fi\n\ndone\necho >> out1\ndepregs=`cat out1 | grep ','| sed 's/.$//'`\nif [ ${#depregs} -gt 0 ]; then\n echo \"-P ${depregs}\" >algdeps.cmd\nfi\n\n# CLEAN the region names\nfor an_algo in $algo_list ; do\n thisline=`head -n $an_algo _algos.ini| tail -n 1`\n this_region_name=`echo $thisline | cut -f2 -d ' '`\n rm -f $this_region_name\ndone\n" }, { "alpha_fraction": 0.530835747718811, "alphanum_fraction": 0.5481268167495728, "avg_line_length": 20.407407760620117, "blob_id": "f71fe5aa20b482dfe042767425c259bd3144f93e", "content_id": "693b1bb460c7abe98847066a8f39cee76a6c25cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1735, "license_type": "no_license", "max_line_length": 101, "num_lines": 81, "path": "/analysis_core/dbx_a.cpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#include \"dbx_a.h\"\n\n#include <iostream>\n#include \"TRandom3.h\"\n\n\ndbxA:: ~dbxA() {}\n\ndbxA:: dbxA(char *aname) {\n GEV = 1000.;\n p_runno=-1;\n p_lumino=-1;\n HFtype=-1;\n sprintf (cname, \"%s\",aname); // more checks here\n\n cout << \"This is \"<<cname<<endl;\n\n char tmp[128];\n sprintf (tmp, \"histoOut-%s.root\",cname);\n\n if (strcmp(aname,\"same\")==0) {\n histoOut= new TFile (tmp,\"update\");\n } else {\n histoOut= new TFile (tmp,\"recreate\");\n }\n setDataCardPrefix(cname);\n}\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nint dbxA:: addRunLumiInfo(int rn, int lbn) { // to keep track of the lumi\n if ((p_runno!=rn) || (p_lumino!= lbn)) {\n p_runno=rn;\n p_lumino=lbn;\n rntuple->Fill(p_runno, p_lumino);\n }\n return 0;\n}\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nint dbxA:: makeAnalysis(AnalysisObjects *ao, int idx) {\n return 0;\n}\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nint dbxA:: makeAnalysis(AnalysisObjects *ao, int idx, int a) {\n return 0;\n}\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nint dbxA::saveHistos() {\n int retval=0;\n cout << \"saving...\\t\";\n histoOut->Flush();\n histoOut->Write(cname);\n cout << \"saved.\\n\";\n return retval;\n}\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nint dbxA::ChangeDir(char *dn) {\n histoOut->cd(dn);\n return 0;\n}\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nint dbxA::setDir(char *dn) {\n int retval=0;\n TDirectory *ndir= new TDirectory();\n ndir = histoOut->mkdir(dn);\n histoOut->cd(dn);\n return retval;\n}\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nint dbxA::defHistos( unsigned int effsize) {\n int retval=0;\n eff= new TH1D(\"cutflow\",\"cutflow event counts \",effsize,0.5,effsize+0.5);\n rntuple = new TNtuple(\"rntuple\",\"run info\",\"rn:lb\");\n return retval;\n\n// if (binsize>0) hbincounts= new TH1F(\"bincounts\",\"event counts in bins \",binsize,0.5,binsize+0.5);\n}\n\n" }, { "alpha_fraction": 0.6006289124488831, "alphanum_fraction": 0.6029874086380005, "avg_line_length": 23, "blob_id": "239ff4a758fa0b00a26bfc41cd3d7399758cbf32", "content_id": "81c1befcaa6c1238ddae8b0096da341d350696a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1272, "license_type": "no_license", "max_line_length": 102, "num_lines": 53, "path": "/Dump/dump_a.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#ifndef DUMP_A_H\n#define DUMP_A_H\n\n#include <map>\n#include \"dbx_a.h\"\n#include \"ReadCard.h\"\n#include <iostream>\n#include \"analysis_core.h\"\n#include \"myParticle.h\"\n#include \"Node.h\"\n\n#include \"DBXNtuple.h\"\n#include \"TFile.h\"\n#include \"TTree.h\"\n\n\n\nclass DumpdbxA : public dbxA {\n public: \n DumpdbxA(char *aname) : dbxA ( aname)\n {\n sprintf (cname,\"%s\",aname); // keep the current analysis name in the class variable\n int r=dbxA::setDir(cname); // make the relevant root directory\n if (r) std::cout <<\"Root Directory Set Failure in:\"<<cname<<std::endl;\n r=dbxA::defHistos(30); // make the relevant root directory\n //grl_cut=false;\n }\n int getInputs();\n int Finalize();\n int initGRL();\n int readAnalysisParams();\n int printEfficiencies();\n int bookAdditionalHistos();\n int makeAnalysis(AnalysisObjects *ao);\n int makeAnalysis(AnalysisObjects *ao, map < int, TVector2 > met_syst_map, vector <double> uncs);\n\n int saveHistos() {\n Finalize();\n int r = dbxA::saveHistos();\n\treturn r;\n }\n\n private:\n bool grl_cut;\n char cname[CHMAX];\n int TRGe, TRGm;\n\n TFile *ftsave;\n TTree *ttsave;\n DBXNtuple *ntsave;\n \n};\n#endif\n" }, { "alpha_fraction": 0.6018916368484497, "alphanum_fraction": 0.6070507168769836, "avg_line_length": 19.05172348022461, "blob_id": "170b6a4a5bfad19bf6f774eab2b6bfe64b9ed5f6", "content_id": "66723b18b13f4acf173c2e7f95aa5e19704a30c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1163, "license_type": "no_license", "max_line_length": 39, "num_lines": 58, "path": "/analysis_core/DBXNtuple.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#ifndef DBX_NT_H\n#define DBX_NT_H\n\n#include <vector>\n#include <cmath>\n#include \"TObject.h\"\n#include \"TLorentzVector.h\"\n#include \"TVector2.h\"\n#include \"TFile.h\"\n#include \"TNtuple.h\"\n#include \"TH1F.h\"\n#include \"TH2F.h\"\n#include \"TCanvas.h\"\n\n#include \"dbx_electron.h\"\n#include \"dbx_muon.h\"\n#include \"dbx_jet.h\"\n#include \"dbx_tau.h\"\n#include \"dbx_photon.h\"\n#include \"dbx_truth.h\"\n#include \"dbxParticle.h\"\n\n\nusing namespace std;\n\nclass DBXNtuple: public TObject {\n public:\n DBXNtuple() ;\n ~DBXNtuple() ;\n\n int nEle;\n int nMuo;\n int nJet;\n\tint nLJet;\n\tint nPhoton;\n\tint nTau;\n\tint nTruth;\n\tint nCombo;\n void Clean( );\n\n vector<dbxElectron> nt_eles;\n vector<dbxMuon> nt_muos;\n vector<dbxJet> nt_jets;\n\tvector<dbxTau>\t nt_taus;\n\tvector<dbxJet> nt_ljets;\n\tvector<dbxPhoton> nt_photons;\n vector<dbxParticle> nt_combos;\n\tvector<dbxTruth> nt_truth;\n vector<double> nt_uncs;\n vector<TVector2> nt_sys_met;\n TVector2 nt_met;\n evt_data nt_evt;\n// http://root.cern.ch/root/Using.html\n\n ClassDef(DBXNtuple,4);\n};\n\n#endif\n" }, { "alpha_fraction": 0.7018702030181885, "alphanum_fraction": 0.7051705121994019, "avg_line_length": 54.65306091308594, "blob_id": "c4148b44855383414449550a5d2bf6c5c3267103", "content_id": "c9617ea6dc0847c9c51956e8a676cea123b582db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2728, "license_type": "no_license", "max_line_length": 153, "num_lines": 49, "path": "/analysis_core/ObjectNode.hpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// ObjectNode.hpp\n// mm\n//\n// Created by Anna-Monica on 8/16/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n\n#ifndef ObjectNode_hpp\n#define ObjectNode_hpp\n#include <vector>\n#include <stdio.h>\n#include \"Node.h\"\nusing namespace std;\n//takes care of user defined objects\nclass ObjectNode : public Node{\n private:\n //not sure if we need to use it---------ObjectNode* previous;\n vector<Node*> criteria;\n //still need to add something to save the modifed AO\n std::vector<myParticle *> particles;//used to collect particle pointers to be changed\n protected:\n void (* createNewSet) (AnalysisObjects* ao,vector<Node*> *criteria,std::vector<myParticle *>* particles, std::string name, std::string basename);\n public:\n string name;\n int type;\n\n ObjectNode(string id,Node* previous, void (* func) (AnalysisObjects* ao,vector<Node*>* criteria,\n std::vector<myParticle *>* particles, std::string name, std::string basename ), vector<Node*> criteria, std::string s );\n \n virtual void Reset() override;\n \n virtual void getParticles(std::vector<myParticle *>* particles) override;\n virtual void getParticlesAt(std::vector<myParticle *>* particles, int index) override;\n virtual double evaluate(AnalysisObjects* ao) override;\n \n virtual ~ObjectNode();\n};\n\nvoid createNewJet (AnalysisObjects* ao,vector<Node*> *criteria,std::vector<myParticle *>* particles, std::string name, std::string basename);\nvoid createNewFJet (AnalysisObjects* ao,vector<Node*> *criteria,std::vector<myParticle *>* particles, std::string name, std::string basename);\nvoid createNewEle (AnalysisObjects* ao,vector<Node*> *criteria,std::vector<myParticle *>* particles, std::string name, std::string basename);\nvoid createNewMuo (AnalysisObjects* ao,vector<Node*> *criteria,std::vector<myParticle *>* particles, std::string name, std::string basename);\nvoid createNewTau (AnalysisObjects* ao,vector<Node*> *criteria,std::vector<myParticle *>* particles, std::string name, std::string basename);\nvoid createNewPho (AnalysisObjects* ao,vector<Node*> *criteria,std::vector<myParticle *>* particles, std::string name, std::string basename);\nvoid createNewCombo (AnalysisObjects* ao,vector<Node*> *criteria,std::vector<myParticle *>* particles, std::string name, std::string basename);\nvoid createNewParti (AnalysisObjects* ao,vector<Node*> *criteria,std::vector<myParticle *>* particles, std::string name, std::string basename);\nvoid createNewTruth (AnalysisObjects* ao,vector<Node*> *criteria,std::vector<myParticle *>* particles, std::string name, std::string basename);\n#endif /* ObjectNode_hpp */\n" }, { "alpha_fraction": 0.3784535825252533, "alphanum_fraction": 0.38878950476646423, "avg_line_length": 51.39583206176758, "blob_id": "519ad6f24f0180602f91dad49cfc218db1d3e307", "content_id": "16b880daa2613c1074fb6a30e5eb5b208df1b7d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5031, "license_type": "no_license", "max_line_length": 131, "num_lines": 96, "path": "/analysis_core/HistoNode.cpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#include \"HistoNode.h\"\n#include \"FuncNode.h\"\n\n//#define _CLV_\n\n#ifdef _CLV_\n#define DEBUG(a) std::cout<<a\n#else\n#define DEBUG(a)\n#endif\n\nusing namespace std;\n\ndouble HistoNode1D::evaluate(AnalysisObjects* ao) {\n this->getParticles(&inputParticles);\n for (int ii=0; ii<inputParticles.size(); ii++){\n DEBUG(\"1DHisto particle ID:\"<<ii<<\" Type:\"<<inputParticles[ii]->type<<\" collection:\"\n << inputParticles[ii]->collection << \" index:\"<<inputParticles[ii]->index<<\"\\n\");\n }\n if (inputParticles.size()>0 ) {\n if (inputParticles[0]->index == 6213){\n std::string bcol2=inputParticles[0]->collection;\n bool constiloop=false;\n std::string consname;\n int ipartMax=0;\n try {\n switch(inputParticles[0]->type){\n case muon_t: ipartMax=(ao->muos).at(bcol2).size(); break;\n case truth_t: ipartMax=(ao->truth).at(bcol2).size(); break;\n case electron_t: ipartMax=(ao->eles).at(bcol2).size(); break;\n case jet_t: ipartMax=(ao->jets).at(bcol2).size(); break;\n case pureV_t: ipartMax=1; break;\n case photon_t: ipartMax=(ao->gams).at(bcol2).size(); break;\n case fjet_t: ipartMax=(ao->ljets).at(bcol2).size(); break;\n case tau_t: ipartMax=(ao->taus).at(bcol2).size(); break;\n case combo_t: ipartMax=(ao->combos)[bcol2].size(); break;\n case consti_t: {constiloop=true;\n TString konsname=bcol2;\n konsname+=\"_\";\n konsname+=inputParticles[0]->index;\n konsname+=\"c\";\n consname=(std::string)konsname;\n ipartMax =(ao->constits).find(consname)->second.size();\n DEBUG(consname<<\" has \"<<ipartMax<<\" constituents\\n\");\n break;}\n \n \n default:\n std::cerr << \"WRONG PARTICLE TYPE:\"<<inputParticles[0]->type << std::endl; break;\n }\n } catch(...) {\n std::cerr << \"YOU WANT TO histo A PARTICLE TYPE YOU DIDN'T CREATE:\"<<bcol2 <<\" !\\n\";\n _Exit(-1);\n }\n DEBUG (\"loop over \"<< ipartMax<<\" particles\\n\");\n FuncNode *pippo;\n DEBUG(\"it will do: \"<<left->getStr()<<\"\\n\");\n if (pippo=dynamic_cast< FuncNode*>(left) ) {\n DEBUG(\"downcast OK\\n\");\n } else {\n DEBUG(\"downcast FAILS\\n\");\n if (pippo=dynamic_cast< FuncNode*>(left->left) ) {\n DEBUG(\"down-downcast OK\\n\");\n }\n }\n for (int ii=0; ii<ipartMax; ii++) {\n DEBUG(\"now for particle \"<<ii<<\"\\n\");\n pippo->setParticleIndex(0, ii);\n double value = left->evaluate(ao);\n DEBUG(\"Histo Loop retval:\"<<value<<\"\\n\");\n\t\t ahisto1->Fill(value, ao->evt.user_evt_weight);\n }\n pippo->setParticleIndex(0, 6213);\n return 1;\n }// end of inner if with 6213\n } // end of >0\n double value = left->evaluate(ao);\n DEBUG(\"Filling with:\"<<value<<\"\\n\");\n\t\t ahisto1->Fill(value, ao->evt.user_evt_weight);\n\t\t return 1;\n};\n//-----\n\ndouble HistoNode2D::evaluate(AnalysisObjects* ao) {\n/*\n this->getParticles(&inputParticles);\n for (int ii=0; ii<inputParticles.size(); ii++){\n DEBUG(\"1DHisto particle ID:\"<<ii<<\" Type:\"<<inputParticles[ii]->type<<\" collection:\"\n << inputParticles[ii]->collection << \" index:\"<<inputParticles[ii]->index<<\"\\n\");\n }\n*/\n\t\t double value1=left->evaluate(ao);\n\t\t double value2=right->evaluate(ao);\n \t ahisto2->Fill(value1, value2, ao->evt.user_evt_weight);\n \t return 1;\n};\n\n" }, { "alpha_fraction": 0.5463196039199829, "alphanum_fraction": 0.5507976412773132, "avg_line_length": 32.39252471923828, "blob_id": "04104e5033622d19695217ff24772532336aa601", "content_id": "520b58f33971e46d85e7c2df9e800c447094e029", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3573, "license_type": "no_license", "max_line_length": 90, "num_lines": 107, "path": "/analysis_core/SaveNode.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "// \n// SaveNode.h\n// Created by Jinen Setpal on 18/2/20.\n//\n\n#ifndef SaveNode_h\n#define SaveNode_h\n#include \"Node.h\"\n#include \"TFile.h\"\n#include \"TTree.h\"\n#include \"DBXNtuple.h\"\n\nclass SaveNode : public Node{\nprivate:\n\tstd::string name, fname;\n\tDBXNtuple *ntsave;\n\tTFile *ftsave;\n\tTTree *ttsave;\npublic:\n\tSaveNode(std::string s){\n symbol=\"save\";\n\t\tname = s;\n\t\tleft = NULL;\n\t\tright = NULL;\n\t\tntsave = new DBXNtuple();\n\t \tfname = \"lvl0_\" + name + \".root\";\n\t}\n virtual void getParticles(std::vector<myParticle *>* particles) override{}\n virtual void getParticlesAt(std::vector<myParticle *>* particles,int index) override{}\n virtual void Reset() override{}\n virtual void createFile() override {\n\t ftsave = new TFile (fname.c_str(),\"RECREATE\"); // il faut changer le nom du fichier\n\t ttsave = new TTree (\"nt_tree\", \"saving data on the grid\");\n ttsave->Branch(\"dbxAsave\", ntsave);\n }\n virtual void saveFile() override {\n std::cout << \"Closing file\\n\";\n\t ftsave->Write();\n\t ftsave->Close();\n }\n virtual double evaluate(AnalysisObjects* ao) override {\n vector<dbxMuon> muons = ao->muos.begin()->second;\n vector<dbxElectron> electrons= ao->eles.begin()->second;\n vector <dbxPhoton> photons= ao->gams.begin()->second;\n vector<dbxJet> jets= ao->jets.begin()->second;\n vector<dbxJet> ljets= ao->ljets.begin()->second;\n vector<dbxTau> taus= ao->taus.begin()->second;\n vector<dbxTruth> truth= ao->truth.begin()->second;\n vector<dbxParticle> combos= ao->combos.begin()->second;\n //-----------------------------------------\n\n TVector2 met = ao->met.begin()->second;\n evt_data anevt = ao->evt;\n // here we save the DBXNTuple\n ntsave->Clean();\n ntsave->nEle=electrons.size();\n for ( int i=0; i<(int)electrons.size(); i++) {\n\tntsave->nt_eles.push_back(electrons.at(i) );\n }\n \n ntsave->nMuo=muons.size();\n for ( int i=0; i<(int)muons.size(); i++) {\n\tntsave->nt_muos.push_back(muons.at(i) );\n }\n ntsave->nJet=jets.size();\n for ( int i=0; i<(int)jets.size(); i++) {\n\tntsave->nt_jets.push_back(jets.at(i) );\n }\n ntsave->nPhoton=photons.size();\n for ( int i=0; i<(int)photons.size(); i++) {\n\tntsave->nt_photons.push_back(photons.at(i) );\n }\n ntsave->nLJet=ljets.size();\n for ( int i=0; i<(int)ljets.size(); i++) {\n\tntsave->nt_ljets.push_back(ljets.at(i) );\n }\n ntsave->nTau=taus.size();\n for ( int i=0; i<(int)taus.size(); i++) {\n\tntsave->nt_taus.push_back(taus.at(i) );\n }\n ntsave->nTruth=truth.size();\n for ( int i=0; i<(int)truth.size(); i++) {\n\tntsave->nt_truth.push_back(truth.at(i) );\n }\n ntsave->nCombo=combos.size();\n for ( int i=0; i<(int)combos.size(); i++) {\n\tntsave->nt_combos.push_back(combos.at(i) );\n }\n \n ntsave->nt_met=met;\n ntsave->nt_evt=anevt;\n ntsave->nt_eles.resize ( electrons.size() );\n ntsave->nt_muos.resize ( muons.size() );\n ntsave->nt_taus.resize ( taus.size() );\n ntsave->nt_jets.resize ( jets.size() );\n ntsave->nt_ljets.resize ( ljets.size() );\n ntsave->nt_photons.resize ( photons.size() );\n ntsave->nt_combos.resize ( combos.size() );\n ntsave->nt_truth.resize ( truth.size() );\n \n ttsave->Fill();\n return 1;\n }\n virtual ~SaveNode() {}\n};\n\n#endif // SaveNode_h\n" }, { "alpha_fraction": 0.4882705807685852, "alphanum_fraction": 0.5681942105293274, "avg_line_length": 36.79381561279297, "blob_id": "902d77c04e27b78aefc5566d4188c64a6543c7a2", "content_id": "6bd28af29f9c4827f20bab7a27577a8ff5ef2045", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 3666, "license_type": "no_license", "max_line_length": 99, "num_lines": 97, "path": "/runs/CLA.ini", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "# PLEASE PAY ATTENTION TO SPACE BEFORE AND AFTER = SIGN\n# format is \" variable = value \"\n\nminpte = 15.0 # min pt of electrons \nminptm = 15.0 # min pt of muons \nminptj = 25.0 # min pt of jets\nmaxetae = 2.47 # max pseudorapidity of electrons \nmaxetam = 2.5 # max pseudorapidity of muons \nmaxetaj = 5.5 # max pseudorapidity of jets\n\nTRGm = 0 # muon Trigger Type: 0=dont trigger, 1=1st trigger (data) 2=2nd trigger (MC)\nTRGe = 1 # electron Trigger Type: 0=dont trigger, 1=1st trigger (data) 2=2nd trigger (MC)\n\n\n###### USER DEFINITIONS\ndef WH1 : JET_-1 JET_-1 # W boson of the first top\ndef WH2 : JET_-3 JET_-3 # W boson of the second top\ndef ajet : JET_-2\ndef bjet : JET_-4\ndef mWHr : { JET_1 JET_0 }m\ndef mWH1 : {WH1 }m # mass of W boson of the first top\ndef mWH2 : {WH2 }m # mass of @ boson of the second top\ndef mTopH1 : {WH1 ajet }m # first top quark's mass\ndef mTopH2 : {WH2 bjet }m # second top quark's mass\ndef topchi2 : ((mTopH1 - mTopH2)/4.2)^2 #chi2 for top finder\ndef Wchi2 : ((mWH1-80.4)/2.1)^2 + ((mWH2-80.4)/2.1)^2 #chi2 for W finder\ndef chi2 : ((mTopH1-mTopH2) / 4.2)^2 + ((mWH1-80.4)/2.1)^2 + ((mWH2-80.4)/2.1)^2 \n\n###### OBJECT SELECTIONS\nobj JETclean : JET \ncmd { JET_ , ELE_ }dR >= 1.0\n#cmd { JET_ }Pt > 25\n\nalgo preselection\ncmd ALL # to count all events\ncmd nJET (JETclean) >= 2 # events with 6 or more jets\ncmd MET < 100 # fully hadronic events should have small MET\ncmd nELE == 1\ncmd {JET_0 }Pt (JETclean) > 35\ncmd {JET_1 }Pt (JETclean) > 30\ncmd nJET (JETclean) == 6 # events with 6 or more jets\ncmd chi2 (JETclean) ~= 0 # reconstruct two hadronic Ws in the event\n#cmd {WH1 }m (JETclean) [] 70 120\n#cmd {WH2 }m (JETclean) [] 70 120\n\n\n#algo preselection\n#cmd ALL # to count all events\n#cmd nJET >= 2 # events with 6 or more jets\n#cmd MET < 100 # fully hadronic events should have small MET\n#cmd nELE == 1\n#cmd {JET_0 }Pt > 35\n#cmd {JET_1 }Pt > 30\n##cmd {JET_0 , JET_1 }dR > 0.6\n#cmd nJET == 6 # events with 6 or more jets\n#cmd chi2 ~= 0 # reconstruct two hadronic Ws in the event\n#cmd {WH1 }m [] 70 120\n#cmd {WH2 }m [] 70 120\n\n\n\n\n\n\n\n\n#cmd topchi2 (JETclean) + Wchi2 (JETclean) ~= 0 # reconstruct two hadronic Ws in the event\n#cmd mWH1 (JETclean) [] 70 120\n#cmd mWH2 (JETclean) [] 70 120\n\n#cmd {JETclean_0 }Pt > 35\n#cmd {JETclean_0 }Pt (JETclean) > 35\n#algo singlestep\n#preselection\n#cmd topchi2 + Wchi2 ~= 0 # reconstruct two hadronic Ws in the event\n#cmd mWH1 (JETclean) [] 50 120\n#cmd mWH2 [] 50 120\n#cmd {WH1 , ajet }dR > 0.6\n#cmd {WH2 , bjet }dR > 0.6\n#histo mWHh1 , \"Hadronic W2 reco (GeV)\", 50, 50, 150, mWH1\n#histo mWHh2 , \"Hadronic W1 reco (GeV)\", 50, 50, 150, mWH2\n#histo mTopHh1, \"Hadronic top1 reco (GeV)\", 70, 0, 700, mTopH1\n#histo mTopHh2, \"Hadronic top2 reco (GeV)\", 70, 0, 700, mTopH2\n\n\n#algo doublestep\n#preselection\n#cmd Wchi2 ~= 0\n#cmd topchi2 ~= 0 # reconstruct two hadronic Ws in the event\n#cmd mWH1 [] 50 120\n#cmd mWH2 [] 50 120\n#cmd { WH1 , ajet }dR > 0.6\n#cmd { WH2 , bjet }dR > 0.6\n#histo mWHh1 , \"Hadronic W1 reco (GeV)\", 50, 50, 150, mWH1\n#histo mWHh2 , \"Hadronic W2 reco (GeV)\", 50, 50, 150, mWH2\n#histo mTopHh1, \"Hadronic top1 reco (GeV)\", 70, 0, 700, mTopH1\n#histo mTopHh2, \"Hadronic top2 reco (GeV)\", 70, 0, 700, mTopH2\n" }, { "alpha_fraction": 0.7335870862007141, "alphanum_fraction": 0.7373929619789124, "avg_line_length": 32.83871078491211, "blob_id": "38902403b58c5f1407e580c8a1f8bfddd3e38c9d", "content_id": "c61f5ac4fc15e01dfadf747b469e697d74226eae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1051, "license_type": "no_license", "max_line_length": 318, "num_lines": 31, "path": "/README.md", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "# CutLang\nThis is the repository for CutLang V3 \n\n\n## Installation\n\nRequirements\n* ROOT6 (root.cern.ch) \n* command line compilation utilities (make, gcc, g++...) \n* flex\n* bison #without installing flex and bison, the make command gets interrupted by a fatal error.\n\nInstall the package using\n```bash\n git clone https://github.com/unelg/CutLang.git\n cd CutLang/CLA\n make\n cd ../runs\n```\n\n## Running\n\nCutLang is run using the `CLA.sh` or `CLA.py` script as\n\n```bash\n ./CLA.sh (or ./CLA.py) [inputrootfile] [inputeventformat] -i [adlfilename.adl] -e [numberofevents]\n```\n* Input event formats can be: DELPHES, CMSNANO, LHCO, FCC, ATLASVLL, ATLASOD, CMSOD, VLLBG3 and LVL0 (CutLang internal format) \n* Number of events is optional.\n\nThe output will be saved in `histoOut-[adlfilename].root`. This ROOT file will have a separate directory for each search region, which contains the relevant histograms and ADL content defining the region. The histogram(s) `cutflow` (and `bincounts`, in case search bins are specified in the region) exist by default. \n" }, { "alpha_fraction": 0.6396396160125732, "alphanum_fraction": 0.6396396160125732, "avg_line_length": 21.200000762939453, "blob_id": "6859f1714e84c9c2b6e01ff09d0c42d6a63eabc2", "content_id": "7a0c7a32d664d583076915b056bb4044de2d8352", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 111, "license_type": "no_license", "max_line_length": 36, "num_lines": 5, "path": "/parser_test/cppMake", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#!/bin/bash\n/usr/bin/bison -d -v -ob.cpp parse.y\nflex -o l.cpp parse.l\ng++ b.cpp l.cpp main.cpp -o main\n./main\n" }, { "alpha_fraction": 0.628157913684845, "alphanum_fraction": 0.6284210681915283, "avg_line_length": 68.09091186523438, "blob_id": "6e0b95b7106eeb649d7bbc3e58f38e2020b71aaa", "content_id": "14c41e6be9a16d0ccaeeff329db0a9da1a51eb40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 3800, "license_type": "no_license", "max_line_length": 134, "num_lines": 55, "path": "/analysis_core/Makefile", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "objects := $(patsubst %.cpp,%.o,$(wildcard *.cpp))\n\nROOTCFLAGS = $(shell root-config --cflags)\nCXXFLAGS += $(ROOTCFLAGS) -O3 -I../analysis_core -D__STANDALONE__ \nCXX = $(shell root-config --cxx) -g\n\n\n%.o : %.cxx\n\t$(CXX) $(CXXFLAGS) -c $< -o $@\n\nall : $(objects)\n#\trm -f *_dict.C\n\n#\trootcint dbxParticle_dict.C -c dbxParticle.h\n#\trootcint dbx_muon_dict.C -c dbx_muon.h\n#\trootcint dbx_electron_dict.C -c dbx_electron.h\n#\trootcint dbx_photon_dict.C -c dbx_photon.h\n#\trootcint dbx_jet_dict.C -c dbx_jet.h\n#\trootcint DBXNtuple_dict.C -c DBXNtuple.h\n#\t$(CXX) $(CXXFLAGS) -c dbx_muon.h\n#\t$(CXX) $(CXXFLAGS) -c dbx_electron.h\n#\t$(CXX) $(CXXFLAGS) -c dbx_photon.h\n#\t$(CXX) $(CXXFLAGS) -c dbx_jet.h\n#\t$(CXX) $(CXXFLAGS) -shared -o dbxParticle.so dbxParticle.o dbxParticle_dict.C -I`root-config --incdir` `root-config --libs`\n#\t$(CXX) $(CXXFLAGS) -shared -o dbx_muon.so dbx_muon.o dbx_muon_dict.C -I`root-config --incdir` `root-config --libs`\n#\t$(CXX) $(CXXFLAGS) -shared -o dbx_electron.so dbx_electron.o dbx_electron_dict.C -I`root-config --incdir` `root-config --libs`\n#\t$(CXX) $(CXXFLAGS) -shared -o dbx_photon.so dbx_photon.o dbx_photon_dict.C -I`root-config --incdir` `root-config --libs`\n#\t$(CXX) $(CXXFLAGS) -shared -o dbx_jet.so dbx_jet.o dbx_jet_dict.C -I`root-config --incdir` `root-config --libs`\n\troot -q -l -b -x makeSos.C\n\ttest -L ../runs/DBXNtuple_cpp_ACLiC_dict_rdict.pcm || ( ln -s ../analysis_core/DBXNtuple_cpp_ACLiC_dict_rdict.pcm ../runs/ )\n\ttest -L ../runs/dbxParticle_cpp_ACLiC_dict_rdict.pcm || ( ln -s ../analysis_core/dbxParticle_cpp_ACLiC_dict_rdict.pcm ../runs/ )\n\ttest -L ../runs/dbx_electron_h_ACLiC_dict_rdict.pcm || ( ln -s ../analysis_core/dbx_electron_h_ACLiC_dict_rdict.pcm ../runs/ )\n\ttest -L ../runs/dbx_jet_h_ACLiC_dict_rdict.pcm || ( ln -s ../analysis_core/dbx_jet_h_ACLiC_dict_rdict.pcm ../runs/ )\n\ttest -L ../runs/dbx_muon_h_ACLiC_dict_rdict.pcm || ( ln -s ../analysis_core/dbx_muon_h_ACLiC_dict_rdict.pcm ../runs/ )\n\ttest -L ../runs/dbx_photon_h_ACLiC_dict_rdict.pcm || ( ln -s ../analysis_core/dbx_photon_h_ACLiC_dict_rdict.pcm ../runs/ )\n\ttest -L ../runs/dbx_tau_h_ACLiC_dict_rdict.pcm || ( ln -s ../analysis_core/dbx_tau_h_ACLiC_dict_rdict.pcm ../runs/ )\n\ttest -L ../runs/dbx_truth_h_ACLiC_dict_rdict.pcm || ( ln -s ../analysis_core/dbx_truth_h_ACLiC_dict_rdict.pcm ../runs/ )\n\ttest -L ../runs/delphesParticles_h_ACLiC_dict_rdict.pcm|| ( ln -s ../analysis_core/delphesParticles_h_ACLiC_dict_rdict.pcm ../runs/ )\n\ttest -L ../CLA/DBXNtuple_cpp_ACLiC_dict_rdict.pcm || ( ln -s ../analysis_core/DBXNtuple_cpp_ACLiC_dict_rdict.pcm ../CLA/ )\n\ttest -L ../CLA/dbxParticle_cpp_ACLiC_dict_rdict.pcm || ( ln -s ../analysis_core/dbxParticle_cpp_ACLiC_dict_rdict.pcm ../CLA/ )\n\ttest -L ../CLA/dbx_electron_h_ACLiC_dict_rdict.pcm || ( ln -s ../analysis_core/dbx_electron_h_ACLiC_dict_rdict.pcm ../CLA/ )\n\ttest -L ../CLA/dbx_jet_h_ACLiC_dict_rdict.pcm || ( ln -s ../analysis_core/dbx_jet_h_ACLiC_dict_rdict.pcm ../CLA/ )\n\ttest -L ../CLA/dbx_muon_h_ACLiC_dict_rdict.pcm || ( ln -s ../analysis_core/dbx_muon_h_ACLiC_dict_rdict.pcm ../CLA/ )\n\ttest -L ../CLA/dbx_photon_h_ACLiC_dict_rdict.pcm || ( ln -s ../analysis_core/dbx_photon_h_ACLiC_dict_rdict.pcm ../CLA/ )\n\ttest -L ../CLA/dbx_tau_h_ACLiC_dict_rdict.pcm || ( ln -s ../analysis_core/dbx_tau_h_ACLiC_dict_rdict.pcm ../CLA/ )\n\ttest -L ../CLA/dbx_truth_h_ACLiC_dict_rdict.pcm || ( ln -s ../analysis_core/dbx_truth_h_ACLiC_dict_rdict.pcm ../CLA/ )\n\ttest -L ../CLA/delphesParticles_h_ACLiC_dict_rdict.pcm|| ( ln -s ../analysis_core/delphesParticles_h_ACLiC_dict_rdict.pcm ../CLA/ )\n\n\nclean:\n\trm -f *.o *.so *.d *.pcm\n\n\nclean:\n\trm -f *.o *.so *.d *.pcm\n" }, { "alpha_fraction": 0.5616438388824463, "alphanum_fraction": 0.5675146579742432, "avg_line_length": 22.494253158569336, "blob_id": "d0e56d94a513c87eb464b1e8754635e965d679a7", "content_id": "43d0a088d8ba658eacb61c770fb5a63f97e1f4c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2044, "license_type": "no_license", "max_line_length": 138, "num_lines": 87, "path": "/analysis_core/Comb.cpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#include \"Comb.h\"\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <iterator>\n\nusing namespace std;\n\n\nvoid suppr_bad_combi_Comb(vector<int>& temp, vector<int> tab_select, int& n, int pas)\n{\n vector<int> temp_combi(pas);\n int k = 0;\n\n do\n {\n for(int i = 0; i<pas; i++) { temp_combi[i] = temp[i+k]; }\n if(temp_combi==tab_select)\n {\n temp.erase(temp.begin()+k, temp.begin()+ k + pas );\n k-=pas;\n n-=pas;\n }\n k+=pas;\n }while(k<n);\n}\n\nvoid suppr_by_set_Comb(vector<vector<int> >&output, vector<int> temp, vector<vector<int> > set_select, int n, int pas)\n{\n int N = n;\n for(int i = 0; i<set_select.size(); i++) suppr_bad_combi_Comb(temp, set_select[i], N, pas);\n temp.erase(temp.begin()+N, temp.end());\n if(N!=0)\n {\n if(output.size()>0){ if(temp!=output.back()) output.push_back(temp); }\n else output.push_back(temp);\n }\n}\n\nvoid combinaison(int N, int K, vector<vector<int> >& output, vector<vector<int> > tab_select)\n{\n vector<int> temp;\n string bitmask(K, 1);\n bitmask.resize(N, 0);\n\n do\n {\n temp.clear();\n for (int k = 0; k < N; ++k) \n {\n if (bitmask[k]) {temp.push_back(k);}\n }\n suppr_by_set_Comb(output, temp, tab_select, 2, 2);\n }while (std::prev_permutation(bitmask.begin(), bitmask.end()));\n}\n\nComb::Comb(int JetTotal, int JetReco) : nJetTotal(JetTotal), nJetReco(JetReco)\n{\n combinaison(nJetTotal, nJetReco, output_, tab_selection);\n}\n\nComb::Comb(int JetTotal, int JetReco, vector<vector<int> > tab_select) : nJetTotal(JetTotal), nJetReco(JetReco), tab_selection(tab_select)\n{\n combinaison(nJetTotal, nJetReco, output_, tab_selection);\n}\n\nComb::~Comb()\n{\n //dtor\n}\n\nvoid Comb::affiche()\n{\n for(size_t i = 0; i<output_.size(); ++i)\n {\n for(size_t j = 0; j<nJetReco; ++j)\n cout << output_[i][j] << \" \" ;\n cout << endl;\n }\n}\n\nvector<vector<int> > Comb::output()\n{\n return output_;\n}\n" }, { "alpha_fraction": 0.45968368649482727, "alphanum_fraction": 0.47446200251579285, "avg_line_length": 46.32515335083008, "blob_id": "f989bebb02d0cb50c33612fcc7f842248a309ecd", "content_id": "cab9190071d9b977009e538d4418c6f18d7b563c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 15428, "license_type": "no_license", "max_line_length": 199, "num_lines": 326, "path": "/analysis_core/SearchNode.cpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#include \"SearchNode.h\"\n\n//#define _CLV_\n#ifdef _CLV_\n#define DEBUG(a) std::cout<<a\n#else\n#define DEBUG(a)\n#endif\n\nusing namespace std;\n\nvoid SearchNode::performInnerOperation(vector<int> *v,vector<int> *indices, double *current_difference,AnalysisObjects* ao){\n \n for(int i=0;i<v->size();i++){\n DEBUG(v->at(i)<<\" \");\n particles.at(indices->at(i))->index=v->at(i);\n }\n\n//-------~1min in 25k events\n double tmpval=left->evaluate(ao); // enabling this makes total 1min6s, without it 12s\n double diff=right->evaluate(ao)-tmpval;\n\n \n if ( (*f)(diff,*current_difference) ) {\n DEBUG(\"diff:\"<<diff<<\" c_diff:\"<<*current_difference<<\"\\n\");\n *current_difference = fabs(diff);\n bestIndices=*v;\n } else { DEBUG(\"\\n\");}\n }\n\nvoid SearchNode::runNestedLoopBarb( int start, int N, int level, int maxDepth, vector<int> *v,\n vector<int> *indices,double *curr_diff,AnalysisObjects* ao, int type, string ac) {\n const int unk_MAX=6;\n bool found_at_least_one=false;\n int ip_N[unk_MAX]={N,N,N,N,N,N}; \n int kN=particles.size();\n// int ip_N[unk_MAX]={kN,kN,kN,kN,kN,kN}; \n int ip[unk_MAX]; \n int oi[unk_MAX]={N,N,N,N,N,N}; \n int ip2_min=0, ip3_min=0, ip4_min=0, ip5_min=0, ip1_min=0;\n\n\n//------------if less than 6, no other loops\n for (int i=maxDepth; i<6; i++) ip_N[i]=1;\n\n for(int i=0;i<particles.size();i++){\n oi[i]=particles.at(i)->index;\n DEBUG(\" oi:\"<<oi[i]<<\" \");\n }\n int forbidit_size;\n std::map<string,unordered_set<int> >::iterator forbidit;\n//-----TODO: put a check mechanism\n if ( FORBIDDEN_INDEX_LIST.find(ac) !=FORBIDDEN_INDEX_LIST.end() ){\n DEBUG(\"FORBIDDEN_INDEX_LIST is NOT Empty.\\n\");\n forbidit=FORBIDDEN_INDEX_LIST.find(ac);\n forbidit_size=forbidit->second.size();\n } else {\n DEBUG(\"FORBIDDEN_INDEX_LIST is Empty.\\n\");\n forbidit_size=0;\n }\n\n string s=particles.at(0)->collection;\n DEBUG(\" -|:\"<<maxDepth<<\" N:\"<<N<< \" #ForbiddenIndexSize:\"<<forbidit_size\n << \" Type:\"<<type<<\" Collection:\"<<s<<\" ac:\"<<ac<<\"\\n\");\n\n if ((type==20) && (ao->combosA[s].tableA.size() > 0)){\n DEBUG(\"-------------combo-------------------\\n\");\n for (int k1=0; k1<ao->combosA.at(s).tableA.size(); k1++) {\n if (ao->combosA.at(s).tableA[k1].size()==maxDepth) {\n for (int k2=0; k2<ao->combosA.at(s).tableA[k1].size(); k2++) {\n DEBUG(ao->combosA.at(s).tableA[k1][k2] << \" \");\n// the indice @ k1,k2 should be used\n if (k2 < maxDepth) v->push_back( ao->combosA.at(s).tableA[k1][k2] );\n }\n for(int i=0;i<v->size();i++){\n particles.at(indices->at(i))->index=v->at(i);\n } \n double tmpval=left->evaluate(ao); // enabling this makes total 1min6s, without it 12s\n double diff=right->evaluate(ao)-tmpval;\n\n if ( (*f)(diff,*curr_diff) ) {\n DEBUG(\"diff:\"<<diff<<\" c_diff:\"<<*curr_diff<<\"\\n\");\n *curr_diff = fabs(diff);\n bestIndices.clear();\n for(int i=0;i<v->size();i++){ bestIndices.push_back(v->at(i) ); }\n } else { DEBUG(\"\\n\");}\n v->clear();\n }\n }\n return;\n }\n DEBUG(\"NON COMBO\\n\");\n // loops start ~~~~~~~~~~~\n DEBUG(\"MAX ips:\"<< ip_N[0]<< \" \"<<ip_N[1]<<\" \"<<ip_N[2]<<\" \"<< ip_N[3]<<\" \"<<ip_N[4]<<\" \"<<ip_N[5]<<\"\\n\");\n unordered_set<int> Forbidden_Indices;\n if (forbidit_size > 0) Forbidden_Indices=forbidit->second;\n DEBUG(\"Before LOOP\\n\");\n for (ip[0]=0; ip[0]<ip_N[0]; ip[0]++) {\n DEBUG(\"0:\"<<ip[0]<<\"\\n\");\n if ( Forbidden_Indices.find( ip[0] )!=Forbidden_Indices.end() ) continue; \n for (ip[1]=ip1_min; ip[1]<ip_N[1]; ip[1]++) {\n DEBUG(\"1:\"<<ip[1]<<\"\\n\");\n if (Forbidden_Indices.find( ip[1] )!=Forbidden_Indices.end() ) { DEBUG(\"FORBIDDEN\\n\"); continue; } \n if (particles.size()>1 && (ip[1]==ip[0])) { DEBUG(\"Repeated \\n\"); continue; }\n if ( (oi[0] == oi[1] ) && (ip[0]>ip[1]) ) { DEBUG(\"Same OI, repated\\n\"); continue; }\n\n for (ip[2]=ip2_min; ip[2]<ip_N[2]; ip[2]++) {\n DEBUG(\"2:\"<< ip[2]<<\"\\n\");\n if ( maxDepth>2 ){ \n if ( particles.size()>2 && (ip[2]==ip[0] || ip[2]==ip[1])) continue;\n if ( Forbidden_Indices.find( ip[2] )!=Forbidden_Indices.end() ) continue; \n }\n for (ip[3]=ip3_min; ip[3]<ip_N[3]; ip[3]++) {\n DEBUG(\"3:\"<< ip[3]<<\"\\n\" );\n if ( maxDepth>3){ \n if ( particles.size()>3 && (ip[3]==ip[0] || ip[3]==ip[1] || ip[3]==ip[2])) continue;\n if ( Forbidden_Indices.find( ip[3] )!=Forbidden_Indices.end() ) continue; \n if ( (oi[2]==oi[3]) && (ip[2]>ip[3]) ) continue;\n }\n for (ip[4]=ip4_min; ip[4]<ip_N[4]; ip[4]++) {\n DEBUG(\"4:\"<<ip[4] <<\"\\n\");\n //if (ip_N[5]>1)\n if ( maxDepth>4) {\n if ( particles.size()>4 && (ip[4]==ip[0] || ip[4]==ip[1] || ip[4]==ip[2] || ip[4]==ip[3])) continue;\n if ( Forbidden_Indices.find( ip[4] )!=Forbidden_Indices.end() ) continue; \n if ( ( oi[3] == oi[4]) &&(ip[3]>ip[4]) ) continue;\n }\n for (ip[5]=ip5_min; ip[5]<ip_N[5]; ip[5]++) {\n DEBUG(\"5:\"<<ip[5] <<\"\\n\");\n //if (ip_N[5]>1)\n if (maxDepth>5) {\n if ( particles.size()>5 &&(ip[5]==ip[0] || ip[5]==ip[1] || ip[5]==ip[2] || ip[5]==ip[3] || ip[5]==ip[4])) continue;\n if ( Forbidden_Indices.find( ip[5] )!=Forbidden_Indices.end() ) continue; \n if ( ( oi[4] == oi[5]) &&(ip[4]>ip[5]) ) continue;\n }\n\n if ( (oi[3]== (-10+oi[0]) ) && (ip[0]>ip[3]) ) continue;\n \n DEBUG(\"testing:\"<<ip[0]<<\" \"<<ip[1]<<\" \"<<ip[2]<<\" \"<<ip[3]<<\" \"<<ip[4]<<\" \"<<ip[5]<<\"\\n\");\n for (int i=0; i<maxDepth; i++) v->push_back(ip[i]);\n DEBUG(\"Keeping: \");\n for(int i=0;i<v->size();i++){\n DEBUG(v->at(i)<<\" --> \"<<indices->at(i)<<\" was:\"<<particles.at(indices->at(i))->index <<\" \" );\n particles.at(indices->at(i))->index=v->at(i);\n }\n DEBUG(\"now left evaluate\\n\");\n\n//-------~1min in 25k events\n double tmpval=left->evaluate(ao); // enabling this makes total 1min6s, without it 12s\n DEBUG(\"left ok: \\n\");\n double diff=right->evaluate(ao)-tmpval;\n\n DEBUG(\"compare: \\n\");\n if ( (*f)(diff,*curr_diff) ) {\n DEBUG(\"diff:\"<<diff<<\" c_diff:\"<<*curr_diff<<\"\\n\");\n *curr_diff = fabs(diff);\n bestIndices.clear();\n for(int i=0;i<v->size();i++){ bestIndices.push_back( v->at(i) ); }\n found_at_least_one=true;\n } else { DEBUG(\"Comparison failed...\\n\");}\n\n v->clear();\n }}\n }}}} //all iN loops end\n\n DEBUG(\"Search Ended.\\n\");\n }\n\n void SearchNode::runNestedLoopRec( int start, int N, int level, int maxDepth, vector<int> *v,\n vector<int> *indices,double *curr_diff,AnalysisObjects* ao, int type, string ac) {\n if(level==maxDepth) performInnerOperation (v,indices,curr_diff,ao); //18 without this function call\n else{\n bool skip=false;\n for (int x = start; x < N; x++ ) {\n\n skip=false;\n for (int kk=0; kk<v->size(); kk++){\n if (v->at(kk)==x) {\n skip=true; break;}\n //check if particle x is forbidden\n std::cout<<\"FIXME\\n\";\n {skip=true; break;}\n }\n if (skip) continue;\n\n v->push_back(x); //add the current value\n runNestedLoopRec( start, N, level + 1, maxDepth, v,indices, curr_diff, ao, type, ac);\n v->pop_back();//remove the value\n }\n }\n}\n\n\nSearchNode::SearchNode(double (*func)(double, double), Node* l, Node* r, std::string s){\n f=func;\n symbol=s;\n left=l;\n right=r;\n}\n\ndouble SearchNode::evaluate(AnalysisObjects* ao) {\n DEBUG(\"\\nSearchN ---------------\"<<getStr()<<\"\\n\"); \n particles.clear();\n left->getParticles(&particles);//should fill with particles pointers no more cast needed\n\n std::map<string,unordered_set<int> >::iterator forbidit;\n vector<int> indices;\n for(int i=0;i<particles.size();i++){\n DEBUG(\"SearchN Part:\"<<i<<\" idx:\"<<particles.at(i)->index<< \" addr:\"<<particles.at(i)<<\" name:\"<< particles.at(i)->collection<<\"\\n\");\n if(particles.at(i)->index<0) indices.push_back(i);\n else {\n forbidit=FORBIDDEN_INDEX_LIST.find( particles.at(i)->collection );\n if (forbidit == FORBIDDEN_INDEX_LIST.end() ){\n DEBUG(\"was NOT blacklisted, now adding. \\n\");\n unordered_set<int> pippo;\n pippo.insert(particles.at(i)->index);\n FORBIDDEN_INDEX_LIST.insert(std::pair<string, unordered_set<int> >(particles.at(i)->collection, pippo));\n } else forbidit->second.insert(particles.at(i)->index);\n }\n }\n\n int MaxDepth=indices.size();//number of nested loops needed\n DEBUG(\"SearchN Depth:\"<<MaxDepth<<\"\\n\");\n if(MaxDepth>0){\n int type=particles.at(indices[0])->type;\n string ac=particles.at(indices[0])->collection;\n int Max;\n switch(type){//assuming all particles have the same type // FIXME\n case muon_t: Max=ao->muos[ac].size();break;\n case electron_t: Max=ao->eles[ac].size();break;\n case jet_t: Max=ao->jets[ac].size();break;\n case fjet_t : Max=ao->ljets[ac].size();break;\n case bjet_t: Max=left->tagJets(ao,1,ac).size();break;\n case lightjet_t: Max=left->tagJets(ao,0,ac).size();break;\n\t\t case photon_t: Max=ao->gams[ac].size();break;\n\t\t\tcase tau_t: Max=ao->taus[ac].size();break;\n\t\t\tcase combo_t: Max=ao->combos[ac].size();break;\n default :\n std::cout<<\"optimizing for Unkown type... ERROR!\\n\";\n exit(-11);\n break;\n }\n DEBUG(\"Before find, Max:\"<<Max<<\" collection:\"<< ac<< \" Best index vector size:\"<<bestIndices.size()<<\"\\n\");\n vector<int> v;//--------------------why not pass it by reference?!\n double current_difference =9999999999.9;\n runNestedLoopBarb( 0, Max, 0, MaxDepth, &v,&indices, &current_difference,ao, type, ac);\n // runNestedLoopRec( 0, Max, 0, MaxDepth, &v,&indices, &current_difference,ao, type, ac);\n\n DEBUG(\"After find, Best index vector size:\"<<bestIndices.size()<<\" MaxDepth\"<<MaxDepth<<\"\\n\");\n if (bestIndices.size() < 1) return 0;\n int maxFound = bestIndices.size();\n// if (MaxDepth < bestIndices.size()) maxFound = MaxDepth;\n for(int i=0;i<maxFound;i++){\n particles.at(indices[i])->index=bestIndices[i]; //directly changing the concerned particle -i-->bestIndices[i]\n //-------------------add found indices to FORBIDDEN \n forbidit=FORBIDDEN_INDEX_LIST.find( ac );\n DEBUG(\"forbidding:\"<<bestIndices[i]<<\" for \"<<ac<<\"\\n\");\n if (forbidit == FORBIDDEN_INDEX_LIST.end() ){\n DEBUG(ac<<\" was NOT there, now adding. \\n\");\n unordered_set<int> pippo;\n pippo.insert(bestIndices[i]);\n FORBIDDEN_INDEX_LIST.insert( std::pair<string, unordered_set<int> >(ac, pippo) );\n } else {\n forbidit->second.insert(bestIndices[i]);\n }\n DEBUG(\"BEST\"<<particles.at(indices[i])->index<<\" : \"<<bestIndices[i]<<\"@\"<<indices[i] <<\" type:\"<<particles.at(indices[i])->type<<\" addr:\"<<particles.at(indices[i]) <<\" \\n\");\n }\n } else{\n DEBUG(\"SearchN No negative index found... Returning evaluation as is.\\n\");\n double leftval=left->evaluate(ao); // enabling this makes total 1min6s, without it 12s\n DEBUG(\"SearchN left:\"<<leftval<<\"\\t\");\n double rightval=right->evaluate(ao);\n DEBUG(\" right:\"<<rightval<<\"\\n\");\n if (leftval == rightval) { return 1; }\n else { return 0;} // NGU TODO we should improve.\n }\n DEBUG(\"\\n\");\n return 1;\n }\n\n void SearchNode::Reset() {\n DEBUG(\"Clearing ForbiddenIndices on all names\\t\");\n for (std::map<string, unordered_set<int> >::iterator it=FORBIDDEN_INDEX_LIST.begin(); it!=FORBIDDEN_INDEX_LIST.end(); ++it){\n DEBUG( it->first << \" clearing \\n\"); \n it->second.clear();\n }\n bestIndices.clear();\n DEBUG(\"done.\\n\");\n left->Reset();//assuming right doesnt need a Reset because it's a value Node\n }\n\n void SearchNode::getParticles(std::vector<myParticle *>* particles) {\n left->getParticles(particles);\n }\n void SearchNode::getParticlesAt(std::vector<myParticle *>* particles, int index) {\n \n }\n\n SearchNode::~SearchNode() {\n// if (left!=NULL) delete left;\n// if (right!=NULL) delete right;\n }\n//-------set particles\n void SearchNode::setParticles(std::vector<myParticle *>* bankParticles) {\n particles.clear();\n left->getParticles(&particles);//should fill with particles pointers no more cast needed\n int frombank=0;\n for(int i=0;i<particles.size();i++){\n DEBUG(\"Fill Part:\"<<i<<\" idx:\"<<particles.at(i)->index<< \" addr:\"<<particles.at(i)<<\" name:\"<< particles.at(i)->collection<<\"\\n\");\n if(particles.at(i)->index<0) {\n particles.at(i)->index=bankParticles->at(frombank)->index;\n frombank++;\n DEBUG(\"Filled.\\n\");\n }\n }\n }\n\n//---------------------------------------------------------------------general functions\ndouble maxim( double difference, double current_difference){\n return (fabs(difference) > current_difference );\n}\n\ndouble minim( double difference, double current_difference){\n DEBUG(\"dif:\"<<difference <<\" cur_diff:\"<<current_difference<<\"\\n\");\n return fabs(difference) < current_difference ;\n}\n" }, { "alpha_fraction": 0.5379206538200378, "alphanum_fraction": 0.5640599131584167, "avg_line_length": 64.37193298339844, "blob_id": "12d2dcba20ad86ab77f2a9992713a435b391dfba", "content_id": "a3824732c04732a6ed0eb30a26f430a463f1f6fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 18631, "license_type": "no_license", "max_line_length": 206, "num_lines": 285, "path": "/CLA/lvl0.C", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#define lvl0_cxx\n#include \"lvl0.h\"\n#include <TH2.h>\n#include <TStyle.h>\n#include <TCanvas.h>\n#include <signal.h>\n\n#include \"dbx_electron.h\"\n#include \"dbx_muon.h\"\n#include \"dbx_jet.h\"\n#include \"dbx_tau.h\"\n#include \"dbx_a.h\"\n#include \"DBXNtuple.h\"\n#include \"analysis_core.h\"\n#include \"AnalysisController.h\"\n\n//#define __DEBUG__\n//using namespace Root;\n\n// header and lines to handle ctrl+C gracefully\nextern void _fsig_handler (int) ;\nextern bool fctrlc;\n\nvoid lvl0::Loop(analy_struct aselect, char *extname)\n{\n\n// Signal HANDLER\n signal (SIGINT, _fsig_handler); // signal handler has issues with CINT\n\n if (fChain == 0) {\n cout <<\"Error opening the data file\"<<endl; return;\n }\n\n int verboseFreq(aselect.verbfreq);\n int extra_analysis_count=1;\n int prev_RunNumber=-1;\n\n map < string, int > syst_names;\n syst_names[\"01_pileup\"] = 2;\n syst_names[\"02_elTRG\"] = 2;\n syst_names[\"03_elRECO\"] = 2;\n syst_names[\"04_elID\"] = 2;\n syst_names[\"05_elISOL\"] = 2;\n syst_names[\"06_muTRGStat\"] = 2;\n syst_names[\"07_muTRGSys\"] = 2;\n syst_names[\"08_muIDStat\"] = 2;\n syst_names[\"09_muIDSys\"] = 2;\n syst_names[\"10_muIDStatLowPT\"] = 2;\n syst_names[\"11_muIDSysLowPT\"] = 2;\n syst_names[\"12_muISOLStat\"] = 2;\n syst_names[\"13_muISOLSys\"] = 2;\n syst_names[\"14_muTTVAStat\"] = 2;\n syst_names[\"15_muTTVASys\"] = 2;\n syst_names[\"16_btagSF77extraP\"] = 2;\n syst_names[\"17_btagSF77extraPfromC\"] = 2;\n syst_names[\"18_btagSF77eigenvarsB\"] = 2;\n syst_names[\"19_btagSF77eigenvarsC\"] = 2;\n syst_names[\"20_btagSF77eigenvarsLight\"] = 2;\n syst_names[\"21_jvt\"] = 2;\n\n\n\n AnalysisController aCtrl(&aselect, syst_names);\n aCtrl.Initialize(extname);\n cout << \"End of analysis initialization\"<<endl;\n\n Long64_t nentries = fChain->GetEntriesFast();\n if (aselect.maxEvents>0 ) nentries=aselect.maxEvents;\n cout << \"number of entries \" << nentries << endl;\n Long64_t startevent = 0;\n if (aselect.startpt>0 ) startevent=aselect.startpt;\n cout << \"starting entry \" << startevent << endl;\n Long64_t lastevent = startevent + nentries;\n if (lastevent > fChain->GetEntriesFast() ) { lastevent=fChain->GetEntriesFast();\n cout << \"Interval exceeds tree. Analysis is done on max available events starting from event : \" << startevent << endl;\n }\n\n Long64_t nbytes = 0, nb = 0;\n for (Long64_t j=startevent; j<lastevent; ++j) {\n\n if ( fctrlc ) { cout << \"Processed \" << j << \" events\\n\"; break; }\n if (0 > LoadTree (j)) break;\n if ( j%verboseFreq == 0 ) cout << \"Processing event \" << j << endl;\n\n//--------variables-------\n vector<dbxMuon> muons_sf_pos, muons_sf_neg, muons_ms_pos,muons_ms_neg,muons_id_pos,muons_id_neg;\n vector<dbxElectron> eles_sf_pos, eles_sf_neg;\n vector<dbxJet> jets_goodjee ;\n vector<dbxJet> jetBtaggedUp, jetBtaggedDown;\n vector<dbxJet> jets_jes_pos, jets_jes_neg, jets_jespileup_pos, jets_jesbjetescale_pos;\n vector<dbxJet> jets_jer_pos, jets_jer_neg, jets_jespileup_neg, jets_jesbjetescale_neg;\n vector<dbxJet> jesu_jets_Down [16];\n vector<dbxJet> jesu_jets_Up [16];\n\n vector<dbxMuon> muons;\n vector<dbxElectron> electrons;\n vector<dbxTau> taus;\n vector<dbxPhoton> photons;\n vector<dbxJet> jets;\n vector<dbxJet> ljets;\n vector<dbxTruth> truth;\n vector<dbxParticle> combos;\n vector<dbxParticle> constis;\n\n\n map<string, vector<dbxMuon> > muos_map;\n map<string, vector<dbxElectron> > eles_map;\n map<string, vector<dbxTau> > taus_map;\n map<string, vector<dbxPhoton> > gams_map;\n map<string, vector<dbxJet> > jets_map;\n map<string, vector<dbxJet> >ljets_map;\n map<string, vector<dbxTruth> >truth_map;\n map<string, vector<dbxParticle> >combo_map;\n map<string, vector<dbxParticle> >constits_map;\n map<string, TVector2 > met_map;\n\n std::vector<double> scale_mus_msup, scale_mus_mslow, scale_mus_idup, scale_mus_idlow;\n std::vector<double> scale_mus_sfup, scale_mus_sflow, scale_ele_rescaleup, scale_ele_rescalelow;\n std::vector<double> scale_ele_sfup, scale_ele_sflow;\n bool is_mc=true;\n TVector2 met;\n TVector2 met_jesp, met_jesn, met_jerp, met_jern, met_jespileupp, met_jespileupn, met_jesbjetp, met_jesbjetn;//Jets\n TVector2 met_escalerp, met_escalern, met_esfp, met_esfn;//Electrons\n TVector2 met_msfp, met_msfn, met_mmsp, met_mmsn, met_midp, met_midn; //Muons\n\n//---get an event--------\n fChain->GetEntry(j);\n// cout << \"Got an event\\n\";\n int RunNumber=137;\n if (int(RunNumber)!=prev_RunNumber) {\n cout << \"Working on Run #:\"<<RunNumber<<endl;\n prev_RunNumber=RunNumber;\n }\n\n\n if (j<2) {\n std::cout << \"Main says hello @evt:\"<< event->nt_evt.run_no<<endl;\n cout << \"------------- event #:\"<<j<< endl;\n cout << \"#E:\"<< event->nEle <<endl;\n cout << \"#M:\"<< event->nMuo <<endl;\n cout << \"#J:\"<< event->nJet << \" ==?\" << \" #J:\"<< event->nt_jets.size() <<endl;\n cout << \"#Run:\"<< event->nt_evt.run_no<<endl;\n cout << \"#Evt:\"<< event->nt_evt.event_no<<endl;\n cout << \"#Evt W:\"<< event->nt_evt.user_evt_weight<<endl;\n cout << \"METsize:\"<<event->nt_sys_met.size() << endl;\n for (unsigned int jk=0; jk<event->nt_sys_met.size(); jk++) {\n cout << (event->nt_sys_met.at(jk)).Mod() << \" \" << (event->nt_sys_met.at(jk)).Phi() << endl;\n }\n }\n\n// analysis using info from lvl0 file\n evt_data ev0;\n muons=event->nt_muos;\n electrons=event->nt_eles;\n jets=event->nt_jets;\n met=event->nt_met;\n\n// take a copy of the event info\n ev0=event->nt_evt;\n/*\n cout << \"Ev0 UW:\"<<ev0.user_evt_weight<< endl;\n cout << \"Ev0:\"<<ev0.weight_mc<< \" \"<<ev0.weight_pileup<<\" \"<<ev0.weight_jvt<< endl;\n cout << event->nt_evt.weight_bTagSF_77_eigenvars_B_up.size();\n cout << \"~~~~~~~~~~~\\n\";\n for (int iii=0; iii<event->nt_evt.weight_bTagSF_77_eigenvars_B_up.size(); iii++){ cout<< event->nt_evt.weight_bTagSF_77_eigenvars_B_up.at(iii)<<\" \";}\n cout <<\"\\n\";\n*/\n int km=0; // this is to count number of systematics\n map < string, AnalysisObjects > analysis_objs_map;\n/*\n if (aselect.dosystematics) {\n#ifdef __DEBUG__\n cout << \"Running with systematics.\\n\";\n#endif\n ev0.weight_pileup=ev0.weight_pileup_UP;\n analysis_objs_map[\"01_pileup_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_pileup=ev0.weight_pileup_DOWN;\n analysis_objs_map[\"01_pileup_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_EL_SF_Trigger_UP;\n analysis_objs_map[\"02_elTRG_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_EL_SF_Trigger_DOWN;\n analysis_objs_map[\"02_elTRG_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_EL_SF_Reco_UP;\n analysis_objs_map[\"03_elRECO_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_EL_SF_Reco_DOWN;\n analysis_objs_map[\"03_elRECO_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_EL_SF_ID_UP;\n analysis_objs_map[\"04_elID_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_EL_SF_ID_DOWN;\n analysis_objs_map[\"04_elID_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_EL_SF_Isol_UP;\n analysis_objs_map[\"05_elISOL_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_EL_SF_Isol_DOWN;\n analysis_objs_map[\"05_elISOL_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_Trigger_STAT_UP;\n analysis_objs_map[\"06_muTRGStat_0\"]=(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_Trigger_STAT_DOWN;\n analysis_objs_map[\"06_muTRGStat_1\"]=(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_Trigger_SYST_UP;\n analysis_objs_map[\"07_muTRGSys_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_Trigger_SYST_DOWN;\n analysis_objs_map[\"07_muTRGSys_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_ID_STAT_UP;\n analysis_objs_map[\"08_muIDStat_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_ID_STAT_DOWN;\n analysis_objs_map[\"08_muIDStat_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_ID_SYST_UP;\n analysis_objs_map[\"09_muIDSys_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_ID_SYST_DOWN;\n analysis_objs_map[\"09_muIDSys_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP;\n analysis_objs_map[\"10_muIDStatLowPT_0\"]=(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN;\n analysis_objs_map[\"10_muIDStatLowPT_1\"]=(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP;\n analysis_objs_map[\"11_muIDSysLowPT_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN;\n analysis_objs_map[\"11_muIDSysLowPT_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_Isol_STAT_UP;\n analysis_objs_map[\"12_muISOLStat_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_Isol_STAT_DOWN;\n analysis_objs_map[\"12_muISOLStat_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_Isol_SYST_UP;\n analysis_objs_map[\"13_muISOLSys_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_Isol_SYST_DOWN;\n analysis_objs_map[\"13_muISOLSys_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_TTVA_STAT_UP;\n analysis_objs_map[\"14_muTTVAStat_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_TTVA_STAT_DOWN;\n analysis_objs_map[\"14_muTTVAStat_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_TTVA_SYST_UP;\n analysis_objs_map[\"15_muTTVASys_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_leptonSF=ev0.weight_leptonSF_MU_SF_TTVA_SYST_DOWN;\n analysis_objs_map[\"15_muTTVASys_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_bTagSF_77=ev0.weight_bTagSF_77_extrapolation_up;\n analysis_objs_map[\"16_btagSF77extraP_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_bTagSF_77=ev0.weight_bTagSF_77_extrapolation_down;\n analysis_objs_map[\"16_btagSF77extraP_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_bTagSF_77=ev0.weight_bTagSF_77_extrapolation_from_charm_up;\n analysis_objs_map[\"17_btagSF77extraPfromC_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_bTagSF_77=ev0.weight_bTagSF_77_extrapolation_from_charm_down;\n analysis_objs_map[\"17_btagSF77extraPfromC_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_bTagSF_77=ev0.weight_bTagSF_77_eigenvars_B_up.size();\n analysis_objs_map[\"18_btagSF77eigenvarsB_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_bTagSF_77=ev0.weight_bTagSF_77_eigenvars_B_down.size();\n analysis_objs_map[\"18_btagSF77eigenvarsB_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_bTagSF_77=ev0.weight_bTagSF_77_eigenvars_C_up.size();\n analysis_objs_map[\"19_btagSF77eigenvarsC_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_bTagSF_77=ev0.weight_bTagSF_77_eigenvars_C_down.size();\n analysis_objs_map[\"19_btagSF77eigenvarsC_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_bTagSF_77=ev0.weight_bTagSF_77_eigenvars_Light_up.size();\n analysis_objs_map[\"20_btagSF77eigenvarsLight_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_bTagSF_77=ev0.weight_bTagSF_77_eigenvars_Light_down.size();\n analysis_objs_map[\"20_btagSF77eigenvarsLight_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_jvt=ev0.weight_jvt_UP;\n analysis_objs_map[\"21_jvt_0\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n ev0.weight_jvt=ev0.weight_jvt_DOWN;\n analysis_objs_map[\"21_jvt_1\"] =(AnalysisObjects){event->nt_muos,event->nt_eles, ga0, event->nt_jets, event->nt_met, ev0}; km++;\n\n\n }\n aCtrl.RunTasks(a0, analysis_objs_map);\n// ---------no systematics for now\n*/\n\n// now run\n\n muos_map.insert( pair <string,vector<dbxMuon> > (\"MUO\", muons) );\n eles_map.insert( pair <string,vector<dbxElectron> > (\"ELE\", electrons) );\n taus_map.insert( pair <string,vector<dbxTau> > (\"TAU\", taus) );\n gams_map.insert( pair <string,vector<dbxPhoton> > (\"PHO\", photons) );\n jets_map.insert( pair <string,vector<dbxJet> > (\"JET\", jets) );\n ljets_map.insert( pair <string,vector<dbxJet> > (\"FJET\", ljets) );\n truth_map.insert( pair <string,vector<dbxTruth> > (\"Truth\", truth) );\n combo_map.insert( pair <string,vector<dbxParticle> > (\"Combo\", combos) );\n constits_map.insert( pair <string,vector<dbxParticle> > (\"Constits\", constis) );\n met_map.insert( pair <string,TVector2> (\"MET\", met) );\n\n AnalysisObjects a0={muos_map, eles_map, taus_map, gams_map, jets_map, ljets_map, truth_map, combo_map, constits_map, met_map, ev0};\n aCtrl.RunTasks(a0);\n\n } // end of event loop\n aCtrl.Finalize();\n\n}\n" }, { "alpha_fraction": 0.5787515044212341, "alphanum_fraction": 0.6046918034553528, "avg_line_length": 48.811798095703125, "blob_id": "ab6309733c5f93a1722dd351c2f71f465a2c4414", "content_id": "075e3de57b15bef51596a1529b4c80277d8ce203", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 17733, "license_type": "no_license", "max_line_length": 232, "num_lines": 356, "path": "/CLA/VLLBG3.C", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#define VLLBG3_cxx\n#include \"VLLBG3.h\"\n#include <TH2.h>\n#include <TStyle.h>\n#include <TCanvas.h>\n#include <signal.h>\n\n#include \"dbx_electron.h\"\n#include \"dbx_muon.h\"\n#include \"dbx_jet.h\"\n#include \"dbx_tau.h\"\n#include \"dbx_a.h\"\n#include \"DBXNtuple.h\"\n#include \"analysis_core.h\"\n#include \"AnalysisController.h\"\n\nvoid VLLBG3::GetPhysicsObjects( Long64_t j, AnalysisObjects *a0 )\n{\n fChain->GetEntry(j);\n \n vector<dbxMuon> muons;\n vector<dbxElectron> electrons;\n vector<dbxPhoton> photons;\n vector<dbxJet> jets;\n vector<dbxTau> taus;\n vector<dbxJet> ljets;\n vector<dbxTruth> truth;\n vector<dbxParticle> combos;\n vector<dbxParticle> constis;\n\n map<string, vector<dbxMuon> > muos_map;\n map<string, vector<dbxElectron> > eles_map;\n map<string, vector<dbxTau> > taus_map;\n map<string, vector<dbxPhoton> > gams_map;\n map<string, vector<dbxJet> > jets_map;\n map<string, vector<dbxJet> >ljets_map;\n map<string, vector<dbxTruth> >truth_map;\n map<string, vector<dbxParticle> >combo_map;\n map<string, vector<dbxParticle> >constits_map;\n map<string, TVector2 > met_map;\n\n evt_data anevt;\n int extra_analysis_count=1;\n int year=2015;\n int prev_RunNumber=-1;\n\n //temporary variables\n TLorentzVector alv;\n TLorentzVector dummyTlv(0.,0.,0.,0.);\n TVector2 mets;\n dbxJet *adbxj;\n dbxElectron *adbxe;\n dbxMuon *adbxm;\n dbxPhoton *adbxp;\n\n #ifdef __DEBUG__\n std::cout << \"Begin Filling\"<<std::endl;\n #endif\n /*\n // PHOTONS -------- // now tau info\n for (unsigned int i=0; i<tau_pt->size(); i++) {\n alv.SetPtEtaPhiE( tau_pt->at(i)*0.001, tau_eta->at(i), tau_phi->at(i), tau_m->at(i)*0.001 ); // all in GeV\n adbxp= new dbxPhoton(alv);\n adbxp->setCharge(tau_charge->at(i) );\n photons.push_back(*adbxp);\n delete adbxp;\n }\n #ifdef __DEBUG__\n std::cout << \"Photons OK:\"<< tau_pt->size()<<std::endl;\n #endif\n */\n //MUONS\n for (unsigned int i=0; i<mu_pt->size(); i++) {\n alv.SetPtEtaPhiM( mu_pt->at(i)*0.001, mu_eta->at(i), mu_phi->at(i), 0.1056583755 ); // all in GeV\n adbxm= new dbxMuon(alv);\n adbxm->setCharge(mu_charge->at(i) );\n //adbxm->setEtCone(mu_topoetcone20->at(i) ); we couldn't find et or pt cones.\n //adbxm->setPtCone(mu_ptvarcone30->at(i) );\n adbxm->setParticleIndx(i);\n //adbxm->setisZCand(mu_isZCand->at(i) ); no such thing in vll analysis\n //adbxm->settrigMatch_HLT_mu26_ivarmedium(muon_TrigEff_SF_HLT_mu8noL1_RecoTight->at(i)); //we got the first one, this should be decided.\n //adbxm->settrigMatch_HLT_mu50(muon_TrigMCEff_HLT_mu8noL1_RecoTight->at(i)); //we got the second one, this should be decided\n //adbxm->settrigMatch_HLT_mu20_iloose_L1MU15(muon_TrigEff_SF_HLT_mu18_RecoTight->at(i)); // we got the the third one, this should be decided.\n\n muons.push_back(*adbxm);\n delete adbxm;\n }\n #ifdef __DEBUG__\n std::cout << \"Muons OK:\"<< mu_pt->size()<<std::endl;\n #endif\n\n //ELECTRONS\n for (unsigned int i=0; i<el_pt->size(); i++) {\n alv.SetPtEtaPhiM( el_pt->at(i)*0.001, el_eta->at(i), el_phi->at(i), 0.000511 ); // all in GeV\n // std::cout << \"ETA:\"<<el_eta->at(i) <<std::endl;\n adbxe= new dbxElectron(alv);\n adbxe->setCharge(el_charge->at(i) );\n // adbxe->setPtCone(el_ptvarcone20->at(i));// 30 has // this does not exist in vll analysis 20 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n // adbxe->setEtCone20(el_ptvarcone20->at(i) );\n // adbxe->settrue_origin(el_true_origin->at(i));\n // adbxe->settrue_type(el_true_type->at(i));\n adbxe->setParticleIndx(i);\n adbxe->setClusterEta(el_caloCluster_eta->at(i) );\n // adbxe->setd0sig(el_trkd0sig->at(i) ); // BU IKISI YOK BULAMADIM MK NTUPLEINDA\n // adbxe->setdelta_z0_sintheta(el_trkz0sintheta->at(i) );BU IKISI YOK BULAMADIM MK NTUPLEINDA\n // adbxe->setisZCand(el_isZCand->at(i) );\n\n\n //adbxe->settrigMatch_HLT_e60_lhmedium_nod0(el_TrigEff_SF_TRI_E_2015_e17_lhloose_2016_e17_lhloose_nod0_2017_e24_lhvloose_nod0_L1EM20VH_TightLLH->at(i)); // we got the first six ones, this should be decided in the future.\n //adbxe->settrigMatch_HLT_e26_lhtight_nod0_ivarloose(el_TrigMCEff_TRI_E_2015_e17_lhloose_2016_e17_lhloose_nod0_2017_e24_lhvloose_nod0_L1EM20VH_TightLLH->at(i));\n //adbxe->settrigMatch_HLT_e140_lhloose_nod0(el_TrigEff_SF_DI_E_2015_e12_lhloose_L1EM10VH_2016_e17_lhvloose_nod0_2017_e24_lhvloose_nod0_L1EM20VH_TightLLH->at(i));\n //adbxe->settrigMatch_HLT_e60_lhmedium(el_TrigMCEff_DI_E_2015_e12_lhloose_L1EM10VH_2016_e17_lhvloose_nod0_2017_e24_lhvloose_nod0_L1EM20VH_TightLLH->at(i));\n //adbxe->settrigMatch_HLT_e24_lhmedium_L1EM20VH(el_TrigEff_SF_MULTI_L_2015_e12_lhloose_2016_e12_lhloose_nod0_2017_e12_lhloose_nod0_TightLLH->at(i));\n //adbxe->settrigMatch_HLT_e120_lhloose(el_TrigMCEff_MULTI_L_2015_e12_lhloose_2016_e12_lhloose_nod0_2017_e12_lhloose_nod0_TightLLH->at(i));\n\n electrons.push_back(*adbxe);\n delete adbxe;\n }\n\n #ifdef __DEBUG__\n std::cout << \"Electrons OK:\"<< el_pt->size() <<std::endl;\n #endif\n\n //JETS\n for (unsigned int i=0; i<jet_pt->size(); i++) {\n alv.SetPtEtaPhiM( jet_pt->at(i)*0.001, jet_eta->at(i), jet_phi->at(i), jet_m->at(i)*0.001 ); // all in GeV\n adbxj= new dbxJet(alv);\n adbxj->setCharge(-99);\n // adbxj->setjvt(jet_JvtPass_Medium->at(i)); // this also should be decided in the future.\n adbxj->setParticleIndx(i);\n // adbxj->setFlavor(jet_truthflav->at(i) );\n //adbxj->set_isbtagged_77(bool(jet_FTag_MV2c10_FixedCutBEff_77_NOSYS->at(i))); // Bora removed this\n // adbxj->setmv2c00(jet_mv2c00->at(i));\n // adbxj->setmv2c10(jet_mv2c10->at(i));\n // adbxj->setmv2c20(jet_mv2c20->at(i));\n // adbxj->setip3dsv1(jet_ip3dsv1->at(i));\n\n // adbxj->set_isbtagged_77( jet_MV2c10mu[i] > 0.7892 ); // is btag\n jets.push_back(*adbxj);\n delete adbxj;\n }\n #ifdef __DEBUG__\n std::cout << \"Jets OK:\"<< jet_pt->size() <<std::endl;\n #endif\n //MET\n // met.SetMagPhi( met*0.001, met_phi); //mev-->gev //I am not sure about met. this should be checked.\n mets.SetMagPhi( met->at(5)*0.001, met_phi->at(5)); //mev-->gev //I am not sure about met. this should be checked.\n // std::cout <<\"met values: \"<<met->at(i)<<endl;\n // std::cout <<\"met size: \"<<met->size()<<endl;\n #ifdef __DEBUG__\n std::cout << \"MET OK\"<<std::endl;\n #endif\n\n\n anevt.run_no=runNumber;\n anevt.user_evt_weight=1;\n anevt.event_no=eventNumber;\n anevt.lumiblk_no=1;\n anevt.top_hfor_type=0;\n anevt.TRG_e= 1;\n anevt.TRG_m= 0;\n anevt.TRG_j= 0;\n anevt.vxp_maxtrk_no= 1;\n anevt.badjet=0;\n \n //anevt.weight_mc=mcEventWeights\n //anevt.weight_mc=mcEventWeights->at(0);\n anevt.weight_mc=generatorWeight;\n //if (std::abs(generatorWeight)>100.0) {\n // anevt.weight_mc=1;\n // cout<<\"MCEventWeight>100.0. It is set to 1\"<<endl;\n //}\n //std::cout<< \"EvtW: \" << anevt.weight_mc<<std::endl;\n anevt.weight_pileup=pileupWeight;\n //std::cout<< \"PileW: \" << anevt.weight_pileup<<std::endl;\n anevt.correction_weight=correctionWeight;\n anevt.luminosity_weight=luminosityWeight;\n\n anevt.weight_jvt=1;\n //std::ifstream f(\"/home/boreas/DNEME/oku3.txt\");\n //std::vector<float> dsid;\n //std::vector<float> xsec;\n //int index=0;\n //int index2=0;\n //if (f.is_open()){\n // float tmpdsid;\n // float tmpxsec;\n // while(!f.eof()) // reads file to end of *file*, not line\n // { \n // f >> tmpdsid; // read first column number\n // f >> tmpxsec; // read second column \n // \n // dsid.push_back(tmpdsid);\n // xsec.push_back(tmpxsec);\n // }\n // f.close();\n // //cout<<dsid.size()<<endl;\n // //cout<<\"DSID: \"<<mcChannelNumber<<endl;\n // std::vector<float>::iterator it = std::find(dsid.begin(), dsid.end(), mcChannelNumber*100);\n // index = std::distance(dsid.begin(), it);\n // if (index==dsid.size()){\n // anevt.weight_xsec=1;\n // }\n // else { \n // std::vector<float>::iterator it = std::find(dsid.begin(), dsid.end(), mcChannelNumber);\n // int index2 = std::distance(dsid.begin(), it);\n // anevt.weight_xsec=xsec[index]/xsec[index2];\n // cout<<\"Xsecs and Ratio: \"<< xsec[index] << \" \"<< xsec[index2]<< \" \"<<anevt.weight_xsec<<endl; \n // }\n // \n // //cout<<\"Index: \"<<index<<endl;\n // //cout<<\"Xsec: \"<<xsec[index]<<endl;\n //}\n //else{cout<<\"Failed to open\"<<endl;}\n anevt.weight_xsec=1;\n //anevt.weight_xsec=xsec[index];\n // anevt.weight_jvt=correctionWeight*luminosityWeight*xsec[index]; // didnt have jvt, others multiplied here for convenience\n //std::cout<< \"CorrW: \" << correctionWeight<<std::endl;\n //std::cout<< \"LumW: \" << luminosityWeight<<std::endl;\n //std::cout<<\"Combined Weight for \"<<j<<\"th Event: \" << anevt.weight_jvt*anevt.weight_pileup*anevt.weight_mc*anevt.weight_xsec*anevt.luminosity_weight*anevt.correction_weight<<endl;\n //std::cout<< \"Xsec: \" << xsec[index]<<std::endl;\n //std::cout<< \"CorrW*LumW*Xsec: \" << anevt.weight_jvt<<std::endl;\n //ofstream dumpfile;\n //dumpfile.open(\"/home/boreas/DNEME/cwdump.txt\",ios::app);\n //dumpfile<<\"Combined Weight for \"<<j<<\"th Event: \" << anevt.weight_jvt*anevt.weight_pileup*anevt.weight_mc*anevt.weight_xsec*anevt.luminosity_weight*anevt.correction_weight<<endl;\n //dumpfile.close();\n //anevt.weight_leptonSF=actualMu; //this is completely wrong. electron and muon has different scale factors.\n /*anevt.weight_bTagSF_77=weight_bTagSF_MV2c10_77;\n anevt.weight_jvt=weight_jvt;\n\n anevt.weight_pileup_UP=weight_pileup_UP;\n anevt.weight_pileup_DOWN=weight_pileup_DOWN;\n anevt.weight_leptonSF_EL_SF_Trigger_UP=weight_leptonSF_EL_SF_Trigger_UP;\n anevt.weight_leptonSF_EL_SF_Trigger_DOWN=weight_leptonSF_EL_SF_Trigger_DOWN;\n anevt.weight_leptonSF_EL_SF_Reco_UP=weight_leptonSF_EL_SF_Reco_UP;\n anevt.weight_leptonSF_EL_SF_Reco_DOWN=weight_leptonSF_EL_SF_Reco_DOWN;\n anevt.weight_leptonSF_EL_SF_ID_UP=weight_leptonSF_EL_SF_ID_UP;\n anevt.weight_leptonSF_EL_SF_ID_DOWN=weight_leptonSF_EL_SF_ID_DOWN;\n anevt.weight_leptonSF_EL_SF_Isol_UP=weight_leptonSF_EL_SF_Isol_UP;\n anevt.weight_leptonSF_EL_SF_Isol_DOWN=weight_leptonSF_EL_SF_Isol_DOWN;\n anevt.weight_leptonSF_MU_SF_Trigger_STAT_UP=weight_leptonSF_MU_SF_Trigger_STAT_UP;\n anevt.weight_leptonSF_MU_SF_Trigger_STAT_DOWN=weight_leptonSF_MU_SF_Trigger_STAT_DOWN;\n anevt.weight_leptonSF_MU_SF_Trigger_SYST_UP=weight_leptonSF_MU_SF_Trigger_SYST_UP;\n anevt.weight_leptonSF_MU_SF_Trigger_SYST_DOWN=weight_leptonSF_MU_SF_Trigger_SYST_DOWN;\n anevt.weight_leptonSF_MU_SF_ID_STAT_UP=weight_leptonSF_MU_SF_ID_STAT_UP;\n anevt.weight_leptonSF_MU_SF_ID_STAT_DOWN=weight_leptonSF_MU_SF_ID_STAT_DOWN;\n anevt.weight_leptonSF_MU_SF_ID_SYST_UP=weight_leptonSF_MU_SF_ID_SYST_UP;\n anevt.weight_leptonSF_MU_SF_ID_SYST_DOWN=weight_leptonSF_MU_SF_ID_SYST_DOWN;\n anevt.weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP=weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP;\n anevt.weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN=weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN;\n anevt.weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP=weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP;\n anevt.weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN=weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN;\n anevt.weight_leptonSF_MU_SF_Isol_STAT_UP=weight_leptonSF_MU_SF_Isol_STAT_UP;\n anevt.weight_leptonSF_MU_SF_Isol_STAT_DOWN=weight_leptonSF_MU_SF_Isol_STAT_DOWN;\n anevt.weight_leptonSF_MU_SF_Isol_SYST_UP=weight_leptonSF_MU_SF_Isol_SYST_UP;\n anevt.weight_leptonSF_MU_SF_Isol_SYST_DOWN=weight_leptonSF_MU_SF_Isol_SYST_DOWN;\n anevt.weight_leptonSF_MU_SF_TTVA_STAT_UP=weight_leptonSF_MU_SF_TTVA_STAT_UP;\n anevt.weight_leptonSF_MU_SF_TTVA_STAT_DOWN=weight_leptonSF_MU_SF_TTVA_STAT_DOWN;\n anevt.weight_leptonSF_MU_SF_TTVA_SYST_UP=weight_leptonSF_MU_SF_TTVA_SYST_UP;\n anevt.weight_leptonSF_MU_SF_TTVA_SYST_DOWN=weight_leptonSF_MU_SF_TTVA_SYST_DOWN;\n anevt.weight_jvt_UP=weight_jvt_UP;\n anevt.weight_jvt_DOWN=weight_jvt_DOWN;\n anevt.weight_bTagSF_77_extrapolation_up=weight_bTagSF_MV2c10_77_extrapolation_up;\n anevt.weight_bTagSF_77_extrapolation_down=weight_bTagSF_MV2c10_77_extrapolation_down;\n anevt.weight_bTagSF_77_extrapolation_from_charm_up=weight_bTagSF_MV2c10_77_extrapolation_from_charm_up;\n anevt.weight_bTagSF_77_extrapolation_from_charm_down=weight_bTagSF_MV2c10_77_extrapolation_from_charm_down;\n // anevt.mc_generator_weights=*mc_generator_weights;\n anevt.weight_bTagSF_77_eigenvars_B_up=*weight_bTagSF_MV2c10_77_eigenvars_B_up;\n anevt.weight_bTagSF_77_eigenvars_C_up=*weight_bTagSF_MV2c10_77_eigenvars_C_up;\n anevt.weight_bTagSF_77_eigenvars_Light_up=*weight_bTagSF_MV2c10_77_eigenvars_Light_up;\n anevt.weight_bTagSF_77_eigenvars_B_down=*weight_bTagSF_MV2c10_77_eigenvars_B_down;\n anevt.weight_bTagSF_77_eigenvars_C_down=*weight_bTagSF_MV2c10_77_eigenvars_C_down;\n anevt.weight_bTagSF_77_eigenvars_Light_down=*weight_bTagSF_MV2c10_77_eigenvars_Light_down;*/\n\n #ifdef __DEBUG__\n std::cout << \"Filling finished\"<<std::endl;\n #endif\n\n muos_map.insert( pair <string,vector<dbxMuon> > (\"MUO\", muons) );\n eles_map.insert( pair <string,vector<dbxElectron> > (\"ELE\", electrons) );\n taus_map.insert( pair <string,vector<dbxTau> > (\"TAU\", taus) );\n gams_map.insert( pair <string,vector<dbxPhoton> > (\"PHO\", photons) );\n jets_map.insert( pair <string,vector<dbxJet> > (\"JET\", jets) );\n ljets_map.insert( pair <string,vector<dbxJet> > (\"FJET\", ljets) );\n truth_map.insert( pair <string,vector<dbxTruth> > (\"Truth\", truth) );\n combo_map.insert( pair <string,vector<dbxParticle> > (\"Combo\", combos) );\n constits_map.insert( pair <string,vector<dbxParticle> > (\"Constits\", constis) );\n met_map.insert( pair <string,TVector2> (\"MET\", mets) );\n\n *a0={muos_map, eles_map, taus_map, gams_map, jets_map, ljets_map, truth_map, combo_map, constits_map, met_map, anevt};\n }\n\n\nvoid VLLBG3::Loop(analy_struct aselect, char *extname)\n{\n// In a ROOT session, you can do:\n// root> .L VLLBG3.C\n// root> VLLBG3 t\n// root> t.GetEntry(12); // Fill t data members with entry number 12\n// root> t.Show(); // Show values of entry 12\n// root> t.Show(16); // Read and show values of entry 16\n// root> t.Loop(); // Loop on all entries\n//\n\n// This is the loop skeleton where:\n// jentry is the global entry number in the chain\n// ientry is the entry number in the current Tree\n// Note that the argument to GetEntry must be:\n// jentry for TChain::GetEntry\n// ientry for TTree::GetEntry and TBranch::GetEntry\n//\n// To read only selected branches, Insert statements like:\n// METHOD1:\n// fChain->SetBranchStatus(\"*\",0); // disable all branches\n// fChain->SetBranchStatus(\"branchname\",1); // activate branchname\n// METHOD2: replace line\n// fChain->GetEntry(jentry); //read all branches\n//by b_branchname->GetEntry(ientry); //read only this branch\n cout << \"I am in VLLBG3.C \" << endl;\n if (fChain == 0) {\n cout <<\"Error opening the data file\"<<endl; return;\n }\n int verboseFreq(aselect.verbfreq);\n \n map < string, int > syst_names;\n syst_names[\"01_jes\"] = 2;\n \n AnalysisController aCtrl(&aselect, syst_names);\n aCtrl.Initialize(extname);\n cout << \"End of analysis initialization\"<<endl;\n \n Long64_t nentries = fChain->GetEntriesFast();\n if (aselect.maxEvents>0 ) nentries=aselect.maxEvents;\n cout << \"number of entries \" << nentries << endl;\n Long64_t startevent = 0;\n if (aselect.startpt>0 ) startevent=aselect.startpt;\n cout << \"starting entry \" << startevent << endl;\n Long64_t lastevent = startevent + nentries;\n if (lastevent> fChain->GetEntriesFast() ){ lastevent=fChain->GetEntriesFast();\n cout << \"Interval exceeds tree. Analysis is done on max available events starting from event : \" << startevent << endl;\n }\n Long64_t nbytes = 0, nb = 0;\n for (Long64_t j=startevent; j<lastevent; ++j) {\n\n // if ( fctrlc ) { cout << \"Processed \" << j << \" events\\n\"; break; }\n if (0 > LoadTree (j)) break;\n if ( j%verboseFreq == 0 ) cout << \"Processing event \" << j << endl;\n\n AnalysisObjects a0;\n GetPhysicsObjects(j, &a0);\n aCtrl.RunTasks(a0);\n\n }// event loop ends.\n aCtrl.Finalize();\n\n }\n" }, { "alpha_fraction": 0.6806451678276062, "alphanum_fraction": 0.6838709712028503, "avg_line_length": 16.22222137451172, "blob_id": "f1f0c076834182fe955466a8fd7a0d7053ae29b5", "content_id": "631a4b553450c14f4f612189783e3d6ce6315a38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 310, "license_type": "no_license", "max_line_length": 56, "num_lines": 18, "path": "/analysis_core/dbx_truth.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#ifndef DBX_TRUTH_H\n#define DBX_TRUTH_H\n\n#ifdef VLQLIGHT\n#include \"VLQLight/dbxParticle.h\"\n#else\n#include \"dbxParticle.h\"\n#endif\n\nclass dbxTruth: public dbxParticle {\n public:\n dbxTruth( ): dbxParticle(){};\n dbxTruth( TLorentzVector lv): dbxParticle(lv){};\n\n ClassDef(dbxTruth,1);\n};\n\n#endif\n" }, { "alpha_fraction": 0.5381113290786743, "alphanum_fraction": 0.5535899996757507, "avg_line_length": 33.168888092041016, "blob_id": "aeb909d27dd8437570d6bb44c51d898144769941", "content_id": "144a64730187063a43fceecaceb7ddfe9c3742d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7688, "license_type": "no_license", "max_line_length": 141, "num_lines": 225, "path": "/CLA/atlasopen.C", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#define atlasopen_cxx\n#include \"atlasopen.h\"\n#include <TH2.h>\n#include <TStyle.h>\n#include <TCanvas.h>\n#include <signal.h>\n\n#include \"dbx_electron.h\"\n#include \"dbx_muon.h\"\n#include \"dbx_jet.h\"\n#include \"dbx_tau.h\"\n#include \"dbx_a.h\"\n#include \"DBXNtuple.h\"\n#include \"analysis_core.h\"\n#include \"AnalysisController.h\"\n\n//#define __DEBUG__\nextern void _fsig_handler (int) ;\nextern bool fctrlc;\n\nvoid atlasopen::Loop(analy_struct aselect, char *extname)\n{\n// Signal HANDLER\n signal (SIGINT, _fsig_handler); // signal handler has issues with CINT\n\n if (fChain == 0) {\n cout <<\"Error opening the data file\"<<endl; return;\n }\n\n int verboseFreq(aselect.verbfreq);\n evt_data anevt;\n float blow_th=0.7892;\n int prev_RunNumber=-1;\n\n map < string, int > syst_names;\n syst_names[\"01_jes\"] = 2;\n AnalysisController aCtrl(&aselect, syst_names);\n aCtrl.Initialize(extname);\n cout << \"End of analysis initialization\"<<endl;\n\n\n Long64_t nentries = fChain->GetEntriesFast();\n if (aselect.maxEvents>0 ) nentries=aselect.maxEvents;\n cout << \"number of entries \" << nentries << endl;\n Long64_t startevent = 0;\n if (aselect.startpt>0 ) startevent=aselect.startpt;\n cout << \"starting entry \" << startevent << endl;\n Long64_t lastevent = startevent + nentries;\n if (lastevent > fChain->GetEntriesFast() ) { lastevent=fChain->GetEntriesFast();\n cout << \"Interval exceeds tree. Analysis is done on max available events starting from event : \" << startevent << endl;\n }\n\n Long64_t nbytes = 0, nb = 0;\n for (Long64_t j=startevent; j<lastevent; ++j) {\n\n if ( fctrlc ) { cout << \"Processed \" << j << \" events\\n\"; break; }\n if ( j%verboseFreq == 0 ) cout << \"Processing event \" << j << endl;\n fChain->GetEntry(j);\n#ifdef __DEBUG__\nstd::cout << \"Read Event\"<<std::endl;\n#endif\n/*\n int RunNumber=137;\n if (int(RunNumber)!=prev_RunNumber) {\n cout << \"Working on Run #:\"<<RunNumber<<endl;\n prev_RunNumber=RunNumber;\n }\n*/\n vector<dbxMuon> muons;\n vector<dbxElectron> electrons;\n vector<dbxTau> taus;\n vector<dbxPhoton> photons;\n vector<dbxJet> jets;\n vector<dbxJet> ljets;\n vector<dbxTruth> truth;\n vector<dbxParticle> combos;\n vector<dbxParticle> constis;\n\n map<string, vector<dbxMuon> > muos_map;\n map<string, vector<dbxElectron> > eles_map;\n map<string, vector<dbxTau> > taus_map;\n map<string, vector<dbxPhoton> > gams_map;\n map<string, vector<dbxJet> > jets_map;\n map<string, vector<dbxJet> >ljets_map;\n map<string, vector<dbxTruth> >truth_map;\n map<string, vector<dbxParticle> >combo_map;\n map<string, vector<dbxParticle> >constits_map;\n map<string, TVector2 > met_map;\n\n//temporary variables\n TLorentzVector alv;\n TVector2 met;\n dbxJet *adbxj;\n dbxElectron *adbxe;\n dbxMuon *adbxm;\n dbxTau *adbxt;\n dbxPhoton *adbxp;\n\n#ifdef __DEBUG__\nstd::cout << \"Begin Filling\"<<std::endl;\n#endif\n\n for (unsigned int i=0; i<lep_n; i++) {\n alv.SetPtEtaPhiE( lep_pt[i]*0.001, lep_eta[i], lep_phi[i], lep_E[i]*0.001 ); // all in GeV\n if (lep_type[i]==13) {\n adbxm= new dbxMuon(alv);\n adbxm->setCharge(lep_charge[i] );\n\t\tadbxm->setPdgID(-13*lep_charge[i]);\n adbxm->setEtCone(lep_etcone20[i] );\n adbxm->setPtCone(lep_ptcone30[i] );\n adbxm->setParticleIndx(i);\n adbxm->setZ0(lep_z0[i] );\n muons.push_back(*adbxm);\n delete adbxm;\n }\n if (lep_type[i]==11) {\n adbxe= new dbxElectron(alv);\n adbxe->setCharge(lep_charge[i] );\n\t\tadbxe->setPdgID(-11*lep_charge[i]);\n adbxe->setParticleIndx(i);\n adbxe->setEtCone(lep_etcone20[i] );\n adbxe->setPtCone(lep_ptcone30[i] );\n adbxe->setZ0(lep_z0[i] );\n electrons.push_back(*adbxe);\n delete adbxe;\n }\n\t if (lep_type[i]==15) {\n adbxt= new dbxTau(alv);\n adbxt->setCharge(lep_charge[i] );\n\t\tadbxt->setPdgID(-15*lep_charge[i]);\n adbxt->setEtCone(lep_etcone20[i] );\n adbxt->setPtCone(lep_ptcone30[i] );\n adbxt->setParticleIndx(i);\n adbxt->setZ0(lep_z0[i] );\n taus.push_back(*adbxt);\n delete adbxt;\n }\n }\n\n#ifdef __DEBUG__\nstd::cout << \"Muons, Electrons and Taus OK:\"<< Electron_ <<std::endl;\n#endif\n\n/*\n//PHOTONS\n for (unsigned int i=0; i<Photon_size; i++) {\n alv.SetPtEtaPhiM( Photon_PT[i], Photon_Eta[i], Photon_Phi[i], 0 ); // all in GeV\n adbxp= new dbxPhoton(alv);\n adbxp->setCharge(0);\n adbxp->setParticleIndx(i);\n adbxp->setClusterE(Photon_EhadOverEem[i] );\n photons.push_back(*adbxp);\n delete adbxp;\n }\n#ifdef __DEBUG__\nstd::cout << \"Photons OK:\"<<Photon_size<<std::endl;\n#endif\n*/\n//JETS\n for (unsigned int i=0; i<alljet_n; i++) {\n alv.SetPtEtaPhiE( jet_pt[i]*0.001, jet_eta[i], jet_phi[i], jet_E[i]*0.001 ); // all in GeV\n adbxj= new dbxJet(alv);\n adbxj->setCharge(-99);\n adbxj->setJVtxf(jet_jvf[i]);\n adbxj->setParticleIndx(i);\n adbxj->setFlavor(jet_MV1[i] );\n adbxj->set_isbtagged_77( jet_MV1[i] > blow_th ); // 5 is btag\n jets.push_back(*adbxj);\n delete adbxj;\n }\n#ifdef __DEBUG__\nstd::cout << \"Jets:\"<<Jet_<<std::endl;\n#endif\n//MET\n met.SetMagPhi( met_et*0.001, met_phi);\n#ifdef __DEBUG__\nstd::cout << \"MET OK\"<<std::endl;\n#endif\n\n\n//------------ auxiliary information -------\n anevt.run_no=runNumber;\n anevt.user_evt_weight=1.0;\n anevt.lumiblk_no=1;\n anevt.top_hfor_type=0;\n anevt.event_no=eventNumber;\n anevt.TRG_e= trigE;\n anevt.TRG_m= trigM;\n anevt.TRG_j= 0;\n anevt.vxp_maxtrk_no= 9;\n anevt.badjet=0;\n anevt.mcevt_weight=1.0;\n anevt.pileup_weight=1.0;\n anevt.z_vtx_weight = 1.0;\n anevt.weight_bTagSF_77 = 1.0;\n anevt.weight_leptonSF = 1.0;\n anevt.vxpType=0;\n anevt.lar_Error=0;\n anevt.core_Flags=0;\n\tanevt.maxEvents=nentries;\n\n#ifdef __DEBUG__\nstd::cout << \"Filling finished\"<<std::endl;\n#endif\n\n muos_map.insert( pair <string,vector<dbxMuon> > (\"MUO\", muons) );\n eles_map.insert( pair <string,vector<dbxElectron> > (\"ELE\", electrons) );\n taus_map.insert( pair <string,vector<dbxTau> > (\"TAU\", taus) );\n gams_map.insert( pair <string,vector<dbxPhoton> > (\"PHO\", photons) );\n jets_map.insert( pair <string,vector<dbxJet> > (\"JET\", jets) );\n ljets_map.insert( pair <string,vector<dbxJet> > (\"FJET\", ljets) );\n truth_map.insert( pair <string,vector<dbxTruth> > (\"Truth\", truth) );\n combo_map.insert( pair <string,vector<dbxParticle> > (\"Combo\", combos) );\n constits_map.insert( pair <string,vector<dbxParticle> > (\"Constits\", constis) );\n met_map.insert( pair <string,TVector2> (\"MET\", met) );\n\n AnalysisObjects a0={muos_map, eles_map, taus_map, gams_map, jets_map, ljets_map, truth_map, combo_map, constits_map, met_map, anevt};\n\n aCtrl.RunTasks(a0);\n\n }// event loop ends.\n\n aCtrl.Finalize();\n\n}\n" }, { "alpha_fraction": 0.5915420055389404, "alphanum_fraction": 0.5982465147972107, "avg_line_length": 23.54430389404297, "blob_id": "246fadae891c42ae466c830e2f319a93682fe075", "content_id": "0405ca5a9fac042eabd05ef2e6eb4d810f5d2aee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1939, "license_type": "no_license", "max_line_length": 90, "num_lines": 79, "path": "/analysis_core/LoopNode.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// LoopNode.h\n//\n//\n\n#ifndef LoopNode_h\n#define LoopNode_h\n#include \"Node.h\"\n#include <TRandom3.h>\n\n//Looping over variables\nclass LoopNode : public Node{\nprivate:\n double (*f)(std::vector<double>);\n std::vector<bool> (*g)(std::vector<double>);\n std::vector <Node*> lefs;\n TRandom3 rand3; \n\nprotected:\n std::vector<myParticle*> inputParticles;\n\npublic:\n LoopNode(std::vector<bool> (*func)(std::vector<double>), Node* l, std::string s){\n g=func;\n f=NULL;\n symbol=s;\n left=l;\n lefs.push_back(l);\n right=NULL;\n // rand3=new TRandom3();\n }\n LoopNode(double (*func)(std::vector<double>), Node* l, std::string s){\n f=func;\n g=NULL;\n symbol=s;\n left=l;\n lefs.push_back(l);\n right=NULL;\n // rand3=new TRandom3();\n }\n LoopNode(double (*func)(std::vector<double>), std::vector<Node*> ls, std::string s){\n f=func;\n g=NULL;\n symbol=s;\n left=ls[0]; // just in case if someone asks the list of particles for example\n lefs=ls;\n right=NULL;\n // rand3=new TRandom3();\n }\n \n static double getRand(); //{return (rand3.Uniform(0,1) );}\n virtual void getParticles(std::vector<myParticle *>* particles) override{\n left->getParticles(particles);\n }\n\n virtual void getParticlesAt(std::vector<myParticle *>* particles, int index) override{\n left->getParticlesAt(particles,index);\n }\n\n virtual void Reset() override{\n left->Reset();\n }\n\n virtual double evaluate(AnalysisObjects* ao) override;\n \n virtual ~LoopNode() {\n if (left!=NULL) delete left;\n }\n \n};\n\ndouble sumof(std::vector<double> xlist);\ndouble minof(std::vector<double> xlist);\ndouble maxof(std::vector<double> xlist);\nstd::vector<bool> hitmissA(std::vector<double> xlist);\nstd::vector<bool> hitmissR(std::vector<double> xlist);\n\n\n#endif /* LoopNode_h */\n" }, { "alpha_fraction": 0.6226266026496887, "alphanum_fraction": 0.6431962251663208, "avg_line_length": 24.280000686645508, "blob_id": "951072501d2d55e175f64be96f276bd73dd3a7af", "content_id": "27adb42edcb9663bbddb839ac92a54f535c09193", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1265, "license_type": "no_license", "max_line_length": 157, "num_lines": 50, "path": "/parser_test/LFuncNode.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// LFuncNode.h\n// mm\n//\n// Created by Anna-Monica on 8/2/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n\n#ifndef LFuncNode_h\n#define LFuncNode_h\n#include <vector>\n#include \"myParticle.h\"\n#include \"Node.h\"\nusing namespace std;\n//takes care of functions with arguments\nclass LFuncNode : public Node{\nprivate:\n double (*f)(std::vector<myParticle>,std::vector<myParticle>);\n std::vector<myParticle> inputParticles1;\n std::vector<myParticle> inputParticles2;\npublic:\n LFuncNode(double (*func)(std::vector<myParticle>,std::vector<myParticle> ),std::vector<myParticle> input1,std::vector<myParticle> input2,std::string s ){\n f=func;\n symbol=s;\n inputParticles1=input1;\n inputParticles2=input2;\n left=NULL;\n right=NULL;\n }\n \n virtual double evaluate() {\n return (*f)(inputParticles1,inputParticles2);\n }\n virtual ~LFuncNode() {}\n};\n\ndouble dR(vector<myParticle> v,vector<myParticle> w){\n double mass1=0;\n for(vector<myParticle>::iterator i=v.begin();i!=v.end();i++){\n mass1+=i->index;\n }\n double mass2=0;\n for(vector<myParticle>::iterator i=w.begin();i!=w.end();i++){\n mass2+=i->index;\n }\n\n return mass1-mass2;\n}\n\n#endif /* LFuncNode_h */\n" }, { "alpha_fraction": 0.5801405310630798, "alphanum_fraction": 0.5912491679191589, "avg_line_length": 28.993196487426758, "blob_id": "89fa7f100b161230e7804c1568bf911aa3763283", "content_id": "9f46839ddb68efd5f3072f32b68fce1770a1daba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4411, "license_type": "no_license", "max_line_length": 170, "num_lines": 147, "path": "/runs/CLA.sh", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#!/bin/bash\nexport PATH=$PATH:$ROOTSYS/bin\nexport LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ROOTSYS/lib:.:/usr/lib:/usr/lib/system\nEVENTS=0\nINIFILE=CLA.ini\nVERBOSE=5000\nSTRT=0\nDEPS=\" \"\ndatafile=$1\ndatatype=$2\n\nif [ $# -lt 2 ]; then\n echo ERROR: not enough arguments\n echo $0 ROOTfile_name ROOTfile_type [-h]\n cat $0 | grep '|-'|grep -v grep| cut -f1 -d')'\n echo \"ROOT file type can be:\"; grep \"inptype ==\" ../CLA/CLA.C | cut -f3 -d'=' | cut -f1 -d')'\n exit 1\nfi\n\n\n\n\n\nPOSITIONAL=()\nwhile [[ $# -gt 2 ]]\ndo\nkey=\"$3\"\n\ncase $key in\n -i|--inifile)\n INIFILE=\"$4\"\n if [ ! -f \"$INIFILE\" ]; then\n echo \"$INIFILE does NOT exist!\"\n exit 1\n fi\n\n cat ${INIFILE} | grep -v '#' | grep \"region \" > pippo\n cat ${INIFILE} | grep -v '#' | grep \"algo \" >> pippo\n Nalgo=`cat pippo | wc -l`\n rm pippo\n \n # for HistoList command\n if grep -q \"histoList\" \"$INIFILE\"; then\n cp ${INIFILE} ${INIFILE}.tmp\n INIFILE=${INIFILE}.tmp\n fi\n \n while grep -q \"histoList\" \"$INIFILE\"; do #while there is a histoList command in the .ini file, loop continues\n a=($(awk '/histoList/{ print NR; }' \"$INIFILE\")) #get the line numbers where histoList command written\n b=${a[0]} #always work on zeroth variable. Since they will disappear one-by-one, working on the zeroth variable won't cause any harm.\n histListName=$(awk -v b=\"$b\" 'FNR == b {print $2}' ${INIFILE})\n echo \"************\", $histListName\n c=$(awk -v histListName=\"${histListName}\" '$2 == histListName {print NR}' \"$INIFILE\")\n let c++\n whereToInsert=$( awk -v histListName=\"${histListName}\" '$1 == histListName {print NR;}' ${INIFILE}) #get line number to insert\n while grep -w -A1 \"histoList ${histListName}\" ${INIFILE} | grep -q -w 'histo'; do\n awk -v c=\"$c\" -v d=\"${whereToInsert}\" 'NR==c{store=$0;next}1;NR==d{print store}' ${INIFILE} > ${INIFILE}.tmp && cp ${INIFILE}.tmp ${INIFILE} && rm -f ${INIFILE}.tmp\n done\n sed \"/${histListName}/d\" ${INIFILE} > ${INIFILE}.tmp && cp ${INIFILE}.tmp ${INIFILE} && rm -f ${INIFILE}.tmp\n done\n \n if [ $Nalgo -gt 1 ]; then\n echo Analysis with Multiple Regions\n ../scripts/separate_algos.sh ${INIFILE}\n else\n echo Single Analysis\n cp ${INIFILE} BP_1-card.ini\n Nalgo=1\n fi\n shift # past argument\n shift # past value\n ;;\n -e|--events)\n EVENTS=\"$4\"\n shift # past argument\n shift # past value\n ;;\n -s|--start)\n STRT=\"$4\"\n shift # past argument\n shift # past value\n ;;\n -h|--help)\n echo command line arguments:\n cat $0 | grep '|-'|grep -v grep| cut -f1 -d')'\n echo \"ROOT file type can be:\"; grep \"inptype ==\" ../CLA/CLA.C | cut -f3 -d'=' | cut -f1 -d')'\n exit 1\n ;;\n -d|--deps)\n if [ -f \"algdeps.cmd\" ]; then\n DEPS=`cat algdeps.cmd`\n rm -f algdeps.cmd\n fi\n shift # past argument\n ;;\n -v|--verbose)\n VERBOSE=\"$4\"\n shift # past argument\n shift # past value\n ;;\n --default)\n DEFAULT=YES\n shift # past argument\n ;;\n *) # unknown option\n POSITIONAL+=(\"$1\") # save it in an array for later\n shift # past argument\n ;;\nesac\ndone\nset -- \"${POSITIONAL[@]}\" # restore positional parameters\n\nif [ -n ${datafile+x} ] && [ ! -f \"$datafile\" ]; then\n tput setaf 1; echo \"${datafile} does not exist.\"\n tput sgr0\nfi\n\n\n# for ialgo in `seq $Nalgo`; do\n# ../scripts/ini2txt.sh BP_$ialgo\n# done\n\nif [ `echo $LD_LIBRARY_PATH | grep CLA > /dev/null ; echo $?` -ne 0 ]; then\n export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:../CLA/\nfi\n\nrm histoOut-BP_*.root 2>/dev/null \necho ../CLA/CLA.exe $datafile -inp $datatype -BP $Nalgo -EVT $EVENTS -V ${VERBOSE} -ST $STRT ${DEPS}\n../CLA/CLA.exe $datafile -inp $datatype -BP $Nalgo -EVT $EVENTS -V ${VERBOSE} -ST $STRT ${DEPS}\nif [ $? -eq 0 ]; then\n echo \"CutLang finished successfully, now adding histograms\"\n rbase=`echo ${INIFILE} | rev | cut -d'/' -f 1 | rev|cut -f1 -d'.'`\n if [ -f \"histoOut-${rbase}.root\" ]; then\n rm -f histoOut-${rbase}.root\n fi\n hadd histoOut-${rbase}.root histoOut-BP_*.root\n #if histoList command is given, the ${INIFILE}.tmp is produced, and now it gets deleted.\n if grep -q \"histoList\" `echo ${INIFILE} | sed 's/.tmp//g'`; then\n rm -f ${INIFILE}\n fi\n if [ $? -eq 120 ]; then\n echo \"hadd finished successfully, now removing auxiliary files\"\n rm -f histoOut-BP_*.root\n rm -f _head.ini _algos.ini _inifile\n rm -f BP_*-card.ini\n fi\nfi\n\n\n" }, { "alpha_fraction": 0.5732078552246094, "alphanum_fraction": 0.5843316316604614, "avg_line_length": 35.9052619934082, "blob_id": "7468a6227307c09438a609e2d6796cb69ef273d9", "content_id": "abaaf5971b98ae674983ef05da3d7d289e7f7547", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10519, "license_type": "no_license", "max_line_length": 201, "num_lines": 285, "path": "/analysis_core/SFuncNode.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// SFuncNode.h\n// mm\n//\n// Created by Anna-Monica on 8/2/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n\n#ifndef SFuncNode_h\n#define SFuncNode_h\n#include \"Node.h\"\n#include \"Hemisphere.h\"\n#include \"mt2_bisect.h\"\n\n\n//#define _CLV_\n#ifdef _CLV_\n#define DEBUG(a) std::cout<<a\n#else\n#define DEBUG(a)\n#endif\n\nusing namespace std;\n//takes care of functions with arguments\n\nclass SFuncNode : public Node {\nprivate:\n static std::map< std::string, double > BUFFERED_VALUES;\n //should add something related to trigger types\n Node* userObjectA;\n Node* userObjectB;\n double (*f )(AnalysisObjects*, string, float); // the regular\n double (*g1)(AnalysisObjects*, string, int, std::vector<TLorentzVector> (*func)(std::vector<TLorentzVector>, int));\n double (*g2)(AnalysisObjects*, string, int, double (*func)(std::vector<TLorentzVector>));\n double (*g3)(AnalysisObjects*, string, int, double (*func)(std::vector<TLorentzVector>, TVector2 ));\n double (*g4)(AnalysisObjects*, string, int, TLorentzVector, double (*func)(std::vector<TLorentzVector>, TLorentzVector ));\n double (*g5)(AnalysisObjects*, string, int, TLorentzVector, TLorentzVector, TLorentzVector, double (*func)(TLorentzVector, TLorentzVector, TLorentzVector ));\n std::vector<TLorentzVector> (*h1)(std::vector<TLorentzVector>, int);\n double (*h2)(std::vector<TLorentzVector>);\n double (*h3)(std::vector<TLorentzVector>, TVector2 );\n double (*h4)(std::vector<TLorentzVector>, TLorentzVector );\n double (*h5)(TLorentzVector, TLorentzVector, TLorentzVector );\n bool ext;\n int type = 1;\n float value = 1.0;\n std::vector<myParticle*> inputParticlesA;\n std::vector<myParticle*> inputParticlesB;\n std::vector<myParticle*> inputParticlesC;\npublic:\n SFuncNode(double (*func)(AnalysisObjects* ao, string s, float val), \n float val, \n std::string s, \n Node *objectNodeA = NULL, Node *objectNodeB = NULL){\n f=func;\n g1=NULL;\n g2=NULL;\n g3=NULL;\n g4=NULL;\n g5=NULL;\n ext=false;\n value=val;\n symbol=s;\n left=NULL;\n right=NULL;\n userObjectA = objectNodeA;\n userObjectB = objectNodeB;\n\n}\n SFuncNode(double (*func)(AnalysisObjects* ao, string s, float val), Node *child, std::string s, \n Node *objectNodeA = NULL, Node *objectNodeB = NULL){\n f=func;\n g1=NULL;\n g2=NULL;\n g3=NULL;\n g4=NULL;\n g5=NULL;\n ext=false;\n symbol=s;\n left=child;\n right=NULL;\n userObjectA = objectNodeA;\n userObjectB = objectNodeB;\n\n}\n\n//------------------------- g1 with userfuncA\n SFuncNode(double (*func)(AnalysisObjects* ao, string s, int id, std::vector<TLorentzVector> (*gunc) (std::vector<TLorentzVector> jets, int p1)),\n std::vector<TLorentzVector> (*tunc) (std::vector<TLorentzVector> jets, int p1),\n int id, \n std::string s, \n Node *objectNodeA = NULL, Node *objectNodeB = NULL){\n DEBUG(\"*****************************************EXTERN SF :\"<<s <<\"\\n\");\n f=NULL;\n g3=NULL;\n g2=NULL;\n g4=NULL;\n g5=NULL;\n g1=func;\n h1=tunc;\n ext=true;\n type=id;\n symbol=s;\n left=NULL;\n right=NULL;\n userObjectA = objectNodeA;\n userObjectB = objectNodeB;\n}\nSFuncNode(double (*func)(AnalysisObjects* ao, string s, int id, double (*gunc) (std::vector<TLorentzVector> jets)),\n double (*tunc) (std::vector<TLorentzVector> jets),\n int id, \n std::string s, \n Node *objectNodeA = NULL, Node *objectNodeB = NULL){\n DEBUG(\"*****************************************EXTERN SF :\"<<s <<\"\\n\");\n f=NULL;\n g5=NULL;\n g4=NULL;\n g3=NULL;\n g1=NULL;\n g2=func;\n h2=tunc;\n ext=true;\n type=id;\n symbol=s;\n left=NULL;\n right=NULL;\n userObjectA = objectNodeA;\n userObjectB = objectNodeB;\n\n}\nSFuncNode(double (*func)(AnalysisObjects* ao, string s, int id, double (*gunc) (std::vector<TLorentzVector> jets, TVector2 amet)),\n double (*tunc) (std::vector<TLorentzVector> jets, TVector2 amet),\n int id, \n std::string s, \n Node *objectNodeA = NULL, Node *objectNodeB = NULL){\n DEBUG(\"*****************************************EXTERN SF :\"<<s <<\"\\n\");\n f=NULL;\n g1=NULL;\n g2=NULL;\n g4=NULL;\n g5=NULL;\n g3=func;\n h3=tunc;\n ext=true;\n type=id;\n symbol=s;\n left=NULL;\n right=NULL;\n userObjectA = objectNodeA;\n userObjectB = objectNodeB;\n\n}\nSFuncNode(double (*func)(AnalysisObjects* ao, string s, int id, TLorentzVector alv, double (*gunc) (std::vector<TLorentzVector> jets, TLorentzVector amet)),\n double (*tunc) (std::vector<TLorentzVector> jets, TLorentzVector amet),\n int id, \n std::string s,\n std::vector<myParticle*> input, \n Node *objectNodeA = NULL, Node *objectNodeB = NULL){\n DEBUG(\"*****************************************EXTERN SF :\"<<s <<\"\\n\");\n f=NULL;\n g1=NULL;\n g2=NULL;\n g3=NULL;\n g5=NULL;\n g4=func;\n h4=tunc;\n ext=true;\n type=id;\n symbol=s;\n left=NULL;\n right=NULL;\n inputParticlesA=input;\n userObjectA = objectNodeA;\n userObjectB = objectNodeB;\n}\nSFuncNode(double (*func)(AnalysisObjects* ao, string s, int id, TLorentzVector a1, TLorentzVector a2, TLorentzVector b1, double (*gunc) (TLorentzVector lep1, TLorentzVector lep2, TLorentzVector amet)),\n double (*tunc) (TLorentzVector lep1, TLorentzVector lep2, TLorentzVector amet),\n int id, \n std::string s,\n std::vector<myParticle*> input1, \n std::vector<myParticle*> input2, \n std::vector<myParticle*> input3, \n Node *objectNodeA = NULL, Node *objectNodeB = NULL){\n DEBUG(\"*****************************************EXTERN SF T5:\"<<s <<\"\\n\");\n f=NULL;\n g1=NULL;\n g2=NULL;\n g3=NULL;\n g4=NULL;\n g5=func;\n h5=tunc;\n ext=true;\n type=id;\n symbol=s;\n left=NULL;\n right=NULL;\n inputParticlesA=input1;\n inputParticlesB=input2;\n inputParticlesC=input3;\n userObjectA = objectNodeA;\n userObjectB = objectNodeB;\n}\n//---------------------------end of extern function types\n \n virtual double evaluate(AnalysisObjects* ao) override ;\n virtual void Reset() override;\n virtual void getParticles(std::vector<myParticle *>* particles) override{}\n virtual void getParticlesAt(std::vector<myParticle *>* particles, int index) override{}\n virtual void setSymbol(string s) { symbol=s; }\n virtual ~SFuncNode() {}\n};\n\ndouble all(AnalysisObjects* ao, string s, float id);\ndouble uweight(AnalysisObjects* ao, string s, float value);\ndouble lepsf(AnalysisObjects* ao, string s, float value);\ndouble btagsf(AnalysisObjects* ao, string s, float value);\ndouble xslumicorrsf(AnalysisObjects* ao, string s, float value);\ndouble count(AnalysisObjects* ao, string s, float id);\ndouble getIndex(AnalysisObjects* ao, string s, float id); // new internal function\ndouble met(AnalysisObjects* ao, string s, float id);\ndouble hlt_iso_mu(AnalysisObjects* ao, string s, float id);\ndouble ht(AnalysisObjects* ao, string s, float id);\ndouble userfuncA(AnalysisObjects* ao, string s, int id, std::vector<TLorentzVector> (*func)(std::vector<TLorentzVector> jets, int p1) );\ndouble userfuncB(AnalysisObjects* ao, string s, int id, double (*func)(std::vector<TLorentzVector> jets ) );\ndouble userfuncC(AnalysisObjects* ao, string s, int id, double (*func)(std::vector<TLorentzVector> jets, TVector2 amet ) );\ndouble userfuncD(AnalysisObjects* ao, string s, int id, TLorentzVector alv, double (*func)(std::vector<TLorentzVector> jets, TLorentzVector amet ));\ndouble userfuncE(AnalysisObjects* ao, string s, int id, TLorentzVector l1, TLorentzVector l2, TLorentzVector m1,\n double (*func)(TLorentzVector la, TLorentzVector lb, TLorentzVector amet ) );\n\nstd::vector<TLorentzVector> sumobj(std::vector<TLorentzVector> myjets, int p1);\nstd::vector<TLorentzVector> fhemisphere(std::vector<TLorentzVector> myjets, int p1);\ndouble fMT2(TLorentzVector lep1, TLorentzVector lep2, TLorentzVector amet);\n\n\n/*\ndouble nbjets(AnalysisObjects* ao){\n ValueNode abc=ValueNode();\n// return (abc.tagJets(ao, 1).size() );\n return (1);\n}\n\ndouble nljets(AnalysisObjects* ao){\n ValueNode abc=ValueNode();\n// return (abc.tagJets(ao, 0).size() );\n return (1);\n}\n\n\ndouble emwt(AnalysisObjects* ao){\n double theLeptonTrkPhi = ao->eles.at(0).lv().Phi();\n double leppt = ao->eles.at(0).lv().Pt();\n double dphi_e_et = fabs(theLeptonTrkPhi - ao->met.Phi());\n if (dphi_e_et>M_PI) dphi_e_et=2*M_PI-dphi_e_et;\n float mwt=sqrt(2*leppt*ao->met.Mod()*(1-cos(dphi_e_et)));\n return (mwt);\n} \n\ndouble mmwt(AnalysisObjects* ao){\n double theLeptonTrkPhi = ao->muos.at(0).lv().Phi();\n double leppt = ao->muos.at(0).lv().Pt();\n double dphi_e_et = fabs(theLeptonTrkPhi - ao->met.Phi());\n if (dphi_e_et>M_PI) dphi_e_et=2*M_PI-dphi_e_et;\n float mwt=sqrt(2*leppt*ao->met.Mod()*(1-cos(dphi_e_et)));\n return (mwt);\n} \n\ndouble mmetmwt(AnalysisObjects* ao){\n double theLeptonTrkPhi = ao->muos.at(0).lv().Phi();\n double leppt = ao->muos.at(0).lv().Pt();\n double dphi_e_et = fabs(theLeptonTrkPhi - ao->met.Phi());\n if (dphi_e_et>M_PI) dphi_e_et=2*M_PI-dphi_e_et;\n float mwt=sqrt(2*leppt*ao->met.Mod()*(1-cos(dphi_e_et)));\n return (mwt+ao->met.Mod() );\n}\n\ndouble emetmwt(AnalysisObjects* ao){\n double theLeptonTrkPhi = ao->eles.at(0).lv().Phi();\n double leppt = ao->eles.at(0).lv().Pt();\n double dphi_e_et = fabs(theLeptonTrkPhi - ao->met.Phi());\n if (dphi_e_et>M_PI) dphi_e_et=2*M_PI-dphi_e_et;\n float mwt=sqrt(2*leppt*ao->met.Mod()*(1-cos(dphi_e_et)));\n return (mwt+ao->met.Mod() );\n}\n*/\n\n#endif /* SFuncNode_h */\n" }, { "alpha_fraction": 0.6430232524871826, "alphanum_fraction": 0.6476744413375854, "avg_line_length": 20.772151947021484, "blob_id": "483caa095bbe0afd38ded7e330acbf5be655f28f", "content_id": "10d1bdc4e1173d1bed6145d0d4d5ca7fc370c346", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1721, "license_type": "no_license", "max_line_length": 83, "num_lines": 79, "path": "/parser_test/BinaryNode.hpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// AONode.hpp\n// mm\n//\n// Created by Anna-Monica on 8/1/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n\n#ifndef BinaryNode_hpp\n#define BinaryNode_hpp\n\n#include <stdio.h>\n#include <math.h>\n#include \"Node.h\"\n//takes care of Arithmetical Operators, Logical Operators, and Comparison Operators\nclass BinaryNode : public Node{\nprivate:\n double (*f)(double, double);\npublic:\n BinaryNode(double (*func)(double, double), Node* l, Node* r, std::string s){\n f=func;\n symbol=s;\n left=l;\n right=r;\n }\n\n virtual double evaluate(){\n return (*f)(left->evaluate(),right->evaluate());\n }\n virtual ~BinaryNode() {\n// if (left!=NULL) delete left;\n// if (right!=NULL) delete right;\n }\n\n};\n\ndouble add(double left, double right) {\n return left + right;\n}\n\ndouble mult(double left, double right) {\n return left * right;\n}\n\ndouble sub(double left, double right) {\n return left - right;\n}\n\ndouble div(double left, double right) {\n return left / right;\n}\n\n//double power ALREADY EXIST\ndouble lt(double left, double right){\n return (double)(left<right);\n}\ndouble le(double left, double right){\n return (double)(left<=right);\n}\ndouble ge(double left, double right){\n return (double)(left>=right);\n}\ndouble gt(double left, double right){\n return (double)(left>right);\n}\ndouble eq(double left, double right){\n return (double)(left==right);\n}\ndouble ne(double left, double right){\n return (double)(left!=right);\n}\ndouble LogicalAnd(double left, double right){\n return (double)(left&&right);\n}\ndouble LogicalOr(double left, double right){\n return (double)(left||right);\n}\n//if CONDITION-> later\n#endif /* AONode_hpp */\n" }, { "alpha_fraction": 0.557356059551239, "alphanum_fraction": 0.5918976664543152, "avg_line_length": 35.07692337036133, "blob_id": "a68c7b77fb54b90e78e7a9b036654d289edf4d95", "content_id": "b1a5dd5a8aa5ef13f2c23eefc810a69a050d5525", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2345, "license_type": "no_license", "max_line_length": 91, "num_lines": 65, "path": "/analysis_core/PrintEfficiencies.cpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#ifndef __PRINTEFFICIENCIES_C\n#define __PRINTEFFICIENCIES_C\n\n#include <iomanip>\n#include <TH1F.h>\n#include <cmath>\n#include <iostream>\n\n\nvoid PrintEfficiencies(TH1D* effh, bool skip_histos) {\n using namespace std;\n\n // Prints out the efficiencies\n if (!effh) return;\n double eff, err;\n cout << \"Based on \" << effh->GetBinContent(2) << \" events:\\n\";\n\n int s;\n for (s=2; s<=effh->GetNbinsX(); ++s) {\n eff = effh->GetBinContent(s) / effh->GetBinContent(s-1);\n err = sqrt(eff*(1-eff)/effh->GetBinContent(s-1));\n TString cutname=effh->GetXaxis()->GetBinLabel(s);\n if ( cutname.Sizeof() <1) break;\n if (skip_histos) { if ( cutname.BeginsWith(\"[Histo]\") ) continue; }\n cout << setw(66) << effh->GetXaxis()->GetBinLabel(s)\n\t << \" : \" << setw(6) << setprecision(4) << eff\n\t << \" +- \" << setw(9) << setprecision(3) << err \n << setw(6) <<\" evt: \"<<setw(8)<< setprecision(10)<<effh->GetBinContent(s) <<endl; \n }\n eff = effh->GetBinContent(s-1) / effh->GetBinContent(2);\n err = sqrt(eff*(1-eff)/effh->GetBinContent(2));\n cout << \"\\t\\t\\t\\t\\t --> Overall efficiency\\t = \"\n << setw(6) << setprecision(3) << eff*100.\n << \" % +- \" << setw(6) << setprecision(3) << err*100. << \" %\" <<endl; \n return;\n}\n\nvoid ComputeEfficiences(TH1D *eff1, double xsec1, TH1F *eff2, double xsec2) {\n using namespace std;\n\n // Compute and print out efficiencies by combining two separate samples\n if (!eff1 || !eff2) return;\n if (eff1->GetNbinsX() != eff2->GetNbinsX()) return;\n\n cout << \"Based on \" << eff1->GetBinContent(2) << \" events with xsec=\"\n << xsec1 << \" and \" << eff2->GetBinContent(2)\n << \" events with xsec=\" << xsec2 << endl;\n\n double eff(0), before(1), after(0);\n\n for (int s=2; s<=eff1->GetNbinsX(); ++s) {\n before = xsec1 * eff1->GetBinContent(s-1) / eff1->GetBinContent(2)\n + xsec2 * eff2->GetBinContent(s-1) / eff2->GetBinContent(2);\n after = xsec1 * eff1->GetBinContent(s) / eff1->GetBinContent(2)\n + xsec2 * eff2->GetBinContent(s) / eff2->GetBinContent(2);\n eff = after / before;\n cout << \"Efficiency for \" << eff1->GetXaxis()->GetBinLabel(s) << \"\\t = \"\n\t << setw(6) << setprecision(4) << eff << endl; }\n\n eff = after / (xsec1+xsec2);\n cout << \" --> Overall efficiency\\t = \"\n\t<< setw(6) << setprecision(4) << eff*100. << endl;\n return;\n}\n#endif\n" }, { "alpha_fraction": 0.5514557957649231, "alphanum_fraction": 0.55870121717453, "avg_line_length": 37.025508880615234, "blob_id": "3c79e0156c0dac9aae21c53b42d4d3b02391ad29", "content_id": "4ec3f14728d9fdcf5384f49589feb590edb883de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7453, "license_type": "no_license", "max_line_length": 130, "num_lines": 196, "path": "/runs/CLA.py", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport os\nimport sys\nimport glob\nimport platform\nimport concurrent.futures\n\n\n# noinspection PyShadowingBuiltins,PyShadowingNames\ndef help():\n for i in placeholders:\n for j in i:\n print(j, end=' ')\n print(\"\")\n print('ROOT file type can be:')\n os.system('grep \"inptype ==\" ../CLA/CLA.C | cut -f3 -d\\'=\\' | cut -f1 -d\\')\\'')\n\n\n# noinspection PyShadowingNames,SpellCheckingInspection\ndef removePattern(pattern):\n if type(pattern) is str:\n for i in glob.glob(pattern):\n try:\n os.remove(i)\n except FileNotFoundError:\n pass\n elif type(pattern) is list:\n for i in pattern:\n try:\n os.remove(i)\n except FileNotFoundError:\n pass\n\n\ndef getStringCount(filename, query):\n n = 0\n if type(query) is str:\n for line in open(filename).readlines():\n if query in line and '#' not in line:\n n += 1\n elif type(query) is list:\n for line in open(filename).readlines():\n for single_query in query:\n if single_query in line and '#' not in line:\n n += 1\n return n\n\n\n# noinspection PyShadowingNames\ndef singleAnalysis(arguments, histoId=None):\n algorithm_count = getStringCount(arguments['inifile'], ['region', 'algo'])\n if algorithm_count > 1:\n print(\"Analysis with Multiple Regions\")\n os.system(base_dir + \"scripts/separate_algos.sh \" + arguments['inifile'])\n else:\n print(\"Single Analysis\")\n os.system(\"cp \" + arguments['inifile'] + \" BP_1-card.ini\")\n\n removePattern('histoOut-BP_*.root')\n print(base_dir + 'CLA/CLA.exe $datafile -inp $datatype -BP $Nalgo -EVT $EVENTS -V ${VERBOSE} -ST $STRT')\n res = os.system('export PATH=$PATH:$ROOTSYS/bin ;\\\n export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ROOTSYS/lib:.:/usr/lib:/usr/lib/system:../CLA/ ;\\\n ' + base_dir + 'CLA/CLA.exe ' + arguments['datafile'] + ' -inp ' + arguments['datatype'] + ' -BP ' + str(\n algorithm_count) + ' -EVT ' + str(arguments['events']) + ' -V ' + str(arguments['verbose']) + ' -ST ' + str(\n arguments['start']))\n\n if res == 0:\n print('CutLang finished successfully, now adding histograms')\n try:\n os.remove('histoOut-' + arguments['inifile'].split('/')[-1][:-4] + '.root')\n except FileNotFoundError:\n pass\n if histoId is not None:\n hadd_query = 'hadd -f histoOut-' + arguments['inifile'].split('/')[-1][:-4] + str(histoId) + '.root'\n else:\n hadd_query = 'hadd -f histoOut-' + arguments['inifile'].split('/')[-1][:-4] + '.root'\n for i in glob.glob('histoOut-BP_*.root'):\n hadd_query += \" \" + i\n res = os.system(hadd_query)\n if res == 120:\n print(\"hadd finished successfully, now removing auxiliary files\")\n removePattern('histoOut-BP_*.root')\n removePattern(['_head.ini', '_algos.ini', '_inifile'])\n removePattern('BP_*-card.ini')\n return res\n\n\nplaceholders = [\n [\"-i\", \"--inifile\"],\n [\"-e\", \"--events\"],\n [\"-j\", \"--parallel\"],\n [\"-s\", \"--start\"],\n [\"-v\", \"--verbose\"],\n [\"-h\", \"--help\"]]\n\nif '-h' in sys.argv or '--help' in sys.argv:\n help()\n sys.exit(1)\n\nif len(sys.argv) < 3:\n print(\"ERROR: Not enough arguments\")\n help()\n sys.exit(1)\n\narguments = {'inifile': \"CLA.ini\",\n 'datafile': sys.argv[1],\n 'datatype': sys.argv[2],\n 'parallel': 1,\n 'verbose': 5000,\n 'events': 0,\n 'start': 0}\nPOSITIONAL = ()\n\nfor i, arg in enumerate(sys.argv[3::2]):\n if arg in placeholders[3]:\n print(\"command line arguments:\")\n help()\n sys.exit(1)\n elif arg in placeholders[i]:\n arguments[placeholders[i][1][2:]] = sys.argv[i * 2 + 4]\n\narguments['parallel'] = int(arguments['parallel']) // 1\nif not os.path.exists(arguments['datafile']):\n sys.exit(arguments['datafile'] + \" does not exist.\")\n\nalgorithm_count = getStringCount(arguments['inifile'], ['region', 'algo'])\nn_cpu = os.cpu_count()\nbase_dir = os.path.dirname(os.path.abspath(__file__))[:-4]\n\nif arguments['parallel'] > n_cpu or arguments['parallel'] == 0:\n arguments['parallel'] = n_cpu - 1\n\nif arguments['parallel'] > 1:\n # skip_count = getStringCount(arguments['inifile'], ['SkipHistos', 'SkipEffs'])\n skip_histos = getStringCount(arguments['inifile'], 'SkipHistos')\n skip_effs = getStringCount(arguments['inifile'], 'SkipEffs')\n print(\"Using\", arguments['parallel'], \"cores\")\n if int(arguments['events']) == 0:\n arguments['events'] = int(os.popen('../scripts/event_count.sh ' + arguments['datafile']).read().split()[-1])\n print(\"*\" * 100,\n base_dir + 'CLA/CLA.exe $datafile -inp $datatype -BP $Nalgo -EVT $EVENTS -V ${VERBOSE} -ST $STRT -PLL ${PRLL}',\n sep='\\n')\n\n os.system('rm -r temp')\n temp_dir = 'temp'\n os.mkdir(temp_dir)\n for i in range(arguments['parallel']):\n dir_name = 'cut_' + str(i)\n os.mkdir(os.path.join(temp_dir, dir_name))\n os.system(\n 'mkdir ' + os.path.join(temp_dir, dir_name) + '/runs; cp ' + base_dir + 'runs/* ' + os.path.join(temp_dir,\n dir_name) + '/runs/')\n os.system('cp -r ' + base_dir + 'CLA ' + os.path.join(temp_dir, dir_name))\n os.system('cp -r ' + base_dir + 'analysis_core ' + os.path.join(temp_dir, dir_name))\n os.system('cp -r ' + base_dir + 'BP ' + os.path.join(temp_dir, dir_name))\n # Copied {runs, CLA, analysis_core, BP}\n removePattern('histoOut-BP_*.root')\n print(dir_name, 'copied from runs')\n\n interval = int(arguments['events']) // arguments['parallel']\n processes = []\n for i in range(arguments['parallel']):\n cur_arguments = arguments.copy()\n cur_arguments['start'] = cur_arguments['start'] + interval * i\n cur_arguments['events'] = interval\n if i + 1 == arguments['parallel']:\n cur_arguments['events'] += int(arguments['events']) % interval\n cur_arguments['inifile'] = temp_dir + '/cut_' + str(i) + '/runs/' + arguments['inifile']\n processes.append(cur_arguments)\n\n with concurrent.futures.ThreadPoolExecutor(max_workers=arguments['parallel']) as executor:\n executor.map(singleAnalysis, processes)\n executor.shutdown(wait=True)\n\n try:\n os.remove('histoOut-' + arguments['inifile'][:-4] + '.root')\n except FileNotFoundError:\n pass\n arguments['inifile'] = arguments['inifile'].split('/')[-1][:-4]\n res = 0\n\n for i in os.listdir(base_dir + 'runs/temp/'):\n res = os.system(\n 'hadd -a histoOut-' + arguments['inifile'] + '.root ' + base_dir + 'runs/temp/' + i + '/runs/histoOut-' +\n arguments['inifile'] + '.root')\n print(\"removing auxiliary files\")\n if res == 0:\n os.system('root -l -q \\'' + base_dir + 'analysis_core/FinalEff.C(\"' + base_dir + 'runs/histoOut-' + arguments[\n 'inifile'] + '.root\", \\'' + str(skip_histos) + '\\', \\'' + str(skip_effs) + '\\')\\'')\n removePattern('histoOut-BP_*.root')\n removePattern(['_head.ini', '_algos.ini', '_inifile'])\n removePattern('BP_*-card.ini')\n os.system('rm -r temp')\nelse:\n singleAnalysis(arguments)\n" }, { "alpha_fraction": 0.644518256187439, "alphanum_fraction": 0.6544850468635559, "avg_line_length": 49.16666793823242, "blob_id": "7efabcea9bc520b6f267df71b595363af7eb1395", "content_id": "099ca0ba442ac48631018b2f810d43fe13014936", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "Shell", "length_bytes": 301, "license_type": "no_license", "max_line_length": 97, "num_lines": 6, "path": "/.github/workflows/filter.sh", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\necho $'Efficacy Charts:\\n' | tee ./efficacy_charts.txt \ncat ./raw_output.txt | grep -e Overall -e .adl -e SOD -e DELPHES | tee -a ./efficacy_charts.txt\necho $'Errors: \\n' | tee ./errors.txt\ncat ./raw_output.txt | grep -A10 -B5 --colour -e error -e WARNING -e syntax | tee -a ./errors.txt\n" }, { "alpha_fraction": 0.5244817137718201, "alphanum_fraction": 0.5430404543876648, "avg_line_length": 38.88188934326172, "blob_id": "18f74e93733817bab6115c55d7e525f118c96261", "content_id": "e5755e9db877fc4438dda5b2ff8876fcee568b9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10130, "license_type": "no_license", "max_line_length": 130, "num_lines": 254, "path": "/analysis_core/LoopNode.cpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// LoopNode.cpp\n//\n//\n\n#ifndef LoopNode_cpp\n#define LoopNode_cpp\n#include \"LoopNode.h\"\n#include \"FuncNode.h\"\n#include \"LFuncNode.h\"\n#include <TRandom3.h>\n\n//#define _CLV_\n#ifdef _CLV_\n#define DEBUG(a) std::cout<<a\n#else\n#define DEBUG(a)\n#endif\n\nTRandom3 MYrand4;\n\ndouble LoopNode::getRand(){\n double rv=MYrand4.Uniform(0,1);\n std::cout<<\"RAND:\"<<rv<<\"\\n\";\n return rv;\n};\n\ndouble LoopNode::evaluate(AnalysisObjects* ao) {\n // here we need to loop over all functions\n std::vector <double> result_list;\n double retval;\n std::string bcol2;\n int ipart2_max;\n\n DEBUG(\"\\nWe are in LoopNode, \"<<this->getStr()<<\"\\n\");\n DEBUG(\"LeftNodes size:\"<<lefs.size()<<\"\\n\");\n for (int in=0; in<lefs.size(); in++){ // loop over all possible left branches.\n left=lefs[in];\n this->getParticles(&inputParticles); \n \n bool oneParticleAtATime=false;\n for (int ii=0; ii<inputParticles.size(); ii++){\n DEBUG(\"Loop particle ID:\"<<ii<<\" Type:\"<<inputParticles[ii]->type<<\" collection:\"\n << inputParticles[ii]->collection << \" index:\"<<inputParticles[ii]->index<<\"\\n\");\n if (inputParticles[ii]->index > 9999) oneParticleAtATime=true; \n }\n ipart2_max=0; // loop counter\n bool constiloop=false;\n std::string consname;\n int base_type2=inputParticles[0]->type;\n std::vector<myParticle*> spareParticles;\n\n if (inputParticles[0]->index==16213 || inputParticles[0]->index==6213) // here we loop over all particles in the collection\n {\n bcol2=inputParticles[0]->collection;\n consname=bcol2;\n try {\n switch(inputParticles[0]->type){\n case muon_t: ipart2_max=(ao->muos).at(bcol2).size(); break;\n case truth_t: ipart2_max=(ao->truth).at(bcol2).size(); break;\n case electron_t: ipart2_max=(ao->eles).at(bcol2).size(); break;\n case jet_t: ipart2_max=(ao->jets).at(bcol2).size(); break;\n case pureV_t: ipart2_max=1; break;\n case photon_t: ipart2_max=(ao->gams).at(bcol2).size(); break;\n case fjet_t: ipart2_max=(ao->ljets).at(bcol2).size(); break;\n case tau_t: ipart2_max=(ao->taus).at(bcol2).size(); break;\n case combo_t: ipart2_max=(ao->combos)[bcol2].size(); break;\n case consti_t: {constiloop=true;\n TString konsname=bcol2;\n konsname+=\"_\";\n konsname+=inputParticles[0]->index;\n konsname+=\"c\";\n consname=(std::string)konsname;\n ipart2_max =(ao->constits).find(consname)->second.size();\n DEBUG(consname<<\" has \"<<ipart2_max<<\" constituents\\n\");\n base_type2=consti_t;\n break;}\n\n\n default:\n std::cerr << \"WRONG PARTICLE TYPE:\"<<inputParticles[0]->type << std::endl; break;\n }\n } catch(...) {\n std::cerr << \"YOU WANT TO LOOP A PARTICLE TYPE YOU DIDN'T CREATE:\"<<bcol2 <<\" !\\n\";\n _Exit(-1);\n }\n // now we know how many we want\n DEBUG (\"loop over \"<< ipart2_max<<\" particles\\n\");\n if (inputParticles[0]->index==16213) {\n for (int ii=0; ii<ipart2_max; ii++) {\n myParticle* a = new myParticle;\n a->type = base_type2; a->index =ii; a->collection =bcol2;\n spareParticles.push_back(a); \n }\n }\n for (int ii=0; ii<spareParticles.size(); ii++){\n DEBUG(\"Loop spare particle ID:\"<<ii<<\" Type:\"<<spareParticles[ii]->type<<\" collection:\"\n << spareParticles[ii]->collection << \" index:\"<<spareParticles[ii]->index<<\"\\n\");\n }\n }\n\n if (inputParticles.size()==1 && inputParticles[0]->index==6213) // here we loop over all particles in the collection\n {\n DEBUG(\"Looping one by one\\n\");\n FuncNode *pippo;\n DEBUG(\"it will do: \"<<left->getStr()<<\"\\n\");\n if (pippo=dynamic_cast< FuncNode*>(left) ) {\n DEBUG(\"downcast OK\\n\");\n } else {\n DEBUG(\"downcast FAILS\\n\");\n if (pippo=dynamic_cast< FuncNode*>(left->left) ) {\n DEBUG(\"down-downcast OK\\n\");\n }\n }\n \n for (int ii=0;ii<ipart2_max; ii++){\n DEBUG(\"now for particle \"<<ii<<\"\\n\");\n pippo->setParticleIndex(0, ii);\n DEBUG(\"I will do: \"<<left->getStr()<<\"\\t\");\n DEBUG(\"over: \"<<right<<\"\\n\");\n if (inputParticles[0]->index != 6213){\n pippo->setParticleType(0, base_type2);\n pippo->setParticleCollection(0, consname);\n }\n retval=left->evaluate(ao);\n DEBUG(\"Loop retval:\"<<retval<<\"\\n\");\n result_list.push_back(retval); \n }\n pippo->setParticleIndex(0, 6213);\n } else if(oneParticleAtATime){ // here we give an explicit list, like 1,3,4,6..\n DEBUG(\"Explicit list in LoopNode #:\"<<inputParticles.size()<<\" #spares:\"<< spareParticles.size() <<\"\\n\");\n if (spareParticles.size() == 0 )\n for (int ii=0;ii<inputParticles.size(); ii++){\n int anindex=inputParticles[ii]->index;\n if (anindex > 9999) { // Indices around 10000 are to be looped over\n ((LFuncNode*)left)->setParticleIndex(ii, anindex-10000 );\n retval=left->evaluate(ao);\n DEBUG(\"retval:\"<<retval<<\"\\n\");\n result_list.push_back(retval); \n ((LFuncNode*)left)->setParticleIndex(ii, anindex );\n }\n DEBUG(\"end of loop\\n\");\n }// endof over loop over particles for explicit list\n else {\n for (int ii=0;ii<spareParticles.size(); ii++){\n int anindex=spareParticles[ii]->index;\n ((LFuncNode*)left)->setParticleIndex(0, anindex);\n retval=left->evaluate(ao);\n DEBUG(\"retval:\"<<retval<<\"\\n\");\n result_list.push_back(retval); \n }\n ((LFuncNode*)left)->setParticleIndex(0, 16213);\n DEBUG(\"end of loop\\n\");\n }// endof over loop over particles for implicit list, 0 to many\n\n } else {\n//--------- here we will simply evaluate the left node and push the result, we use this in object definition\n DEBUG(\"Obj Driven Loop node, just push the result\\n\");\n DEBUG(\"Size:\"<<inputParticles.size()<<\"\\n\");\n retval=left->evaluate(ao);\n DEBUG(\"retval:\"<<retval<<\"\\n\");\n result_list.push_back(retval); \n }\n }// end of loop over multiple lefts\n\n if (g==NULL) { return (*f)(result_list);} // 1D case\n else {\n std::vector<bool> retvals=(*g)(result_list);\n if (inputParticles.size()==1) { // here we loop over all particles in the collection\n if (retvals.size() < ipart2_max) {\n std::cerr <<\"HitMiss LoopObj has a problem\\n\"; exit(12);\n } else { // we return the status for one particle, the loop is driven by the object loop\n return retvals[0];\n }\n for (int ii=ipart2_max-1; ii>=0; ii--){\n if (!retvals[ii]) { // we will kill this guy\n DEBUG(\"Killing \"<<ii<<\"th of \"<<bcol2<<\"\\n\");\n switch(inputParticles[0]->type){\n case muon_t: ( ao->muos)[bcol2].erase((ao->muos ).find(bcol2)->second.begin()+ii); break;\n case truth_t: (ao->truth)[bcol2].erase((ao->truth ).find(bcol2)->second.begin()+ii); break;\n case electron_t: ( ao->eles)[bcol2].erase((ao->eles ).find(bcol2)->second.begin()+ii); break;\n case jet_t: ( ao->jets)[bcol2].erase((ao->jets ).find(bcol2)->second.begin()+ii); break;\n case photon_t: ( ao->gams)[bcol2].erase((ao->gams ).find(bcol2)->second.begin()+ii); break;\n case fjet_t: (ao->ljets)[bcol2].erase((ao->ljets ).find(bcol2)->second.begin()+ii); break;\n case tau_t: ( ao->taus)[bcol2].erase((ao->taus ).find(bcol2)->second.begin()+ii); break;\n case combo_t: (ao->combos)[bcol2].erase((ao->combos).find(bcol2)->second.begin()+ii); break;\n case pureV_t: break;\n }//loop over switch \n }// loop over kill \n } // loop over particles and results\n } // loop over all particles or not\n return 1;\n }\n}\n\n\ndouble sumof(std::vector<double> xlist){\n double retval=0;\n for (unsigned int ii=0; ii<xlist.size(); ii++) retval+=xlist[ii];\n DEBUG(\"Sum:\"<<retval<<\"\\n\");\n return retval;\n}\n\ndouble minof(std::vector<double> xlist){\n double retval=999999999999.9;\n for (unsigned int ii=0; ii<xlist.size(); ii++) {\n if (xlist[ii]< retval) retval=xlist[ii];\n }\n DEBUG(\"min:\"<<retval<<\"\\n\");\n return retval;\n}\n\ndouble maxof(std::vector<double> xlist){\n double retval=-999999999999.9;\n for (unsigned int ii=0; ii<xlist.size(); ii++) {\n if (xlist[ii]> retval) retval=xlist[ii];\n }\n DEBUG(\"max:\"<<retval<<\"\\n\");\n return retval;\n}\n//-----------------------------------------------------\nstd::vector<bool> hitmissA(std::vector<double> xlist){\n// random number setup is here\n std::vector<bool> retvals;\n\n for (unsigned int ii=0; ii<xlist.size(); ii++) {\n //double r = LoopNode::getRand();\n double r = MYrand4.Uniform(0,1);\n// std::cout <<r<<\"\\n\";\n DEBUG(\"hit/miss to Accept:\"<<xlist[ii]<< \" vs \" << r << \"\\t\");\n if (xlist[ii]< r ) { retvals.push_back(false); DEBUG(\"Missed.\\n\");} \n else { retvals.push_back(true); DEBUG(\"Hit.\\n\"); }\n }\n return retvals;\n}\n\n//-----------------------------------------------------\nstd::vector<bool> hitmissR(std::vector<double> xlist){\n// random number setup is here\n std::vector<bool> retvals;\n\n for (unsigned int ii=0; ii<xlist.size(); ii++) {\n double r = MYrand4.Uniform(0,1);\n// double r = LoopNode::getRand();\n// std::cout <<r<<\"\\n\";\n DEBUG(\"hit/miss to Reject:\"<<xlist[ii]<< \" vs \" << r << \"\\t\");\n if (xlist[ii]> r ) { retvals.push_back(false); DEBUG(\"Missed.\\n\");} \n else { retvals.push_back(true); DEBUG(\"Hit.\\n\"); }\n }\n return retvals;\n}\n\n \n#endif /* LoopNode_cpp */\n" }, { "alpha_fraction": 0.6144200563430786, "alphanum_fraction": 0.6175548434257507, "avg_line_length": 29.870967864990234, "blob_id": "52fb0479869d514687fb7d288cd3543b26093dd9", "content_id": "f2f91a73155e4aeea3e8ff5f0120b568d5ef7a73", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "JavaScript", "length_bytes": 957, "license_type": "no_license", "max_line_length": 146, "num_lines": 31, "path": "/.github/workflows/sendgrid.js", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#! /usr/bin/env node\n\nconst sgMail = require('@sendgrid/mail');\nsgMail.setApiKey(process.env.SENDGRID_API_KEY);\n\nconst fs = require('fs'),\n filename = 'errors.txt',\n fileType = 'plain/text',\n data = fs.readFileSync('./.github/workflows/artifacts/' + filename);\n\nconst error_message = fs.readFileSync('./.github/workflows/artifacts/temp.txt', 'utf8')\n\nconst msg = {\n to: ['[email protected]','[email protected]','[email protected]','[email protected]'],\n from: '[email protected]',\n subject: 'CutLang Build Report',\n text: 'Built successfully but run errors reported. Output file as attached.\\nErrors:\\n'+error_message+'\\nError context in attached document.',\n attachments: [\n {\n content: data.toString('base64'),\n filename: filename,\n type: fileType,\n disposition: 'attachment',\n },\n ],\n};\n\nsgMail\n .send(msg)\n .then(() => console.log('Mail sent successfully'))\n .catch(error => console.error(error.toString()));\n" }, { "alpha_fraction": 0.5948509573936462, "alphanum_fraction": 0.6056910753250122, "avg_line_length": 19.5, "blob_id": "b660e7a85f8f1e63620c547f85eb1ff45cab3ecc", "content_id": "6ed6c7578f5b0645cd47a23d535081edc2f0bd5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 739, "license_type": "no_license", "max_line_length": 64, "num_lines": 36, "path": "/parser_test/UnaryAONode.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// UnaryAONode.h\n// mm\n//\n// Created by Anna-Monica on 8/1/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n\n#ifndef UnaryAONode_h\n#define UnaryAONode_h\n#include \"Node.h\"\n//takes care of Unary Minus and other Math.h functions\nclass UnaryAONode : public Node{\nprivate:\n double (*f)(double);\npublic:\n UnaryAONode(double (*func)(double), Node* l, std::string s){\n f=func;\n symbol=s;\n left=l;\n right=NULL;\n }\n \n virtual double evaluate() {\n return (*f)(left->evaluate());\n }\n virtual ~UnaryAONode() {\n if (left!=NULL) delete left;\n }\n \n};\ndouble unaryMinu(double left) {\n return -left;\n}\n//double COS SIN TAN ALREADY EXIST\n#endif /* UnaryAONode_h */\n" }, { "alpha_fraction": 0.5523281693458557, "alphanum_fraction": 0.5716424584388733, "avg_line_length": 38.755950927734375, "blob_id": "6fead6345cd9ce1afbb5cfcaef0bd7db1081bdb0", "content_id": "1e167ffcb53ca9bb101571ad36e5e61aed049ed5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6679, "license_type": "no_license", "max_line_length": 314, "num_lines": 168, "path": "/analysis_core/LFuncNode.cpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#include \"LFuncNode.h\"\n\n//#define _CLV_\n#ifdef _CLV_\n#define DEBUG(a) std::cout<<a\n#else\n#define DEBUG(a)\n#endif\n\nvoid LFuncNode::ResetParticles() {\n for(int i=0;i<originalParticles.size();i++){\n *(inputParticles[i])=originalParticles[i];\n\n }\n for(int i=0;i<originalParticles2.size();i++){\n *(inputParticles2[i])=originalParticles2[i];\n\n }\n }\n\nvoid LFuncNode::setParticleIndex(int order, int newIndex) {\n if(order<inputParticles.size()){\n inputParticles.at(order)->index=newIndex;\n }\n else{\n inputParticles2.at(order-inputParticles.size())->index=newIndex;\n }\n }\n \n\nLFuncNode::LFuncNode(double (*func)(dbxParticle* part1,dbxParticle* part2),std::vector<myParticle*> input1,std::vector<myParticle*> input2,std::string s, Node *objectNodea, Node *objectNodeb, Node *objectNodec, Node *objectNoded ) : FuncNode(NULL,input1,s, objectNodea,\"\", objectNodeb, objectNodec, objectNoded) {\n//after objnodea the correct string needs to be put, NGU-----\n f2=func;\n inputParticles2=input2;\n myParticle apart2;\n userObjectA=objectNodea;\n userObjectB=objectNodeb;\n userObjectC=objectNodec;\n userObjectD=objectNoded;\n\n for (int i=0; i<input2.size(); i++){\n apart2.index=input2[i]->index;\n apart2.type=input2[i]->type;\n apart2.collection=input2[i]->collection;\n originalParticles2.push_back(apart2);\n }\n }\n \n\nvoid LFuncNode::getParticles(std::vector<myParticle *>* particles) {\n// cout<<\"MODIFY TO CHECK FOR EXISTING INDICES in ListFuncNode------\\n\";\n int size=particles->size();\n for (int i=0; i<inputParticles.size(); i++){\n bool found=false;\n for(int j=0;j<size;j++){\n if (inputParticles[i]->index==particles->at(j)->index)\n { found=true;break; }\n }\n if(!found){ particles->push_back(inputParticles[i]); }\n\n } \n for (int i=0; i<inputParticles2.size(); i++){\n bool found=false;\n for(int j=0;j<size;j++){\n if (inputParticles2[i]->index==particles->at(j)->index)\n { found=true;break; }\n }\n if(!found){ particles->push_back(inputParticles2[i]); }\n } \n }\n\nvoid LFuncNode::getParticlesAt(std::vector<myParticle *>* particles, int index){\n particles->push_back(inputParticles[index]);\n particles->push_back(inputParticles2[index]);\n}\n\nvoid LFuncNode::setUserObjects(Node *objectNodea, Node *objectNodeb, Node *objectNodec, Node *objectNoded){\n userObjectA=objectNodea;\n userObjectB=objectNodeb;\n userObjectC=objectNodec;\n userObjectD=objectNoded;\n}\n\n \ndouble LFuncNode::evaluate(AnalysisObjects* ao) {\n DEBUG(\"In L function Node evaluate: \"<< inputParticles.size() << \",\"<< inputParticles2.size()<<\"\\n\");\n\n if(userObjectA) userObjectA->evaluate(ao); // returns 1, hardcoded. see ObjectNode.cpp\n if(userObjectB) userObjectB->evaluate(ao); // returns 1, hardcoded. see ObjectNode.cpp\n if(userObjectC) userObjectC->evaluate(ao); // returns 1, hardcoded. see ObjectNode.cpp\n if(userObjectD) userObjectD->evaluate(ao); // returns 1, hardcoded. see ObjectNode.cpp\n\n for (int jj=0; jj< inputParticles.size(); jj++){\n DEBUG(\"P0_\"<<jj<<\" Type:\"<<inputParticles[jj]->type<< \" index:\"<<inputParticles[jj]->index<<\"\\n\");\n }\n DEBUG(\"P1_0 Type:\"<<inputParticles2[0]->type<<\" collection:\"<< inputParticles2[0]->collection << \" index:\"<<inputParticles2[0]->index<<\"\\n\");\n if ( inputParticles2[0]->index == 6213) {\n string base_collection2=inputParticles2[0]->collection;\n int base_type2=inputParticles2[0]->type;\n int ipart2_max=-1;\n try {\n switch(abs(inputParticles2[0]->type)){\n case 0: ipart2_max=(ao->muos).at(base_collection2).size(); break;\n case 10: ipart2_max=(ao->truth).at(base_collection2).size(); break;\n case 1: ipart2_max=(ao->eles).at(base_collection2).size(); break;\n case 2: ipart2_max=(ao->jets).at(base_collection2).size(); break;\n case 7: ipart2_max=1; break;\n case 8: ipart2_max=(ao->gams).at(base_collection2).size(); break;\n case 9: ipart2_max=(ao->ljets).at(base_collection2).size(); break;\n case 11: ipart2_max=(ao->taus).at(base_collection2).size(); break;\n case 20: ipart2_max=(ao->combos)[base_collection2].size(); break;\n\n default:\n std::cerr << \"WRONG PARTICLE TYPE:\"<<inputParticles2[0]->type << std::endl; break;\n }\n } catch(...) {\n std::cerr << \"YOU WANT A PARTICLE TYPE YOU DIDN'T CREATE:\"<<base_collection2 <<\" !\\n\";\n _Exit(-1);\n }\n // now we know how many we want\n DEBUG (\"Sum \"<< ipart2_max<<\" particles\\t\");\n std::vector<myParticle*> inputParticles1;\n std::vector<myParticle> inputParticles0;\n for (int ip2=0; ip2 < ipart2_max; ip2++){\n myParticle * aparticle = new myParticle;\n aparticle->type= base_type2;\n aparticle->collection= base_collection2;\n aparticle->index=ip2;\n DEBUG( \"index=\"<<ip2<<\" \");\n inputParticles0.push_back(*aparticle);\n delete aparticle;\n }\n DEBUG(\"\\n\");\n for (int ji=0; ji<inputParticles0.size(); ji++){\n inputParticles1.push_back( &inputParticles0[ji]);\n }\n partConstruct(ao, &inputParticles1,&myPart2);\n inputParticles0.clear();\n inputParticles1.clear();\n } else {\n partConstruct(ao, &inputParticles2,&myPart2);\n }\n \n partConstruct(ao, &inputParticles,&myPart);\n return (*f2)(&myPart,&myPart2);\n}\n\nLFuncNode::~LFuncNode() {}\n \n\n\ndouble dR(dbxParticle* apart,dbxParticle* apart2){\n double deltaR=apart->lv().DeltaR(apart2->lv() );\n DEBUG(\" dR:\"<<deltaR<<\"\\t\");\n return deltaR;\n}\n\ndouble dPhi(dbxParticle* apart,dbxParticle* apart2){\n double deltaPhi=fabs(apart->lv().DeltaPhi(apart2->lv() ) );\n DEBUG(\" dPhi:\"<<deltaPhi<<\"\\t\");\n return deltaPhi;\n}\n\ndouble dEta(dbxParticle* apart,dbxParticle* apart2){\n double deltaEta=fabs(apart->lv().Eta() - apart2->lv().Eta() );\n DEBUG(\" dEta:\"<<deltaEta<<\"\\t\");\n return deltaEta;\n}\n" }, { "alpha_fraction": 0.6005982160568237, "alphanum_fraction": 0.6155533194541931, "avg_line_length": 33.82638931274414, "blob_id": "46851667319b29e977eb32a18d34825d5aebbe6d", "content_id": "7f65343405fd46a27e9a1d89c2ca841ca9a58927", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5015, "license_type": "no_license", "max_line_length": 105, "num_lines": 144, "path": "/analysis_core/ReadCard.cpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "#ifndef __READCARD_CPP\n#define __READCARD_CPP\n\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <bitset>\n#include <stdlib.h>\n\n#include \"ReadCard.h\"\n// If the variable cannot be found in the cardfile or the cardfile\n// has problems, the 3rd argument defval is returned.\n// The fourth argument can be set to -1,0,1. -1 suppresses the warning\n// issued when defval is being used. 1 prints the varname = value\n// pairs as read from the cardfile.\n\n\n// improved atof that can also handle binary strings ( 0b0110 = 6 )\ndouble satof( std::string str ) {\n std::string tmp = str;\n //tmp.erase(remove_if(tmp.begin(), tmp.end(), ::isspace), tmp.end());\n // we do the next two lines instead of the above line thanks to ROOT CINT!\n std::string::size_type pos = std::string::npos;\n while ((pos=tmp.find_first_of(\" \\t\"))!=std::string::npos) tmp.erase(pos,1);\n if ( tmp[0] == '0' && tmp[1] == 'b' && // if binary, handle differently\n str.find_last_of('b') == 1 ) {\n return (std::bitset<32>(tmp.substr(2))).to_ulong(); }\n return atof(str.c_str());\n}\n\ndouble ReadCard(const char *filename, const char *varname,\n const double defval, const int verbose ) {\n \n using namespace std;\n\n ifstream cardfile(filename);\n if ( ! cardfile.good()) {\n cerr << \"The cardfile \" << filename << \" file has problems... \" << endl;\n return defval;\n }\n\n string tempLine;\n string tempS1, tempS2, tempS3;\n string subdelimiter = \"=\";\n string hashdelimiter = \"#\";\n double value(defval);\n bool foundInFile(false);\n\n//cout << \"search this:\"<<varname<<\"\\n\";\n while ( ! cardfile.eof() ) {\n\n getline( cardfile, tempLine );\n if ( tempLine[0] == '#' ) continue; // skip comment lines\n\n size_t apos=tempLine.find(subdelimiter);\n tempS1 = tempLine.substr(0, apos); //\n size_t found = tempS1.find(string(varname) );\n if (found==std::string::npos) continue; // skip line if not found.\n std::string::size_type pos = std::string::npos;\n while ((pos=tempS1.find_first_of(\" \\t\"))!=std::string::npos) tempS1.erase(pos,1);\n// cout << \"Match is:\"<<tempS1<<\"\\n\";\n if (tempS1 != string(varname)) continue; // skip line if not exact match\n tempS2 = tempLine.substr(apos+subdelimiter.length(),std::string::npos); //\n// cout << \"Word is:\"<<tempS2<<\"\\n\";\n size_t bpos=tempS2.find(hashdelimiter);\n tempS3=tempS2.substr(0,bpos); //\n// cout << \"GoodWord is:\"<<tempS3<<\"\\n\";\n value = satof(tempS3);\n\n if ( verbose>0 ) cout << varname << \" = \" << value << endl;\n foundInFile = true;\n break;\n }\n\n if ( verbose>=0 && !foundInFile )\n cout << \"Warning! ReadCard using the default value for \" << varname << \" as:\"<< value<< endl;\n cardfile.close();\n return value;\n}\n\nstd::string ReadCardString(const char *filename, const char *varname,\n const char *defval, const int verbose) {\n using namespace std;\n ifstream cardfile(filename);\n if ( ! cardfile.good()) {\n cerr << \"The cardfile \" << filename << \" file has problems... \" << endl;\n return defval;\n }\n\n string tempLine, tmpvar;\n string value=defval;\n bool foundInFile(false);\n\n string tempS1, tempS2, tempS3;\n string subdelimiter = \"=\";\n string hashdelimiter = \"#\";\n string quotedelimiter = \"\\\"\";\n std::string::size_type pos = std::string::npos;\n\n// cout << \"search this:\"<<varname<<\"\\n\";\n while ( ! cardfile.eof() ) {\n\n getline( cardfile, tempLine );\n if ( tempLine[0] == '#' ) continue; // skip comment lines\n\n size_t apos=tempLine.find(subdelimiter);\n tempS1 = tempLine.substr(0, apos); //\n size_t found = tempS1.find(string(varname) );\n if (found==std::string::npos) continue; // skip line if not found.\n while ((pos=tempS1.find_first_of(\" \\t\"))!=std::string::npos) tempS1.erase(pos,1);\n// cout << \"Match is:\"<<tempS1<<\"\\n\";\n if (tempS1 != string(varname)) continue; // skip line if not exact match\n\n tempS2 = tempLine.substr(apos+subdelimiter.length(),std::string::npos); //\n// cout << \"Word is:\"<<tempS2<<\".\\n\";\n size_t bpos=tempS2.find(hashdelimiter);\n tempS3=tempS2.substr(0,bpos); //\n// cout << \"simple Word is:\"<<tempS3<<\".\\n\";\n bpos=tempS2.find(quotedelimiter);\n if (bpos==std::string::npos) { // no quotes found clean the spaces\n pos=std::string::npos;\n while ((pos=tempS3.find_first_of(\" \\t\"))!=std::string::npos) tempS3.erase(pos,1);\n } else { //clean the space before and after quotes\n tempS3.erase(0, bpos+1); //clean before\n// cout << \"new Word is:\"<<tempS3<<\".\\n\";\n bpos=tempS3.find(quotedelimiter);\n tempS3.erase(bpos,std::string::npos);\n }\n// cout << \"GoodWord is:\"<<tempS3<<\".\\n\";\n value = tempS3;\n\n if ( verbose>0 ) cout << varname << \" = \" << value << endl;\n foundInFile = true;\n break;\n }\n\n if ( verbose>=0 && !foundInFile )\n cout << \"Warning! ReadCardString is using the default value for \" << varname << \" as:\"<< value<<endl;\n cardfile.close();\n return value;\n\n}\n\n#endif // __READCARD_CPP\n" }, { "alpha_fraction": 0.7121679782867432, "alphanum_fraction": 0.7251389622688293, "avg_line_length": 33.446807861328125, "blob_id": "1ff9cc2e74f582a4aa657dcf351c503403af3ab3", "content_id": "d256cb30c6cf73f3020e3fdc152a2d717758d7e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1620, "license_type": "no_license", "max_line_length": 146, "num_lines": 47, "path": "/analysis_core/LFuncNode.h", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\n// LFuncNode.h\n// mm\n//\n// Created by Anna-Monica on 8/2/18.\n// Copyright © 2018 Anna-Monica. All rights reserved.\n//\n\n#ifndef LFuncNode_h\n#define LFuncNode_h\n#include <vector>\n#include \"myParticle.h\"\n#include \"FuncNode.h\"\nusing namespace std;\n//takes care of functions with two arguments\nclass LFuncNode : public FuncNode{\nprivate:\n double (*f2)(dbxParticle* part1,dbxParticle* part2);\n Node* userObjectA;\n Node* userObjectB;\n Node* userObjectC;\n Node* userObjectD;\n\n std::vector<myParticle*> inputParticles2;\n std::vector<myParticle> originalParticles2;\n dbxParticle myPart2;\n\n friend class LoopNode;\n\nprotected:\n virtual void ResetParticles() override;\n virtual void setParticleIndex(int order, int newIndex) override;\n\npublic:\n LFuncNode(double (*func)(dbxParticle* part1,dbxParticle* part2),std::vector<myParticle*> input1,std::vector<myParticle*> input2,std::string s,\n Node *objectNodea = NULL, Node *objectNodeb = NULL, Node *objectNodec = NULL, Node *objectNoded = NULL);\n virtual void getParticles(std::vector<myParticle *>* particles) override;\n virtual void getParticlesAt(std::vector<myParticle *>* particles, int index) override;\n virtual double evaluate(AnalysisObjects* ao) override;\n virtual void setUserObjects(Node *objectNodea = NULL, Node *objectNodeb = NULL, Node *objectNodec = NULL, Node *objectNoded = NULL);\n virtual ~LFuncNode() ;\n};\n\ndouble dR (dbxParticle* apart,dbxParticle* apart2);\ndouble dPhi(dbxParticle* apart,dbxParticle* apart2);\ndouble dEta(dbxParticle* apart,dbxParticle* apart2);\n#endif /* LFuncNode_h */\n" }, { "alpha_fraction": 0.7409470677375793, "alphanum_fraction": 0.7409470677375793, "avg_line_length": 22.866666793823242, "blob_id": "df4d430088a0a0c2fa048188e271b45f3c4707d4", "content_id": "3b6aef27addf55db7166eaa5a9a9a09220f9a0c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 359, "license_type": "no_license", "max_line_length": 75, "num_lines": 15, "path": "/scripts/README.md", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "## Syntax Highlighting \nvim plugin for highlighting .adl syntax for CutLang [cutlang.vim]\n\n## Installation \nThe plugin is installed by copying the .vim file to filepath ~/.vim/syntax \n```bash\n cp CutLang/scripts/cutlang.vim ~/.vim/syntax/\n```\n\n## Usage\nSyntax Highlighting is triggered by entering\n```bash\n :set syntax=cutlang\n```\non the vim terminal window \n" }, { "alpha_fraction": 0.6894409656524658, "alphanum_fraction": 0.6894409656524658, "avg_line_length": 28.272727966308594, "blob_id": "4d8b7d7149c3e5527af6e3d1eb51c920c8dd736b", "content_id": "6db34499fa85d8d141a658c543e828455937866f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 322, "license_type": "no_license", "max_line_length": 40, "num_lines": 11, "path": "/analysis_core/makeSos.C", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "{\ngROOT->LoadMacro(\"dbxParticle.cpp+\");\ngROOT->LoadMacro(\"dbx_muon.h+\");\ngROOT->LoadMacro(\"dbx_tau.h+\");\ngROOT->LoadMacro(\"dbx_electron.h+\");\ngROOT->LoadMacro(\"dbx_photon.h+\");\ngROOT->LoadMacro(\"dbx_jet.h+\");\ngROOT->LoadMacro(\"dbx_truth.h+\");\ngROOT->LoadMacro(\"DBXNtuple.cpp+\");\ngROOT->LoadMacro(\"delphesParticles.h+\");\n}\n" }, { "alpha_fraction": 0.5020267963409424, "alphanum_fraction": 0.5103795528411865, "avg_line_length": 26.358884811401367, "blob_id": "b767e28902c0243313cb15267bdabb28e86b750c", "content_id": "779db7a587b5ccafc86a67e36cad7c09807b994a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8141, "license_type": "no_license", "max_line_length": 256, "num_lines": 287, "path": "/analysis_core/Denombrement.cpp", "repo_name": "morbikdon/CutLang", "src_encoding": "UTF-8", "text": "//\r\n//\r\n//\r\n//\r\n//\r\n\r\n#include <iostream>\r\n#include <algorithm>\r\n#include \"Denombrement.h\"\r\n#include \"Comb.h\"\r\n#include <vector>\r\n#include <string>\r\n#include <iterator>\r\n\r\n\r\n//#define _CLV_\r\n#ifdef _CLV_\r\n#define DEBUG(a) std::cout<<a\r\n#else\r\n#define DEBUG(a)\r\n#endif\r\n\r\n\r\n\r\nusing namespace std;\r\nint itteration = 1;\r\n\r\nstruct curseur\r\n{\r\n int left;\r\n int right;\r\n};\r\n\r\nvoid suppr_bad_combi(vector<int>& temp, vector<int>& tab_select, int& n, int pas)\r\n{\r\n vector<int> temp_combi(pas);\r\n int k = 0;\r\n vector<int> tab;\r\n\r\n do\r\n {\r\n for(int i = 0; i<pas; i++)\r\n temp_combi[i] = temp[i+k]; \r\n\r\n if(temp_combi==tab_select)\r\n {\r\n for(int l = 0; l<k; l++)\r\n tab.push_back(temp[l]);\r\n\r\n for(int l = k+pas; l<temp.size(); l++)\r\n tab.push_back(temp[l]);\r\n\r\n temp=tab;\r\n k-=pas;\r\n n-=pas;\r\n }\r\n\r\n k+=pas;\r\n }while(k<n);\r\n}\r\n\r\nvoid suppr_by_set(vector<vector<int>>&output, vector<int> temp, vector<vector<int>> set_select, int n, int pas)\r\n{\r\n int N = n;\r\n vector<int>tab;\r\n for(int i = 0; i<set_select.size(); i++)\r\n {\r\n suppr_bad_combi(temp, set_select[i], N, pas);\r\n }\r\n\r\n for(int i = 0; i<N; i++)\r\n tab.push_back(temp[i]);\r\n if(N!=0)\r\n {\r\n if( output.size()==0 || tab!=output.back() ) output.push_back(tab);\r\n }\r\n}\r\n\r\nvoid reccursion(void c(int, int, int,vector<vector<int>>, vector<vector<int>>&, vector<int>, int&, int), void e( vector<vector<int>>, vector<int>, vector<vector<int>>&, int, int, int, int, int, int, int), vector<vector<int>> tab_select, vector<int> temp ,\r\n vector<vector<int>>& output, int& left_begin, int& right_end, int& real_end,int& interrup, int& pas, int nbZ)\r\n{\r\n if(right_end > real_end)\r\n c(right_end-real_end + pas, pas, real_end+1-pas, tab_select, output, temp, itteration, nbZ);\r\n\r\n if (left_begin < real_end - pas)\r\n {\r\n int n = left_begin;\r\n while(n < real_end - pas)\r\n n = n + pas;\r\n\r\n for(int j(n); j > (left_begin + 1); j = j - pas)\r\n e(tab_select, temp, output, j, j+1 , right_end, real_end, j, pas, 0);\r\n }\r\n}\r\n\r\nvoid sort(vector<int>& input, int pas, int nbZ)\r\n{\r\n for(int i = 0; i<nbZ; ++i)\r\n {\r\n for(int j = i*pas; j<pas+i*pas-1; ++j)\r\n {\r\n for(int k = j+1; k<pas+i*pas; ++k)\r\n {\r\n if(input[j]>input[k])\r\n swap(input[j],input[k]);\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid comb(int N, int K, int n, vector<vector<int>> tab_select, vector<vector<int>>& output, vector<int> tab, int& itt, int nbZ)\r\n{\r\n vector<int> temp = tab;\r\n string bit_conteur(K, 1);\r\n bit_conteur.resize(N, 0);\r\n int total = n+K;\r\n\r\n while (std::prev_permutation(bit_conteur.begin(), bit_conteur.end()))\r\n {\r\n int i(0), j(0);\r\n for (int k = 0; k < N; ++k)\r\n {\r\n if (bit_conteur[k]) {temp[i+n] = tab[k+n]; ++i;}\r\n else {temp[j+n+K] = tab[k+n]; ++j;}\r\n\r\n }\r\n sort(temp, K, nbZ);\r\n suppr_by_set(output, temp, tab_select, total, K);\r\n ++itt;\r\n }\r\n}\r\n\r\nvoid etape(vector<vector<int>> tab_select, vector<int> tab , vector<vector<int>>& output, int left_begin, int right_begin, int right_end, int real_end, int interrup, int pas, int stop = 0)// ici le pas est le nombre \"nJet\" de jets // tab\r\n{\r\n int arret = stop;\r\n int nbZ = (real_end + 1)/pas;\r\n curseur a;\r\n vector<int> temp = tab;\r\n vector<int> tab2 = tab;\r\n\r\n int righ_begin_temp = right_begin;\r\n\r\n a.left = left_begin;\r\n a.right = right_begin;\r\n int total = real_end+1;\r\n\r\n do\r\n {\r\n do\r\n {\r\n for(int i(right_begin); i <= right_end; i++)\r\n {\r\n a.right = i;\r\n swap(temp[a.left],temp[a.right]);\r\n sort(temp,pas, nbZ);\r\n suppr_by_set(output, temp, tab_select, real_end+1, pas);\r\n ++itteration;\r\n reccursion(comb, etape, tab_select, temp, output, left_begin, right_end, real_end, interrup, pas, nbZ);\r\n\r\n if (a.left != left_begin && i != right_end)\r\n {\r\n etape(tab_select, temp,output, left_begin, a.right+1, right_end, real_end, a.left, pas );\r\n right_begin = righ_begin_temp;\r\n }\r\n }\r\n\r\n if(a.left != interrup + 1)\r\n {\r\n --a.left;\r\n temp = tab2;\r\n }\r\n else\r\n arret = 1;\r\n\r\n }while( (a.left>(left_begin-pas+1) || a.right != right_end) && (arret == 0) );\r\n\r\n --right_end;\r\n\r\n if(right_end >= real_end && arret==0)\r\n {\r\n temp = tab2;\r\n\r\n for(int i(a.left); i<tab.size()-1; ++i)\r\n temp[i] = temp[i+1];\r\n temp[tab.size() - 1] = tab2[a.left];\r\n\r\n tab2 = temp;\r\n\r\n a.left = left_begin;\r\n a.right = right_begin;\r\n\r\n sort(temp, pas, nbZ);\r\n suppr_by_set(output, temp, tab_select, total, pas);\r\n ++itteration;\r\n\r\n reccursion(comb, etape, tab_select, temp, output, left_begin, right_end, real_end, interrup, pas, nbZ);\r\n }\r\n }while(right_end >= real_end && arret==0);\r\n}\r\n\r\nvoid etape_combinatoire(vector<vector<int>> tab_select, vector<int> tab , vector<vector<int>>& output, int left_begin, int right_begin, int right_end, int real_end, int interrup, int pas, int stop = 0) // tab, output\r\n{\r\n int n = left_begin;\r\n while(n < real_end - pas)\r\n {\r\n n = n + pas;\r\n }\r\n comb(right_end-real_end + pas, pas, real_end+1-pas, tab_select, output, tab, itteration, (real_end+1)/pas);\r\n\r\n for(int i(n); i > (left_begin - 1); i= i - pas)\r\n {\r\n etape(tab_select, tab, output, i, i+1 , right_end, real_end, i, pas);\r\n }\r\n}\r\n\r\nDenombrement::Denombrement( int JetReconstr, int JetTotal, vector<vector<int>> tab_select) : nJetRecontr(JetReconstr), nJetTotal(JetTotal), tab_selection(tab_select)\r\n{\r\n if(JetTotal>2)\r\n {\r\n vector<int> tab(nJetTotal+1);\r\n for(int i = 0; i<nJetTotal+1 ; ++i)\r\n {\r\n tab[i] = i;\r\n }\r\n suppr_by_set(out, tab, tab_selection, nZ*nJetRecontr, nJetRecontr);\r\n etape_combinatoire( tab_selection, tab, out, nJetRecontr-1, nJetRecontr, nJetTotal, nZ*nJetRecontr-1, nJetRecontr-1, nJetRecontr, 0);\r\n }\r\n else\r\n {\r\n Comb simple_combination = Comb(nJetTotal+1, nJetRecontr, tab_selection);\r\n out = simple_combination.output();\r\n }\r\n}\r\n\r\nDenombrement::Denombrement( int JetReconstr, int JetTotal) : nJetRecontr(JetReconstr), nJetTotal(JetTotal) //,nParticles(JetTotal)\r\n{\r\n//---------------------------combine JetReconstr particles, out of JetTotal \r\n// if (nParticles.size()<2){\r\n if (nJetTotal>2)\r\n {\r\n vector<int> tab(nJetTotal+1);\r\n for(int i = 0; i<nJetTotal+1 ; ++i) { tab[i] = i; }\r\n suppr_by_set(out, tab, tab_selection, nZ*nJetRecontr, nJetRecontr);\r\n etape_combinatoire( tab_selection, tab, out, nJetRecontr-1, nJetRecontr, nJetTotal, nZ*nJetRecontr-1, nJetRecontr-1, nJetRecontr, 0);\r\n } else {\r\n Comb simple_combination = Comb(nJetTotal+1, nJetRecontr);\r\n out = simple_combination.output();\r\n }\r\n// } else { // now we have 2 particle types to be merged, like muons and taus, \r\n\r\n// }\r\n}\r\n\r\nDenombrement::~Denombrement()\r\n{\r\n //dtor\r\n}\r\n\r\nvector<vector<int>> Denombrement::output()\r\n{\r\n return out;\r\n}\r\n\r\nvoid Denombrement::affiche()\r\n{\r\n for(int i = 0; i<out.size(); ++i)\r\n {\r\n for(int j = 0; j<out[i].size(); ++j)\r\n {\r\n cout<< out[i][j] << \" \";\r\n if(j%nJetRecontr == nJetRecontr-1) cout<<\" \";\r\n }\r\n cout<<\"\\n\";\r\n }\r\n}\r\n\r\nvoid Denombrement::itt()\r\n{\r\n itteration_ = itteration;\r\n DEBUG(\"\\nLe nombre d'itterations est: \" << itteration_ << \"\\n\");\r\n itteration = 1;\r\n}\r\n\r\nvoid Denombrement::output(vector<vector<int>>& tab)\r\n{\r\n out = tab;\r\n}\r\n\r\n" } ]
70
yang2640/ZeroSearch
https://github.com/yang2640/ZeroSearch
adf0d03654c3957491e5280d1ce1d863b9cdfc42
a28ef243c001d6865b7de6a2206eeb05a39d8ca8
145aeac4b00a9434d4ab4d25dd1183ade235b718
refs/heads/master
2021-05-28T08:24:05.501536
2015-02-26T19:32:36
2015-02-26T19:32:36
31,345,750
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6128550171852112, "alphanum_fraction": 0.6487294435501099, "avg_line_length": 18.676469802856445, "blob_id": "b5ae54882830515568ee81628deb00dd6a640841", "content_id": "77640c2e36fcbfcb7cb57598542c3a618c6ea49a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 669, "license_type": "no_license", "max_line_length": 77, "num_lines": 34, "path": "/VocabTree/VocabLib/Makefile", "repo_name": "yang2640/ZeroSearch", "src_encoding": "UTF-8", "text": "# Makefile for VocabLib\n\nMACHTYPE=$(shell uname -m)\n\nGCC\t\t\t= x86_64-nacl-g++\n\nCC=x86_64-nacl-g++\n# OPTFLAGS=-g2\nOPTFLAGS=-O3 -ffast-math -Wall -mfpmath=sse -msse2 -funroll-loops\nOTHERFLAGS=-Wall\n\nINCLUDE_PATH=-I../lib/ann_1.1/include/ANN -I../lib/ann_1.1_char/include/ANN \\\n\t-I../lib/imagelib \n\nOBJS=keys2.o kmeans.o kmeans_kd.o VocabTreeBuild.o VocabTreeIO.o \\\n\tVocabTreeUtil.o VocabTree.o VocabFlatNode.o\n\nCPPFLAGS=$(INCLUDE_PATH) $(OTHERFLAGS) $(OPTFLAGS)\n\nLIB=libvocab.a\n\nall: $(LIB)\n\n$(LIB): $(OBJS)\n\tx86_64-nacl-ar ruvs $(LIB) $(OBJS)\n\tx86_64-nacl-ranlib $(LIB)\n\tcp $(LIB) ..\n\n%.o: %.cpp\n\t$(GCC) $(CPPFLAGS) -c -o $@ $<\n\nclean:\n\trm -f *.o *~ $(LIB)\n\trm ../$(LIB)\n" }, { "alpha_fraction": 0.5785547494888306, "alphanum_fraction": 0.5864802002906799, "avg_line_length": 29.211267471313477, "blob_id": "e05f1b7b646dd059076f4e0fafab294cf6d53097", "content_id": "6ca46c0620784b458bafb3db78a4e7f63fb59cdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4290, "license_type": "no_license", "max_line_length": 120, "num_lines": 142, "path": "/snakebin/snakebin.py", "repo_name": "yang2640/ZeroSearch", "src_encoding": "UTF-8", "text": "import base64\nimport hashlib\nimport json\nimport os\nimport random\nimport sqlite3\nimport string\nimport sys\nimport urlparse\nimport re\n\n\n\ndef http_resp(code, reason, content_type='message/http', msg='',\n extra_headers=None):\n if extra_headers is None:\n extra_header_text = ''\n else:\n extra_header_text = '\\r\\n'.join(\n ['%s: %s' % (k, v) for k, v in extra_headers.items()]\n )\n extra_header_text += '\\r\\n'\n\n resp = \"\"\"HTTP/1.1 %(code)s %(reason)s\\r\n%(extra_headers)sContent-Type: %(content_type)s\\r\nContent-Length: %(msg_len)s\\r\n\\r\n%(msg)s\"\"\"\n resp %= dict(code=code, reason=reason, content_type=content_type,\n msg_len=len(msg), msg=msg, extra_headers=extra_header_text)\n sys.stdout.write(resp)\n\n\nclass Job(object):\n\n def __init__(self, name, args, exe=None):\n self.name = name\n self.args = args\n\tif exe is not None:\n\t self.execuation = exe\n\telse:\n\t self.execuation = 'file://python2.7:python'\n\n\n self.devices = [\n {'name': 'python2.7'},\n {'name': 'stdout', 'content_type': 'message/http'},\n {'name': 'image', 'path': 'swift://~/snakebin-app/snakebin.zapp'},\n ]\n self.env = {}\n\n def add_device(self, name, content_type=None, path=None):\n dev = {'name': name}\n if content_type is not None:\n dev['content_type'] = content_type\n if path is not None:\n dev['path'] = path\n self.devices.append(dev)\n\n def set_envvar(self, key, value):\n self.env[key] = value\n\n def to_json(self):\n return json.dumps([self.to_dict()])\n\n def to_dict(self):\n return {\n 'name': self.name,\n 'exec': {\n 'path': self.execuation,\n 'args': self.args,\n 'env': self.env,\n },\n 'devices': self.devices,\n }\n\n\ndef _object_exists(name):\n \"\"\"Check the local container (mapped to ) to see if it contains\n an object with the given name. /dev/input is expected to be a sqlite\n database.\n \"\"\"\n conn = sqlite3.connect('/dev/input')\n try:\n cur = conn.cursor()\n sql = 'SELECT ROWID FROM object WHERE name=? AND deleted=0'\n cur.execute(sql, (name, ))\n result = cur.fetchall()\n return len(result) > 0\n finally:\n conn.close()\n\n\n\n\n# HTTP request\n# GET /snakebin-api Generate a template index.html to reply back\n# GET /snakebin-api/:script/search create a job chain for VocabMatch\n# GET /snakebin-api/:script create a job chain for get_file.py\n\ndef get():\n path_info = os.environ.get('PATH_INFO')\n file_name = None\n search = None\n file_name, search = re.match('.*/snakebin-api/?(\\w+)?(/search)?', path_info).groups()\n\n if not file_name:\n\t# Get empty form page:\n\twith open('index.html') as fp:\n\t index_page = fp.read()\n\thttp_resp(200, 'OK', content_type='text/html; charset=utf-8',\n\t\t msg=index_page)\n elif _object_exists('%s.jpg.pgm.sift' % file_name):\n\t# The client has requested a real document.\n\t# Spawn a job to go and retrieve it:\n\tif search:\n\t private_file_path = 'swift://~/snakebin-store/%s.jpg.pgm.sift' % file_name\n\n\t job = Job('VocabMatch', 'vocab.db list.txt /dev/input 10', exe='swift://~/snakebin-api/VocabMatch.nexe')\n\t job.add_device('input', path=private_file_path)\n\t job.add_device('stderr', path='swift://~/snakebin-api/err.txt')\n\t job.set_envvar('HTTP_ACCEPT', os.environ.get('HTTP_ACCEPT'))\n\n\t http_resp(200, 'OK', content_type='application/json', msg=job.to_json(), extra_headers={'X-Zerovm-Execute': '1.0'})\n\telse:\n\t private_file_path = 'swift://~/snakebin-store/%s.jpg' % file_name\n\t job = Job('snakebin-get-file', 'get_file.py')\n\t job.add_device('input', path=private_file_path)\n\t job.set_envvar('HTTP_ACCEPT', os.environ.get('HTTP_ACCEPT'))\n\t http_resp(200, 'OK', content_type='application/json', msg=job.to_json(), extra_headers={'X-Zerovm-Execute': '1.0'})\n else:\n\thttp_resp(404, 'Not Found')\n\nif __name__ == '__main__':\n request_method = os.environ.get('REQUEST_METHOD')\n\n if request_method == 'POST':\n post()\n elif request_method == 'GET':\n get()\n else:\n http_resp(405, 'Method Not Allowed')\n" }, { "alpha_fraction": 0.6039387583732605, "alphanum_fraction": 0.6433260440826416, "avg_line_length": 14.758620262145996, "blob_id": "e7d9b88bb09a862dd5d2240d8ec62763a3cbeecc", "content_id": "2a383c93c04ec0c2aebdad2941adf271b95ad166", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 457, "license_type": "no_license", "max_line_length": 49, "num_lines": 29, "path": "/VocabTree/lib/imagelib/Makefile", "repo_name": "yang2640/ZeroSearch", "src_encoding": "UTF-8", "text": "# Makefile for imagelib\n\nMACHTYPE=$(shell uname -m)\n\nGCC\t\t\t= x86_64-nacl-gcc\n\nCC=x86_64-nacl-gcc\nOPTFLAGS=-g2\n# OPTFLAGS=-O3\nOTHERFLAGS=-Wall\n\nIMAGELIB_OBJS= qsort.o util.o\n\nCFLAGS=$(OTHERFLAGS) $(OPTFLAGS)\n\nIMAGELIB=libimage.a\n\n%.$(P).o : %.c\n\t$(CC) -c -o $@ $(CFLAGS) $<\n\nall: $(IMAGELIB)\n\n$(IMAGELIB): $(IMAGELIB_OBJS)\n\tx86_64-nacl-ar rusv $(IMAGELIB) $(IMAGELIB_OBJS)\n\tx86_64-nacl-ranlib $(IMAGELIB)\n\tcp $(IMAGELIB) ..\n\nclean:\n\trm -f *.o *~ $(IMAGELIB)\n" }, { "alpha_fraction": 0.6398390531539917, "alphanum_fraction": 0.653923511505127, "avg_line_length": 21.590909957885742, "blob_id": "7486be0400c83448681dfb19f1e797994c439b33", "content_id": "7bb6b564644407618c4ced880ad6dd3615e4d549", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 994, "license_type": "no_license", "max_line_length": 77, "num_lines": 44, "path": "/VocabTree/VocabMatch/Makefile", "repo_name": "yang2640/ZeroSearch", "src_encoding": "UTF-8", "text": "# Makefile for VocabMatch\n\nMACHTYPE=$(shell uname -m)\n\nGCC\t\t\t= x86_64-nacl-g++\n\nCC=x86_64-nacl-gcc\n# OPTFLAGS=-g2\nOPTFLAGS=-O3 \nOTHERFLAGS=-Wall\n\nINCLUDE_PATH=-I../lib/ann_1.1/include/ANN -I../lib/ann_1.1_char/include/ANN \\\n\t-I../lib/imagelib -I../VocabLib -I../lib/zlib/include\nLIB_PATH=-L../lib -L../VocabLib\n\nOBJS=VocabMatch.o\nOBJS_DESC=VocabMatch_desc.o\n\nLIBS=-lvocab -lANN -lANN_char -limage -lz\n\nCPPFLAGS=$(INCLUDE_PATH) $(LIB_PATH) $(OTHERFLAGS) $(OPTFLAGS)\n\nBIN=VocabMatch.nexe\nBIN_DESC=VocabMatch_desc\n\nall: $(BIN) $(BIN_DESC) VocabMatchScript VocabMatchScript_desc\n\n$(BIN): $(OBJS)\n\t$(GCC) -o $(CPPFLAGS) -o $(BIN) $(OBJS) $(LIBS)\n\n$(BIN_DESC): $(OBJS_DESC)\n\t$(GCC) -o $(CPPFLAGS) -o $@ $^ $(LIBS)\n\nVocabMatchScript: VocabMatchScript.o\n\t$(GCC) $(CPPFLAGS) -o $@ $^ $(LIBS)\n\nVocabMatchScript_desc: VocabMatchScript_desc.o\n\t$(GCC) $(CPPFLAGS) -o $@ $^ $(LIBS)\n\n%.o: %.cpp\n\t$(GCC) $(CPPFLAGS) -c -o $@ $^\n\nclean:\n\trm -f *.o *~ $(BIN_DESC) $(BIN) VocabMatchScript VocabMatchScript_desc\n" }, { "alpha_fraction": 0.5766666531562805, "alphanum_fraction": 0.5933333039283752, "avg_line_length": 17.4375, "blob_id": "e7155156ab7202562eed554a6886d08096533da1", "content_id": "035b057a47a14eeef9843f63f17a12913679aa05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 300, "license_type": "no_license", "max_line_length": 67, "num_lines": 16, "path": "/siftpp/Makefile", "repo_name": "yang2640/ZeroSearch", "src_encoding": "UTF-8", "text": "CC=x86_64-nacl-g++\nCFLAGS=-I. -Wall -g -O3 -DNDEBUG -DVL_LOWE_STRICT -DVL_USEFASTMATH\nall:sift.nexe\n\nsift.nexe:sift.o sift-driver.o\n\t$(CC) $(CFLAGS) $^ -o $@\n\nsift.o:sift.cpp\n\t$(CC) $(CFLAGS) $< -c -o $@\n\nsift-driver.o:sift-driver.cpp\n\t$(CC) $(CFLAGS) $< -c -o $@\n\nclean:\n\trm *.o\n\trm sift.nexe\n \n" }, { "alpha_fraction": 0.5975610017776489, "alphanum_fraction": 0.6056910753250122, "avg_line_length": 35.900001525878906, "blob_id": "5807e1dae6d8a0aeeb5eca13089a36d2f13c254b", "content_id": "2e6ffdeaad83ace42a847a93c9f952cf7ef4da91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 738, "license_type": "no_license", "max_line_length": 79, "num_lines": 20, "path": "/snakebin/get_file.py", "repo_name": "yang2640/ZeroSearch", "src_encoding": "UTF-8", "text": "import os\nfrom xml.sax.saxutils import escape\nimport snakebin\n\n\nif __name__ == '__main__':\n with open('/dev/input') as fp:\n contents = fp.read()\n\n http_accept = os.environ.get('HTTP_ACCEPT', '')\n if 'text/html' in http_accept:\n # Something that looks like a browser is requesting the document:\n # with open('/index.html') as fp:\n # html_page_template = fp.read()\n # html_page = html_page_template.replace('{code}', escape(contents))\n snakebin.http_resp(200, 'OK', content_type='image/jpeg',\n msg=contents)\n else:\n # Some other type of client is requesting the document:\n snakebin.http_resp(200, 'OK', content_type='image/jpeg', msg=contents)\n" } ]
6
Mike-M-87/studious-octo-carnival
https://github.com/Mike-M-87/studious-octo-carnival
12770d3e41d5c5ca4e65c60a9d265fd45246ed87
3aa01bab32825f2c7c69d8fbe718e76725f70ae2
b7a33561b9a2cb2ba6135fb9064fdbd650d10ef0
refs/heads/main
2023-06-19T00:33:17.156802
2021-07-11T20:12:12
2021-07-11T20:12:12
383,120,072
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5905511975288391, "alphanum_fraction": 0.625984251499176, "avg_line_length": 24.399999618530273, "blob_id": "c83f8638e2931046d2fd50d1821e4e7c04c61c25", "content_id": "74c7aad69437c11350e18431f60375e85b909cf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 254, "license_type": "no_license", "max_line_length": 76, "num_lines": 10, "path": "/ext/background.js", "repo_name": "Mike-M-87/studious-octo-carnival", "src_encoding": "UTF-8", "text": "let color = '#3aa757';\nlet d = 0;\nchrome.runtime.onInstalled.addListener(() => {\n chrome.storage.sync.set({ color });\n setInterval(()=>{\n\t d++;\n\t console.log(d)\n },1000)\n console.log('Default background color set to %cgreen', `color: ${color}`);\n});\n" }, { "alpha_fraction": 0.5681234002113342, "alphanum_fraction": 0.5938303470611572, "avg_line_length": 27.814815521240234, "blob_id": "474cbf3ff468007b41fb873b258e4a4a973dd87f", "content_id": "78608f1f4510b98f61207b8a530b6d389e433b0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 778, "license_type": "no_license", "max_line_length": 71, "num_lines": 27, "path": "/lawz/attorney.py", "repo_name": "Mike-M-87/studious-octo-carnival", "src_encoding": "UTF-8", "text": "import random\n\nwith open(\"names.txt\") as f:\n names = f.read().strip().split(\"\\n\")\nwith open(\"address.txt\") as f:\n addresses = f.read().strip().split(\"\\n\")\nwith open(\"city.txt\") as f:\n cities = f.read().strip().split(\"\\n\")\nwith open(\"specializations.txt\") as f:\n specialties = f.read().strip().split(\"\\n\")\nwith open(\"lawz.txt\") as f:\n barz = f.read().strip().split(\"\\n\")\n\nnoatton = 30\n\n\nfor i in range(1,30*2,2):\n aid = (i//2)+1\n address = random.choice(addresses)\n name = names[i] +' ' + names[i+1]\n city = random.choice(cities)\n zip = random.randint(10000,99999)\n speacial= random.choice(specialties)\n bar = random.choice(barz) \n\n formatted = f\"{aid},{name},{address},{city},{zip},{speacial},{bar}\"\n print(formatted)\n" }, { "alpha_fraction": 0.5564516186714172, "alphanum_fraction": 0.5645161271095276, "avg_line_length": 24, "blob_id": "f10032e703535cd4e898481b06566cad26f15476", "content_id": "1ee561eadbf2719cd2125a644591d8f42e717484", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 124, "license_type": "no_license", "max_line_length": 40, "num_lines": 5, "path": "/lawz/cases.py", "repo_name": "Mike-M-87/studious-octo-carnival", "src_encoding": "UTF-8", "text": "with open(\"cases.txt\") as f:\n cases = f.read().strip().split(\"\\n\")\n\nfor k,v in enumerate(cases):\n print(f\"{k+1},,{v}\")" }, { "alpha_fraction": 0.5043290257453918, "alphanum_fraction": 0.5432900190353394, "avg_line_length": 23.263158798217773, "blob_id": "a4b57c77205ffce1707fe5eef501da9049b7dee6", "content_id": "290f17e43f8473185bcb622eb9f8ac899d421cf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 462, "license_type": "no_license", "max_line_length": 54, "num_lines": 19, "path": "/lawz/judge.py", "repo_name": "Mike-M-87/studious-octo-carnival", "src_encoding": "UTF-8", "text": "import random\n\nwith open(\"names.txt\") as f:\n names = f.read().strip().split(\"\\n\")\n \nnojudge = 50\nnocourts = 13\n\n\nfor i in range(1,nojudge+1,2):\n jid = (i//2)+1 \n fname = random.choice(names) \n lname = random.choice(names) \n name = f\"{fname} {lname}\"\n yop = random.randint(2004,2021)\n courtid = random.randint(1,nocourts)\n\n formatted = f\"{jid},{name},{yop},{courtid}\"\n print(formatted)\n\n" }, { "alpha_fraction": 0.5353845953941345, "alphanum_fraction": 0.5930769443511963, "avg_line_length": 30.682926177978516, "blob_id": "d8d0abee600100e683a0f4ba397d990e079cb2c0", "content_id": "cee808dfa67c00aee760ec95a02a0a3177886a93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1300, "license_type": "no_license", "max_line_length": 119, "num_lines": 41, "path": "/orders.py", "repo_name": "Mike-M-87/studious-octo-carnival", "src_encoding": "UTF-8", "text": "import random\n\n\nwith open(\"city.txt\") as fhand:\n city = (fhand.read().split('\\n'))\n \nwith open(\"skill.txt\") as fhand:\n skill = (fhand.read().split('\\n'))\n\nwith open(\"title.txt\") as fhand:\n title = (fhand.read().split('\\n'))\n \nwith open(\"capitals.txt\") as fhand:\n capitals = (fhand.read().split('\\n'))\n\nwith open(\"address.txt\") as fhand:\n address = (fhand.read().split('\\n'))\n\nnorders = 180\nbranch = [1,2,3]\nlanguage = [\"English\",\"Kiswahili\",\"French\",\"Spanish\",\"Hindi\",\"Chinese\"]\n\nfor i in range(1,norders+1):\n custid = random.randint(1,55)\n ID = i\n state = random.choice(capitals)\n cty = random.choice(city)\n tit = random.choice(title)\n ski = random.choice(skill)\n b = random.choice(branch)\n lang = random.choice(language)\n addr = random.choice(address) \n age = f\"{random.randint(21,60)}\"\n sal = random.randint(1000,999999)\n zipc = random.randint(10000,99999)\n stre = f\"ST{random.randint(23,99)}\"\n tel = f\"07{random.randint(10000000,99999999)}\"\n doo = f\"{str(random.randint(1,28)).zfill(2)}/{str(random.randint(1,12)).zfill(2)}/{random.randint(2015,2021)}\"\n credAuts = random.randint(0,1)\n formated = f\"{ID},{doo},{credAuts},{custid},{b}\"\n print(formated)\n\n" }, { "alpha_fraction": 0.5527156591415405, "alphanum_fraction": 0.6325878500938416, "avg_line_length": 30.200000762939453, "blob_id": "e20d43d085f53e4c7932e09e4e6314923d757591", "content_id": "219395a43ab7765f587d2008ab089eef9193c58f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 313, "license_type": "no_license", "max_line_length": 119, "num_lines": 10, "path": "/superenrolment.py", "repo_name": "Mike-M-87/studious-octo-carnival", "src_encoding": "UTF-8", "text": "import random\n\nnorders = 13\n\nfor i in range(1,norders+1):\n superid = random.randint(1,4)\n itemid = random.randint(1,35)\n doo = f\"{str(random.randint(1,28)).zfill(2)}/{str(random.randint(1,12)).zfill(2)}/{random.randint(2015,2021)}\"\n formated = f\"{superid},{itemid},{doo}\"\n print(formated)\n\n" }, { "alpha_fraction": 0.5216952562332153, "alphanum_fraction": 0.5812310576438904, "avg_line_length": 30.935483932495117, "blob_id": "bd30843e208b535573a16353feb879bd0140c928", "content_id": "fe029a7e6ae9ff578610d53dac1e645122f4f8a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 991, "license_type": "no_license", "max_line_length": 118, "num_lines": 31, "path": "/lawz/clients.py", "repo_name": "Mike-M-87/studious-octo-carnival", "src_encoding": "UTF-8", "text": "\nimport random\n\nwith open(\"names.txt\") as f:\n names = f.read().strip().split(\"\\n\")\nwith open(\"address.txt\") as f:\n addresses = f.read().strip().split(\"\\n\")\nwith open(\"city.txt\") as f:\n cities = f.read().strip().split(\"\\n\")\nwith open(\"specializations.txt\") as f:\n specialties = f.read().strip().split(\"\\n\")\n\nn = 50\nnoatton = 30\nnocourts = 10 \nbars = [\"Kenya\"]\n\n\nfor i in range(1,n*2,2):\n cliid = (i//2)+1 # Coz 0 we add + 1\n name = names[i] +' ' + names[i+1]\n address = random.choice(addresses)\n city = random.choice(cities)\n zip = random.randint(10000,99999)\n tel = f\"07{random.randint(10000000,99999999)}\"\n special = random.choice(specialties)\n dob = f\"{str(random.randint(1,28)).zfill(2)}/{str(random.randint(1,12)).zfill(2)}/{random.randint(1930,1990)}\"\n court = random.randint(1,nocourts)\n\n formatted = f\"{cliid},{name},{address},{city},{zip},{tel},{dob},{court}\"\n \n print(formatted)\n" }, { "alpha_fraction": 0.5137614607810974, "alphanum_fraction": 0.5963302850723267, "avg_line_length": 22.428571701049805, "blob_id": "eea8d5e07d134735997f7cccdc580ecbfbf84b86", "content_id": "a839cbb7ca4f8a2bd3eca31822a563f232408878", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 327, "license_type": "no_license", "max_line_length": 114, "num_lines": 14, "path": "/lawz/proccedings.py", "repo_name": "Mike-M-87/studious-octo-carnival", "src_encoding": "UTF-8", "text": "import random\n\nn = 35\nc = 21\ncl = 23\nat = 30\n\nfor i in range(n):\n cid = random.randint(1,c)\n cli = random.randint(1,cl)\n att = random.randint(1,at)\n doc = f\"{str(random.randint(1,28)).zfill(2)}/{str(random.randint(1,12)).zfill(2)}/{random.randint(2019,2021)}\"\n form = f\"{cid},{cli},{att},{doc}\"\n print(form)" }, { "alpha_fraction": 0.5596264600753784, "alphanum_fraction": 0.6113505959510803, "avg_line_length": 32.92683029174805, "blob_id": "45b29982000fa4b236d73ffc40b59f7553a119e3", "content_id": "bc5e9da71f002d3b18bae43b965e982a9730f7a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1392, "license_type": "no_license", "max_line_length": 119, "num_lines": 41, "path": "/accounts.py", "repo_name": "Mike-M-87/studious-octo-carnival", "src_encoding": "UTF-8", "text": "import random\n\nwith open(\"city.txt\") as fhand:\n city = (fhand.read().split('\\n'))\n \nwith open(\"skill.txt\") as fhand:\n skill = (fhand.read().split('\\n'))\n\nwith open(\"title.txt\") as fhand:\n title = (fhand.read().split('\\n'))\n \nwith open(\"capitals.txt\") as fhand:\n capitals = (fhand.read().split('\\n'))\n\nwith open(\"address.txt\") as fhand:\n address = (fhand.read().split('\\n'))\n\nnaccounts = 60\nbranch = [1,2,3]\nrelationship = [\"Father\",\"Mother\",\"Son\",\"Daughter\",\"Cousin\",\"Aunt\",\"Sister\",\"Brother\"]\naccountype = [\"Currrent\",\"Savings\",\"Recurring Deposit\"]\n\nfor i in range(1,naccounts+1):\n customid = random.randint(1,50)\n ID = (i)\n state = random.choice(capitals)\n atypes = random.choice(accountype)\n cty = random.choice(city)\n tit = random.choice(title)\n ski = random.choice(skill)\n b = random.choice(branch)\n addr = random.choice(address) \n relation = random.choice(relationship)\n age = f\"{random.randint(21,60)}\"\n amount = random.randint(1000,999999)\n zipc = random.randint(10000,99999)\n stre = f\"ST{random.randint(23,99)}\"\n tel = f\"07{random.randint(10000000,99999999)}\"\n lastp = f\"{str(random.randint(1,28)).zfill(2)}/{str(random.randint(1,12)).zfill(2)}/{random.randint(2020,2021)}\"\n formated = f\"{ID},{lastp},{amount},{atypes},{customid}\"\n print(formated)\n\n" }, { "alpha_fraction": 0.5302491188049316, "alphanum_fraction": 0.5843416452407837, "avg_line_length": 31.65116310119629, "blob_id": "7f344ab0e0bb3f84568c56c9c3139781f1590f37", "content_id": "9b4b885946f89c2bd32e8205e125d018932e0ff7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1405, "license_type": "no_license", "max_line_length": 119, "num_lines": 43, "path": "/dependants.py", "repo_name": "Mike-M-87/studious-octo-carnival", "src_encoding": "UTF-8", "text": "import random\n\nwith open(\"dependants.txt\") as fhand:\n name = (fhand.read().split('\\n'))\n\nwith open(\"city.txt\") as fhand:\n city = (fhand.read().split('\\n'))\n \nwith open(\"skill.txt\") as fhand:\n skill = (fhand.read().split('\\n'))\n\nwith open(\"title.txt\") as fhand:\n title = (fhand.read().split('\\n'))\n \nwith open(\"capitals.txt\") as fhand:\n capitals = (fhand.read().split('\\n'))\n\nwith open(\"address.txt\") as fhand:\n address = (fhand.read().split('\\n'))\n\nusers = 25\nbranch = [1,2,3]\nrelationship = [\"Father\",\"Mother\",\"Son\",\"Daughter\",\"Cousin\",\"Aunt\",\"Sister\",\"Brother\"]\n\nfor i in range(0,users*2,2):\n empid = random.randint(1,50)\n ID = (i // 2) +1\n state = random.choice(capitals)\n cty = random.choice(city)\n tit = random.choice(title)\n ski = random.choice(skill)\n b = random.choice(branch)\n addr = random.choice(address) \n relation = random.choice(relationship)\n age = f\"{random.randint(21,60)}\"\n n = f\"{name[i]} {name[i+1]}\"\n sal = random.randint(1000,999999)\n zipc = random.randint(10000,99999)\n stre = f\"ST{random.randint(23,99)}\"\n tel = f\"07{random.randint(10000000,99999999)}\"\n doh = f\"{str(random.randint(1,28)).zfill(2)}/{str(random.randint(1,12)).zfill(2)}/{random.randint(2015,2021)}\"\n formated = f\"{ID},{n},{age},{relation},{empid}\"\n print(formated)\n\n" }, { "alpha_fraction": 0.5658153295516968, "alphanum_fraction": 0.5893909335136414, "avg_line_length": 24.450000762939453, "blob_id": "1b0581d7e8bd515fda23f3551ff4cdce5a665555", "content_id": "4076bf909c9f049fa3d28fb40407c81937d224a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 509, "license_type": "no_license", "max_line_length": 52, "num_lines": 20, "path": "/lawz/courts.py", "repo_name": "Mike-M-87/studious-octo-carnival", "src_encoding": "UTF-8", "text": "import random\n\nwith open(\"courtnames.txt\") as f:\n cnames = f.read().strip().split(\"\\n\")\nwith open(\"city.txt\") as f:\n cities = f.read().strip().split(\"\\n\")\nwith open(\"capitals.txt\") as f:\n states = f.read().strip().split(\"\\n\")\n\nnocourts = 9\n\nfor i in range(nocourts):\n cid = i + 1\n name = cnames[i]\n city = random.choice(cities)\n state = random.choice(states)\n zip = random.randint(10000,99999)\n\n formatted = f\"{cid},{name},{city},{state},{zip}\"\n print(formatted)\n" }, { "alpha_fraction": 0.48022598028182983, "alphanum_fraction": 0.5762711763381958, "avg_line_length": 24.214284896850586, "blob_id": "d37e394db8910f9e54ceaaf7f73b6aa7c1747b48", "content_id": "0c33384bda007d30e33a5b4a3b021ee711125ca8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 354, "license_type": "no_license", "max_line_length": 43, "num_lines": 14, "path": "/ordersdetails.py", "repo_name": "Mike-M-87/studious-octo-carnival", "src_encoding": "UTF-8", "text": "import random\n\nnorders = 180\nbranch = [1,2,3]\n\nfor i in range(1,norders+1):\n ID = i\n b = random.choice(branch)\n sal = random.randint(1000,999999)\n sal = random.randint(1000,999999)\n quant = random.randint(1,30)\n itemid = random.randint(1,36)\n formated = f\"{ID},{b},{quant},{itemid}\"\n print(formated)\n\n" } ]
12
vyakhorev/Py4J_try
https://github.com/vyakhorev/Py4J_try
620d7be3372e52180fa927a453c755cb2e4edc9f
e369e9b1e9c7c03a61f1fb14d5370e87bc6eec5e
c684dd1f547e3cd2a47fe6e82cc3b95c36f79c58
refs/heads/master
2020-03-31T02:38:20.928881
2018-10-09T20:19:04
2018-10-09T20:19:04
151,833,439
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6683119535446167, "alphanum_fraction": 0.701875627040863, "avg_line_length": 31.677419662475586, "blob_id": "ebd5ac3dea52007ad418136eebc3d65e1c26cbb3", "content_id": "116358f7585950d64c8dccc05ea302498ac460a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1013, "license_type": "no_license", "max_line_length": 108, "num_lines": 31, "path": "/user_file.py", "repo_name": "vyakhorev/Py4J_try", "src_encoding": "UTF-8", "text": "\n'''\nBy design, this file is edited by user.\nTodo: multiple files design, call queue, non-static context\n'''\n\nimport time # TODO: Keras\nimport random\n\nimport logging\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(logging.StreamHandler())\n\ndef NeuralNetCall(data_dict):\n logger.info(\"I am a really smart neuralnet and I need some time to think about this point of data\")\n time.sleep(0.5)\n logger.info(\"So this is {}\".format(data_dict))\n time.sleep(0.5)\n logger.info(\"Getting really convolutional\")\n time.sleep(2)\n ans = random.random()\n logger.info(\"I found it! The PD is equal to {}\".format(ans))\n return ans\n\n\ndef SomeLogisticRegression(data_dict):\n logger.info(\"I wonder can I classify this mess?... This is some peace of outliner {}\".format(data_dict))\n time.sleep(1)\n ans = random.choice([3.1415926, 2.718281828, 1.618033988])\n logger.info(\"have no idea what PD is but the answer should be equal to {}\".format(ans))\n return ans" }, { "alpha_fraction": 0.6495575308799744, "alphanum_fraction": 0.6707964539527893, "avg_line_length": 28.736841201782227, "blob_id": "a9552e871da987afd4f48ea91a79d14ccdd8c668", "content_id": "4acb4ecb69f81c04374f87414f38a9f4fac88413", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 565, "license_type": "no_license", "max_line_length": 88, "num_lines": 19, "path": "/JavaApp/src/py4jJavaCalcServer/DataBaseObjectInstance.java", "repo_name": "vyakhorev/Py4J_try", "src_encoding": "UTF-8", "text": "package py4jJavaCalcServer;\n\nimport java.util.HashMap;\n\npublic class DataBaseObjectInstance {\n /** Represents an object in the database\n * */\n\n public HashMap<Object, Object> getDataFromDatabase() {\n HashMap<Object, Object> immutable_database_data = new HashMap<Object, Object>();\n /* Some data required to calculate */\n immutable_database_data.put(\"Height\", 170.0);\n immutable_database_data.put(\"AverageIncome\", 100000.0);\n immutable_database_data.put(\"Gender\", \"M\");\n return immutable_database_data;\n }\n\n\n}\n" }, { "alpha_fraction": 0.708791196346283, "alphanum_fraction": 0.7472527623176575, "avg_line_length": 44.375, "blob_id": "eb8ac4fab400c0e19db86a15d90973893ac3ca43", "content_id": "06a5b65f4960375b35e4d8dd8b5d2695d9add504", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 364, "license_type": "no_license", "max_line_length": 92, "num_lines": 8, "path": "/README.md", "repo_name": "vyakhorev/Py4J_try", "src_encoding": "UTF-8", "text": "An example on how to use Python toghether with Java.\n\nSetup:\n1. Python 3.7 and Java 1.8 \n2. Install [py4j module](https://www.py4j.org/advanced_topics.html) (available in pip).\n3. Take the .jar file from PythonDirectory\\share\\py4j\\ and paste it to Py4J_try\\JavaApp\\ext\\\n4. Open JavaApp directory as a Java project, run it.\n5. Run main.py from Py4J_try directory.\n " }, { "alpha_fraction": 0.6564748287200928, "alphanum_fraction": 0.6594724059104919, "avg_line_length": 36.0444450378418, "blob_id": "e721a3689f4cde630ada8ed15b9104439ee7541f", "content_id": "cb798dfd8c51cfae949f703e396146bface2ae4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1668, "license_type": "no_license", "max_line_length": 95, "num_lines": 45, "path": "/py4jPythonCalcServer/interfaces/PythonScriptCallback.py", "repo_name": "vyakhorev/Py4J_try", "src_encoding": "UTF-8", "text": "\nimport logging\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(logging.StreamHandler())\n\n\n# TODO: heap queue in calculate call to manage the load\nclass PythonScriptCallback:\n '''\n 1. On statup we create an instance of this class per function in user_file.py.\n 2. RiskCalcServer.register_callback(callback) registers this instance in Java application.\n 3. When needed, Java application calls public Double callPythonScript(String script_name)\n and passes immutable data (a dictionary with strings-numbers) into it. This invokes\n calculate(self, calc_context) call.\n '''\n\n class Java:\n implements = [\"py4jJavaCalcServer.PythonScriptCallback\"]\n\n def __init__(self, server, script):\n '''\n :param server: RiskCalcServer instance. Not in use yet.\n :param script: python callable that can take a dictionary.\n '''\n self.server = server\n self.script = script\n self.script_name = script.__name__ # function name to be precise\n\n def __repr__(self):\n return \"a callback to {}\".format(self.script_name)\n\n def get_script_name(self) -> str:\n '''\n :return: a unique-per-app string. Shall be used as a key to call this script\n '''\n return self.script_name\n\n def calculate(self, calc_context) -> float:\n '''\n :param calc_context: py4j.java_collections.JavaMap instance - works as a regular dict()\n :return: some float number that results from this calculation\n '''\n ans = self.script(calc_context)\n logger.info(\"{} is called\".format(self.script_name))\n return ans\n" }, { "alpha_fraction": 0.6729810833930969, "alphanum_fraction": 0.6819541454315186, "avg_line_length": 27.657142639160156, "blob_id": "1b44508c0775062450368aac6aee34c690b89b3f", "content_id": "4a52275a389a062ff422e61237c254a7471e1f78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1003, "license_type": "no_license", "max_line_length": 85, "num_lines": 35, "path": "/main.py", "repo_name": "vyakhorev/Py4J_try", "src_encoding": "UTF-8", "text": "\n'''\nBy design this application is supplied with open source\n'''\n\n__author__ = \"Alexey Vyakhorev\"\n\nfrom py4jPythonCalcServer.interfaces.PythonScriptCallback import PythonScriptCallback\nfrom py4jPythonCalcServer.server import RiskCalcServer\n\nimport time\nimport user_file\n\nimport logging\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(logging.StreamHandler())\n\nif __name__ == \"__main__\":\n # Start python server\n java_connector = RiskCalcServer() # uses Py4J event loop\n java_connector.start()\n\n # register all callables from user_file (not the best design yet)\n for f in user_file.__dict__.values():\n if callable(f):\n callback = PythonScriptCallback(java_connector, f)\n java_connector.register_callback(callback)\n\n # shutdown after a ~minute\n for x in range(0, 59):\n time.sleep(1)\n if x%2 == 0: logger.debug('{} - tick'.format(x))\n else: logger.debug('{} - tock'.format(x))\n\n java_connector.shutdown()" }, { "alpha_fraction": 0.7322899699211121, "alphanum_fraction": 0.7364085912704468, "avg_line_length": 38.129032135009766, "blob_id": "16a579a9646d748685b70ee5d301187dbd288154", "content_id": "f5d3486041ce4bc1692e65ac417a0d3a382fc3ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1214, "license_type": "no_license", "max_line_length": 96, "num_lines": 31, "path": "/py4jPythonCalcServer/server.py", "repo_name": "vyakhorev/Py4J_try", "src_encoding": "UTF-8", "text": "\n# Alternative (https://www.py4j.org/py4j_client_server.html#module-py4j.clientserver):\n# from py4j.clientserver import ClientServer, JavaParameters, PythonParameters\n# gateway = ClientServer(java_parameters=JavaParameters(), python_parameters=PythonParameters())\n\nfrom py4j.java_gateway import JavaGateway, CallbackServerParameters\n\nimport logging\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(logging.StreamHandler())\n\nclass RiskCalcServer:\n\n def __init__(self):\n self.java_gateway = None # gateway\n\n def start(self):\n # self.java_gateway.entry_point - a PythonServiceApp instance replica\n # self.java_gateway.jvm - jvm replica\n self.java_gateway = JavaGateway(callback_server_parameters=CallbackServerParameters())\n self.java_gateway.setPythonCalcServerStatusAlive()\n logger.info(\"String the server\")\n\n def shutdown(self):\n self.java_gateway.setPythonCalcServerStatusDead()\n self.java_gateway.shutdown()\n logger.info(\"Shutting down the server\")\n\n def register_callback(self, new_callback):\n self.java_gateway.registerCallback(new_callback)\n logger.info(\"Registering the callback\")\n" } ]
6
kubzoey95/GildedRose-Refactoring-Kata
https://github.com/kubzoey95/GildedRose-Refactoring-Kata
207f54b52d78dd5040273177b2bda031c26e48f7
2a7ea20bb4db3a699a41ce07c4d632a38a6556e8
9b5c007b5cb3bf74de9375499ac928bae587ee50
refs/heads/master
2020-04-05T22:34:21.074255
2019-01-08T18:54:27
2019-01-08T18:54:27
157,260,941
0
0
null
2018-11-12T18:54:21
2018-11-03T18:35:54
2018-10-31T06:32:41
null
[ { "alpha_fraction": 0.58849036693573, "alphanum_fraction": 0.5947970151901245, "avg_line_length": 24.626262664794922, "blob_id": "9baaf6c6c65e2fc926736d49d866a05f78bf316d", "content_id": "e04914b607e5bd751cda08165bc23023f057383a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2537, "license_type": "permissive", "max_line_length": 72, "num_lines": 99, "path": "/python/gilded_rose.py", "repo_name": "kubzoey95/GildedRose-Refactoring-Kata", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nCONJURED_ITEM = \"Conjured\"\n\nBACKSTAGE_PASSES = \"Backstage passes to a TAFKAL80ETC concert\"\n\nSULFURAS = \"Sulfuras, Hand of Ragnaros\"\n\nAGED_BRIE = \"Aged Brie\"\n\n\nclass GildedRose(object):\n\n def __init__(self, items):\n self.items = items\n\n def update_quality(self):\n for item in self.items:\n item.update_quality()\n\n\nclass Item:\n def __init__(self, name, sell_in, quality):\n self.name = name\n self.sell_in = sell_in\n self.quality = quality\n\n def __repr__(self):\n return \"%s, %s, %s\" % (self.name, self.sell_in, self.quality)\n\n\nclass UpdateableItem(Item):\n\n @staticmethod\n def item_from_name(name, sell_in, quality):\n types = {\n AGED_BRIE: lambda: AgedBrie(sell_in, quality),\n SULFURAS: lambda: Sulfuras(sell_in, quality),\n BACKSTAGE_PASSES: lambda: BackstagePasses(sell_in, quality),\n CONJURED_ITEM: lambda: Conjured(sell_in, quality)\n }\n\n is_other = {\n True: lambda: types[name](),\n False: lambda: PlainItem(name, sell_in, quality)\n }\n\n return is_other[name in types]()\n\n def item_specific_update(self):\n pass\n\n def update_quality(self):\n self.item_specific_update()\n self.quality = max(0, self.quality)\n self.quality = min(50, self.quality)\n self.sell_in -= 1\n\n\nclass AgedBrie(UpdateableItem):\n def __init__(self, sell_in, quality):\n super().__init__(AGED_BRIE, sell_in, quality)\n\n def item_specific_update(self):\n self.quality += 1 + (self.sell_in <= 0)\n\n\nclass Sulfuras(UpdateableItem):\n def __init__(self, sell_in, quality):\n super().__init__(SULFURAS, sell_in, quality)\n\n def update_quality(self):\n pass\n\n\nclass BackstagePasses(UpdateableItem):\n def __init__(self, sell_in, quality):\n super().__init__(BACKSTAGE_PASSES, sell_in, quality)\n\n def item_specific_update(self):\n self.quality += (self.sell_in <= 5) + (self.sell_in <= 10) + 1\n self.quality *= self.sell_in > 0\n\n\nclass PlainItem(UpdateableItem):\n def __init__(self, name, sell_in, quality):\n super().__init__(name, sell_in, quality)\n\n def item_specific_update(self):\n self.quality -= 1 + (self.sell_in <= 0)\n\n\nclass Conjured(PlainItem):\n def __init__(self, sell_in, quality):\n super().__init__(CONJURED_ITEM, sell_in, quality)\n\n def item_specific_update(self):\n super().item_specific_update()\n super().item_specific_update()\n" }, { "alpha_fraction": 0.5196772813796997, "alphanum_fraction": 0.5539272427558899, "avg_line_length": 46.077518463134766, "blob_id": "7355006247bf224fb0bb3e0af32dcfbeb23fde0d", "content_id": "e96925835c7b6c393447bec2c9fca7311bcdb03c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6073, "license_type": "permissive", "max_line_length": 120, "num_lines": 129, "path": "/python/test_gilded_rose.py", "repo_name": "kubzoey95/GildedRose-Refactoring-Kata", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport unittest\nimport random\n\nfrom gilded_rose import UpdateableItem, GildedRose\n\n\nclass GildedRoseTest(unittest.TestCase):\n def test_foo(self):\n items = [UpdateableItem.item_from_name(\"foo\", 0, 0)]\n gilded_rose = GildedRose(items)\n gilded_rose.update_quality()\n self.assertEqual(\"foo\", items[0].name)\n\n def test_conjured(self):\n for _ in range(200):\n primary = [random.randint(-100, -1), random.randint(15, 50)]\n items = [UpdateableItem.item_from_name(name=\"Conjured\", sell_in=primary[0], quality=primary[1])]\n gild = GildedRose(items)\n gild.update_quality()\n self.assertEqual(primary[1] - gild.items[0].quality, 4)\n primary[1] = gild.items[0].quality\n gild.items[0].sell_in = random.randint(2, 100)\n gild.update_quality()\n self.assertEqual(primary[1] - gild.items[0].quality, 2)\n\n def test_sulfuras(self):\n for _ in range(10):\n qual = random.randint(0, 500)\n items = [UpdateableItem.item_from_name(\"Sulfuras, Hand of Ragnaros\", sell_in=random.randint(10, 500),\n quality=qual)]\n gild = GildedRose(items)\n [gild.update_quality() for _ in range(random.randint(10, 1000))]\n self.assertEqual(qual, gild.items[0].quality)\n\n def test_brie(self):\n for _ in range(100):\n qual = random.randint(0, 25)\n items = [UpdateableItem.item_from_name(\"Aged Brie\", sell_in=random.randint(10, 50), quality=qual)]\n gild = GildedRose(items)\n iters = random.randint(1, 5)\n [gild.update_quality() for _ in range(iters)]\n after_qual = gild.items[0].quality\n self.assertEqual(1, (after_qual - qual) / iters)\n\n def test_brie_aging(self):\n for _ in range(100):\n qual = random.randint(0, 25)\n items = [UpdateableItem.item_from_name(\"Aged Brie\", sell_in=random.randint(-10, -1), quality=qual)]\n gild = GildedRose(items)\n iters = random.randint(1, 5)\n [gild.update_quality() for _ in range(iters)]\n after_qual = gild.items[0].quality\n self.assertEqual(2, (after_qual - qual) / iters)\n\n def test_passes_3(self):\n for _ in range(3):\n qual = random.randint(0, 20)\n sell = random.randint(1, 5)\n items = [\n UpdateableItem.item_from_name(\"Backstage passes to a TAFKAL80ETC concert\", sell_in=sell, quality=qual)]\n gild = GildedRose(items)\n gild.update_quality()\n after_qual = gild.items[0].quality\n self.assertEqual(3, (after_qual - qual))\n\n def test_passes_2(self):\n for _ in range(3):\n qual = random.randint(0, 40)\n items = [UpdateableItem.item_from_name(\"Backstage passes to a TAFKAL80ETC concert\",\n sell_in=random.randint(6, 10), quality=qual)]\n gild = GildedRose(items)\n gild.update_quality()\n after_qual = gild.items[0].quality\n self.assertEqual(2, (after_qual - qual))\n\n def test_passes_1(self):\n for _ in range(3):\n qual = random.randint(0, 40)\n items = [UpdateableItem.item_from_name(\"Backstage passes to a TAFKAL80ETC concert\",\n sell_in=random.randint(11, 100), quality=qual)]\n gild = GildedRose(items)\n gild.update_quality()\n after_qual = gild.items[0].quality\n self.assertEqual(1, (after_qual - qual))\n\n def test_passes_0(self):\n for _ in range(3):\n items = [UpdateableItem.item_from_name(\"Backstage passes to a TAFKAL80ETC concert\",\n sell_in=random.randint(10, 100), quality=random.randint(0, 50))]\n gild = GildedRose(items)\n [gild.update_quality() for _ in range(200)]\n self.assertEqual(0, gild.items[0].quality)\n\n def test_positive(self):\n items = [\n UpdateableItem.item_from_name(\"Backstage passes to a TAFKAL80ETC concert\", sell_in=random.randint(6, 10),\n quality=random.randint(10, 20)),\n UpdateableItem.item_from_name(\"Aged Brie\", sell_in=random.randint(0, 20), quality=random.randint(5, 15)),\n UpdateableItem.item_from_name(\"Sulfuras, Hand of Ragnaros\", sell_in=random.randint(0, 20),\n quality=random.randint(5, 25)),\n UpdateableItem.item_from_name(name=\"Conjured Mana Cake\", sell_in=random.randint(0, 20),\n quality=random.randint(1, 8)),\n UpdateableItem.item_from_name(\"foo\", 0, 0)]\n gild = GildedRose(items)\n for _ in range(200):\n gild.update_quality()\n for item in gild.items:\n self.assertTrue(item.quality >= 0)\n\n def test_always_smaller_than_50(self):\n items = [\n UpdateableItem.item_from_name(\"Backstage passes to a TAFKAL80ETC concert\", sell_in=random.randint(200, 300),\n quality=random.randint(10, 20)),\n UpdateableItem.item_from_name(\"Aged Brie\", sell_in=random.randint(200, 300), quality=random.randint(5, 15)),\n UpdateableItem.item_from_name(\"Sulfuras, Hand of Ragnaros\", sell_in=random.randint(200, 300),\n quality=random.randint(5, 25)),\n UpdateableItem.item_from_name(name=\"Conjured Mana Cake\", sell_in=random.randint(200, 300),\n quality=random.randint(1, 8)),\n UpdateableItem.item_from_name(\"foo\", 0, 0)]\n gild = GildedRose(items)\n for _ in range(200):\n gild.update_quality()\n for item in gild.items:\n self.assertTrue(item.quality <= 50)\n\n\nif __name__ == '__main__':\n unittest.main()\n" } ]
2
chiragsolanki18/AutobotX
https://github.com/chiragsolanki18/AutobotX
2fe616f9e0c8461663bdc20c9005984dd7b9b5b1
caee27496a52a307c56fa2b32e3b09922c8ff394
fd9d058445272fb5f63543c26dbef3832763b16f
refs/heads/master
2020-05-01T16:34:58.299664
2019-05-24T18:16:13
2019-05-24T18:16:13
177,575,702
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.775957465171814, "alphanum_fraction": 0.7761744856834412, "avg_line_length": 33.781131744384766, "blob_id": "ca170348209c8ebf3e184e7e2999390c8f43d3a0", "content_id": "03fbdc1a9c5cb84f864bdc91997e65e119dfc3c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 9217, "license_type": "no_license", "max_line_length": 190, "num_lines": 265, "path": "/catkin_ws/build/autobotx/cmake/autobotx-genmsg.cmake", "repo_name": "chiragsolanki18/AutobotX", "src_encoding": "UTF-8", "text": "# generated from genmsg/cmake/pkg-genmsg.cmake.em\n\nmessage(STATUS \"autobotx: 1 messages, 0 services\")\n\nset(MSG_I_FLAGS \"-Iautobotx:/home/robox/catkin_ws/src/autobotx/msg;-Igeometry_msgs:/opt/ros/kinetic/share/geometry_msgs/cmake/../msg;-Istd_msgs:/opt/ros/kinetic/share/std_msgs/cmake/../msg\")\n\n# Find all generators\nfind_package(gencpp REQUIRED)\nfind_package(geneus REQUIRED)\nfind_package(genlisp REQUIRED)\nfind_package(gennodejs REQUIRED)\nfind_package(genpy REQUIRED)\n\nadd_custom_target(autobotx_generate_messages ALL)\n\n# verify that message/service dependencies have not changed since configure\n\n\n\nget_filename_component(_filename \"/home/robox/catkin_ws/src/autobotx/msg/Unicycle.msg\" NAME_WE)\nadd_custom_target(_autobotx_generate_messages_check_deps_${_filename}\n COMMAND ${CATKIN_ENV} ${PYTHON_EXECUTABLE} ${GENMSG_CHECK_DEPS_SCRIPT} \"autobotx\" \"/home/robox/catkin_ws/src/autobotx/msg/Unicycle.msg\" \"\"\n)\n\n#\n# langs = gencpp;geneus;genlisp;gennodejs;genpy\n#\n\n### Section generating for lang: gencpp\n### Generating Messages\n_generate_msg_cpp(autobotx\n \"/home/robox/catkin_ws/src/autobotx/msg/Unicycle.msg\"\n \"${MSG_I_FLAGS}\"\n \"\"\n ${CATKIN_DEVEL_PREFIX}/${gencpp_INSTALL_DIR}/autobotx\n)\n\n### Generating Services\n\n### Generating Module File\n_generate_module_cpp(autobotx\n ${CATKIN_DEVEL_PREFIX}/${gencpp_INSTALL_DIR}/autobotx\n \"${ALL_GEN_OUTPUT_FILES_cpp}\"\n)\n\nadd_custom_target(autobotx_generate_messages_cpp\n DEPENDS ${ALL_GEN_OUTPUT_FILES_cpp}\n)\nadd_dependencies(autobotx_generate_messages autobotx_generate_messages_cpp)\n\n# add dependencies to all check dependencies targets\nget_filename_component(_filename \"/home/robox/catkin_ws/src/autobotx/msg/Unicycle.msg\" NAME_WE)\nadd_dependencies(autobotx_generate_messages_cpp _autobotx_generate_messages_check_deps_${_filename})\n\n# target for backward compatibility\nadd_custom_target(autobotx_gencpp)\nadd_dependencies(autobotx_gencpp autobotx_generate_messages_cpp)\n\n# register target for catkin_package(EXPORTED_TARGETS)\nlist(APPEND ${PROJECT_NAME}_EXPORTED_TARGETS autobotx_generate_messages_cpp)\n\n### Section generating for lang: geneus\n### Generating Messages\n_generate_msg_eus(autobotx\n \"/home/robox/catkin_ws/src/autobotx/msg/Unicycle.msg\"\n \"${MSG_I_FLAGS}\"\n \"\"\n ${CATKIN_DEVEL_PREFIX}/${geneus_INSTALL_DIR}/autobotx\n)\n\n### Generating Services\n\n### Generating Module File\n_generate_module_eus(autobotx\n ${CATKIN_DEVEL_PREFIX}/${geneus_INSTALL_DIR}/autobotx\n \"${ALL_GEN_OUTPUT_FILES_eus}\"\n)\n\nadd_custom_target(autobotx_generate_messages_eus\n DEPENDS ${ALL_GEN_OUTPUT_FILES_eus}\n)\nadd_dependencies(autobotx_generate_messages autobotx_generate_messages_eus)\n\n# add dependencies to all check dependencies targets\nget_filename_component(_filename \"/home/robox/catkin_ws/src/autobotx/msg/Unicycle.msg\" NAME_WE)\nadd_dependencies(autobotx_generate_messages_eus _autobotx_generate_messages_check_deps_${_filename})\n\n# target for backward compatibility\nadd_custom_target(autobotx_geneus)\nadd_dependencies(autobotx_geneus autobotx_generate_messages_eus)\n\n# register target for catkin_package(EXPORTED_TARGETS)\nlist(APPEND ${PROJECT_NAME}_EXPORTED_TARGETS autobotx_generate_messages_eus)\n\n### Section generating for lang: genlisp\n### Generating Messages\n_generate_msg_lisp(autobotx\n \"/home/robox/catkin_ws/src/autobotx/msg/Unicycle.msg\"\n \"${MSG_I_FLAGS}\"\n \"\"\n ${CATKIN_DEVEL_PREFIX}/${genlisp_INSTALL_DIR}/autobotx\n)\n\n### Generating Services\n\n### Generating Module File\n_generate_module_lisp(autobotx\n ${CATKIN_DEVEL_PREFIX}/${genlisp_INSTALL_DIR}/autobotx\n \"${ALL_GEN_OUTPUT_FILES_lisp}\"\n)\n\nadd_custom_target(autobotx_generate_messages_lisp\n DEPENDS ${ALL_GEN_OUTPUT_FILES_lisp}\n)\nadd_dependencies(autobotx_generate_messages autobotx_generate_messages_lisp)\n\n# add dependencies to all check dependencies targets\nget_filename_component(_filename \"/home/robox/catkin_ws/src/autobotx/msg/Unicycle.msg\" NAME_WE)\nadd_dependencies(autobotx_generate_messages_lisp _autobotx_generate_messages_check_deps_${_filename})\n\n# target for backward compatibility\nadd_custom_target(autobotx_genlisp)\nadd_dependencies(autobotx_genlisp autobotx_generate_messages_lisp)\n\n# register target for catkin_package(EXPORTED_TARGETS)\nlist(APPEND ${PROJECT_NAME}_EXPORTED_TARGETS autobotx_generate_messages_lisp)\n\n### Section generating for lang: gennodejs\n### Generating Messages\n_generate_msg_nodejs(autobotx\n \"/home/robox/catkin_ws/src/autobotx/msg/Unicycle.msg\"\n \"${MSG_I_FLAGS}\"\n \"\"\n ${CATKIN_DEVEL_PREFIX}/${gennodejs_INSTALL_DIR}/autobotx\n)\n\n### Generating Services\n\n### Generating Module File\n_generate_module_nodejs(autobotx\n ${CATKIN_DEVEL_PREFIX}/${gennodejs_INSTALL_DIR}/autobotx\n \"${ALL_GEN_OUTPUT_FILES_nodejs}\"\n)\n\nadd_custom_target(autobotx_generate_messages_nodejs\n DEPENDS ${ALL_GEN_OUTPUT_FILES_nodejs}\n)\nadd_dependencies(autobotx_generate_messages autobotx_generate_messages_nodejs)\n\n# add dependencies to all check dependencies targets\nget_filename_component(_filename \"/home/robox/catkin_ws/src/autobotx/msg/Unicycle.msg\" NAME_WE)\nadd_dependencies(autobotx_generate_messages_nodejs _autobotx_generate_messages_check_deps_${_filename})\n\n# target for backward compatibility\nadd_custom_target(autobotx_gennodejs)\nadd_dependencies(autobotx_gennodejs autobotx_generate_messages_nodejs)\n\n# register target for catkin_package(EXPORTED_TARGETS)\nlist(APPEND ${PROJECT_NAME}_EXPORTED_TARGETS autobotx_generate_messages_nodejs)\n\n### Section generating for lang: genpy\n### Generating Messages\n_generate_msg_py(autobotx\n \"/home/robox/catkin_ws/src/autobotx/msg/Unicycle.msg\"\n \"${MSG_I_FLAGS}\"\n \"\"\n ${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/autobotx\n)\n\n### Generating Services\n\n### Generating Module File\n_generate_module_py(autobotx\n ${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/autobotx\n \"${ALL_GEN_OUTPUT_FILES_py}\"\n)\n\nadd_custom_target(autobotx_generate_messages_py\n DEPENDS ${ALL_GEN_OUTPUT_FILES_py}\n)\nadd_dependencies(autobotx_generate_messages autobotx_generate_messages_py)\n\n# add dependencies to all check dependencies targets\nget_filename_component(_filename \"/home/robox/catkin_ws/src/autobotx/msg/Unicycle.msg\" NAME_WE)\nadd_dependencies(autobotx_generate_messages_py _autobotx_generate_messages_check_deps_${_filename})\n\n# target for backward compatibility\nadd_custom_target(autobotx_genpy)\nadd_dependencies(autobotx_genpy autobotx_generate_messages_py)\n\n# register target for catkin_package(EXPORTED_TARGETS)\nlist(APPEND ${PROJECT_NAME}_EXPORTED_TARGETS autobotx_generate_messages_py)\n\n\n\nif(gencpp_INSTALL_DIR AND EXISTS ${CATKIN_DEVEL_PREFIX}/${gencpp_INSTALL_DIR}/autobotx)\n # install generated code\n install(\n DIRECTORY ${CATKIN_DEVEL_PREFIX}/${gencpp_INSTALL_DIR}/autobotx\n DESTINATION ${gencpp_INSTALL_DIR}\n )\nendif()\nif(TARGET geometry_msgs_generate_messages_cpp)\n add_dependencies(autobotx_generate_messages_cpp geometry_msgs_generate_messages_cpp)\nendif()\nif(TARGET std_msgs_generate_messages_cpp)\n add_dependencies(autobotx_generate_messages_cpp std_msgs_generate_messages_cpp)\nendif()\n\nif(geneus_INSTALL_DIR AND EXISTS ${CATKIN_DEVEL_PREFIX}/${geneus_INSTALL_DIR}/autobotx)\n # install generated code\n install(\n DIRECTORY ${CATKIN_DEVEL_PREFIX}/${geneus_INSTALL_DIR}/autobotx\n DESTINATION ${geneus_INSTALL_DIR}\n )\nendif()\nif(TARGET geometry_msgs_generate_messages_eus)\n add_dependencies(autobotx_generate_messages_eus geometry_msgs_generate_messages_eus)\nendif()\nif(TARGET std_msgs_generate_messages_eus)\n add_dependencies(autobotx_generate_messages_eus std_msgs_generate_messages_eus)\nendif()\n\nif(genlisp_INSTALL_DIR AND EXISTS ${CATKIN_DEVEL_PREFIX}/${genlisp_INSTALL_DIR}/autobotx)\n # install generated code\n install(\n DIRECTORY ${CATKIN_DEVEL_PREFIX}/${genlisp_INSTALL_DIR}/autobotx\n DESTINATION ${genlisp_INSTALL_DIR}\n )\nendif()\nif(TARGET geometry_msgs_generate_messages_lisp)\n add_dependencies(autobotx_generate_messages_lisp geometry_msgs_generate_messages_lisp)\nendif()\nif(TARGET std_msgs_generate_messages_lisp)\n add_dependencies(autobotx_generate_messages_lisp std_msgs_generate_messages_lisp)\nendif()\n\nif(gennodejs_INSTALL_DIR AND EXISTS ${CATKIN_DEVEL_PREFIX}/${gennodejs_INSTALL_DIR}/autobotx)\n # install generated code\n install(\n DIRECTORY ${CATKIN_DEVEL_PREFIX}/${gennodejs_INSTALL_DIR}/autobotx\n DESTINATION ${gennodejs_INSTALL_DIR}\n )\nendif()\nif(TARGET geometry_msgs_generate_messages_nodejs)\n add_dependencies(autobotx_generate_messages_nodejs geometry_msgs_generate_messages_nodejs)\nendif()\nif(TARGET std_msgs_generate_messages_nodejs)\n add_dependencies(autobotx_generate_messages_nodejs std_msgs_generate_messages_nodejs)\nendif()\n\nif(genpy_INSTALL_DIR AND EXISTS ${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/autobotx)\n install(CODE \"execute_process(COMMAND \\\"/usr/bin/python\\\" -m compileall \\\"${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/autobotx\\\")\")\n # install generated code\n install(\n DIRECTORY ${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/autobotx\n DESTINATION ${genpy_INSTALL_DIR}\n )\nendif()\nif(TARGET geometry_msgs_generate_messages_py)\n add_dependencies(autobotx_generate_messages_py geometry_msgs_generate_messages_py)\nendif()\nif(TARGET std_msgs_generate_messages_py)\n add_dependencies(autobotx_generate_messages_py std_msgs_generate_messages_py)\nendif()\n" }, { "alpha_fraction": 0.801047146320343, "alphanum_fraction": 0.801047146320343, "avg_line_length": 46.75, "blob_id": "4e8c62efae0bc6472bd252b60323ccefdb866178", "content_id": "ec84e340fea1ba46716b15027b71fbf16a40e70a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 191, "license_type": "no_license", "max_line_length": 71, "num_lines": 4, "path": "/catkin_ws/devel/share/autobotx/cmake/autobotx-msg-paths.cmake", "repo_name": "chiragsolanki18/AutobotX", "src_encoding": "UTF-8", "text": "# generated from genmsg/cmake/pkg-msg-paths.cmake.develspace.in\n\nset(autobotx_MSG_INCLUDE_DIRS \"/home/robox/catkin_ws/src/autobotx/msg\")\nset(autobotx_MSG_DEPENDENCIES geometry_msgs;std_msgs)\n" }, { "alpha_fraction": 0.7838541865348816, "alphanum_fraction": 0.7838541865348816, "avg_line_length": 37.400001525878906, "blob_id": "dfdae3e53f304fd1d8dfb9fb3f46081dc01ccd0f", "content_id": "18efcc764d054cd1a2dd742892047d74e2d9e783", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 384, "license_type": "no_license", "max_line_length": 91, "num_lines": 10, "path": "/catkin_ws/build/autobotx/CMakeFiles/autobotx_generate_messages_eus.dir/cmake_clean.cmake", "repo_name": "chiragsolanki18/AutobotX", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/autobotx_generate_messages_eus\"\n \"/home/robox/catkin_ws/devel/share/roseus/ros/autobotx/msg/Unicycle.l\"\n \"/home/robox/catkin_ws/devel/share/roseus/ros/autobotx/manifest.l\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang )\n include(CMakeFiles/autobotx_generate_messages_eus.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7438634037971497, "alphanum_fraction": 0.7481323480606079, "avg_line_length": 57.625, "blob_id": "56d011466daabacf12bed40b75d663cf60e60abe", "content_id": "614dacf1518295bbbd4cefeb4141b239c7e25653", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 937, "license_type": "no_license", "max_line_length": 152, "num_lines": 16, "path": "/catkin_ws/build/autobotx/catkin_generated/package.cmake", "repo_name": "chiragsolanki18/AutobotX", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"autobotx\")\nset(autobotx_VERSION \"0.0.0\")\nset(autobotx_MAINTAINER \"robox <[email protected]>\")\nset(autobotx_PACKAGE_FORMAT \"2\")\nset(autobotx_BUILD_DEPENDS \"message_generation\" \"roscpp\" \"rospy\" \"std_msgs\" \"tf\" \"nav_msgs\" \"message_runtime\" \"geometry_msgs\" \"depthimage_to_laserscan\")\nset(autobotx_BUILD_EXPORT_DEPENDS \"roscpp\" \"rospy\" \"std_msgs\" \"tf\" \"nav_msgs\" \"geometry_msgs\" \"depthimage_to_laserscan\")\nset(autobotx_BUILDTOOL_DEPENDS \"catkin\")\nset(autobotx_BUILDTOOL_EXPORT_DEPENDS )\nset(autobotx_EXEC_DEPENDS \"message_runtime\" \"roscpp\" \"rospy\" \"std_msgs\" \"tf\" \"nav_msgs\" \"geometry_msgs\" \"depthimage_to_laserscan\")\nset(autobotx_RUN_DEPENDS \"message_runtime\" \"roscpp\" \"rospy\" \"std_msgs\" \"tf\" \"nav_msgs\" \"geometry_msgs\" \"depthimage_to_laserscan\")\nset(autobotx_TEST_DEPENDS )\nset(autobotx_DOC_DEPENDS )\nset(autobotx_URL_WEBSITE \"\")\nset(autobotx_URL_BUGTRACKER \"\")\nset(autobotx_URL_REPOSITORY \"\")\nset(autobotx_DEPRECATED \"\")" }, { "alpha_fraction": 0.7584415674209595, "alphanum_fraction": 0.7584415674209595, "avg_line_length": 34, "blob_id": "a53e345389d1054d1f95988e4261c02d464d9c13", "content_id": "f9886a2875193e8207b8ad9504d9d87ec9e139dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 385, "license_type": "no_license", "max_line_length": 68, "num_lines": 11, "path": "/catkin_ws/build/autobotx/CMakeFiles/my_libs.dir/cmake_clean.cmake", "repo_name": "chiragsolanki18/AutobotX", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/my_libs.dir/src/mavlink_communication.cpp.o\"\n \"CMakeFiles/my_libs.dir/src/serial_port.cpp.o\"\n \"/home/robox/catkin_ws/devel/lib/libmy_libs.pdb\"\n \"/home/robox/catkin_ws/devel/lib/libmy_libs.so\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/my_libs.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7795458436012268, "alphanum_fraction": 0.7817658185958862, "avg_line_length": 44.14842987060547, "blob_id": "654d6cc1e477997b2524d208f1b647740e7a795e", "content_id": "7f6bee711c88138e61f6f2be698289b8fdabda46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 59010, "license_type": "no_license", "max_line_length": 206, "num_lines": 1307, "path": "/catkin_ws/build/autobotx/Makefile", "repo_name": "chiragsolanki18/AutobotX", "src_encoding": "UTF-8", "text": "# CMAKE generated file: DO NOT EDIT!\n# Generated by \"Unix Makefiles\" Generator, CMake Version 3.5\n\n# Default target executed when no arguments are given to make.\ndefault_target: all\n\n.PHONY : default_target\n\n# Allow only one \"make -f Makefile2\" at a time, but pass parallelism.\n.NOTPARALLEL:\n\n\n#=============================================================================\n# Special targets provided by cmake.\n\n# Disable implicit rules so canonical targets will work.\n.SUFFIXES:\n\n\n# Remove some rules from gmake that .SUFFIXES does not remove.\nSUFFIXES =\n\n.SUFFIXES: .hpux_make_needs_suffix_list\n\n\n# Suppress display of executed commands.\n$(VERBOSE).SILENT:\n\n\n# A target that is always out of date.\ncmake_force:\n\n.PHONY : cmake_force\n\n#=============================================================================\n# Set environment variables for the build.\n\n# The shell in which to execute make rules.\nSHELL = /bin/sh\n\n# The CMake executable.\nCMAKE_COMMAND = /usr/bin/cmake\n\n# The command to remove a file.\nRM = /usr/bin/cmake -E remove -f\n\n# Escaping for special characters.\nEQUALS = =\n\n# The top-level source directory on which CMake was run.\nCMAKE_SOURCE_DIR = /home/robox/catkin_ws/src\n\n# The top-level build directory on which CMake was run.\nCMAKE_BINARY_DIR = /home/robox/catkin_ws/build\n\n#=============================================================================\n# Targets provided globally by CMake.\n\n# Special rule for the target edit_cache\nedit_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"No interactive CMake dialog available...\"\n\t/usr/bin/cmake -E echo No\\ interactive\\ CMake\\ dialog\\ available.\n.PHONY : edit_cache\n\n# Special rule for the target edit_cache\nedit_cache/fast: edit_cache\n\n.PHONY : edit_cache/fast\n\n# Special rule for the target install/local\ninstall/local: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing only the local directory...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake\n.PHONY : install/local\n\n# Special rule for the target install/local\ninstall/local/fast: install/local\n\n.PHONY : install/local/fast\n\n# Special rule for the target install/strip\ninstall/strip: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Installing the project stripped...\"\n\t/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake\n.PHONY : install/strip\n\n# Special rule for the target install/strip\ninstall/strip/fast: install/strip\n\n.PHONY : install/strip/fast\n\n# Special rule for the target rebuild_cache\nrebuild_cache:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running CMake to regenerate build system...\"\n\t/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)\n.PHONY : rebuild_cache\n\n# Special rule for the target rebuild_cache\nrebuild_cache/fast: rebuild_cache\n\n.PHONY : rebuild_cache/fast\n\n# Special rule for the target list_install_components\nlist_install_components:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Available install components are: \\\"Unspecified\\\"\"\n.PHONY : list_install_components\n\n# Special rule for the target list_install_components\nlist_install_components/fast: list_install_components\n\n.PHONY : list_install_components/fast\n\n# Special rule for the target install\ninstall: preinstall\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install\n\n# Special rule for the target install\ninstall/fast: preinstall/fast\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Install the project...\"\n\t/usr/bin/cmake -P cmake_install.cmake\n.PHONY : install/fast\n\n# Special rule for the target test\ntest:\n\t@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan \"Running tests...\"\n\t/usr/bin/ctest --force-new-ctest-process $(ARGS)\n.PHONY : test\n\n# Special rule for the target test\ntest/fast: test\n\n.PHONY : test/fast\n\n# The main all target\nall: cmake_check_build_system\n\tcd /home/robox/catkin_ws/build && $(CMAKE_COMMAND) -E cmake_progress_start /home/robox/catkin_ws/build/CMakeFiles /home/robox/catkin_ws/build/autobotx/CMakeFiles/progress.marks\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/all\n\t$(CMAKE_COMMAND) -E cmake_progress_start /home/robox/catkin_ws/build/CMakeFiles 0\n.PHONY : all\n\n# The main clean target\nclean:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/clean\n.PHONY : clean\n\n# The main clean target\nclean/fast: clean\n\n.PHONY : clean/fast\n\n# Prepare targets for installation.\npreinstall: all\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/preinstall\n.PHONY : preinstall\n\n# Prepare targets for installation.\npreinstall/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/preinstall\n.PHONY : preinstall/fast\n\n# clear depends\ndepend:\n\tcd /home/robox/catkin_ws/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1\n.PHONY : depend\n\n# Convenience name for target.\nautobotx/CMakeFiles/autobotx_genpy.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/autobotx_genpy.dir/rule\n.PHONY : autobotx/CMakeFiles/autobotx_genpy.dir/rule\n\n# Convenience name for target.\nautobotx_genpy: autobotx/CMakeFiles/autobotx_genpy.dir/rule\n\n.PHONY : autobotx_genpy\n\n# fast build rule for target.\nautobotx_genpy/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/autobotx_genpy.dir/build.make autobotx/CMakeFiles/autobotx_genpy.dir/build\n.PHONY : autobotx_genpy/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/autobotx_gennodejs.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/autobotx_gennodejs.dir/rule\n.PHONY : autobotx/CMakeFiles/autobotx_gennodejs.dir/rule\n\n# Convenience name for target.\nautobotx_gennodejs: autobotx/CMakeFiles/autobotx_gennodejs.dir/rule\n\n.PHONY : autobotx_gennodejs\n\n# fast build rule for target.\nautobotx_gennodejs/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/autobotx_gennodejs.dir/build.make autobotx/CMakeFiles/autobotx_gennodejs.dir/build\n.PHONY : autobotx_gennodejs/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/autobotx_generate_messages_nodejs.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/autobotx_generate_messages_nodejs.dir/rule\n.PHONY : autobotx/CMakeFiles/autobotx_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nautobotx_generate_messages_nodejs: autobotx/CMakeFiles/autobotx_generate_messages_nodejs.dir/rule\n\n.PHONY : autobotx_generate_messages_nodejs\n\n# fast build rule for target.\nautobotx_generate_messages_nodejs/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/autobotx_generate_messages_nodejs.dir/build.make autobotx/CMakeFiles/autobotx_generate_messages_nodejs.dir/build\n.PHONY : autobotx_generate_messages_nodejs/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/autobotx_genlisp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/autobotx_genlisp.dir/rule\n.PHONY : autobotx/CMakeFiles/autobotx_genlisp.dir/rule\n\n# Convenience name for target.\nautobotx_genlisp: autobotx/CMakeFiles/autobotx_genlisp.dir/rule\n\n.PHONY : autobotx_genlisp\n\n# fast build rule for target.\nautobotx_genlisp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/autobotx_genlisp.dir/build.make autobotx/CMakeFiles/autobotx_genlisp.dir/build\n.PHONY : autobotx_genlisp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/autobotx_generate_messages_lisp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/autobotx_generate_messages_lisp.dir/rule\n.PHONY : autobotx/CMakeFiles/autobotx_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nautobotx_generate_messages_lisp: autobotx/CMakeFiles/autobotx_generate_messages_lisp.dir/rule\n\n.PHONY : autobotx_generate_messages_lisp\n\n# fast build rule for target.\nautobotx_generate_messages_lisp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/autobotx_generate_messages_lisp.dir/build.make autobotx/CMakeFiles/autobotx_generate_messages_lisp.dir/build\n.PHONY : autobotx_generate_messages_lisp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/autobotx_geneus.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/autobotx_geneus.dir/rule\n.PHONY : autobotx/CMakeFiles/autobotx_geneus.dir/rule\n\n# Convenience name for target.\nautobotx_geneus: autobotx/CMakeFiles/autobotx_geneus.dir/rule\n\n.PHONY : autobotx_geneus\n\n# fast build rule for target.\nautobotx_geneus/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/autobotx_geneus.dir/build.make autobotx/CMakeFiles/autobotx_geneus.dir/build\n.PHONY : autobotx_geneus/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/autobotx_gencpp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/autobotx_gencpp.dir/rule\n.PHONY : autobotx/CMakeFiles/autobotx_gencpp.dir/rule\n\n# Convenience name for target.\nautobotx_gencpp: autobotx/CMakeFiles/autobotx_gencpp.dir/rule\n\n.PHONY : autobotx_gencpp\n\n# fast build rule for target.\nautobotx_gencpp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/autobotx_gencpp.dir/build.make autobotx/CMakeFiles/autobotx_gencpp.dir/build\n.PHONY : autobotx_gencpp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/autobotx_generate_messages_cpp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/autobotx_generate_messages_cpp.dir/rule\n.PHONY : autobotx/CMakeFiles/autobotx_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nautobotx_generate_messages_cpp: autobotx/CMakeFiles/autobotx_generate_messages_cpp.dir/rule\n\n.PHONY : autobotx_generate_messages_cpp\n\n# fast build rule for target.\nautobotx_generate_messages_cpp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/autobotx_generate_messages_cpp.dir/build.make autobotx/CMakeFiles/autobotx_generate_messages_cpp.dir/build\n.PHONY : autobotx_generate_messages_cpp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/_autobotx_generate_messages_check_deps_Unicycle.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/_autobotx_generate_messages_check_deps_Unicycle.dir/rule\n.PHONY : autobotx/CMakeFiles/_autobotx_generate_messages_check_deps_Unicycle.dir/rule\n\n# Convenience name for target.\n_autobotx_generate_messages_check_deps_Unicycle: autobotx/CMakeFiles/_autobotx_generate_messages_check_deps_Unicycle.dir/rule\n\n.PHONY : _autobotx_generate_messages_check_deps_Unicycle\n\n# fast build rule for target.\n_autobotx_generate_messages_check_deps_Unicycle/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/_autobotx_generate_messages_check_deps_Unicycle.dir/build.make autobotx/CMakeFiles/_autobotx_generate_messages_check_deps_Unicycle.dir/build\n.PHONY : _autobotx_generate_messages_check_deps_Unicycle/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/nav_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/nav_msgs_generate_messages_nodejs.dir/rule\n.PHONY : autobotx/CMakeFiles/nav_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nnav_msgs_generate_messages_nodejs: autobotx/CMakeFiles/nav_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : nav_msgs_generate_messages_nodejs\n\n# fast build rule for target.\nnav_msgs_generate_messages_nodejs/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/nav_msgs_generate_messages_nodejs.dir/build.make autobotx/CMakeFiles/nav_msgs_generate_messages_nodejs.dir/build\n.PHONY : nav_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/nav_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/nav_msgs_generate_messages_lisp.dir/rule\n.PHONY : autobotx/CMakeFiles/nav_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nnav_msgs_generate_messages_lisp: autobotx/CMakeFiles/nav_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : nav_msgs_generate_messages_lisp\n\n# fast build rule for target.\nnav_msgs_generate_messages_lisp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/nav_msgs_generate_messages_lisp.dir/build.make autobotx/CMakeFiles/nav_msgs_generate_messages_lisp.dir/build\n.PHONY : nav_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/nav_msgs_generate_messages_eus.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/nav_msgs_generate_messages_eus.dir/rule\n.PHONY : autobotx/CMakeFiles/nav_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nnav_msgs_generate_messages_eus: autobotx/CMakeFiles/nav_msgs_generate_messages_eus.dir/rule\n\n.PHONY : nav_msgs_generate_messages_eus\n\n# fast build rule for target.\nnav_msgs_generate_messages_eus/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/nav_msgs_generate_messages_eus.dir/build.make autobotx/CMakeFiles/nav_msgs_generate_messages_eus.dir/build\n.PHONY : nav_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/tf_generate_messages_cpp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/tf_generate_messages_cpp.dir/rule\n.PHONY : autobotx/CMakeFiles/tf_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\ntf_generate_messages_cpp: autobotx/CMakeFiles/tf_generate_messages_cpp.dir/rule\n\n.PHONY : tf_generate_messages_cpp\n\n# fast build rule for target.\ntf_generate_messages_cpp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/tf_generate_messages_cpp.dir/build.make autobotx/CMakeFiles/tf_generate_messages_cpp.dir/build\n.PHONY : tf_generate_messages_cpp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/actionlib_generate_messages_eus.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/actionlib_generate_messages_eus.dir/rule\n.PHONY : autobotx/CMakeFiles/actionlib_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nactionlib_generate_messages_eus: autobotx/CMakeFiles/actionlib_generate_messages_eus.dir/rule\n\n.PHONY : actionlib_generate_messages_eus\n\n# fast build rule for target.\nactionlib_generate_messages_eus/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/actionlib_generate_messages_eus.dir/build.make autobotx/CMakeFiles/actionlib_generate_messages_eus.dir/build\n.PHONY : actionlib_generate_messages_eus/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/autobotx_generate_messages_eus.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/autobotx_generate_messages_eus.dir/rule\n.PHONY : autobotx/CMakeFiles/autobotx_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nautobotx_generate_messages_eus: autobotx/CMakeFiles/autobotx_generate_messages_eus.dir/rule\n\n.PHONY : autobotx_generate_messages_eus\n\n# fast build rule for target.\nautobotx_generate_messages_eus/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/autobotx_generate_messages_eus.dir/build.make autobotx/CMakeFiles/autobotx_generate_messages_eus.dir/build\n.PHONY : autobotx_generate_messages_eus/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/rule\n.PHONY : autobotx/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nrosgraph_msgs_generate_messages_lisp: autobotx/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : rosgraph_msgs_generate_messages_lisp\n\n# fast build rule for target.\nrosgraph_msgs_generate_messages_lisp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/build.make autobotx/CMakeFiles/rosgraph_msgs_generate_messages_lisp.dir/build\n.PHONY : rosgraph_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/roscpp_generate_messages_nodejs.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/roscpp_generate_messages_nodejs.dir/rule\n.PHONY : autobotx/CMakeFiles/roscpp_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nroscpp_generate_messages_nodejs: autobotx/CMakeFiles/roscpp_generate_messages_nodejs.dir/rule\n\n.PHONY : roscpp_generate_messages_nodejs\n\n# fast build rule for target.\nroscpp_generate_messages_nodejs/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/roscpp_generate_messages_nodejs.dir/build.make autobotx/CMakeFiles/roscpp_generate_messages_nodejs.dir/build\n.PHONY : roscpp_generate_messages_nodejs/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/tf_generate_messages_eus.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/tf_generate_messages_eus.dir/rule\n.PHONY : autobotx/CMakeFiles/tf_generate_messages_eus.dir/rule\n\n# Convenience name for target.\ntf_generate_messages_eus: autobotx/CMakeFiles/tf_generate_messages_eus.dir/rule\n\n.PHONY : tf_generate_messages_eus\n\n# fast build rule for target.\ntf_generate_messages_eus/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/tf_generate_messages_eus.dir/build.make autobotx/CMakeFiles/tf_generate_messages_eus.dir/build\n.PHONY : tf_generate_messages_eus/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/rule\n.PHONY : autobotx/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nrosgraph_msgs_generate_messages_cpp: autobotx/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : rosgraph_msgs_generate_messages_cpp\n\n# fast build rule for target.\nrosgraph_msgs_generate_messages_cpp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/build.make autobotx/CMakeFiles/rosgraph_msgs_generate_messages_cpp.dir/build\n.PHONY : rosgraph_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/rule\n.PHONY : autobotx/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\ntf2_msgs_generate_messages_cpp: autobotx/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : tf2_msgs_generate_messages_cpp\n\n# fast build rule for target.\ntf2_msgs_generate_messages_cpp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/build.make autobotx/CMakeFiles/tf2_msgs_generate_messages_cpp.dir/build\n.PHONY : tf2_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/rosgraph_msgs_generate_messages_eus.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/rosgraph_msgs_generate_messages_eus.dir/rule\n.PHONY : autobotx/CMakeFiles/rosgraph_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nrosgraph_msgs_generate_messages_eus: autobotx/CMakeFiles/rosgraph_msgs_generate_messages_eus.dir/rule\n\n.PHONY : rosgraph_msgs_generate_messages_eus\n\n# fast build rule for target.\nrosgraph_msgs_generate_messages_eus/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/rosgraph_msgs_generate_messages_eus.dir/build.make autobotx/CMakeFiles/rosgraph_msgs_generate_messages_eus.dir/build\n.PHONY : rosgraph_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/roscpp_generate_messages_eus.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/roscpp_generate_messages_eus.dir/rule\n.PHONY : autobotx/CMakeFiles/roscpp_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nroscpp_generate_messages_eus: autobotx/CMakeFiles/roscpp_generate_messages_eus.dir/rule\n\n.PHONY : roscpp_generate_messages_eus\n\n# fast build rule for target.\nroscpp_generate_messages_eus/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/roscpp_generate_messages_eus.dir/build.make autobotx/CMakeFiles/roscpp_generate_messages_eus.dir/build\n.PHONY : roscpp_generate_messages_eus/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/rule\n.PHONY : autobotx/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\ngeometry_msgs_generate_messages_nodejs: autobotx/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : geometry_msgs_generate_messages_nodejs\n\n# fast build rule for target.\ngeometry_msgs_generate_messages_nodejs/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/build.make autobotx/CMakeFiles/geometry_msgs_generate_messages_nodejs.dir/build\n.PHONY : geometry_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/roscpp_generate_messages_lisp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/roscpp_generate_messages_lisp.dir/rule\n.PHONY : autobotx/CMakeFiles/roscpp_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nroscpp_generate_messages_lisp: autobotx/CMakeFiles/roscpp_generate_messages_lisp.dir/rule\n\n.PHONY : roscpp_generate_messages_lisp\n\n# fast build rule for target.\nroscpp_generate_messages_lisp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/roscpp_generate_messages_lisp.dir/build.make autobotx/CMakeFiles/roscpp_generate_messages_lisp.dir/build\n.PHONY : roscpp_generate_messages_lisp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/std_msgs_generate_messages_eus.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/std_msgs_generate_messages_eus.dir/rule\n.PHONY : autobotx/CMakeFiles/std_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nstd_msgs_generate_messages_eus: autobotx/CMakeFiles/std_msgs_generate_messages_eus.dir/rule\n\n.PHONY : std_msgs_generate_messages_eus\n\n# fast build rule for target.\nstd_msgs_generate_messages_eus/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/std_msgs_generate_messages_eus.dir/build.make autobotx/CMakeFiles/std_msgs_generate_messages_eus.dir/build\n.PHONY : std_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/my_libs.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/my_libs.dir/rule\n.PHONY : autobotx/CMakeFiles/my_libs.dir/rule\n\n# Convenience name for target.\nmy_libs: autobotx/CMakeFiles/my_libs.dir/rule\n\n.PHONY : my_libs\n\n# fast build rule for target.\nmy_libs/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/my_libs.dir/build.make autobotx/CMakeFiles/my_libs.dir/build\n.PHONY : my_libs/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/rosgraph_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/rosgraph_msgs_generate_messages_nodejs.dir/rule\n.PHONY : autobotx/CMakeFiles/rosgraph_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nrosgraph_msgs_generate_messages_nodejs: autobotx/CMakeFiles/rosgraph_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : rosgraph_msgs_generate_messages_nodejs\n\n# fast build rule for target.\nrosgraph_msgs_generate_messages_nodejs/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/rosgraph_msgs_generate_messages_nodejs.dir/build.make autobotx/CMakeFiles/rosgraph_msgs_generate_messages_nodejs.dir/build\n.PHONY : rosgraph_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/nav_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/nav_msgs_generate_messages_cpp.dir/rule\n.PHONY : autobotx/CMakeFiles/nav_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nnav_msgs_generate_messages_cpp: autobotx/CMakeFiles/nav_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : nav_msgs_generate_messages_cpp\n\n# fast build rule for target.\nnav_msgs_generate_messages_cpp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/nav_msgs_generate_messages_cpp.dir/build.make autobotx/CMakeFiles/nav_msgs_generate_messages_cpp.dir/build\n.PHONY : nav_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/rule\n.PHONY : autobotx/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\ngeometry_msgs_generate_messages_lisp: autobotx/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : geometry_msgs_generate_messages_lisp\n\n# fast build rule for target.\ngeometry_msgs_generate_messages_lisp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/build.make autobotx/CMakeFiles/geometry_msgs_generate_messages_lisp.dir/build\n.PHONY : geometry_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/std_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/std_msgs_generate_messages_lisp.dir/rule\n.PHONY : autobotx/CMakeFiles/std_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nstd_msgs_generate_messages_lisp: autobotx/CMakeFiles/std_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : std_msgs_generate_messages_lisp\n\n# fast build rule for target.\nstd_msgs_generate_messages_lisp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/std_msgs_generate_messages_lisp.dir/build.make autobotx/CMakeFiles/std_msgs_generate_messages_lisp.dir/build\n.PHONY : std_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/nav_msgs_generate_messages_py.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/nav_msgs_generate_messages_py.dir/rule\n.PHONY : autobotx/CMakeFiles/nav_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\nnav_msgs_generate_messages_py: autobotx/CMakeFiles/nav_msgs_generate_messages_py.dir/rule\n\n.PHONY : nav_msgs_generate_messages_py\n\n# fast build rule for target.\nnav_msgs_generate_messages_py/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/nav_msgs_generate_messages_py.dir/build.make autobotx/CMakeFiles/nav_msgs_generate_messages_py.dir/build\n.PHONY : nav_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/std_msgs_generate_messages_py.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/std_msgs_generate_messages_py.dir/rule\n.PHONY : autobotx/CMakeFiles/std_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\nstd_msgs_generate_messages_py: autobotx/CMakeFiles/std_msgs_generate_messages_py.dir/rule\n\n.PHONY : std_msgs_generate_messages_py\n\n# fast build rule for target.\nstd_msgs_generate_messages_py/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/std_msgs_generate_messages_py.dir/build.make autobotx/CMakeFiles/std_msgs_generate_messages_py.dir/build\n.PHONY : std_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/geometry_msgs_generate_messages_eus.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/geometry_msgs_generate_messages_eus.dir/rule\n.PHONY : autobotx/CMakeFiles/geometry_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\ngeometry_msgs_generate_messages_eus: autobotx/CMakeFiles/geometry_msgs_generate_messages_eus.dir/rule\n\n.PHONY : geometry_msgs_generate_messages_eus\n\n# fast build rule for target.\ngeometry_msgs_generate_messages_eus/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/geometry_msgs_generate_messages_eus.dir/build.make autobotx/CMakeFiles/geometry_msgs_generate_messages_eus.dir/build\n.PHONY : geometry_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/roscpp_generate_messages_cpp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/roscpp_generate_messages_cpp.dir/rule\n.PHONY : autobotx/CMakeFiles/roscpp_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nroscpp_generate_messages_cpp: autobotx/CMakeFiles/roscpp_generate_messages_cpp.dir/rule\n\n.PHONY : roscpp_generate_messages_cpp\n\n# fast build rule for target.\nroscpp_generate_messages_cpp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/roscpp_generate_messages_cpp.dir/build.make autobotx/CMakeFiles/roscpp_generate_messages_cpp.dir/build\n.PHONY : roscpp_generate_messages_cpp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/actionlib_msgs_generate_messages_py.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/actionlib_msgs_generate_messages_py.dir/rule\n.PHONY : autobotx/CMakeFiles/actionlib_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\nactionlib_msgs_generate_messages_py: autobotx/CMakeFiles/actionlib_msgs_generate_messages_py.dir/rule\n\n.PHONY : actionlib_msgs_generate_messages_py\n\n# fast build rule for target.\nactionlib_msgs_generate_messages_py/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/actionlib_msgs_generate_messages_py.dir/build.make autobotx/CMakeFiles/actionlib_msgs_generate_messages_py.dir/build\n.PHONY : actionlib_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/rule\n.PHONY : autobotx/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\ngeometry_msgs_generate_messages_cpp: autobotx/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : geometry_msgs_generate_messages_cpp\n\n# fast build rule for target.\ngeometry_msgs_generate_messages_cpp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/build.make autobotx/CMakeFiles/geometry_msgs_generate_messages_cpp.dir/build\n.PHONY : geometry_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/rule\n.PHONY : autobotx/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nsensor_msgs_generate_messages_nodejs: autobotx/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : sensor_msgs_generate_messages_nodejs\n\n# fast build rule for target.\nsensor_msgs_generate_messages_nodejs/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/build.make autobotx/CMakeFiles/sensor_msgs_generate_messages_nodejs.dir/build\n.PHONY : sensor_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/std_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/std_msgs_generate_messages_nodejs.dir/rule\n.PHONY : autobotx/CMakeFiles/std_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nstd_msgs_generate_messages_nodejs: autobotx/CMakeFiles/std_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : std_msgs_generate_messages_nodejs\n\n# fast build rule for target.\nstd_msgs_generate_messages_nodejs/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/std_msgs_generate_messages_nodejs.dir/build.make autobotx/CMakeFiles/std_msgs_generate_messages_nodejs.dir/build\n.PHONY : std_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/geometry_msgs_generate_messages_py.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/geometry_msgs_generate_messages_py.dir/rule\n.PHONY : autobotx/CMakeFiles/geometry_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\ngeometry_msgs_generate_messages_py: autobotx/CMakeFiles/geometry_msgs_generate_messages_py.dir/rule\n\n.PHONY : geometry_msgs_generate_messages_py\n\n# fast build rule for target.\ngeometry_msgs_generate_messages_py/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/geometry_msgs_generate_messages_py.dir/build.make autobotx/CMakeFiles/geometry_msgs_generate_messages_py.dir/build\n.PHONY : geometry_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/autobotx_generate_messages_py.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/autobotx_generate_messages_py.dir/rule\n.PHONY : autobotx/CMakeFiles/autobotx_generate_messages_py.dir/rule\n\n# Convenience name for target.\nautobotx_generate_messages_py: autobotx/CMakeFiles/autobotx_generate_messages_py.dir/rule\n\n.PHONY : autobotx_generate_messages_py\n\n# fast build rule for target.\nautobotx_generate_messages_py/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/autobotx_generate_messages_py.dir/build.make autobotx/CMakeFiles/autobotx_generate_messages_py.dir/build\n.PHONY : autobotx_generate_messages_py/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/rule\n.PHONY : autobotx/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\nrosgraph_msgs_generate_messages_py: autobotx/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/rule\n\n.PHONY : rosgraph_msgs_generate_messages_py\n\n# fast build rule for target.\nrosgraph_msgs_generate_messages_py/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/build.make autobotx/CMakeFiles/rosgraph_msgs_generate_messages_py.dir/build\n.PHONY : rosgraph_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/tf_generate_messages_lisp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/tf_generate_messages_lisp.dir/rule\n.PHONY : autobotx/CMakeFiles/tf_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\ntf_generate_messages_lisp: autobotx/CMakeFiles/tf_generate_messages_lisp.dir/rule\n\n.PHONY : tf_generate_messages_lisp\n\n# fast build rule for target.\ntf_generate_messages_lisp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/tf_generate_messages_lisp.dir/build.make autobotx/CMakeFiles/tf_generate_messages_lisp.dir/build\n.PHONY : tf_generate_messages_lisp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/rule\n.PHONY : autobotx/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\ntf2_msgs_generate_messages_nodejs: autobotx/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : tf2_msgs_generate_messages_nodejs\n\n# fast build rule for target.\ntf2_msgs_generate_messages_nodejs/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/build.make autobotx/CMakeFiles/tf2_msgs_generate_messages_nodejs.dir/build\n.PHONY : tf2_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/roscpp_generate_messages_py.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/roscpp_generate_messages_py.dir/rule\n.PHONY : autobotx/CMakeFiles/roscpp_generate_messages_py.dir/rule\n\n# Convenience name for target.\nroscpp_generate_messages_py: autobotx/CMakeFiles/roscpp_generate_messages_py.dir/rule\n\n.PHONY : roscpp_generate_messages_py\n\n# fast build rule for target.\nroscpp_generate_messages_py/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/roscpp_generate_messages_py.dir/build.make autobotx/CMakeFiles/roscpp_generate_messages_py.dir/build\n.PHONY : roscpp_generate_messages_py/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/tf_generate_messages_nodejs.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/tf_generate_messages_nodejs.dir/rule\n.PHONY : autobotx/CMakeFiles/tf_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\ntf_generate_messages_nodejs: autobotx/CMakeFiles/tf_generate_messages_nodejs.dir/rule\n\n.PHONY : tf_generate_messages_nodejs\n\n# fast build rule for target.\ntf_generate_messages_nodejs/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/tf_generate_messages_nodejs.dir/build.make autobotx/CMakeFiles/tf_generate_messages_nodejs.dir/build\n.PHONY : tf_generate_messages_nodejs/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/link.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/link.dir/rule\n.PHONY : autobotx/CMakeFiles/link.dir/rule\n\n# Convenience name for target.\nlink: autobotx/CMakeFiles/link.dir/rule\n\n.PHONY : link\n\n# fast build rule for target.\nlink/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/link.dir/build.make autobotx/CMakeFiles/link.dir/build\n.PHONY : link/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/tf_generate_messages_py.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/tf_generate_messages_py.dir/rule\n.PHONY : autobotx/CMakeFiles/tf_generate_messages_py.dir/rule\n\n# Convenience name for target.\ntf_generate_messages_py: autobotx/CMakeFiles/tf_generate_messages_py.dir/rule\n\n.PHONY : tf_generate_messages_py\n\n# fast build rule for target.\ntf_generate_messages_py/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/tf_generate_messages_py.dir/build.make autobotx/CMakeFiles/tf_generate_messages_py.dir/build\n.PHONY : tf_generate_messages_py/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/rule\n.PHONY : autobotx/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nsensor_msgs_generate_messages_cpp: autobotx/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : sensor_msgs_generate_messages_cpp\n\n# fast build rule for target.\nsensor_msgs_generate_messages_cpp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/build.make autobotx/CMakeFiles/sensor_msgs_generate_messages_cpp.dir/build\n.PHONY : sensor_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/rule\n.PHONY : autobotx/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nsensor_msgs_generate_messages_lisp: autobotx/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : sensor_msgs_generate_messages_lisp\n\n# fast build rule for target.\nsensor_msgs_generate_messages_lisp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/build.make autobotx/CMakeFiles/sensor_msgs_generate_messages_lisp.dir/build\n.PHONY : sensor_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/rule\n.PHONY : autobotx/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\ntf2_msgs_generate_messages_lisp: autobotx/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : tf2_msgs_generate_messages_lisp\n\n# fast build rule for target.\ntf2_msgs_generate_messages_lisp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/build.make autobotx/CMakeFiles/tf2_msgs_generate_messages_lisp.dir/build\n.PHONY : tf2_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/sensor_msgs_generate_messages_py.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/sensor_msgs_generate_messages_py.dir/rule\n.PHONY : autobotx/CMakeFiles/sensor_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\nsensor_msgs_generate_messages_py: autobotx/CMakeFiles/sensor_msgs_generate_messages_py.dir/rule\n\n.PHONY : sensor_msgs_generate_messages_py\n\n# fast build rule for target.\nsensor_msgs_generate_messages_py/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/sensor_msgs_generate_messages_py.dir/build.make autobotx/CMakeFiles/sensor_msgs_generate_messages_py.dir/build\n.PHONY : sensor_msgs_generate_messages_py/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/actionlib_generate_messages_cpp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/actionlib_generate_messages_cpp.dir/rule\n.PHONY : autobotx/CMakeFiles/actionlib_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nactionlib_generate_messages_cpp: autobotx/CMakeFiles/actionlib_generate_messages_cpp.dir/rule\n\n.PHONY : actionlib_generate_messages_cpp\n\n# fast build rule for target.\nactionlib_generate_messages_cpp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/actionlib_generate_messages_cpp.dir/build.make autobotx/CMakeFiles/actionlib_generate_messages_cpp.dir/build\n.PHONY : actionlib_generate_messages_cpp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/std_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/std_msgs_generate_messages_cpp.dir/rule\n.PHONY : autobotx/CMakeFiles/std_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nstd_msgs_generate_messages_cpp: autobotx/CMakeFiles/std_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : std_msgs_generate_messages_cpp\n\n# fast build rule for target.\nstd_msgs_generate_messages_cpp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/std_msgs_generate_messages_cpp.dir/build.make autobotx/CMakeFiles/std_msgs_generate_messages_cpp.dir/build\n.PHONY : std_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/actionlib_msgs_generate_messages_cpp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/actionlib_msgs_generate_messages_cpp.dir/rule\n.PHONY : autobotx/CMakeFiles/actionlib_msgs_generate_messages_cpp.dir/rule\n\n# Convenience name for target.\nactionlib_msgs_generate_messages_cpp: autobotx/CMakeFiles/actionlib_msgs_generate_messages_cpp.dir/rule\n\n.PHONY : actionlib_msgs_generate_messages_cpp\n\n# fast build rule for target.\nactionlib_msgs_generate_messages_cpp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/actionlib_msgs_generate_messages_cpp.dir/build.make autobotx/CMakeFiles/actionlib_msgs_generate_messages_cpp.dir/build\n.PHONY : actionlib_msgs_generate_messages_cpp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/sensor_msgs_generate_messages_eus.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/sensor_msgs_generate_messages_eus.dir/rule\n.PHONY : autobotx/CMakeFiles/sensor_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nsensor_msgs_generate_messages_eus: autobotx/CMakeFiles/sensor_msgs_generate_messages_eus.dir/rule\n\n.PHONY : sensor_msgs_generate_messages_eus\n\n# fast build rule for target.\nsensor_msgs_generate_messages_eus/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/sensor_msgs_generate_messages_eus.dir/build.make autobotx/CMakeFiles/sensor_msgs_generate_messages_eus.dir/build\n.PHONY : sensor_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/actionlib_generate_messages_nodejs.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/actionlib_generate_messages_nodejs.dir/rule\n.PHONY : autobotx/CMakeFiles/actionlib_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nactionlib_generate_messages_nodejs: autobotx/CMakeFiles/actionlib_generate_messages_nodejs.dir/rule\n\n.PHONY : actionlib_generate_messages_nodejs\n\n# fast build rule for target.\nactionlib_generate_messages_nodejs/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/actionlib_generate_messages_nodejs.dir/build.make autobotx/CMakeFiles/actionlib_generate_messages_nodejs.dir/build\n.PHONY : actionlib_generate_messages_nodejs/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/actionlib_generate_messages_py.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/actionlib_generate_messages_py.dir/rule\n.PHONY : autobotx/CMakeFiles/actionlib_generate_messages_py.dir/rule\n\n# Convenience name for target.\nactionlib_generate_messages_py: autobotx/CMakeFiles/actionlib_generate_messages_py.dir/rule\n\n.PHONY : actionlib_generate_messages_py\n\n# fast build rule for target.\nactionlib_generate_messages_py/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/actionlib_generate_messages_py.dir/build.make autobotx/CMakeFiles/actionlib_generate_messages_py.dir/build\n.PHONY : actionlib_generate_messages_py/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/actionlib_generate_messages_lisp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/actionlib_generate_messages_lisp.dir/rule\n.PHONY : autobotx/CMakeFiles/actionlib_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nactionlib_generate_messages_lisp: autobotx/CMakeFiles/actionlib_generate_messages_lisp.dir/rule\n\n.PHONY : actionlib_generate_messages_lisp\n\n# fast build rule for target.\nactionlib_generate_messages_lisp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/actionlib_generate_messages_lisp.dir/build.make autobotx/CMakeFiles/actionlib_generate_messages_lisp.dir/build\n.PHONY : actionlib_generate_messages_lisp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/actionlib_msgs_generate_messages_eus.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/actionlib_msgs_generate_messages_eus.dir/rule\n.PHONY : autobotx/CMakeFiles/actionlib_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\nactionlib_msgs_generate_messages_eus: autobotx/CMakeFiles/actionlib_msgs_generate_messages_eus.dir/rule\n\n.PHONY : actionlib_msgs_generate_messages_eus\n\n# fast build rule for target.\nactionlib_msgs_generate_messages_eus/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/actionlib_msgs_generate_messages_eus.dir/build.make autobotx/CMakeFiles/actionlib_msgs_generate_messages_eus.dir/build\n.PHONY : actionlib_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/autobotx_generate_messages.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/autobotx_generate_messages.dir/rule\n.PHONY : autobotx/CMakeFiles/autobotx_generate_messages.dir/rule\n\n# Convenience name for target.\nautobotx_generate_messages: autobotx/CMakeFiles/autobotx_generate_messages.dir/rule\n\n.PHONY : autobotx_generate_messages\n\n# fast build rule for target.\nautobotx_generate_messages/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/autobotx_generate_messages.dir/build.make autobotx/CMakeFiles/autobotx_generate_messages.dir/build\n.PHONY : autobotx_generate_messages/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/actionlib_msgs_generate_messages_lisp.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/actionlib_msgs_generate_messages_lisp.dir/rule\n.PHONY : autobotx/CMakeFiles/actionlib_msgs_generate_messages_lisp.dir/rule\n\n# Convenience name for target.\nactionlib_msgs_generate_messages_lisp: autobotx/CMakeFiles/actionlib_msgs_generate_messages_lisp.dir/rule\n\n.PHONY : actionlib_msgs_generate_messages_lisp\n\n# fast build rule for target.\nactionlib_msgs_generate_messages_lisp/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/actionlib_msgs_generate_messages_lisp.dir/build.make autobotx/CMakeFiles/actionlib_msgs_generate_messages_lisp.dir/build\n.PHONY : actionlib_msgs_generate_messages_lisp/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/tf2_msgs_generate_messages_eus.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/tf2_msgs_generate_messages_eus.dir/rule\n.PHONY : autobotx/CMakeFiles/tf2_msgs_generate_messages_eus.dir/rule\n\n# Convenience name for target.\ntf2_msgs_generate_messages_eus: autobotx/CMakeFiles/tf2_msgs_generate_messages_eus.dir/rule\n\n.PHONY : tf2_msgs_generate_messages_eus\n\n# fast build rule for target.\ntf2_msgs_generate_messages_eus/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/tf2_msgs_generate_messages_eus.dir/build.make autobotx/CMakeFiles/tf2_msgs_generate_messages_eus.dir/build\n.PHONY : tf2_msgs_generate_messages_eus/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/actionlib_msgs_generate_messages_nodejs.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/actionlib_msgs_generate_messages_nodejs.dir/rule\n.PHONY : autobotx/CMakeFiles/actionlib_msgs_generate_messages_nodejs.dir/rule\n\n# Convenience name for target.\nactionlib_msgs_generate_messages_nodejs: autobotx/CMakeFiles/actionlib_msgs_generate_messages_nodejs.dir/rule\n\n.PHONY : actionlib_msgs_generate_messages_nodejs\n\n# fast build rule for target.\nactionlib_msgs_generate_messages_nodejs/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/actionlib_msgs_generate_messages_nodejs.dir/build.make autobotx/CMakeFiles/actionlib_msgs_generate_messages_nodejs.dir/build\n.PHONY : actionlib_msgs_generate_messages_nodejs/fast\n\n# Convenience name for target.\nautobotx/CMakeFiles/tf2_msgs_generate_messages_py.dir/rule:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f CMakeFiles/Makefile2 autobotx/CMakeFiles/tf2_msgs_generate_messages_py.dir/rule\n.PHONY : autobotx/CMakeFiles/tf2_msgs_generate_messages_py.dir/rule\n\n# Convenience name for target.\ntf2_msgs_generate_messages_py: autobotx/CMakeFiles/tf2_msgs_generate_messages_py.dir/rule\n\n.PHONY : tf2_msgs_generate_messages_py\n\n# fast build rule for target.\ntf2_msgs_generate_messages_py/fast:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/tf2_msgs_generate_messages_py.dir/build.make autobotx/CMakeFiles/tf2_msgs_generate_messages_py.dir/build\n.PHONY : tf2_msgs_generate_messages_py/fast\n\nsrc/link.o: src/link.cpp.o\n\n.PHONY : src/link.o\n\n# target to build an object file\nsrc/link.cpp.o:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/link.dir/build.make autobotx/CMakeFiles/link.dir/src/link.cpp.o\n.PHONY : src/link.cpp.o\n\nsrc/link.i: src/link.cpp.i\n\n.PHONY : src/link.i\n\n# target to preprocess a source file\nsrc/link.cpp.i:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/link.dir/build.make autobotx/CMakeFiles/link.dir/src/link.cpp.i\n.PHONY : src/link.cpp.i\n\nsrc/link.s: src/link.cpp.s\n\n.PHONY : src/link.s\n\n# target to generate assembly for a file\nsrc/link.cpp.s:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/link.dir/build.make autobotx/CMakeFiles/link.dir/src/link.cpp.s\n.PHONY : src/link.cpp.s\n\nsrc/mavlink_communication.o: src/mavlink_communication.cpp.o\n\n.PHONY : src/mavlink_communication.o\n\n# target to build an object file\nsrc/mavlink_communication.cpp.o:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/my_libs.dir/build.make autobotx/CMakeFiles/my_libs.dir/src/mavlink_communication.cpp.o\n.PHONY : src/mavlink_communication.cpp.o\n\nsrc/mavlink_communication.i: src/mavlink_communication.cpp.i\n\n.PHONY : src/mavlink_communication.i\n\n# target to preprocess a source file\nsrc/mavlink_communication.cpp.i:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/my_libs.dir/build.make autobotx/CMakeFiles/my_libs.dir/src/mavlink_communication.cpp.i\n.PHONY : src/mavlink_communication.cpp.i\n\nsrc/mavlink_communication.s: src/mavlink_communication.cpp.s\n\n.PHONY : src/mavlink_communication.s\n\n# target to generate assembly for a file\nsrc/mavlink_communication.cpp.s:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/my_libs.dir/build.make autobotx/CMakeFiles/my_libs.dir/src/mavlink_communication.cpp.s\n.PHONY : src/mavlink_communication.cpp.s\n\nsrc/serial_port.o: src/serial_port.cpp.o\n\n.PHONY : src/serial_port.o\n\n# target to build an object file\nsrc/serial_port.cpp.o:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/my_libs.dir/build.make autobotx/CMakeFiles/my_libs.dir/src/serial_port.cpp.o\n.PHONY : src/serial_port.cpp.o\n\nsrc/serial_port.i: src/serial_port.cpp.i\n\n.PHONY : src/serial_port.i\n\n# target to preprocess a source file\nsrc/serial_port.cpp.i:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/my_libs.dir/build.make autobotx/CMakeFiles/my_libs.dir/src/serial_port.cpp.i\n.PHONY : src/serial_port.cpp.i\n\nsrc/serial_port.s: src/serial_port.cpp.s\n\n.PHONY : src/serial_port.s\n\n# target to generate assembly for a file\nsrc/serial_port.cpp.s:\n\tcd /home/robox/catkin_ws/build && $(MAKE) -f autobotx/CMakeFiles/my_libs.dir/build.make autobotx/CMakeFiles/my_libs.dir/src/serial_port.cpp.s\n.PHONY : src/serial_port.cpp.s\n\n# Help Target\nhelp:\n\t@echo \"The following are some of the valid targets for this Makefile:\"\n\t@echo \"... all (the default if no target is provided)\"\n\t@echo \"... clean\"\n\t@echo \"... depend\"\n\t@echo \"... edit_cache\"\n\t@echo \"... install/local\"\n\t@echo \"... autobotx_genpy\"\n\t@echo \"... autobotx_gennodejs\"\n\t@echo \"... autobotx_generate_messages_nodejs\"\n\t@echo \"... autobotx_genlisp\"\n\t@echo \"... autobotx_generate_messages_lisp\"\n\t@echo \"... autobotx_geneus\"\n\t@echo \"... autobotx_gencpp\"\n\t@echo \"... autobotx_generate_messages_cpp\"\n\t@echo \"... _autobotx_generate_messages_check_deps_Unicycle\"\n\t@echo \"... nav_msgs_generate_messages_nodejs\"\n\t@echo \"... nav_msgs_generate_messages_lisp\"\n\t@echo \"... install/strip\"\n\t@echo \"... nav_msgs_generate_messages_eus\"\n\t@echo \"... tf_generate_messages_cpp\"\n\t@echo \"... actionlib_generate_messages_eus\"\n\t@echo \"... autobotx_generate_messages_eus\"\n\t@echo \"... rosgraph_msgs_generate_messages_lisp\"\n\t@echo \"... roscpp_generate_messages_nodejs\"\n\t@echo \"... rebuild_cache\"\n\t@echo \"... tf_generate_messages_eus\"\n\t@echo \"... rosgraph_msgs_generate_messages_cpp\"\n\t@echo \"... tf2_msgs_generate_messages_cpp\"\n\t@echo \"... rosgraph_msgs_generate_messages_eus\"\n\t@echo \"... list_install_components\"\n\t@echo \"... roscpp_generate_messages_eus\"\n\t@echo \"... geometry_msgs_generate_messages_nodejs\"\n\t@echo \"... roscpp_generate_messages_lisp\"\n\t@echo \"... std_msgs_generate_messages_eus\"\n\t@echo \"... my_libs\"\n\t@echo \"... rosgraph_msgs_generate_messages_nodejs\"\n\t@echo \"... nav_msgs_generate_messages_cpp\"\n\t@echo \"... geometry_msgs_generate_messages_lisp\"\n\t@echo \"... install\"\n\t@echo \"... std_msgs_generate_messages_lisp\"\n\t@echo \"... nav_msgs_generate_messages_py\"\n\t@echo \"... std_msgs_generate_messages_py\"\n\t@echo \"... geometry_msgs_generate_messages_eus\"\n\t@echo \"... roscpp_generate_messages_cpp\"\n\t@echo \"... actionlib_msgs_generate_messages_py\"\n\t@echo \"... test\"\n\t@echo \"... geometry_msgs_generate_messages_cpp\"\n\t@echo \"... sensor_msgs_generate_messages_nodejs\"\n\t@echo \"... std_msgs_generate_messages_nodejs\"\n\t@echo \"... geometry_msgs_generate_messages_py\"\n\t@echo \"... autobotx_generate_messages_py\"\n\t@echo \"... rosgraph_msgs_generate_messages_py\"\n\t@echo \"... tf_generate_messages_lisp\"\n\t@echo \"... tf2_msgs_generate_messages_nodejs\"\n\t@echo \"... roscpp_generate_messages_py\"\n\t@echo \"... tf_generate_messages_nodejs\"\n\t@echo \"... link\"\n\t@echo \"... tf_generate_messages_py\"\n\t@echo \"... sensor_msgs_generate_messages_cpp\"\n\t@echo \"... sensor_msgs_generate_messages_lisp\"\n\t@echo \"... tf2_msgs_generate_messages_lisp\"\n\t@echo \"... sensor_msgs_generate_messages_py\"\n\t@echo \"... actionlib_generate_messages_cpp\"\n\t@echo \"... std_msgs_generate_messages_cpp\"\n\t@echo \"... actionlib_msgs_generate_messages_cpp\"\n\t@echo \"... sensor_msgs_generate_messages_eus\"\n\t@echo \"... actionlib_generate_messages_nodejs\"\n\t@echo \"... actionlib_generate_messages_py\"\n\t@echo \"... actionlib_generate_messages_lisp\"\n\t@echo \"... actionlib_msgs_generate_messages_eus\"\n\t@echo \"... autobotx_generate_messages\"\n\t@echo \"... actionlib_msgs_generate_messages_lisp\"\n\t@echo \"... tf2_msgs_generate_messages_eus\"\n\t@echo \"... actionlib_msgs_generate_messages_nodejs\"\n\t@echo \"... tf2_msgs_generate_messages_py\"\n\t@echo \"... src/link.o\"\n\t@echo \"... src/link.i\"\n\t@echo \"... src/link.s\"\n\t@echo \"... src/mavlink_communication.o\"\n\t@echo \"... src/mavlink_communication.i\"\n\t@echo \"... src/mavlink_communication.s\"\n\t@echo \"... src/serial_port.o\"\n\t@echo \"... src/serial_port.i\"\n\t@echo \"... src/serial_port.s\"\n.PHONY : help\n\n\n\n#=============================================================================\n# Special targets to cleanup operation of make.\n\n# Special rule to run CMake to check the build system integrity.\n# No rule that depends on this can have commands that come from listfiles\n# because they might be regenerated.\ncmake_check_build_system:\n\tcd /home/robox/catkin_ws/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0\n.PHONY : cmake_check_build_system\n\n" }, { "alpha_fraction": 0.7200000286102295, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 24, "blob_id": "2b200397c1c37d07518f05714d53ae45e7623cb3", "content_id": "99ad0660075aa45d97e454515a4edb47122722e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25, "license_type": "no_license", "max_line_length": 24, "num_lines": 1, "path": "/catkin_ws/devel/lib/python2.7/dist-packages/autobotx/msg/__init__.py", "repo_name": "chiragsolanki18/AutobotX", "src_encoding": "UTF-8", "text": "from ._Unicycle import *\n" }, { "alpha_fraction": 0.818463921546936, "alphanum_fraction": 0.8277734518051147, "avg_line_length": 63.45000076293945, "blob_id": "6d588b279c1fa88d84fd4c70e1e6af22af1d4f3d", "content_id": "f8f55bbbd00cf25384f48fa8f5603d14fb10056f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1289, "license_type": "no_license", "max_line_length": 88, "num_lines": 20, "path": "/README.md", "repo_name": "chiragsolanki18/AutobotX", "src_encoding": "UTF-8", "text": "# Autobot\nAutonomous Navigation of Robot in Indoor Environment using SLAM\n\nThe use of Autonomous robotics has increased noticeably in last decade, especially for\nindoor applications. An autonomous robot can map its surrounding environment and\ndecide upon navigation strategy, hence finding great use in many fields such as military\napplication, disaster management, patient assistance etc. In order to achieve complete\nindependent functioning, entire system can be divided in three subsections.\n1. Map generation using Simultaneous Localization and Mapping [SLAM].\n2. Localisation using Adaptive Monte Carlo particle filter.\n3. Path planning using A* algorithm.\n\nMap generation is based on the gmapping ROS package which works on Rao-\nBlackwellized Particle Filter. Generated map is then used for goal tracking and path\nplanning purpose. Localisation in this map is done by amcl ROS package. Navigation\nstack is used for the navigation of robot in the path chosen. All the above-mentioned\nalgorithms are processed on ROS platform based on Ubuntu 16.04 running on Intel\ni5-8300H processor. These algorithms output command velocity which is then sent to\ncontroller using MAVLink protocol. The microcontroller then implements the set\nvelocity based on the unicycle model closed loop control.\n" }, { "alpha_fraction": 0.7471048831939697, "alphanum_fraction": 0.7486376166343689, "avg_line_length": 48.75423812866211, "blob_id": "cdb0aed731ff7bef35f1803cac340b0b8ac4ac51", "content_id": "ebeb939869562e55522b46cd2328553a8ad898f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 5872, "license_type": "no_license", "max_line_length": 196, "num_lines": 118, "path": "/catkin_ws/build/autobotx/cmake_install.cmake", "repo_name": "chiragsolanki18/AutobotX", "src_encoding": "UTF-8", "text": "# Install script for directory: /home/robox/catkin_ws/src/autobotx\n\n# Set the install prefix\nif(NOT DEFINED CMAKE_INSTALL_PREFIX)\n set(CMAKE_INSTALL_PREFIX \"/home/robox/catkin_ws/install\")\nendif()\nstring(REGEX REPLACE \"/$\" \"\" CMAKE_INSTALL_PREFIX \"${CMAKE_INSTALL_PREFIX}\")\n\n# Set the install configuration name.\nif(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n if(BUILD_TYPE)\n string(REGEX REPLACE \"^[^A-Za-z0-9_]+\" \"\"\n CMAKE_INSTALL_CONFIG_NAME \"${BUILD_TYPE}\")\n else()\n set(CMAKE_INSTALL_CONFIG_NAME \"\")\n endif()\n message(STATUS \"Install configuration: \\\"${CMAKE_INSTALL_CONFIG_NAME}\\\"\")\nendif()\n\n# Set the component getting installed.\nif(NOT CMAKE_INSTALL_COMPONENT)\n if(COMPONENT)\n message(STATUS \"Install component: \\\"${COMPONENT}\\\"\")\n set(CMAKE_INSTALL_COMPONENT \"${COMPONENT}\")\n else()\n set(CMAKE_INSTALL_COMPONENT)\n endif()\nendif()\n\n# Install shared libraries without execute permission?\nif(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n set(CMAKE_INSTALL_SO_NO_EXE \"1\")\nendif()\n\nif(NOT CMAKE_INSTALL_COMPONENT OR \"${CMAKE_INSTALL_COMPONENT}\" STREQUAL \"Unspecified\")\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/share/autobotx/msg\" TYPE FILE FILES \"/home/robox/catkin_ws/src/autobotx/msg/Unicycle.msg\")\nendif()\n\nif(NOT CMAKE_INSTALL_COMPONENT OR \"${CMAKE_INSTALL_COMPONENT}\" STREQUAL \"Unspecified\")\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/share/autobotx/cmake\" TYPE FILE FILES \"/home/robox/catkin_ws/build/autobotx/catkin_generated/installspace/autobotx-msg-paths.cmake\")\nendif()\n\nif(NOT CMAKE_INSTALL_COMPONENT OR \"${CMAKE_INSTALL_COMPONENT}\" STREQUAL \"Unspecified\")\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/include\" TYPE DIRECTORY FILES \"/home/robox/catkin_ws/devel/include/autobotx\")\nendif()\n\nif(NOT CMAKE_INSTALL_COMPONENT OR \"${CMAKE_INSTALL_COMPONENT}\" STREQUAL \"Unspecified\")\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/share/roseus/ros\" TYPE DIRECTORY FILES \"/home/robox/catkin_ws/devel/share/roseus/ros/autobotx\")\nendif()\n\nif(NOT CMAKE_INSTALL_COMPONENT OR \"${CMAKE_INSTALL_COMPONENT}\" STREQUAL \"Unspecified\")\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/share/common-lisp/ros\" TYPE DIRECTORY FILES \"/home/robox/catkin_ws/devel/share/common-lisp/ros/autobotx\")\nendif()\n\nif(NOT CMAKE_INSTALL_COMPONENT OR \"${CMAKE_INSTALL_COMPONENT}\" STREQUAL \"Unspecified\")\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/share/gennodejs/ros\" TYPE DIRECTORY FILES \"/home/robox/catkin_ws/devel/share/gennodejs/ros/autobotx\")\nendif()\n\nif(NOT CMAKE_INSTALL_COMPONENT OR \"${CMAKE_INSTALL_COMPONENT}\" STREQUAL \"Unspecified\")\n execute_process(COMMAND \"/usr/bin/python\" -m compileall \"/home/robox/catkin_ws/devel/lib/python2.7/dist-packages/autobotx\")\nendif()\n\nif(NOT CMAKE_INSTALL_COMPONENT OR \"${CMAKE_INSTALL_COMPONENT}\" STREQUAL \"Unspecified\")\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/lib/python2.7/dist-packages\" TYPE DIRECTORY FILES \"/home/robox/catkin_ws/devel/lib/python2.7/dist-packages/autobotx\")\nendif()\n\nif(NOT CMAKE_INSTALL_COMPONENT OR \"${CMAKE_INSTALL_COMPONENT}\" STREQUAL \"Unspecified\")\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/lib/pkgconfig\" TYPE FILE FILES \"/home/robox/catkin_ws/build/autobotx/catkin_generated/installspace/autobotx.pc\")\nendif()\n\nif(NOT CMAKE_INSTALL_COMPONENT OR \"${CMAKE_INSTALL_COMPONENT}\" STREQUAL \"Unspecified\")\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/share/autobotx/cmake\" TYPE FILE FILES \"/home/robox/catkin_ws/build/autobotx/catkin_generated/installspace/autobotx-msg-extras.cmake\")\nendif()\n\nif(NOT CMAKE_INSTALL_COMPONENT OR \"${CMAKE_INSTALL_COMPONENT}\" STREQUAL \"Unspecified\")\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/share/autobotx/cmake\" TYPE FILE FILES\n \"/home/robox/catkin_ws/build/autobotx/catkin_generated/installspace/autobotxConfig.cmake\"\n \"/home/robox/catkin_ws/build/autobotx/catkin_generated/installspace/autobotxConfig-version.cmake\"\n )\nendif()\n\nif(NOT CMAKE_INSTALL_COMPONENT OR \"${CMAKE_INSTALL_COMPONENT}\" STREQUAL \"Unspecified\")\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/share/autobotx\" TYPE FILE FILES \"/home/robox/catkin_ws/src/autobotx/package.xml\")\nendif()\n\nif(NOT CMAKE_INSTALL_COMPONENT OR \"${CMAKE_INSTALL_COMPONENT}\" STREQUAL \"Unspecified\")\n if(EXISTS \"$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libmy_libs.so\" AND\n NOT IS_SYMLINK \"$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libmy_libs.so\")\n file(RPATH_CHECK\n FILE \"$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libmy_libs.so\"\n RPATH \"\")\n endif()\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/lib\" TYPE SHARED_LIBRARY FILES \"/home/robox/catkin_ws/devel/lib/libmy_libs.so\")\n if(EXISTS \"$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libmy_libs.so\" AND\n NOT IS_SYMLINK \"$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libmy_libs.so\")\n if(CMAKE_INSTALL_DO_STRIP)\n execute_process(COMMAND \"/usr/bin/strip\" \"$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/libmy_libs.so\")\n endif()\n endif()\nendif()\n\nif(NOT CMAKE_INSTALL_COMPONENT OR \"${CMAKE_INSTALL_COMPONENT}\" STREQUAL \"Unspecified\")\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/include/autobotx\" TYPE DIRECTORY FILES \"/home/robox/catkin_ws/src/autobotx/include\" FILES_MATCHING REGEX \"/[^/]*\\\\.h$\" REGEX \"/\\\\.svn$\" EXCLUDE)\nendif()\n\nif(NOT CMAKE_INSTALL_COMPONENT OR \"${CMAKE_INSTALL_COMPONENT}\" STREQUAL \"Unspecified\")\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/lib/autobotx\" TYPE PROGRAM FILES\n \"/home/robox/catkin_ws/src/autobotx/scripts/teleop_keys.py\"\n \"/home/robox/catkin_ws/src/autobotx/scripts/reader.py\"\n )\nendif()\n\nif(NOT CMAKE_INSTALL_COMPONENT OR \"${CMAKE_INSTALL_COMPONENT}\" STREQUAL \"Unspecified\")\n file(INSTALL DESTINATION \"${CMAKE_INSTALL_PREFIX}/share/autobotx\" TYPE FILE FILES\n \"/home/robox/catkin_ws/src/autobotx/scripts/teleop_keys.py\"\n \"/home/robox/catkin_ws/src/autobotx/scripts/reader.py\"\n )\nendif()\n\n" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.6470588445663452, "avg_line_length": 13.428571701049805, "blob_id": "cfb041c50f67444abe848e0a4397628e6b8d54c5", "content_id": "95b4782932fa015ab981bd3286e861ff030c55d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 102, "license_type": "no_license", "max_line_length": 40, "num_lines": 7, "path": "/catkin_ws/devel/share/gennodejs/ros/autobotx/msg/_index.js", "repo_name": "chiragsolanki18/AutobotX", "src_encoding": "UTF-8", "text": "\n\"use strict\";\n\nlet Unicycle = require('./Unicycle.js');\n\nmodule.exports = {\n Unicycle: Unicycle,\n};\n" }, { "alpha_fraction": 0.7907692193984985, "alphanum_fraction": 0.7907692193984985, "avg_line_length": 35.11111068725586, "blob_id": "287f699e9b0f525e6dbf37f6f0e423c29cafecb1", "content_id": "a84637ea28df1d89706164575b655e1e48cd4df1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 325, "license_type": "no_license", "max_line_length": 92, "num_lines": 9, "path": "/catkin_ws/build/autobotx/CMakeFiles/autobotx_generate_messages_lisp.dir/cmake_clean.cmake", "repo_name": "chiragsolanki18/AutobotX", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/autobotx_generate_messages_lisp\"\n \"/home/robox/catkin_ws/devel/share/common-lisp/ros/autobotx/msg/Unicycle.lisp\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang )\n include(CMakeFiles/autobotx_generate_messages_lisp.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 38, "blob_id": "70c711af56fa736f35ff549be5291f4a27075300", "content_id": "865e3c383d3668016b5b15e6b7b2ddc2d15b97a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 78, "license_type": "no_license", "max_line_length": 46, "num_lines": 2, "path": "/catkin_ws/build/autobotx/catkin_generated/installspace/autobotx-msg-extras.cmake", "repo_name": "chiragsolanki18/AutobotX", "src_encoding": "UTF-8", "text": "set(autobotx_MESSAGE_FILES \"msg/Unicycle.msg\")\nset(autobotx_SERVICE_FILES \"\")\n" }, { "alpha_fraction": 0.7639902830123901, "alphanum_fraction": 0.7737226486206055, "avg_line_length": 40.099998474121094, "blob_id": "748833add277e566a336aee05553f36f96689bb9", "content_id": "8a2f766f9c766524c04181fe07c639d0f31c8e38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 411, "license_type": "no_license", "max_line_length": 90, "num_lines": 10, "path": "/catkin_ws/build/autobotx/CMakeFiles/autobotx_generate_messages_py.dir/cmake_clean.cmake", "repo_name": "chiragsolanki18/AutobotX", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/autobotx_generate_messages_py\"\n \"/home/robox/catkin_ws/devel/lib/python2.7/dist-packages/autobotx/msg/_Unicycle.py\"\n \"/home/robox/catkin_ws/devel/lib/python2.7/dist-packages/autobotx/msg/__init__.py\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang )\n include(CMakeFiles/autobotx_generate_messages_py.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7594936490058899, "alphanum_fraction": 0.7594936490058899, "avg_line_length": 30.600000381469727, "blob_id": "3bd9ddb9500b727c9721297abc8f1a8dc7e19cd0", "content_id": "5a959e6e33d45b94574a4e1922463c8e330bdb8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 316, "license_type": "no_license", "max_line_length": 65, "num_lines": 10, "path": "/catkin_ws/build/autobotx/CMakeFiles/link.dir/cmake_clean.cmake", "repo_name": "chiragsolanki18/AutobotX", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/link.dir/src/link.cpp.o\"\n \"/home/robox/catkin_ws/devel/lib/autobotx/link.pdb\"\n \"/home/robox/catkin_ws/devel/lib/autobotx/link\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/link.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.7755101919174194, "alphanum_fraction": 0.7755101919174194, "avg_line_length": 48, "blob_id": "e37c5f6bba7647fdf05dcaf2d56278c006d8f435", "content_id": "aa23b62fb27e1c93367646f15f51757a5791a102", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 196, "license_type": "no_license", "max_line_length": 74, "num_lines": 4, "path": "/catkin_ws/build/autobotx/catkin_generated/installspace/autobotx-msg-paths.cmake", "repo_name": "chiragsolanki18/AutobotX", "src_encoding": "UTF-8", "text": "# generated from genmsg/cmake/pkg-msg-paths.cmake.installspace.in\n\n_prepend_path(\"${autobotx_DIR}/..\" \"msg\" autobotx_MSG_INCLUDE_DIRS UNIQUE)\nset(autobotx_MSG_DEPENDENCIES geometry_msgs;std_msgs)\n" }, { "alpha_fraction": 0.7880794405937195, "alphanum_fraction": 0.7880794405937195, "avg_line_length": 32.55555725097656, "blob_id": "a7bb534142e01dc7ea0ebaa7785319024faf5a5d", "content_id": "754d535f8575beebc4101fdf94073488d110786c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 302, "license_type": "no_license", "max_line_length": 91, "num_lines": 9, "path": "/catkin_ws/build/autobotx/CMakeFiles/autobotx_generate_messages_cpp.dir/cmake_clean.cmake", "repo_name": "chiragsolanki18/AutobotX", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/autobotx_generate_messages_cpp\"\n \"/home/robox/catkin_ws/devel/include/autobotx/Unicycle.h\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang )\n include(CMakeFiles/autobotx_generate_messages_cpp.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" } ]
16
titusngiscoding/titus-pytube
https://github.com/titusngiscoding/titus-pytube
e2024f40829624b168e8c56e5181c65a882e8562
88e643028bee3007dbe375b10d46b537a0470956
ab89c2bac1313a04d17f346a1f81fd0b55212ab1
refs/heads/master
2020-05-16T22:42:34.631858
2019-05-06T10:43:33
2019-05-06T10:43:33
183,342,313
2
0
null
2019-04-25T02:36:10
2019-04-30T12:54:25
2019-04-30T13:06:36
null
[ { "alpha_fraction": 0.7101449370384216, "alphanum_fraction": 0.7971014380455017, "avg_line_length": 13, "blob_id": "81b29f5b3c91baadd4af580232ca1b7fa85e09d2", "content_id": "3884626c3c0e539cfc5a6635cf64f106bc3b2b3f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 69, "license_type": "permissive", "max_line_length": 38, "num_lines": 5, "path": "/todo.txt", "repo_name": "titusngiscoding/titus-pytube", "src_encoding": "UTF-8", "text": "Version 1.1\n1)finish validators and error handlers\n\nVersion 2.0\n1)GUI" }, { "alpha_fraction": 0.6701388955116272, "alphanum_fraction": 0.673115074634552, "avg_line_length": 26.616437911987305, "blob_id": "595ec1927f36e1df587b1e49555d92d9d9cbd28b", "content_id": "8eadd58969a703c8a7d82a323a4d61fd0b81f2e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2016, "license_type": "permissive", "max_line_length": 118, "num_lines": 73, "path": "/titus-pytube.py", "repo_name": "titusngiscoding/titus-pytube", "src_encoding": "UTF-8", "text": "import os\nfrom datetime import datetime\nfrom pytube import YouTube\n\nAPP_VERSION=\"1.0\"\nWELCOME_MSG=\"titus-pytube \" + APP_VERSION\nCREDIT_MSG=\"This software is made possible by pytube 9.5.0 (https://github.com/nficano/pytube)\"\nGET_LINK_MSG=\"Please enter Youtube video link: \"\nGET_FILENAME_MSG=\"Desired output file name (Leave blank for default): \"\nGET_IS_TRY_AGAIN_MSG=\"One more time? (y/n): \"\nYES_DECISIONS=[\"y\",\"yes\"]\nNO_DECISIONS=[\"n\",\"no\"]\nTHANKYOU_MSG=\"Thank you for using titus-pytube, Goodbai!\"\nDOWNLOADING_MSG=\"Downloading video from {} ...\"\nDOWNLOADED_MSG=\"Saved video as {}\"\nOUTPUT_FOLDER=\"output/\"\n\ndef welcome():\n print(WELCOME_MSG)\n print(CREDIT_MSG)\n\ndef insertLineBreak():\n print()\n\ndef getLink():\n inputLink = input(GET_LINK_MSG)\n return inputLink\n\ndef generateDefaultFilename():\n return datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\ndef getFilename():\n inputFilename = input(GET_FILENAME_MSG)\n if inputFilename == \"\":\n inputFilename=generateDefaultFilename()\n return inputFilename\n\ndef getVideo(link,filename):\n print(DOWNLOADING_MSG.format(link))\n if not os.path.exists(OUTPUT_FOLDER):\n os.mkdir(OUTPUT_FOLDER)\n downloader = YouTube(link)\n output = downloader.streams.filter(only_audio=True).first().download(output_path=OUTPUT_FOLDER, filename=filename)\n filename = OUTPUT_FOLDER + filename + \".mp3\"\n os.rename(output, filename)\n print(DOWNLOADED_MSG.format(filename))\n \ndef getIsTryAgain():\n while(True):\n inputDecision = input(GET_IS_TRY_AGAIN_MSG).lower()\n if inputDecision in YES_DECISIONS:\n return True\n elif inputDecision in NO_DECISIONS:\n return False\n\ndef thankYou():\n print(THANKYOU_MSG)\n\ndef main():\n welcome()\n insertLineBreak()\n again=True\n while(again):\n link=getLink()\n filename=getFilename()\n getVideo(link,filename)\n again=getIsTryAgain()\n insertLineBreak()\n thankYou()\n exit()\n\nif __name__ == \"__main__\":\n main()\n" } ]
2
bugelseif/semaforo
https://github.com/bugelseif/semaforo
ae8a0923dfadfc0a6111f26d46697d29988f0172
f89cb9f6b38acdec0bc6842abf77e5cabe69fd63
3b767310abc6d2f5c7befc2dba113affa55ece1f
refs/heads/main
2023-07-14T03:39:56.904017
2021-08-30T23:54:24
2021-08-30T23:54:24
401,518,021
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5316455960273743, "alphanum_fraction": 0.5472822189331055, "avg_line_length": 18.66153907775879, "blob_id": "41dbef44ce2817d8c3ed6eae8f0c4f48f31c459f", "content_id": "e5e3e47b1b9e3f67b0b80b6e6cc6dc80615c81f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1345, "license_type": "no_license", "max_line_length": 64, "num_lines": 65, "path": "/semaforos.py", "repo_name": "bugelseif/semaforo", "src_encoding": "UTF-8", "text": "import threading\r\nfrom time import sleep\r\n\r\n\r\nclass Pilha:\r\n def __init__(self, value=0):\r\n self._value = value\r\n self._value_lock = threading.Lock()\r\n\r\n def inc(self, value):\r\n with self._value_lock:\r\n self._value += value\r\n\r\n def dec(self, value):\r\n with self._value_lock:\r\n self._value -= value\r\n\r\n def getValue(self):\r\n with self._value_lock:\r\n return self._value\r\n\r\n\r\ndef th_produtor(valor):\r\n PILHA.inc(valor)\r\n sleep(valor) if valor != 0 else sleep(1)\r\n\r\n\r\ndef produtor(valor):\r\n return threading.Thread(target=th_produtor, args=(valor,))\r\n\r\n\r\ndef th_consumidor(valor):\r\n PILHA.dec(valor)\r\n sleep(valor) if valor != 0 else sleep(1)\r\n\r\n\r\ndef consumidor(valor):\r\n return threading.Thread(target=th_consumidor, args=(valor,))\r\n\r\n\r\nif __name__ == '__main__':\r\n matricula = input('Digite o número da matricula \\n')\r\n\r\n PILHA = Pilha()\r\n vetor = [int(m) for m in matricula]\r\n threads = []\r\n\r\n for i, m in enumerate(vetor):\r\n if i % 2 == 0:\r\n t = produtor(m)\r\n else:\r\n t = consumidor(m)\r\n threads.append(t)\r\n\r\n for t in threads:\r\n t.start()\r\n\r\n sleep(10)\r\n\r\n for t in threads:\r\n t.join()\r\n\r\n print(f'O valor é: {PILHA.getValue()}')\r\n\r\n# matricula 201910004319\r\n" } ]
1
arushs/Projects
https://github.com/arushs/Projects
a8c37f0adda56866a83e3c39397fb4eb998d125b
cd1a9be6d6689215ab9846792b958d3779f791c2
8f2199375c2860c42239de359e7f27ac0111c2ab
refs/heads/master
2016-09-05T12:19:59.658844
2014-05-15T06:44:43
2014-05-15T06:44:43
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.509695291519165, "alphanum_fraction": 0.5373961329460144, "avg_line_length": 18, "blob_id": "d893a60a1c275e0be92c3a0400cdeada6f764cc6", "content_id": "9b5b730ab05bab9ec3bb00cd5de698daa442b903", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 361, "license_type": "permissive", "max_line_length": 41, "num_lines": 19, "path": "/Numbers/factorial.py", "repo_name": "arushs/Projects", "src_encoding": "UTF-8", "text": "import math\ndef factorial(n):\n if n < 0:\n print \"error, number is below, 0\"\n elif(n < 2):\n return 1\n else :\n return factorial(n-1) * n\nn = input(\"Number to find factorial? \")\nnum = n\nsum = 1;\nprint factorial(num)\nif n < 0:\n print \"error, number is below, 0\"\nelse:\n while n > 0:\n sum = sum*n\n n-=1\n print sum\n" }, { "alpha_fraction": 0.5668202638626099, "alphanum_fraction": 0.6036866307258606, "avg_line_length": 24.303030014038086, "blob_id": "b1372094083a64c8c20262a1e85a065c6ac8ca27", "content_id": "b2cc46925f14af0051ee8db3eef997e8a8a0cb4c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 868, "license_type": "permissive", "max_line_length": 72, "num_lines": 33, "path": "/Numbers/change.py", "repo_name": "arushs/Projects", "src_encoding": "UTF-8", "text": "# The user enters a cost and then the amount of money given.\r\n# The program will figure out the change and\r\n# the number of quarters, dimes, nickels, pennies needed for the change.\r\n\r\ncost = float(raw_input(\"cost? \"))\r\nmoney = float(raw_input(\"money? \"))\r\nremainder = 100* money - 100*cost\r\nquarters = 0\r\ndimes = 0\r\nnickels = 0\r\npennies = 0\r\n# remainder = remainder * 100\r\nwhile remainder != 0:\r\n if remainder - 25 >= 0:\r\n remainder = remainder - 25\r\n quarters+= 1\r\n elif remainder - 10 >= 0:\r\n remainder = remainder - 10\r\n dimes+= 1\r\n elif remainder - 5 >= 0:\r\n remainder = remainder - 5\r\n nickels+= 1\r\n else:\r\n remainder = remainder - 1\r\n pennies+= 1\r\nprint(\"quarters = \")\r\nprint(quarters)\r\nprint(\"dimes = \")\r\nprint(dimes)\r\nprint(\"nickels = \")\r\nprint(nickels)\r\nprint(\"pennies = \")\r\nprint(pennies)\r\n" }, { "alpha_fraction": 0.3979591727256775, "alphanum_fraction": 0.44897958636283875, "avg_line_length": 16.81818199157715, "blob_id": "1c60db23f933a245b07f6fb82c7b8f0069f9ab1b", "content_id": "1e8ad196c35822793e6dc024523af9b537fc4374", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 196, "license_type": "permissive", "max_line_length": 55, "num_lines": 11, "path": "/Classic Algorithms/Collatz.py", "repo_name": "arushs/Projects", "src_encoding": "UTF-8", "text": "n = int(raw_input(\"Number to find steps to reach 1? \"))\n\nsteps = 0\nwhile n != 1:\n if n % 2 == 0:\n steps+=1\n n = n / 2\n else:\n steps+=1\n n = n * 3 + 1\nprint steps\n" }, { "alpha_fraction": 0.3702031672000885, "alphanum_fraction": 0.4063205420970917, "avg_line_length": 14.206896781921387, "blob_id": "335184655e3da90ecac515f60cec57c41ea175ab", "content_id": "7b2a1b590209aa660a0e0ba315814240667455d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 443, "license_type": "permissive", "max_line_length": 45, "num_lines": 29, "path": "/Text/countVowels.py", "repo_name": "arushs/Projects", "src_encoding": "UTF-8", "text": "word = raw_input(\"Word to count Vowels in? \")\nvowels = 0\na = 0\ne = 0\ni = 0\no = 0\nu = 0\nfor c in word:\n if c == 'a':\n a+=1\n vowels+=1\n if c == 'e':\n e+=1\n vowels+=1\n if c == 'i':\n i+=1\n vowels+=1\n if c == 'o':\n o+=1\n vowels+=1\n if c == 'u':\n u+=1\n vowels+=1\nprint \"Vowels \", vowels\nprint \"a's \",a\nprint \"e's \",e\nprint \"i's \",i\nprint \"o's \",o\nprint \"u's \",u\n\n\n" }, { "alpha_fraction": 0.504878044128418, "alphanum_fraction": 0.5439024567604065, "avg_line_length": 21.77777862548828, "blob_id": "d7ba81de2a6320b2a0836928cfefb16d2d694804", "content_id": "2c3b8b94527e473dc89a98ab7df935dc84d44755", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 410, "license_type": "permissive", "max_line_length": 53, "num_lines": 18, "path": "/Numbers/binary.py", "repo_name": "arushs/Projects", "src_encoding": "UTF-8", "text": "import math\ndef toBinary(n):\n if n / 2 == 0:\n return n % 2\n else :\n return 10 * toBinary(n / 2) + toBinary(n % 2)\ndef toDec(n):\n if n == 0:\n return 0\n if n == 1:\n return 1\n else:\n return 2 * toDec(n/10) + toDec(n%10)\n\nnum = int(raw_input(\"Num to convert to binary? \"))\nprint(toBinary(num))\ncoo = int(raw_input(\"Num to convert to Decimal? \"))\nprint(toDec(coo))\n" }, { "alpha_fraction": 0.6067415475845337, "alphanum_fraction": 0.6067415475845337, "avg_line_length": 16.799999237060547, "blob_id": "f711bd1e9f98cb2512fb202dd5c0d00157eb0b49", "content_id": "5de0952eb799f87656eea78a922ae0c583729b43", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 89, "license_type": "permissive", "max_line_length": 39, "num_lines": 5, "path": "/Text/reverse.py", "repo_name": "arushs/Projects", "src_encoding": "UTF-8", "text": "word = raw_input(\"String to reverse? \")\ns = \"\"\nfor c in reversed(word):\n s+=c\nprint s\n" }, { "alpha_fraction": 0.6531791687011719, "alphanum_fraction": 0.6647399067878723, "avg_line_length": 23.714284896850586, "blob_id": "e831e010f58a199ff2318babbd6c2b81b050c012", "content_id": "898d41b6838c44932607f11d87d3ec1b6ebe6887", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 173, "license_type": "permissive", "max_line_length": 41, "num_lines": 7, "path": "/Numbers/pi.py", "repo_name": "arushs/Projects", "src_encoding": "UTF-8", "text": "import math\ndigit = raw_input('What digit to go to?')\ndigit = int(digit)\nif digit < 40:\n print(float(round(math.pi, digit)))\nelse:\n print(\"Sorry, digit is too large\")\n" }, { "alpha_fraction": 0.54347825050354, "alphanum_fraction": 0.570652186870575, "avg_line_length": 22, "blob_id": "5efab4ff0d2e6be74a42580b9215ac3212e268b2", "content_id": "8860672e0aa726caef5912e6e2340363db72b370", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 184, "license_type": "permissive", "max_line_length": 49, "num_lines": 8, "path": "/Numbers/flip.py", "repo_name": "arushs/Projects", "src_encoding": "UTF-8", "text": "num = int(raw_input(\"amount of times to flip? \"))\nfrom random import randint\nwhile num != 0:\n if randint(0,1) == 1:\n print \"heads\"\n else:\n print \"tails\"\n num-=1\n" } ]
8
luislobo6/project2-data-mining-visualizations-heroku
https://github.com/luislobo6/project2-data-mining-visualizations-heroku
7042b1061ff1dcaedf8a29f620543491aa7b32f5
55bb77f6595203b173fc2d6b0bc40ae83bd72fa8
31e05251b2c72a50f1871d260eaabb164cf1dbd2
refs/heads/main
2023-03-01T15:30:12.587224
2021-02-10T04:29:56
2021-02-10T04:29:56
337,596,840
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6644902229309082, "alphanum_fraction": 0.6649924516677856, "avg_line_length": 28.22058868408203, "blob_id": "39cb96622c061a665ab0a364c4b6f1dc20045f84", "content_id": "2ec61c52416021945d65600184d6fc865551bad5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1991, "license_type": "no_license", "max_line_length": 124, "num_lines": 68, "path": "/app.py", "repo_name": "luislobo6/project2-data-mining-visualizations-heroku", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, redirect, url_for, Markup\nimport pymongo\nimport json\n\n\napp = Flask(__name__)\n\n\n# Initialize PyMongo to work with MongoDBs\nconn = 'mongodb+srv://sigma2:[email protected]/mexicoMining?retryWrites=true&w=majority'\nclient = pymongo.MongoClient(conn)\n\n# Define database\ndb = client.mexicoMining\n\n# General queries to init application and get all the states GeoJSON and mineral information\ngeneral = db.general.find({},{'_id': False}).next()\nfeatures = list(db.estados.find({},{'_id': False}))\ntabla = list(db.tabla.find({},{'_id': False}))\n# client.close()\n\n# Main url the app is deployed\[email protected](\"/\")\ndef index():\n # return the GeoJSON object\n return render_template(\"index.html\")\n\n# URL where we return all the states (first map)\[email protected](\"/start\")\ndef start():\n \n # Create the GeoJSON object from the queries to the database\n obj_geojson = {\n \"type\": general[\"type\"],\n \"crs\": general[\"crs\"],\n \"features\": features\n } \n # return the GeoJSON object\n return obj_geojson\n\n# In this URL you can get specific information regarding one mineral, example to try: /Barita\[email protected](\"/<mineral>\")\ndef minerals(mineral):\n \n # filter query with the mineral name received in the URL\n features_filtered = list(db.estados.find({f\"properties.minerals.{mineral}\": {\"$exists\":True,\"$ne\":[]}},{'_id': False} ))\n\n # Generate the complete GeoJSON with the general part and the mineral selected part\n obj_geojson = {\n \"type\": general[\"type\"],\n \"crs\": general[\"crs\"],\n \"features\": features_filtered\n }\n # return the GeoJSON object\n return obj_geojson\n\n# In this URL you can get specific information regarding one mineral, example to try: /Barita\[email protected](\"/tabla\")\ndef tabla():\n # go for the tablein the DB\n tabla = list(db.tabla.find({},{'_id': False}))\n # return the array\n return json.dumps(tabla)\n\n\n# Run Flask App\nif __name__ == \"__main__\":\n app.run(debug=True)\n " }, { "alpha_fraction": 0.8064159154891968, "alphanum_fraction": 0.8108407258987427, "avg_line_length": 74.16666412353516, "blob_id": "0669d43c35d37f0eeb4e4431230b7cad7ef6340c", "content_id": "d71071c4d9d47283677b713d9c5b32269ec9a62b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 905, "license_type": "no_license", "max_line_length": 148, "num_lines": 12, "path": "/README.md", "repo_name": "luislobo6/project2-data-mining-visualizations-heroku", "src_encoding": "UTF-8", "text": "# project2-data-mining-visualizations-heroku\nProject for Data Mining Visualizations cleaned to upload to Heroku\n\nWelcome to the Mexico Mining Visualizations Dashboard\nWith the files in this repository you can request, save and visualize the Mexico mining information from the latest national survey.\nPlease follow the next file running sequence to ensure a correct flow of information:\nAPI_request.ipynb - This is a jupyter notebook file that is intended to run a request to INEGI´s API asking for the complete information of over 200\n\t\tdata codes that contains the mining output per localization.\napp.py - Use your python version to run this flask application.\n\nDo not! run file MexicoMaps.ipynb, this file creates a geojson file that will take several minutes to run, since the information processed\nin this file is very large. We provide the output of this code on \"/static/data/mexico_ent.geojson\"\n\n\n" }, { "alpha_fraction": 0.41304346919059753, "alphanum_fraction": 0.8260869383811951, "avg_line_length": 46, "blob_id": "e7be9fbb4e1b541a99ef55d0d22572df5cbf0205", "content_id": "e8c14bfd4f44cafa02cc635036185be1e616fbd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 46, "license_type": "no_license", "max_line_length": 46, "num_lines": 1, "path": "/config.py", "repo_name": "luislobo6/project2-data-mining-visualizations-heroku", "src_encoding": "UTF-8", "text": "api_key=\"92dd58b6-5631-aa47-be93-714cde6f04cd\"" }, { "alpha_fraction": 0.5999162197113037, "alphanum_fraction": 0.6158629059791565, "avg_line_length": 35.95357131958008, "blob_id": "1167ae2aa111ed1406b32ec22dc81fe2e3f506cd", "content_id": "b55df37e8d8743721fdb1ae418adcbf6f15fb908", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 31044, "license_type": "no_license", "max_line_length": 258, "num_lines": 840, "path": "/static/js/dashboard.js", "repo_name": "luislobo6/project2-data-mining-visualizations-heroku", "src_encoding": "UTF-8", "text": "\n//////////*** CODE FOR MAPS MENU ***//////////\n\n// DECLARATOIN OF CONSTANTS\n\n// chart keys defined the properties and button ids\nconst charts = [\n {key: \"oro\", title: \"Gold\", color: \"orange\"}, \n {key: \"plata\", title: \"Silver\", color: \"silver\"}, \n {key: \"cobre\", title: \"Copper\", color: \"red\"},\n {key: \"plomo\", title: \"Lead\", color: \"blue\"}, \n {key: \"zinc\", title: \"Zinc\", color: \"green\"},\n {key: \"coque\", title: \"Coke\", color: \"yellow\"},\n {key: \"fierro\", title: \"Iron\", color: \"brown\"},\n {key: \"azufre\", title: \"Sulfur\", color: \"gray\"},\n {key: \"barita\", title: \"Baryta\", color: \"purple\"},\n {key: \"fluorita\", title: \"Fluorite\", color: \"pink\"},\n];\nvar svg = d3.select(\"svg.bar-chart\");\n\n// Function that highlights in the map when the mouse is over the area\nfunction highlightFeature(e) {\n let layer = e.target;\n\n layer.setStyle({\n fillOpacity: 0.7\n });\n\n if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {\n layer.bringToFront();\n }\n}\n\n// function that returns the highlight to the regular value when mouse is out of the area\nfunction resetHighlight(e) {\n let layer = e.target;\n\n layer.setStyle({\n fillOpacity: 0.1\n });\n\n if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {\n layer.bringToFront();\n }\n}\n\n\n/**\n * Function that receives feature from GeoJSON and if this feature has a property named minerals\n * we add the Popup to the point to display more information when each point is clicked\n * in this case we add Popup's and events for fillColor\n * @param {Object} feature from GeoJSON\n * @param {Object} layer from Leaflet\n */\nfunction onEachFeature(feature, layer) {\n // does this feature have a property named minerals?\n if (feature.properties && feature.properties.minerals) {\n let str_popup = `${feature.properties.NOMGEO}<hr>`\n \n // we get the keys and values for the minerals produced in each state\n let keys = Object.keys(feature.properties.minerals)\n let values = Object.values(feature.properties.minerals)\n\n // for each key/value we add them in the popup tag\n for(let i = 0, a= keys.length; i < a; i++ ){\n str_popup = str_popup + `${keys[i]}: ${values[i]} <br>`\n }\n\n // Here we bind the popup's to each area\n layer.bindPopup(str_popup);\n\n // here we bind the events of the mouse over and out\n layer.on({\n mouseover: highlightFeature,\n mouseout: resetHighlight\n });\n\n }\n}\n\n\n\nfunction initCharts(dataMineria, indice, svg, chart, barScale, colorScale, format){\n \n if(d3.selectAll(\"button\")){\n // Disable all buttons\n d3.selectAll(\"button\").property(\"disabled\", false);\n // enable only buttons not currently selected\n d3.select(\"#\" + chart.current.key).property(\"disabled\", true);\n // update page title\n d3.select(\"#chart\").text(charts.find(o => o.key === indice).title);\n }\n \n // sorting the production data\n dataMineria.sort((a, b) => d3.descending(a[indice], b[indice]))\n\n // update scale domain with data from current selection\n const maxValue = d3.max(dataMineria, d=> d[indice]);\n console.log(\"maxValue=\",maxValue)\n barScale.domain([0,maxValue]);\n colorScale.domain([0, maxValue]);\n\n chart.height = dataMineria.length * 30 // adjust accordingly\n svg.attr(\"width\", chart.width)\n .attr(\"height\", chart.height);\n\n // bind the data and draw the firts chart\n // console.log(\"#########---Aqui\",(charts.find(o => o.key === indice).color))\n svg.selectAll(\"g\")\n .data(dataMineria)\n .enter().append(\"g\")\n .attr(\"class\", \"entry\")\n .attr(\"transform\", (d,i) => `translate(0, ${i * 30})`)\n .each (function(d) {\n \n // console.log(\"Entro en g: \", d)\n var entry = d3.select(this); // the current entry\n\n entry.append(\"text\").attr(\"class\", \"label category\")\n .attr(\"y\", 15)\n .attr(\"x\", 0)\n .attr(\"font-size\", \"9\")\n .text(d.name);\n\n entry.append(\"rect\").attr(\"class\", \"bar\")\n .attr(\"x\", 80)\n .attr(\"height\", 15)\n .attr(\"width\", barScale(d[indice]))\n .style(\"fill\", \n d3.color((charts.find(o => o.key === indice).color))\n .darker(colorScale(d[indice]))\n )\n\n // entry.append(\"text\").attr(\"class\", \"label value\")\n // .attr(\"y\", 12)\n // .attr(\"x\", barScale(d[indice] + 2700)) // ***REVISITED***\n // .attr(\"font-size\", \"9\")\n // .text(format(d[indice]) + \" tons\");\n\n }) // end .each\n \n return (dataMineria,svg)\n \n} // end of setupView function\n\n\nfunction draw(isDropDown, indice, svg, chart, barScale, colorScale, format) {\n \n let dataMineria = []\n let selected_mineral = indice;\n \n // Value Selected from the DropDown Menu\n if(isDropDown == true){\n selected_mineral = d3.select(\"#selDataset\").node().value\n }\n else{ // value selected from the buttons\n\n }\n // change the first letter to UpperCase to consult our API (it needs the first letter in UpperCase)\n selected_mineral = selected_mineral[0].toUpperCase() + selected_mineral.slice(1)\n\n\n // Get the mineral data from the API to plot in the bars\n d3.json(`/${selected_mineral}`, function(data) {\n console.log(data);\n \n data.features.forEach(d => {\n let minerales = d.properties.minerals;\n let keys_min = Object.keys(minerales)\n let values_min = Object.values(minerales)\n \n let aux_minerales = {\n name: d.properties.NOMGEO,\n oro: 0,\n plata: 0,\n cobre: 0,\n plomo: 0,\n zinc: 0,\n coque: 0,\n fierro: 0,\n azufre: 0,\n barita: 0,\n fluorita: 0,\n }\n \n for (let x=0, a=keys_min.length; x < a; x++ ){\n aux_minerales[keys_min[x].toLowerCase()] = values_min[x];\n }\n \n dataMineria.push(aux_minerales)\n })\n \n console.log(\"+++++++++\",dataMineria)\n\n\n dataMineria,svg= initCharts(dataMineria, indice, svg, chart, barScale, colorScale, format);\n \n\n });\n\n console.log(\"(charts.find(o => o.key === selected_mineral_color))=\",(charts.find(o => o.key === indice)))\n console.log(\"indice=\",indice)\n svg.selectAll(\"g.entry\").data(dataMineria)\n .each(function (d,i){\n d3.select(this).select(\".label.category\")\n .text(d.name); // order may have change\n \n d3.select(this).select(\".bar\")\n .transition().duration(10000).delay(50 * i)\n .attr(\"width\", barScale(d[indice]))\n .style(\"fill\", d3.color((charts.find(o => o.key === selected_mineral_color)))\n .darker(colorScale(d[indice])));\n \n // d3.select(this).select(\".label.value\")\n // .transition().duration(10000).delay(50 * i)\n // .attr(\"x\", barScale(d[indice]) + 27000) //+800 ***REVISITED***\n // .text(format(d[indice]) + \" tons\");\n }) // end .each()\n .exit().remove() //This line could be commented if we want to keep the height fixed\n\n}\n\n\n\n\n// THIS NEEDS TO BE UPDATED\n\nvar click1 = d3.select('#click1');\nclick1.on(\"click\", function(){\n\n// to clear space in html \nd3.select(\"#myDiv\").html(\"\");\n\n// To create the header\nd3.select(\"#myDiv\").append(\"h1\").text(\"Mexico Mining Map\")\nd3.select(\"#myDiv\").append(\"hr\")\n\n// Creating myMap Div\nd3.select(\"#myDiv\").append(\"div\").attr(\"id\", \"map\")\n\nlet mymap = L.map('map').setView([23.507173012505426, -103.01796971980406], 6); //Set to Zacatecas and zoom of 5\n\nL.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {\n attribution: 'Map data &copy; <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors, Imagery © <a href=\"https://www.mapbox.com/\">Mapbox</a>',\n maxZoom: 18,\n id: 'mapbox/streets-v11',\n tileSize: 512,\n zoomOffset: -1,\n accessToken: 'pk.eyJ1IjoiaXZpbGNoaXMiLCJhIjoiY2trN2twaDhqMDJmbzJybXVhMzcxNHY3NSJ9.5qG9lj6HT5aXnvZvne4dSg'\n}).addTo(mymap);\n\n// Creating a variable for the map styles\nlet myStyle = {\n \"color\": \"#ff7800\",\n \"weight\": 1,\n \"opacity\": 1,\n \"fillOpacity\": 0.1\n};\n\nd3.json(\"/start\", function(data){\n // L.geoJson(data,{\n // style: myStyle\n // }).addTo(mymap)\n\n L.geoJson(data,{\n pointToLayer: function(data, latlng){\n return L.marker(latlng)\n },\n onEachFeature: onEachFeature,\n style: myStyle\n }).addTo(mymap)\n\n}) // end of d3.json\n\n});//end of event listener .on \"click\"\n\n//////////*** CODE FOR TABLES MENU ***//////////\n\n// WORK IN PROGRESS\n// CLICK 2\nvar click2 = d3.select('#click2');\nclick2.on(\"click\", function(){\n \n // to clear space in html \n d3.select(\"#myDiv\").html(\"\");\n\n d3.select(\"#myDiv\").append(\"h1\").text(\"Data Table of Production in tons*\")\n d3.select(\"#myDiv\").append(\"hr\")\n // Creating a table\n d3.select(\"#myDiv\").append(\"table\").attr(\"class\", \"display\").attr(\"id\", \"mytable\").attr(\"width\", \"100%\")\n let head_table = d3.select(\"#mytable\").append(\"thead\").attr(\"width\", \"100%\").append(\"tr\")\n head_table.append(\"th\").text(\"entidad\")\n head_table.append(\"th\").text(\"oro (kg)\")\n head_table.append(\"th\").text(\"plata (kg)\")\n head_table.append(\"th\").text(\"azufre\")\n head_table.append(\"th\").text(\"cobre\")\n head_table.append(\"th\").text(\"plomo\")\n head_table.append(\"th\").text(\"zinc\")\n head_table.append(\"th\").text(\"barita\")\n head_table.append(\"th\").text(\"coque\")\n head_table.append(\"th\").text(\"fluorita\")\n\n // Creating a data table with ajax\n $(document).ready(function () {\n $('#mytable').DataTable({ \n \"ajax\": {\n url: \"/tabla\", \n dataSrc: \"\"},\n columns: [\n { data: 'entidad' },\n { data: 'oro' },\n { data: 'plata' },\n { data: 'azufre' },\n { data: 'cobre' },\n { data: 'plomo' },\n { data: 'zinc' },\n { data: 'barita' },\n { data: 'coque' },\n { data: 'fluorita' }\n ],\n \"paging\": true,\n \"ordering\": true,\n \"info\": true\n \n })\n }); // end of document.ready\n\n}) // end of event listener click\n\n\n//////////*** CODE FOR BAR CHARTS MENU ***//////////\n// (( CLICK 3))\nvar click3 = d3.select('#click3');\nclick3.on(\"click\", function(){\n \n // to clear space in html \n d3.select(\"#myDiv\").html(\"\");\n d3.select(\"#mytable\").html(\"\");\n // To create the header\n d3.select(\"#myDiv\").append(\"h1\").text(\"Production in tons: \").insert(\"span\").attr(\"id\", \"chart\").text(\"Gold\")\n d3.select(\"#myDiv\").append(\"hr\")\n // Creating an SVG\n d3.select(\"#myDiv\").append(\"svg\").attr(\"class\", \"bar-chart\")\n d3.select(\"#myDiv\").append(\"hr\")\n // To create a form\n d3.select(\"#myDiv\").append(\"form\")\n // to append three buttons under the form\n d3.select(\"form\").append(\"button\").attr(\"type\", \"button\").attr(\"id\", \"oro\").text(\"*** Gold ***\")\n d3.select(\"form\").append(\"button\").attr(\"type\", \"button\").attr(\"id\", \"plata\").text(\"*** Silver ***\")\n d3.select(\"form\").append(\"button\").attr(\"type\", \"button\").attr(\"id\", \"cobre\").text(\"*** Copper ***\")\n d3.select(\"form\").append(\"button\").attr(\"type\", \"button\").attr(\"id\", \"plomo\").text(\"*** Lead ***\")\n d3.select(\"form\").append(\"button\").attr(\"type\", \"button\").attr(\"id\", \"zinc\").text(\"*** Zinc ***\")\n d3.select(\"form\").append(\"button\").attr(\"type\", \"button\").attr(\"id\", \"coque\").text(\"*** Coke ***\")\n // d3.select(\"form\").append(\"button\").attr(\"type\", \"button\").attr(\"id\", \"fierro\").text(\"*** Iron ***\")\n d3.select(\"form\").append(\"button\").attr(\"type\", \"button\").attr(\"id\", \"azufre\").text(\"*** Sulfur ***\")\n d3.select(\"form\").append(\"button\").attr(\"type\", \"button\").attr(\"id\", \"barita\").text(\"*** Baryta ***\")\n d3.select(\"form\").append(\"button\").attr(\"type\", \"button\").attr(\"id\", \"fluorita\").text(\"*** Fluorite ***\")\n \n // chart keys defined the properties and button ids\n const charts = [\n {key: \"oro\", title: \"Gold\", color: \"orange\"}, \n {key: \"plata\", title: \"Silver\", color: \"silver\"}, \n {key: \"cobre\", title: \"Copper\", color: \"red\"},\n {key: \"plomo\", title: \"Lead\", color: \"blue\"}, \n {key: \"zinc\", title: \"Zinc\", color: \"green\"},\n {key: \"coque\", title: \"Coke\", color: \"yellow\"},\n {key: \"fierro\", title: \"Iron\", color: \"brown\"},\n {key: \"azufre\", title: \"Sulfur\", color: \"gray\"},\n {key: \"barita\", title: \"Baryta\", color: \"purple\"},\n {key: \"fluorita\", title: \"Fluorite\", color: \"pink\"},\n ];\n\n // data used for each chart\n var chart = {\n width : 1200,\n height: 0, // the height is set after data is loaded\n current: charts[0] // [0] represents chart to display first\n }\n\n // defining a variable that will hold the data\n var dataMineria = [];\n\n // Setting scale functions for y axis and colors, and format 2 digits \n var barScale = d3.scaleLinear().range([0, 600]); //Validate 600\n var colorScale = d3.scaleLinear().range([0, 1]);\n const format = d3.format(\",.0f\");\n\n const svg = d3.select(\"svg.bar-chart\");\n\n d3.selectAll(\"button\").on(\"click\", function(){\n chart.current = charts.filter(d=> d.key == this.id)[0]; //getting button id\n draw (); //change this to draw() function\n \n }); //end of selectAll(\"button\")\n\n // Load the data from csv\n d3.json(\"/tabla\", function(data) {\n console.log(data);\n data.forEach(function(obj) {\n dataMineria.push({\n name: obj.entidad,\n oro: +obj.oro,\n plata: +obj.plata,\n cobre: +obj.cobre,\n plomo: +obj.plomo,\n zinc: +obj.zinc,\n coque: +obj.coque,\n fierro: +obj.fierro,\n azufre: +obj.azufre,\n barita: +obj.barita,\n fluorita: +obj.fluorita, \n });\n \n });\n // setupView()\n init();\n // console.log(dataMineria)\n });\n\n function setupView(){\n // Disable all buttons\n d3.selectAll(\"button\").property(\"disabled\", false);\n // enable only buttons not currently selected\n d3.select(\"#\" + chart.current.key).property(\"disabled\", true);\n // update page title\n d3.select(\"#chart\").text(chart.current.title);\n \n // sorting the production data\n console.log(chart.current.key)\n dataMineria.sort((a, b) => d3.descending(a[chart.current.key], b[chart.current.key]))\n // var dataMinParsed = dataMineria.filter( d => d.oro != 0 || d.plata != 0 || d.cobre != 0 || d.plomo != 0 || d.zinc != 0 || d.coque != 0 || d.fierro != 0 || d.azufre != 0 || d.barita != 0 || d.fluorita != 0) \n \n if (chart.current.key === \"oro\"){\n var dataMinParsed = dataMineria.filter( d => d.oro)\n } else if(chart.current.key === \"plata\"){\n var dataMinParsed = dataMineria.filter( d => d.plata)\n } else if(chart.current.key === \"cobre\"){\n var dataMinParsed = dataMineria.filter( d => d.cobre)\n } else if(chart.current.key === \"plomo\"){\n var dataMinParsed = dataMineria.filter( d => d.plomo)\n } else if(chart.current.key === \"zinc\"){\n var dataMinParsed = dataMineria.filter( d => d.zinc)\n } else if(chart.current.key === \"coque\"){\n var dataMinParsed = dataMineria.filter( d => d.coque)\n // } else if(chart.current.key === \"fierro\"){\n // var dataMinParsed = dataMineria.filter( d => d.fierro)\n } else if(chart.current.key === \"azufre\"){\n var dataMinParsed = dataMineria.filter( d => d.azufre)\n } else if(chart.current.key === \"barita\"){\n var dataMinParsed = dataMineria.filter( d => d.barita)\n } else if(chart.current.key === \"fluorita\"){\n var dataMinParsed = dataMineria.filter( d => d.fluorita)\n } \n \n console.log(`dataMineria.${chart.current.key}`)\n console.log(\"d.\" + chart.current.key) \n console.log(dataMineria)\n console.log(dataMinParsed) //***REVISITED***\n\n // update scale domain with data from current selection\n const maxValue = d3.max(dataMinParsed, d => d[chart.current.key]);\n barScale.domain([0,maxValue]);\n colorScale.domain([0, maxValue]);\n \n return (dataMinParsed)\n \n } // end of setupView function\n\n // This function runs once\n function init () {\n // Setup svg viewport\n dataMinParsed = setupView();\n \n chart.height = dataMinParsed.length * 30 // adjust accordingly\n svg.attr(\"width\", chart.width)\n .attr(\"height\", chart.height);\n\n // bind the data and draw the firts chart\n \n svg.selectAll(\"g\")\n .data(dataMinParsed)\n .enter().append(\"g\")\n .attr(\"class\", \"entry\")\n .attr(\"transform\", (d,i) => `translate(0, ${i * 30})`)\n .each (function(d) {\n var entry = d3.select(this); // the current entry\n\n entry.append(\"text\").attr(\"class\", \"label category\")\n .attr(\"y\", 15)\n .attr(\"x\", 0)\n .text(d.name);\n\n entry.append(\"rect\").attr(\"class\", \"bar\")\n .attr(\"x\", 150)\n .attr(\"height\", 20)\n .attr(\"width\", barScale(d[chart.current.key]))\n .style(\"fill\", \n d3.color(chart.current.color).darker(colorScale(d[chart.current.key])))\n\n entry.append(\"text\").attr(\"class\", \"label value\")\n .attr(\"y\", 15)\n .attr(\"x\", barScale(d[chart.current.key] + 2700)) // ***REVISITED***\n .attr(\"font-size\", \"9\")\n .text(format(d[chart.current.key]) + \" tons\");\n\n }) // end .each\n \n } // end function init()\n\n function draw() {\n \n init();\n\n dataMinParsed = setupView();\n \n svg.selectAll(\"g.entry\").data(dataMinParsed)\n .each(function (d,i){\n d3.select(this).select(\".label.category\")\n .text(d.name); // order may have change\n \n d3.select(this).select(\".bar\")\n .transition().duration(1000).delay(50 * i)\n .attr(\"width\", barScale(d[chart.current.key]))\n .style(\"fill\", d3.color(chart.current.color)\n .darker(colorScale(d[chart.current.key])));\n \n d3.select(this).select(\".label.value\")\n .transition().duration(1000).delay(50 * i)\n .attr(\"x\", barScale(d[chart.current.key]) + 160) //+800 ***REVISITED***\n .text(format(d[chart.current.key]) + \" tons\");\n }) // end .each()\n .exit().remove() //This line could be commented if we want to keep the height fixed\n\n } // end function draw()\n \n}); //end of event listener .on \"click\"\n\n//////////*** CODE FOR SUMMARY BY TYPE OF MINERAL ***//////////\n\n// THIS NEEDS TO BE UPDATED\n\nvar click4 = d3.select('#click4');\nclick4.on(\"click\", function(){\n \n // to clear space in html \n d3.select(\"#myDiv\").html(\"\"); \n\n // To create the header\n d3.select(\"#myDiv\").append(\"h3\").text(\"Summary by type of mineral\")\n // Creating a row in bootstrap to hold a h8 tag and the select\n var row_Just = d3.select(\"#myDiv\").append(\"div\").attr(\"class\", \"row\")\n //Create a column to hold the bars \n row_Just.append(\"div\").attr(\"class\", \"col-4\").attr(\"id\", \"h8div\")\n // Create a column to hold the table\n row_Just.append(\"div\").attr(\"class\", \"col-4\").attr(\"id\", \"seldiv\")\n // To create h8 tag\n d3.select(\"#h8div\").append(\"h8\").text(\"Select from the list the mineral you want to visualize\")\n \n\n // To create a dropDown select\n let dropdown = d3.select(\"#seldiv\").append(\"select\")\n .attr(\"id\", \"selDataset\");\n\n // Populate it with D3\n dropdown.selectAll(\"option\")\n .data(charts)\n .enter()\n .append(\"option\")\n .attr(\"value\", d => d.key)\n .text(d=>d.title);\n\n d3.select(\"#myDiv\").append(\"hr\")\n ////// This chunk of code is for plotting the map //////\n\n d3.select(\"#myDiv\").append(\"div\").attr(\"class\", \"row\").append(\"div\").attr(\"class\", \"col\").attr(\"id\", \"mapcol\")\n // Creating myMap Div\n d3.select(\"#mapcol\").append(\"div\").attr(\"id\", \"map2\")\n\n let mymap = L.map('map2').setView([23.507173012505426, -103.01796971980406], 5); //Set to Zacatecas and zoom of 4\n\n L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {\n attribution: 'Map data &copy; <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors, Imagery © <a href=\"https://www.mapbox.com/\">Mapbox</a>',\n maxZoom: 18,\n id: 'mapbox/streets-v11',\n tileSize: 512,\n zoomOffset: -1,\n accessToken: 'pk.eyJ1IjoiaXZpbGNoaXMiLCJhIjoiY2trN2twaDhqMDJmbzJybXVhMzcxNHY3NSJ9.5qG9lj6HT5aXnvZvne4dSg'\n }).addTo(mymap);\n\n // Creating a variable for the map styles\n let myStyle = {\n \"color\": \"#ff7800\",\n \"weight\": 1,\n \"opacity\": 1,\n \"fillOpacity\": 0\n };\n\n // Value Selected from the DropDown Menu\n let selected_mineral = d3.select(\"#selDataset\").node().value\n let selected_mineral_color = d3.select(\"#selDataset\").node().value\n // change the first letter to UpperCase to consult our API (it needs the first letter in UpperCase)\n selected_mineral = selected_mineral[0].toUpperCase() + selected_mineral.slice(1)\n \n // $(\".leaflet-interactive\").remove(); //removes previously drawn lines!\n\n // from the constant we get the value of the color, to match colors from the bars and the map\n for (let x=0, a=charts.length; x < a; x++ ){\n // if the selected mineral in the dropdown matches, then we select that color and break from the for cycle\n if (charts[x].key == selected_mineral_color){\n myStyle.color = charts[x].color\n break;\n }\n }\n \n // Here we call our API, it needs the name of the mineral first letter UpperCase\n // this API returns a GeoJSON object with only the states that produces the mineral \n d3.json(`/${selected_mineral}`, function(data){\n // change the fillOpacity to know when we have visited one state, because the initial state is less transparent\n myStyle.fillOpacity = 0.5;\n \n // Add the geoJson layer to highlight only the states that produces the selected mineral\n L.geoJson(data,{\n pointToLayer: function(data, latlng){\n return L.marker(latlng)\n },\n onEachFeature: onEachFeature, // here we add the popups and events\n style: myStyle // change style\n }).addTo(mymap)\n\n \n\n }) // end of d3.json call to API\n\n\n ////// This chunk of code is for displting the table and the bar charts //////\n // Creating a row in bootstrap to hold the table and the bars in the same level\n d3.select(\"#myDiv\").append(\"hr\")\n\n var row_Just = d3.select(\"#myDiv\").append(\"div\").attr(\"class\", \"row justify-content-evenly\")\n //Create a column to hold the bars \n row_Just.append(\"div\").attr(\"class\", \"col-md-7\").attr(\"id\", \"col-bars\")\n // Create a column to hold the table\n row_Just.append(\"div\").attr(\"class\", \"col-md-5\").attr(\"id\", \"col-table\")\n\n\n // data used for each chart\n var chart = {\n width : 800, //\n height: 0, // the height is set after data is loaded\n current: (charts.find(o => o.key === selected_mineral_color)) // [0] represents chart to display first\n }\n\n\n // Setting scale functions for y axis and colors, and format 2 digits \n var barScale = d3.scaleLinear().range([0, 600]); //Validate 600\n var colorScale = d3.scaleLinear().range([0, 1]);\n const format = d3.format(\",.0f\");\n\n const svg = d3.select(\"#col-bars\").append(\"svg\").attr(\"class\", \"bar-chart\").classed(\"svg-container\", true) //container class to make it responsive;\n\n\n\n\n ///////////////// Event Listener for the dropDown\n d3.selectAll(\"#selDataset\").on(\"change\", function(){\n \n // Update selected mineral color\n selected_mineral_color = d3.select(\"#selDataset\").node().value\n\n // Here Changes the values for the charts when you select something from the DropDown\n draw(true,selected_mineral_color,svg,chart,barScale,colorScale,format);\n \n //////// **** Here comes the code for updating the map in a separate function **** ////////\n changeDrop(mymap)\n \n }); //end of selectAll(\"button\")\n \n // let indice = d3.select(\"#selDataset\").node().value\n console.log(\"+++++++++selected_mineral_color\",selected_mineral_color)\n draw(true, selected_mineral_color,svg,chart,barScale,colorScale,format)\n\n}); // End of d3.select #click4\n\n\n\n//////////*** CODE FOR CONCLUSIONS MENU ***//////////\n\n// WORK IN PROGRESS\n\nvar click5 = d3.select('#click5');\nclick5.on(\"click\", function(){\n \n function init() {\n // to clear space in html \n d3.select(\"#myDiv\").html(\"\");\n // To create the header\n d3.select(\"#myDiv\").append(\"h1\").text(\"Conclusions\") \n d3.select(\"#myDiv\").append(\"hr\")\n // Creating a div class \"list-group\"\n d3.select(\"#myDiv\").append(\"div\").attr(\"class\", \"list-group\")\n \n // To create a list of buttons class \"list-group-item list-group-item-action\"\n d3.select(\"div.list-group\").append(\"button\").attr(\"id\", \"one\").attr(\"class\", \"list-group-item list-group-item-action\").text(\" ( 1 ) \")\n d3.select(\"div.list-group\").append(\"button\").attr(\"id\", \"two\").attr(\"class\", \"list-group-item list-group-item-action\").text(\" ( 2 ) \")\n d3.select(\"div.list-group\").append(\"button\").attr(\"id\", \"three\").attr(\"class\", \"list-group-item list-group-item-action\").text(\" ( 3 ) \")\n d3.select(\"div.list-group\").append(\"button\").attr(\"id\", \"four\").attr(\"class\", \"list-group-item list-group-item-action\").text(\" ( 4 ) \")\n d3.select(\"div.list-group\").append(\"button\").attr(\"id\", \"five\").attr(\"class\", \"list-group-item list-group-item-action\").text(\" ( 5 ) \")\n d3.select(\"div.list-group\").append(\"button\").attr(\"id\", \"six\").attr(\"class\", \"list-group-item list-group-item-action\").text(\" ( 6 ) \")\n d3.select(\"div.list-group\").append(\"button\").attr(\"id\", \"seven\").attr(\"class\", \"list-group-item list-group-item-action\").text(\" ( 7 ) \")\n d3.select(\"div.list-group\").append(\"button\").attr(\"id\", \"eight\").attr(\"class\", \"list-group-item list-group-item-action\").text(\" ( 8 ) \")\n d3.select(\"div.list-group\").append(\"button\").attr(\"id\", \"nine\").attr(\"class\", \"list-group-item list-group-item-action\").text(\" ( 9 ) \")\n \n }; \n\n init()\n\n // Take Away #1\n d3.select(\"#one\")\n .on(\"click\", function(){\n d3.selectAll(\"button\").attr(\"class\", \"list-group-item list-group-item-action\")\n d3.select(\"#one\").text(\" ( 1 ) Mexico is the biggest producer of Silver on a World Way Basis, converting to Zacatecas as the principal generator of Silver in Mex, this according to the last Report of Silver Institute\")\n .attr(\"class\", \"list-group-item list-group-item-action active\")\n\n });\n\n // Take Away #2\n d3.select(\"#two\").on(\"click\", function(){\n d3.selectAll(\"button\").attr(\"class\", \"list-group-item list-group-item-action\")\n d3.select(\"#two\").text(\" ( 2 ) The main states that generate the 80% of the national mining production in Mexico are: Chihuahua, Zacatecas, Durango and Guerrero.\")\n .attr(\"class\", \"list-group-item list-group-item-action active\")\n\n })\n\n // Take Away #3\n d3.select(\"#three\").on(\"click\", function(){\n d3.selectAll(\"button\").attr(\"class\", \"list-group-item list-group-item-action\")\n d3.select(\"#three\").text(\" ( 3 ) 23 states in Mexico are dedicated to the Mining Industry, that position Mexico on the 5th place of WW investment on this sector, that based on S&P index\")\n .attr(\"class\", \"list-group-item list-group-item-action active\")\n })\n\n // Take Away #4\n d3.select(\"#four\").on(\"click\", function(){\n d3.selectAll(\"button\").attr(\"class\", \"list-group-item list-group-item-action\")\n d3.select(\"#four\").text(\" ( 4 ) The mining-metallurgical sector in our country represented 8.2% of the industrial Gross Domestic Product (GDP) and 2.4% of GDP. according to figures from the National Institute of Statistics and Geography (INEGI), in 2018.\")\n .attr(\"class\", \"list-group-item list-group-item-action active\")\n })\n\n // Take Away #5\n d3.select(\"#five\").on(\"click\", function(){\n d3.selectAll(\"button\").attr(\"class\", \"list-group-item list-group-item-action\")\n d3.select(\"#five\").text(\" ( 5 ) Mexico ranks among the top 10 producers of 16 different minerals like: silver, bismuth, fluorite, celestite, gold and copper.\")\n .attr(\"class\", \"list-group-item list-group-item-action active\")\n })\n\n // Take Away #6\n d3.select(\"#six\").on(\"click\", function(){\n d3.selectAll(\"button\").attr(\"class\", \"list-group-item list-group-item-action\")\n d3.select(\"#six\").text(\" ( 6 ) From the Proyect, We realized that, the INEGI API is have an inconsistencies at the moment of run and download data, for example the main URL was not available\")\n .attr(\"class\", \"list-group-item list-group-item-action active\")\n })\n\n // Take Away #7\n d3.select(\"#seven\").on(\"click\", function(){\n d3.selectAll(\"button\").attr(\"class\", \"list-group-item list-group-item-action\")\n d3.select(\"#seven\").text(\" ( 7 )Using D3 as main tool of JS, permitted us visualize that it's a big tool to improve and visualize data on JavaScript\")\n .attr(\"class\", \"list-group-item list-group-item-action active\")\n })\n\n // Take Away #8\n d3.select(\"#eight\").on(\"click\", function(){\n d3.selectAll(\"button\").attr(\"class\", \"list-group-item list-group-item-action\")\n d3.select(\"#eight\").text(\" ( 8 ) GeoJson and Fleetmap could work as a pair in order to create tools for decition making process\")\n .attr(\"class\", \"list-group-item list-group-item-action active\")\n })\n\n // Take Away #9\n d3.select(\"#nine\").on(\"click\", function(){\n d3.selectAll(\"button\").attr(\"class\", \"list-group-item list-group-item-action\")\n d3.select(\"#nine\").text(\" ( 9 ) The hardest part of the project was mining and cleaning the data, in order to improve our Programing Codes\")\n .attr(\"class\", \"list-group-item list-group-item-action active\")\n })\n\n}) // end of event listener click\n\n\n//////////*** CODE FOR DROPDOWN SELECTION @ RESUMEN ONLY MAP ***//////////\n\n// WORK IN PROGRESS\nfunction changeDrop(mymap){\n \n L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {\n attribution: 'Map data &copy; <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors, Imagery © <a href=\"https://www.mapbox.com/\">Mapbox</a>',\n maxZoom: 18,\n id: 'mapbox/streets-v11',\n tileSize: 512,\n zoomOffset: -1,\n accessToken: 'pk.eyJ1IjoiaXZpbGNoaXMiLCJhIjoiY2trN2twaDhqMDJmbzJybXVhMzcxNHY3NSJ9.5qG9lj6HT5aXnvZvne4dSg'\n }).addTo(mymap);\n\n // Creating a variable for the map styles\n let myStyle = {\n \"color\": \"#ff7800\",\n \"weight\": 1,\n \"opacity\": 1,\n \"fillOpacity\": 0\n };\n\n // Value Selected from the DropDown Menu\n let selected_mineral = d3.select(\"#selDataset\").node().value\n let selected_mineral_color = d3.select(\"#selDataset\").node().value\n // change the first letter to UpperCase to consult our API (it needs the first letter in UpperCase)\n selected_mineral = selected_mineral[0].toUpperCase() + selected_mineral.slice(1)\n \n $(\".leaflet-interactive\").remove(); //removes previously drawn lines!\n\n // from the constant we get the value of the color, to match colors from the bars and the map\n for (let x=0, a=charts.length; x < a; x++ ){\n // if the selected mineral in the dropdown matches, then we select that color and break from the for cycle\n if (charts[x].key == selected_mineral_color){\n myStyle.color = charts[x].color\n break;\n }\n }\n \n // Here we call our API, it needs the name of the mineral first letter UpperCase\n // this API returns a GeoJSON object with only the states that produces the mineral \n d3.json(`/${selected_mineral}`, function(data){\n // change the fillOpacity to know when we have visited one state, because the initial state is less transparent\n myStyle.fillOpacity = 0.5;\n \n // Add the geoJson layer to highlight only the states that produces the selected mineral\n L.geoJson(data,{\n pointToLayer: function(data, latlng){\n return L.marker(latlng)\n },\n onEachFeature: onEachFeature, // here we add the popups and events\n style: myStyle // change style\n }).addTo(mymap)\n\n }) // end of d3.json call to API\n}" } ]
4
suryaatevellore/SNM-Labs
https://github.com/suryaatevellore/SNM-Labs
6bf15eca4849972faab2a22ef65f392fcd1028ec
6ac872ed5b7a0f1dd9db4104ed0792e1f2f1ded8
2a388d19809e9d9b4f9c417ad54951f66606d550
refs/heads/master
2020-03-29T12:28:23.013560
2018-10-10T21:42:14
2018-10-10T21:42:14
149,900,814
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7161803841590881, "alphanum_fraction": 0.7294429540634155, "avg_line_length": 40.77777862548828, "blob_id": "28ab21fb9ef76b8b3541a17a6298222070aa8156", "content_id": "cecdee06b56ae16d82a87ac1f23938f9833bcdc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 377, "license_type": "no_license", "max_line_length": 112, "num_lines": 9, "path": "/README.md", "repo_name": "suryaatevellore/SNM-Labs", "src_encoding": "UTF-8", "text": "# README #\n\n### What is this repository for? ###\n\n* All code made during SNM-Labs@NCSU\n* Contents\n 1. SSH_to_cisco.py : Basic bootstrap for extracting data from Cisco devices using netmiko\n 2. SSH_to_linux.py : Similar functionality as above, but for linux\n 3. lab25.py : Under construction, but gets cdp information from Cisco devices and places it into a structure\n\n" }, { "alpha_fraction": 0.5368748903274536, "alphanum_fraction": 0.5464097857475281, "avg_line_length": 35.510948181152344, "blob_id": "8b82d45df9353417af0ab8b1cfc51649907f330a", "content_id": "e8caa28ca739fc9f53c09e96392bf9924c31069d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5139, "license_type": "no_license", "max_line_length": 239, "num_lines": 137, "path": "/lab25.py", "repo_name": "suryaatevellore/SNM-Labs", "src_encoding": "UTF-8", "text": "import sys\r\nimport re\r\nfrom netmiko import ConnectHandler\r\nfrom netmiko.ssh_exception import NetMikoTimeoutException\r\n\r\nclass AdjacencyList:\r\n '''\r\n Class for creating Adjacency List\r\n\r\n Variables :\r\n Adj_device - List to store all elements\r\n\r\n Functions:\r\n add_devices - Takes an element object and appends it to Adj_device List\r\n\r\n show_devices - Show all devices along with neighbors\r\n '''\r\n def __init__(self):\r\n self.Adj_device = []\r\n\r\n def add_devices(self, device):\r\n self.Adj_device.append(device)\r\n\r\n def show_devices(self):\r\n for each_device in self.Adj_device:\r\n print(\"================================================\")\r\n print(each_device.hostname)\r\n for each_neighbor_name, each_neighbor_params in each_device.neighbors.items():\r\n print(f\" Neighbor Name: {each_neighbor_name}\")\r\n print(f\" Neighbor IP Address : {each_neighbor_params.get('IP address', None)}\")\r\n print(f\" Neighbor Platform : {each_neighbor_params.get('Platform', None)}\")\r\n print(f\" Neighbor Type : {each_neighbor_params.get('Capabilities', None)}\")\r\n print(f\" Self Local Interface : {each_neighbor_params.get('Interface', None)}\")\r\n print(f\" Local VLAN : {each_neighbor_params.get('Native VLAN', None)}\")\r\n print(f\" Neighbor Local Interface : {each_neighbor_params.get('Port ID (outgoing port)', None)}\")\r\n print(f\" Neighbor VLAN : {each_neighbor_params.get('Native VLAN', None)}\")\r\n\r\n print(\"\\n\")\r\n\r\n\r\nclass Element:\r\n '''\r\n Class for defining each element of Adjacenct List\r\n This is basically the nodes that we will be logging in\r\n\r\n Variables:\r\n device_ip : Device IP of device\r\n hostname : Hostname of device\r\n neighbors = Dictionary of all neighbors of this device\r\n\r\n Functions:\r\n Login : Login into each of the devices\r\n calculate_neighbors : Output formatting for data gathered from each neighbor\r\n Outputs a structure neighbors : {Neighbor1: {Params}, Neighbor N : {Params}}\r\n\r\n '''\r\n def __init__(self, device_ip):\r\n self.device_ip = device_ip\r\n self.hostname = \"\"\r\n self.neighbors = {}\r\n\r\n def login(self, username, password, secret, device_ip):\r\n cisco_iou = {\r\n 'device_type': 'cisco_ios',\r\n 'ip' : device_ip,\r\n 'username' : username,\r\n 'password' : password,\r\n 'secret' : secret,\r\n 'verbose' : True\r\n }\r\n try:\r\n net_connect = ConnectHandler(**cisco_iou)\r\n net_connect.enable()\r\n net_connect.config_mode()\r\n #Checks if CDP is enabled\r\n print(f\"Checking for cdp on {cisco_iou['ip']}\")\r\n cdp_check = net_connect.send_command(\"do show cdp neighbors\")\r\n if \"CDP is not enabled\" in cdp_check:\r\n net_connect.send_command(\"cdp run\")\r\n else:\r\n print(f\"CDP is enabled on this device {cisco_iou['ip']}\")\r\n net_connect.exit_config_mode()\r\n output = net_connect.send_command(\"sh cdp neigh det | i (ID|IP add|Plat|Interface|Port ID|VLAN)\")\r\n\r\n\r\n #Hostname\r\n find_hostname = net_connect.find_prompt()\r\n self.hostname = find_hostname.split(\"#\")[0]\r\n\r\n return output\r\n\r\n\r\n except (EOFError, NetMikoTimeoutException):\r\n print('SSH is not enabled for this device.')\r\n sys.exit()\r\n\r\n def calculate_neighbors(self, output):\r\n temp = output.split(\"\\n\")\r\n device_data = re.findall(\"(Device ID: [A-Za-z0-9.]+)\\n(\\s\\sIP address: [\\d.]+\\n)?(Platform: [a-zA-Z\\s]+,)\\s\\s(Capabilities: [a-zA-Z\\s]+\\n)(Interface: [A-Za-z0-9\\/]+,)\\s\\s(Port ID .*: [a-zA-Z0-9\\/]+)\\n(Native VLAN: [\\d]+)?\", output)\r\n\r\n for device in device_data:\r\n device_hostname = device[0].split(\":\")[1]\r\n self.neighbors[device_hostname] = {}\r\n for item in device[1:]:\r\n if item:\r\n self.neighbors[device_hostname][item.split(\":\")[0].strip()] = item.split(\":\")[1].strip()\r\n # print(self.neighbors)\r\n\r\ndef main():\r\n username = \"exam\"\r\n password = \"exam\"\r\n secret = \"exam\"\r\n # device_ip = [\r\n # \"192.168.130.251\",\r\n # \"192.168.130.252\",\r\n # \"192.168.130.253\"\r\n # ]\r\n\r\n data = input(\"Enter all device IPs seperated by space > \")\r\n if data:\r\n device_ip = data.strip().split()\r\n else:\r\n print(\"Data format incorrect. You probably pressed enter by mistake\")\r\n\r\n Adj_list = AdjacencyList()\r\n\r\n for each_item in device_ip:\r\n device = Element(each_item)\r\n neighbor_data = device.login(username, password, secret, each_item)\r\n device.calculate_neighbors(neighbor_data)\r\n Adj_list.add_devices(device)\r\n\r\n #Show all devices\r\n Adj_list.show_devices()\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n" }, { "alpha_fraction": 0.5776223540306091, "alphanum_fraction": 0.6034964919090271, "avg_line_length": 25.5, "blob_id": "fd35807a9e5b160425291088983c09f3d952de42", "content_id": "00113d79100792b00fcd5c8bdb95a9e66ed53334", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1430, "license_type": "no_license", "max_line_length": 93, "num_lines": 52, "path": "/SSH_to_Cisco_topology.py", "repo_name": "suryaatevellore/SNM-Labs", "src_encoding": "UTF-8", "text": "from netmiko import ConnectHandler\r\n\r\n\r\n#Use this for threading\r\nusername = \"cisco\"\r\npassword = \"cisco\"\r\nsecret = \"cisco\"\r\ndevice_ip = [\r\n \"192.168.130.250\",\r\n \"192.168.130.251\",\r\n \"192.168.130.252\"\r\n]\r\n\r\ndevices_cdp_output = {}\r\nfor item in device_ip:\r\n cisco_iou = {\r\n 'device_type': 'cisco_ios',\r\n 'ip' : item,\r\n 'username' : username,\r\n 'password' : password,\r\n 'secret' : secret,\r\n 'verbose' : True\r\n }\r\n\r\n #Need to add error handling here but otherwise the code works and configures cdp\r\n net_connect = ConnectHandler(**cisco_iou)\r\n # print(\"Check prompt at login\")\r\n # print(net_connect.find_prompt())\r\n net_connect.enable()\r\n net_connect.config_mode()\r\n cdp_flag = net_connect.send_command(\"do show cdp neighbors\")\r\n if \"CDP is not enabled\" in cdp_flag:\r\n net_connect.send_command(\"cdp run\")\r\n print(net_connect.find_prompt())\r\n\r\n else:\r\n print(\"CDP seems to be already enabled\")\r\n\r\n net_connect.exit_config_mode()\r\n output = net_connect.send_command(\"sh cdp ne d | inc (ID|IP add|Plat|Interface|Port ID)\")\r\n\r\n print(output.split(\"\\n\"))\r\n #Perform processing on output\r\n\r\n\r\n\r\n # devices_cdp_output[item] = output.split(\"\\n\")[4:]\r\n net_connect.disconnect()\r\n\r\n# print(devices_cdp_output)\r\n\r\n#paramiko.ssh_exception.AuthenticationException: Authentication timeout.\r\n" }, { "alpha_fraction": 0.5015384554862976, "alphanum_fraction": 0.5015384554862976, "avg_line_length": 24.91666603088379, "blob_id": "151df8e88dc0d545437b56924d44a522c0e936ef", "content_id": "a82c45de71a6121ebb93ca38dc65e2810d226694", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 325, "license_type": "no_license", "max_line_length": 76, "num_lines": 12, "path": "/leetcode_practice.py", "repo_name": "suryaatevellore/SNM-Labs", "src_encoding": "UTF-8", "text": "from itertools import product\r\n\r\nclass Solution:\r\n def letterCasePermutation(self, S):\r\n \"\"\"\r\n :type S: str\r\n :rtype: List[str]\r\n \"\"\"\r\n # S=input()\r\n l = [(c, c.upper()) if not c.isdigit() else (c,) for c in S.lower()]\r\n\r\n return [\"\".join(item) for item in product(*l)]\r\n\r\n" }, { "alpha_fraction": 0.592042088508606, "alphanum_fraction": 0.6075920462608337, "avg_line_length": 34.7310905456543, "blob_id": "9183b87cdf843720ef82ac80d76ee9cb8d819213", "content_id": "0747c4b1e67b6dd815873a23087fae231ac063c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4373, "license_type": "no_license", "max_line_length": 207, "num_lines": 119, "path": "/SSH_to_Linux.py", "repo_name": "suryaatevellore/SNM-Labs", "src_encoding": "UTF-8", "text": "#######################################################################\r\n\"\"\"\r\nDependencies: Python3.6.6, paramiko\r\nFlow:\r\nUserInput for remote device-> Using paramiko, send commands and obtain appropriate output for commands-> Use pyregex to extract data to populate datastructures-> Ask for user input for displaying information\r\n\"\"\"\r\n\r\n\r\nimport re\r\nimport paramiko\r\nimport getpass\r\nimport time\r\n\r\n#Add later\r\nIP_ADDRESS = input(\"Provide device IP> \")\r\nusername = input(\"Enter the username> \")\r\npassword = input(\"Enter the password> \")\r\n\r\n# IP_ADDRESS = '192.168.56.101'\r\n# username = 'vagrant'\r\n# password = 'vagrant'\r\n\r\nremoteIP = IP_ADDRESS\r\nusername = username\r\npassword = password\r\n\r\nhandler = paramiko.SSHClient();\r\n\r\nhandler.set_missing_host_key_policy(paramiko.AutoAddPolicy())\r\nhandler.connect(IP_ADDRESS, username=username, password=password, look_for_keys=False, allow_agent=False)\r\nprint(\"Connection Established..Now sending commands\")\r\ntime.sleep(2)\r\nshell = handler.invoke_shell()\r\n\r\noutput = shell.recv(1000)\r\nshell.send(\"ip addr show\\n\")\r\ntime.sleep(2)\r\ndata = shell.recv(1000)\r\n\r\nEXPRESSION = r\"(eth\\d|lo|wifi\\d):\\s\\<[A-Za-z0-9,_]*\\>\\s[a-zA-Z0-9,_ ]*\\\\r\\\\n\\s{1,10}link/(ether|loopback)\\s([0-9a-zA-Z:]*)\\sbrd\\s[0-9a-z:]*\\\\r\\\\n(\\s{1,6}inet\\s([0-9\\/.]*))?\"\r\n\r\nr1 = re.findall(EXPRESSION,str(data))\r\n\r\ninterfaces = [list(item) for item in r1]\r\n\r\ninterfaces_type_dict = {}\r\ninterfaces_mac_dict = {}\r\ninterfaces_ip_dict = {}\r\n\r\nfor item in interfaces :\r\n interfaces_type_dict[item[0]] = item[1]\r\n interfaces_mac_dict[item[0]] = item[2]\r\n interfaces_ip_dict[item[0]] = item[4]\r\n\r\nfor item in interfaces_ip_dict.keys():\r\n if interfaces_ip_dict[item]!='':\r\n ip = interfaces_ip_dict[item].split(\"/\")[0]\r\n interfaces_ip_dict[item] = ip\r\n else:\r\n interfaces_ip_dict[item] = None\r\nprint(\"Data structures populated\")\r\n\r\n\r\n\r\nprint(\"Now, do you wish to search interfaces by \\n1.IP\\n2.MAC\\n3.TYPE\\n4.Display All Interfaces by IP\\n5.Display All by MAC\\n6.Display all by type. Please Enter your choice\")\r\n\r\nchoice = int(input(\">\"))\r\n\r\nif (choice==1):\r\n ip_address = input(\"Enter the IP Address of the Interface> \")\r\n try:\r\n interface_for_ip = list(interfaces_ip_dict.keys())[list(interfaces_ip_dict.values()).index(ip_address)]\r\n if interface_for_ip:\r\n print (\"#############################\")\r\n print (\"Here is the interface\" ,interface_for_ip)\r\n print (\"Other Details..TYPE :\" + interfaces_type_dict[interface_for_ip] + \" ....MAC :\" + interfaces_mac_dict[interface_for_ip])\r\n except ValueError:\r\n print (\"#############################\")\r\n print (\"The IP does not exist on the box\")\r\n\r\n\r\nelif (choice==2):\r\n mac = input(\"Enter the mac of the interface> \")\r\n try:\r\n interface_for_mac = list(interfaces_mac_dict.keys())[list(interfaces_mac_dict.values()).index(mac)]\r\n print(interface_for_mac)\r\n print (\"#############################\")\r\n print (\"Here is the interface\", interface_for_mac)\r\n print (\"Other Details..TYPE: \" + interfaces_type_dict[interface_for_mac] + \".......IP: \" + str(interfaces_ip_dict[interface_for_mac]))\r\n\r\n except ValueError:\r\n print(\"This mac does not exist on the box\")\r\n\r\nelif (choice==3):\r\n print(\"Some interface types \\n1.loopback\\n2.ether(ethernet)\\n3.ieee802.11\")\r\n type_interface = input(\"Enter the type of the interface> \")\r\n\r\n try:\r\n if type_interface in interfaces_type_dict.values():\r\n l = [k for k in interfaces_type_dict.keys() if interfaces_type_dict[k]==type_interface]\r\n for item in l:\r\n print(\"Interface : \", item)\r\n print(\"IP Details : \", interfaces_ip_dict[item])\r\n print(\"MAC Details : \", interfaces_mac_dict[item])\r\n else:\r\n raise ValueError\r\n except ValueError:\r\n print (\"This interface does not exist on the box\")\r\nelif(choice==4):\r\n for k,v in interfaces_ip_dict.items():\r\n print(f\"Interface {k} : {v}\")\r\nelif(choice==5):\r\n for k,v in interfaces_mac_dict.items():\r\n print(f\"Interface {k} : {v}\")\r\nelif(choice==6):\r\n for k,v in interfaces_type_dict.items():\r\n print(f\"Interface {k} : {v}\")\r\nelse:\r\n print (\"You are a rebel!. But since I am an amateur, could you please pick a value that is stated above ? Thank you!\")\r\n\r\n" }, { "alpha_fraction": 0.5523788332939148, "alphanum_fraction": 0.5593031048774719, "avg_line_length": 36.93043518066406, "blob_id": "c5ad4d3e19b5cdb3018d318e3abc44913c6f6015", "content_id": "ab1c9493b45db5f3192056b4ec63f72f7cffbe34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4477, "license_type": "no_license", "max_line_length": 212, "num_lines": 115, "path": "/SSH_to_Cisco.py", "repo_name": "suryaatevellore/SNM-Labs", "src_encoding": "UTF-8", "text": "from netmiko import ConnectHandler\r\nimport re\r\n\r\ndef does_all_work():\r\n \"\"\"Performs the primary function in the file\r\n Input variables :\r\n device_ip : IP of the device that we should login to\r\n username/password : device username/password\r\n Program variables :\r\n interfaces = stores the configuration for \"show interface\"\r\n ip = stores the configuration for the command \"show ip interface brief\"\r\n IP_EXPRESSIONS = regex for extracting information from interfaces\r\n Expression = regex for extracting information from ip\r\n choice = choice of the user to pick interface parameters\r\n\r\n Output variables : None , print to stdout\r\n\r\n Flow :\r\n Ask for device ip -> Login -> Obtain information by making a connection to the router and passing commands -> populate the dictionaries -> Obtain information from the dictionaries according to user choice\r\n\r\n\r\n \"\"\"\r\n ip_dict = {}\r\n interfaces_dict = {}\r\n username = 'cisco'\r\n password = 'cisco'\r\n\r\n device_ip = raw_input(\"Provide device IP> \")\r\n print \"Username/password is assumed to be cisco/cisco. Change in username/password will be added later\"\r\n\r\n cisco_iou = {\r\n 'device_type': 'cisco_ios',\r\n 'ip' : device_ip,\r\n 'username' : username,\r\n 'password' : password\r\n }\r\n\r\n net_connect = ConnectHandler(**cisco_iou)\r\n print(\"Connection Established\")\r\n print(\"Sending commands to box\")\r\n interfaces = net_connect.send_command(\"show interface\")\r\n ip = net_connect.send_command(\"show ip int br\")\r\n IP_EXPRESSIONS = r\"((Gigabit)?Ethernet\\d(\\/\\d)?)\\s{1,30}([a-zA-Z0-9.]*)\"\r\n r2 = re.findall(IP_EXPRESSIONS, ip)\r\n\r\n for item in r2:\r\n ip_dict[item[0]] = item[3]\r\n\r\n\r\n\r\n EXPRESSION = r\"((Gigabit)?Ethernet)(\\d(\\/\\d)?)\\s(.*\\n)\\s\\sHardware\\sis\\s([a-zA-Z0-9\\s]*),\\saddress\\sis\\s([a-zA-Z0-9.]*)\"\r\n r1 = re.findall(EXPRESSION,interfaces)\r\n\r\n\r\n mac_dict = {}\r\n type_dict = {}\r\n for each_interface in r1:\r\n type_dict[each_interface[0]+each_interface[2]] = each_interface[5]\r\n mac_dict[each_interface[0]+each_interface[2]] = each_interface[6]\r\n # interfaces_dict[each_interface[0]+each_interface[2]] = [(each_interface[5],each_interface[6])]\r\n\r\n print (\"Data Structures populated\")\r\n\r\n #########################################################################\r\n ## Actual Processing\r\n #########################################################################\r\n\r\n print(\"Now, do you wish to search interfaces by \\n1.IP\\n2.MAC\\n3.TYPE. Please Enter your choice\")\r\n choice = int(input(\">\"))\r\n\r\n\r\n if (choice==1):\r\n ip_address = raw_input(\"Enter the IP Address of the Interface> \")\r\n print ip_dict\r\n try:\r\n interface_for_ip = ip_dict.keys()[ip_dict.values().index(ip_address)]\r\n print (\"#############################\")\r\n print \"Here is the interface\" ,interface_for_ip\r\n print \"Other Details..TYPE :\" + type_dict[interface_for_ip] + \" ....MAC :\" + mac_dict[interface_for_ip]\r\n except ValueError:\r\n print (\"#############################\")\r\n print \"The IP does not exist on the box\"\r\n\r\n\r\n elif (choice==2):\r\n mac = raw_input(\"Enter the mac of the interface> \")\r\n try:\r\n interface_for_mac = mac_dict.keys()[mac_dict.values().index(mac)]\r\n print (\"#############################\")\r\n print \"Here is the interface\", interface_for_mac\r\n print \"Other Details..TYPE: \" + type_dict[interface_for_mac] + \".......IP: \" + ip_dict[interface_for_mac]\r\n\r\n except ValueError:\r\n print \"This mac does not exist on the box\"\r\n\r\n elif (choice==3):\r\n type_interface = raw_input(\"Enter the type of the interface> \")\r\n try:\r\n for k,v in type_dict.items():\r\n if v==type_interface:\r\n print \"Interface\" + k, \" IP of Interface :\" + ip_dict[k], \" MAC for Interface: \" + mac_dict[k]\r\n else:\r\n raise ValueError()\r\n except ValueError:\r\n print \"This interface does not exist on the box\"\r\n else:\r\n print (\"You are a rebel!. But since I am an amateur, could you please pick a value that is stated above ? Thank you!\")\r\n\r\n return None\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n \"\"\"Just if the code is called through another program or an app\"\"\"\r\n does_all_work()\r\n" } ]
6
Taycode/teamwave-interview
https://github.com/Taycode/teamwave-interview
d377f2cd86b39415034bff5886945f87d9c09218
9136920d58e945da750f462be2b3bbc22be0d7b1
131b91dd51ac8dfcb648df8ee0e6486420becb1b
refs/heads/master
2022-12-12T11:35:07.182313
2020-01-23T20:51:32
2020-01-23T20:51:32
235,077,582
0
0
MIT
2020-01-20T10:39:22
2020-02-24T22:56:28
2021-09-22T18:27:16
Python
[ { "alpha_fraction": 0.586758017539978, "alphanum_fraction": 0.5878995656967163, "avg_line_length": 28.694915771484375, "blob_id": "94917dde79dd5a6acce5fd3028173da836344148", "content_id": "c3c17b03c67cfe5844a9c17f022e8aac18ff91dc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1752, "license_type": "permissive", "max_line_length": 75, "num_lines": 59, "path": "/stackapp/utils.py", "repo_name": "Taycode/teamwave-interview", "src_encoding": "UTF-8", "text": "import requests\nfrom datetime import datetime\n\n\nclass StackAPIQuestion:\n tags = []\n owner = {}\n is_answered = False\n view_count = None\n answer_count = None\n score = None\n last_activity_date = None\n creation_date = None\n last_edit_date = None\n question_id = None\n link = None\n title = None\n\n def __init__(self, data):\n self.tags = data['tags']\n self.owner = data['owner']\n self.is_answered = data['is_answered']\n self.view_count = data['view_count']\n self.answer_count = data['answer_count']\n self.score = data['score']\n self.last_activity_date = data['last_activity_date']\n self.creation_date = data['creation_date']\n if 'last_edit_date' in data.values():\n self.last_edit_date = data['last_edit_date']\n self.question_id = data['question_id']\n self.link = data['link']\n self.title = data['title']\n\n def __str__(self):\n return self.title\n\n\nclass StackAPIConsumer:\n\n url = 'https://api.stackexchange.com/2.2/search'\n\n params = {'site': 'stackoverflow'}\n\n @classmethod\n def consume(cls, data):\n date = data['fromdate']\n if date is not None:\n date = datetime(year=date.year, month=date.month, day=date.day)\n milliseconds = int(round(date.timestamp()))\n data['fromdate'] = milliseconds\n date = data['todate']\n if date is not None:\n date = datetime(year=date.year, month=date.month, day=date.day)\n milliseconds = int(round(date.timestamp()))\n data['todate'] = milliseconds\n print(data)\n cls.params.update(data)\n response = requests.get(cls.url, params=cls.params)\n return response\n" }, { "alpha_fraction": 0.7210953235626221, "alphanum_fraction": 0.726166307926178, "avg_line_length": 13.716418266296387, "blob_id": "47360e3333d09d68d7baf854585b17d65fa5ea47", "content_id": "9ce5fb9bdef4d19bab2a3934ea5168244b63eb65", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 986, "license_type": "permissive", "max_line_length": 59, "num_lines": 67, "path": "/README.md", "repo_name": "Taycode/teamwave-interview", "src_encoding": "UTF-8", "text": "# teamwave-interview\nan interview project for teamwave\n\n\nFirstly, clone the repo\n\n```\ngit clone https://github.com/Taycode/teamwave-interview.git\n```\n\ngoto the project directory\n\n```\ncd ./teamwave-interview\n```\n\ncreate a virtual environment for the project \n\n```\npython3 -m venv env\n```\n\nactivate the virtual environment\n\nFor windows:\n\n```\ncd ./env/scripts && activate && {project directory}\n```\n\nfor Linux:\n\n```\nsource env/bin/activate\n```\n\nthen install all the necessary dependencies\n\n```\npip install -r requirements.txt\n```\n\nthen make sure you have memcached server running\n\nfirstly, you install memcached\n\nFor Ubuntu:\n```\n$ sudo apt-get update\n$ sudo apt-get install memcached\n```\nthen start the memcached server\n```\n$ sudo systemctl start memcached\n```\nto confirm that memcached is running\n\n```\n$ sudo systemctl status memcached\n```\nthen run the Django server:\n```\npython manage.py migrate && python manage.py runserver\n```\n\n\nnow open your browser and visit http://localhost:8000/\n" }, { "alpha_fraction": 0.7534456253051758, "alphanum_fraction": 0.7534456253051758, "avg_line_length": 39.8125, "blob_id": "282eb255e8a1f7b5a31e6355a631e067285142dc", "content_id": "8a40e3e4a0f23b65338be6ad73708d213f66a467", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 653, "license_type": "permissive", "max_line_length": 72, "num_lines": 16, "path": "/stackapp/forms.py", "repo_name": "Taycode/teamwave-interview", "src_encoding": "UTF-8", "text": "from django import forms\nfrom .choices import sort_choice, order_choice\n\n\nclass StackAPIConsumerForm(forms.Form):\n page = forms.IntegerField(required=False)\n todate = forms.DateField(required=False)\n max = forms.DateField(required=False)\n nottagged = forms.CharField(required=False)\n pagesize = forms.IntegerField(required=False)\n order = forms.ChoiceField(choices=order_choice)\n sort = forms.ChoiceField(choices=sort_choice)\n intitle = forms.CharField(required=False)\n fromdate = forms.DateField(required=False, widget=forms.DateInput())\n min = forms.DateField(required=False)\n tagged = forms.CharField(required=False)\n" }, { "alpha_fraction": 0.5194174647331238, "alphanum_fraction": 0.5194174647331238, "avg_line_length": 17.727272033691406, "blob_id": "2a7d2e2776e473b879d8b6403ab3aba213f33737", "content_id": "ee91dbdb9d4c9628f73f99e0bbe6a551c26f363e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 206, "license_type": "permissive", "max_line_length": 30, "num_lines": 11, "path": "/stackapp/choices.py", "repo_name": "Taycode/teamwave-interview", "src_encoding": "UTF-8", "text": "order_choice = (\n ('desc', 'descending'),\n ('asc', 'ascending')\n)\n\nsort_choice = (\n ('activity', 'activity'),\n ('votes', 'votes'),\n ('creation', 'creation'),\n ('relevance', 'relevance')\n)\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 10.625, "blob_id": "0d5b6f9111da373fb7d19a580486e5a962a81284", "content_id": "7d1198824d8aa8b6b5537ea15c54714bc4bdd689", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 93, "license_type": "permissive", "max_line_length": 28, "num_lines": 8, "path": "/stackapp/urls.py", "repo_name": "Taycode/teamwave-interview", "src_encoding": "UTF-8", "text": "from .views import test\n\n\nfrom django.urls import path\n\nurlpatterns = [\n path('', test)\n]\n" }, { "alpha_fraction": 0.5162454843521118, "alphanum_fraction": 0.7184115648269653, "avg_line_length": 17.46666717529297, "blob_id": "2ac1fe4fbd3ac7ec04e36c7a682df01aec374fc3", "content_id": "1dc7f80404950c682636f821dd7bc1bac7e004aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 277, "license_type": "permissive", "max_line_length": 28, "num_lines": 15, "path": "/requirements.txt", "repo_name": "Taycode/teamwave-interview", "src_encoding": "UTF-8", "text": "asgiref==3.2.3\ncertifi==2019.11.28\nchardet==3.0.4\nDjango==3.0.2\ndjango-rest-framework==0.1.0\ndjango-widget-tweaks==1.4.5\ndjangorestframework==3.11.0\nidna==2.8\npkg-resources==0.0.0\npython-memcached==1.59\npytz==2019.3\nrequests==2.22.0\nsix==1.14.0\nsqlparse==0.3.0\nurllib3==1.25.7\n" }, { "alpha_fraction": 0.5685156583786011, "alphanum_fraction": 0.5764086842536926, "avg_line_length": 41.23147964477539, "blob_id": "d11480a59093970775f8c1140ed9bb754e8d6c08", "content_id": "c1c440855b63086e58b1d521d5c77cc4d24dc609", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4561, "license_type": "permissive", "max_line_length": 102, "num_lines": 108, "path": "/stackapp/views.py", "repo_name": "Taycode/teamwave-interview", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, HttpResponse\nfrom .utils import StackAPIConsumer, StackAPIQuestion\nfrom .forms import StackAPIConsumerForm\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.core.cache import cache\nfrom datetime import datetime, timedelta\n\n\ndef test(request):\n if request.method == 'GET':\n\n # check if it is requesting for a paginated data, if it has the_page in its params\n page = request.GET.get('the_page', None)\n\n form = StackAPIConsumerForm(request.GET or None)\n\n # getting session time for minute and day limits\n day_time = request.session.get('day_time')\n minute_time = request.session.get('minute_time')\n\n # getting amount of searches made\n day_search_number = request.session.get('day_searches')\n minute_search_number = request.session.get('minute_searches')\n data = []\n if page is not None:\n url = request.get_full_path()[:-11]\n res = cache.get(url)\n for response in res.json()['items']:\n data.append(StackAPIQuestion(response))\n else:\n page = 1\n\n url = request.get_full_path()\n\n if day_search_number is None:\n day_search_number = 0\n if minute_search_number is None:\n minute_search_number = 0\n # convert Datetime object to millisecond and save to session\n if day_time is None:\n milliseconds = int(round(datetime.now().timestamp() * 1000))\n day_time = request.session['day_time'] = milliseconds\n if minute_time is None:\n milliseconds = int(round(datetime.now().timestamp() * 1000))\n minute_time = request.session['minute_time'] = milliseconds\n\n # convert back from milliseconds to datetime object\n\n minute_time = datetime.fromtimestamp(minute_time / 1000.0)\n day_time = datetime.fromtimestamp(day_time / 1000.0)\n minutes_delta = timedelta(minutes=1)\n day_delta = timedelta(days=1)\n now_time = datetime.now()\n print(f'day_time {day_time}')\n print(f'minute time {minute_time}')\n print(f'minute delta {now_time - minute_time}')\n print(f'day searches {day_search_number}')\n print(f'minute searches {minute_search_number}')\n # Checking if user has passed session limits\n if ((now_time - minute_time) < minutes_delta and minute_search_number >= 5) \\\n or \\\n ((now_time - day_time) < day_delta and day_search_number >= 100):\n return HttpResponse(\"you have passed the amount of sessions you can have\")\n\n # resetting search number when search limit time has expired\n if (now_time - minute_time) > minutes_delta:\n request.session['minute_time'] = None\n minute_search_number = 0\n if (now_time - day_time) > day_delta:\n request.session['day_time'] = None\n day_search_number = 0\n\n if form.is_valid():\n res = cache.get(request.get_full_path())\n if res is None:\n res = StackAPIConsumer.consume(form.cleaned_data)\n cache.set(request.get_full_path(), res)\n data = []\n\n # return error if no data is returned based on requested parameters\n\n if not res.json()['items']:\n args = {'form': form, 'error': 'There is no data gotten from this search request'}\n return render(request, 'stackapp/test.html', args)\n\n for response in res.json()['items']:\n data.append(StackAPIQuestion(response))\n\n day_search_number += 1\n minute_search_number += 1\n request.session['day_searches'] = day_search_number\n request.session['minute_searches'] = minute_search_number\n\n paginator = Paginator(data, 10)\n try:\n data = paginator.page(page)\n except PageNotAnInteger:\n data = paginator.page(1)\n except EmptyPage:\n data = paginator.page(paginator.num_pages)\n\n # if there is data to display else return form\n\n if data:\n args = {'response': data, 'url': url}\n return render(request, 'stackapp/test.html', args)\n args = {'form': form}\n return render(request, 'stackapp/test.html', args)\n" } ]
7
aqwmost121/Tugas-Besar-GUI
https://github.com/aqwmost121/Tugas-Besar-GUI
8b5f7befaa522eb9e67b6c6c69d49682095f0840
a5336d73972cbdd10ea2b32156df87e23822f58c
d5340fc1175349ea88751a9979803e9a7974b522
refs/heads/master
2020-06-20T17:52:34.278279
2019-07-16T13:26:02
2019-07-16T13:26:02
197,198,884
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49822765588760376, "alphanum_fraction": 0.542733371257782, "avg_line_length": 24.44791603088379, "blob_id": "7e4512efab0bef1ea4aa3d334b95852587e081a7", "content_id": "eac0255590de34a70d49f54df035e95fef468706", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2539, "license_type": "no_license", "max_line_length": 77, "num_lines": 96, "path": "/Suhu.py", "repo_name": "aqwmost121/Tugas-Besar-GUI", "src_encoding": "UTF-8", "text": "import sys\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5.QtCore import *\r\nfrom PyQt5.QtWidgets import *\r\n\r\n\r\nclass Konversi(QWidget):\r\n def __init__ (self):\r\n QWidget.__init__(self)\r\n self.setWindowTitle(\"Konversi Suhu\")\r\n self.resize(450, 300)\r\n self.posisi = self.frameGeometry()\r\n self.tengah = QDesktopWidget().availableGeometry().center()\r\n self.posisi.moveCenter(self.tengah)\r\n\r\n\r\n self.label1()\r\n self.label2()\r\n self.label3()\r\n self.label4()\r\n self.push1()\r\n self.push2()\r\n\r\n\r\n self.kolom1()\r\n self.kolom2()\r\n self.kolom3()\r\n self.kolom4()\r\n\r\n def label1(self):\r\n cf = QLabel(\"Celcius\",self)\r\n cf.move(90, 40)\r\n\r\n def label2(self):\r\n cf = QLabel(\"Celcius ke Fahrenheit\",self)\r\n cf.move(90, 90)\r\n\r\n def label3(self):\r\n cr = QLabel(\"Celcius ke Reamur\",self)\r\n cr.move(90, 140)\r\n def label4(self):\r\n cr = QLabel(\"Celcius ke Kelvin\",self)\r\n cr.move(90, 190)\r\n\r\n def push1(self):\r\n hapus = QPushButton('Hapus',self)\r\n hapus.clicked.connect(self.clear)\r\n hapus.move(260, 250)\r\n\r\n def push2(self):\r\n proses = QPushButton('Process',self)\r\n proses.clicked.connect(self.proses)\r\n proses.move(120, 250)\r\n\r\n def kolom1(self):\r\n self.line1 = QLineEdit(self)\r\n self.line1.move(240, 40)\r\n\r\n def kolom2(self):\r\n self.line2 = QLineEdit(self)\r\n self.line2.setReadOnly(True)\r\n self.line2.move(240, 90)\r\n\r\n def kolom3(self):\r\n self.line3 = QLineEdit(self)\r\n self.line3.setReadOnly(True)\r\n self.line3.move(240, 140)\r\n def kolom4(self):\r\n self.line4 = QLineEdit(self)\r\n self.line4.setReadOnly(True)\r\n self.line4.move(240, 190)\r\n\r\n def proses(self):\r\n if self.kolom1 == 2:\r\n QMessageBox.information(self,'Alert', 'Kolom Tidak Boleh Kosong')\r\n else:\r\n Fah = float(self.line1.text())*(9./5)+32\r\n Ream = float(self.line1.text())*(4./5)\r\n kel = float(self.line1.text())+273\r\n\r\n self.line2.setText(str(Fah))\r\n self.line3.setText(str(Ream))\r\n self.line4.setText(str(kel))\r\n\r\n def clear(self):\r\n self.line1.setText(\"\")\r\n self.line2.setText(\"\")\r\n self.line3.setText(\"\")\r\n self.line4.setText(\"\")\r\n\r\n\r\nif __name__ =='__main__':\r\n app = QApplication(sys.argv)\r\n ex = Konversi()\r\n ex.show()\r\n sys.exit(app.exec_())\r\n" }, { "alpha_fraction": 0.6478606462478638, "alphanum_fraction": 0.674365758895874, "avg_line_length": 24.676767349243164, "blob_id": "d42309b56515db3978509cae7f69ffcfa7d8a70a", "content_id": "b9e0cf153b4d71e80b4ac4b4f6bf80c566e7bdb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2641, "license_type": "no_license", "max_line_length": 66, "num_lines": 99, "path": "/KPanjang2.py", "repo_name": "aqwmost121/Tugas-Besar-GUI", "src_encoding": "UTF-8", "text": "import sys\r\n\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5.QtCore import *\r\nfrom PyQt5.QtWidgets import *\r\n\r\n\r\nclass KPanjang2(QWidget):\r\n\tdef __init__(self):\r\n\t\tsuper().__init__()\r\n\t\tself.setupUi()\r\n\r\n\tdef setupUi(self):\r\n\t\tself.resize(300,150)\r\n\t\tself.move(300,300)\r\n\t\tself.setWindowTitle('Konversi Panjang')\r\n\r\n\t\tself.label1=QLabel()\r\n\t\tself.label1.setText('Masukkan Meter')\r\n\t\tself.linepertama=QLineEdit()\r\n\t\thorizontalLine=QFrame();\r\n\t\thorizontalLine.setFrameShape(QFrame.HLine)\r\n\t\thorizontalLine.setFrameShadow(QFrame.Sunken)\r\n\r\n\r\n\t\tself.KM=QRadioButton()\r\n\t\tself.KM.setText('KM')\r\n\t\tself.HM=QRadioButton()\r\n\t\tself.HM.setText('HM')\r\n\t\tself.DAM=QRadioButton()\r\n\t\tself.DAM.setText('DAM')\r\n\t\tself.DM=QRadioButton()\r\n\t\tself.DM.setText('DM')\r\n\t\tself.M=QRadioButton()\r\n\t\tself.M.setText('M')\r\n\t\tself.CM=QRadioButton()\r\n\t\tself.CM.setText('CM')\r\n\t\tself.MM=QRadioButton()\r\n\t\tself.MM.setText('MM')\r\n\r\n\r\n\t\tself.myfont=QFont()\r\n\t\tself.myfont.setBold(True)\r\n\t\tself.hasil=QLabel()\r\n\t\tself.hasil.setFont(self.myfont)\r\n\t\tself.hasil.setText('Hasil')\r\n\t\tself.hitung=QPushButton()\r\n\t\tself.hitung.setText('Hitung')\r\n\r\n\t\tlayout = QGridLayout()\r\n\t\tlayout.addWidget(self.label1,0,0)\r\n\t\tlayout.addWidget(self.linepertama,0,1,1,7)\r\n\t\tlayout.addWidget(self.KM,2,0)\r\n\t\tlayout.addWidget(self.HM,2,1)\r\n\t\tlayout.addWidget(self.DAM,2,2)\r\n\t\tlayout.addWidget(self.DM,2,4)\r\n\t\tlayout.addWidget(self.CM,2,5)\r\n\t\tlayout.addWidget(self.MM,2,6)\r\n\t\tlayout.addWidget(self.M,2,3)\r\n\r\n\t\tlayout.addWidget(horizontalLine,4,0,1,7)\r\n\t\tlayout.addWidget(self.hasil,5,0,1,7)\r\n\t\tlayout.addWidget(self.hitung,6,0,1,7)\r\n\r\n\t\tself.hitung.clicked.connect(self.hitungan)\r\n\t\tself.setLayout(layout)\r\n\r\n\tdef hitungan(self):\r\n\t\ta = float(self.linepertama.text())\r\n\r\n\t\tif self.KM.isChecked():\r\n\t\t\thitt=a/1000\r\n\t\t\tself.hasil.setText('Hasil Konversi ke Kilometer : '+str(hitt))\r\n\t\telif self.HM.isChecked():\r\n\t\t\thitt=a/100\r\n\t\t\tself.hasil.setText('Hasil Konversi ke Hektometer : '+str(hitt))\r\n\t\telif self.DAM.isChecked():\r\n\t\t\thitt=a/10\r\n\t\t\tself.hasil.setText('Hasil Konversi ke Dekameter : '+str(hitt))\r\n\t\telif self.DM.isChecked():\r\n\t\t\thitt=a*10\r\n\t\t\tself.hasil.setText('Hasil Konversi ke Desimeter : '+str(hitt))\r\n\t\telif self.CM.isChecked():\r\n\t\t\thitt=a*100\r\n\t\t\tself.hasil.setText('Hasil Konversi ke Centimeter : '+str(hitt))\r\n\t\telif self.MM.isChecked():\r\n\t\t\thitt=a*1000\r\n\t\t\tself.hasil.setText('Hasil Konversi ke Milimeter : '+str(hitt))\r\n\t\telif self.M.isChecked():\r\n\t\t\thitt=a\r\n\t\t\tself.hasil.setText('Hasil Konversi ke Meter : '+str(hitt))\r\n\t\telse:\r\n\t\t\tself.hasil.setText('Belum memilih operasi Panjang')\r\n\r\nif __name__ == '__main__':\r\n\ta = QApplication(sys.argv)\r\n\tform = KPanjang2()\r\n\tform.show()\r\n\ta.exec_()\r\n" } ]
2
shrimpyt/First_Game
https://github.com/shrimpyt/First_Game
1ce7e1e1e58fd69a90e5ad7ebfc58fc9094221a0
ca8aefb84c1acff089de3aecd50f16041b604155
389d4151fe9a8b370d8ae297ed5a95d1fc425f08
refs/heads/main
2023-01-29T05:33:59.971370
2020-12-10T18:25:13
2020-12-10T18:25:13
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.639502763748169, "alphanum_fraction": 0.649631679058075, "avg_line_length": 43.32653045654297, "blob_id": "cf3210e9ba1baef309051fadd3afadb00e63d98b", "content_id": "55f099adb1bbfcbaf6aa4a198c2058bba65073d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2172, "license_type": "no_license", "max_line_length": 122, "num_lines": 49, "path": "/FirstGame.py", "repo_name": "shrimpyt/First_Game", "src_encoding": "UTF-8", "text": "print(\"Welcome to my first game!\")\nname = input(\"What is your name? \")\nhealth = 10\n\n\ndef health_check():\n print(\"Your health is\", health),\n if health == 0:\n print(\"the game is now over, you have died.\")\n quit()\n elif health == 15:\n print(\"You have won the game so far, come back later for a longer story.\")\n quit()\n\n\nprint(\"Hello\", name, \"lets begin.\")\nprint(\"You will begin with\", health, \"health.\")\nprint(\"You begin your adventure at an impass.\")\ndecision_1 = input(\"Would you like to go with Honey Biscuit, or with Zeus? (HB/Z) \")\nif decision_1 == \"HB\":\n print(\"Honey Biscuit takes you down the path of sunshine and rainbows.\")\n print(\"As you are walking, you suddenly see a bird, how do you react?\")\n decision_2HB = input(\"Do you attack the bird, or run away? (attack/run) \")\n if decision_2HB == \"attack\":\n print(\"Between you and Honey Biscuit you deal significant damage, and the bird dropped an item.\")\n print(\"You pick up the item and find it's a shield! This shield gives you an additional 5 health.\")\n health += 5\n health_check()\n else:\n print(\"As you run away from the bird, it outpaces you and manages to leave a package on your head.\")\n print(\"This package is a lovely one, as it deals 3 damage to you\")\n health -= 3\n health_check()\nelif decision_1 == \"Z\":\n print(\"Zeus takes you down a path into a cave.\")\n print(\"When you enter the cave, Zeus starts hopping about, until you realize there is a rabbit she is chasing.\")\n print(\"As you help her find this rabbit, you spot two pathways, one is to Litter Boxia, the other is to Laser Pointe\")\n decision_2Z = input(\"Do you go to Litter Boxia, or Laser Pointe (LB/LR)\")\n if decision_2Z == \"LB\":\n print(\"As you head to Litter Boxia the overwhelming stench of bad cat litter overwhelms you, you lose 10 health.\")\n health -= 10\n health_check()\n else:\n print(\"Laser Pointe turns out to be a town full of parties! You gain a helmet that gives you 5 health.\")\n health += 5\n health_check()\nelse:\n print(\"Didn't recognize input, goodbye.\")\n quit()\n" }, { "alpha_fraction": 0.7736842036247253, "alphanum_fraction": 0.7736842036247253, "avg_line_length": 93.5, "blob_id": "f3b94583ce502de82435e4115f44c03a39650a0a", "content_id": "aa054ffd1e820f4976acb62349c0c5ba7b56a107", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 190, "license_type": "no_license", "max_line_length": 175, "num_lines": 2, "path": "/README.md", "repo_name": "shrimpyt/First_Game", "src_encoding": "UTF-8", "text": "# First Game\nThis is my first game, it is a choose your own adventure with extremely limited options so far. I will be improving in the future, just wanting a place to upload it right now. \n" } ]
2
MarsX1e/random_word_Django
https://github.com/MarsX1e/random_word_Django
f53bb99075925f7c05201ff4ffdab5b5be2502ea
c667dd3a80b6b30e3c8bbf63a1dfb2619583329b
e1d1ffa49e6f47cb5d66816e7891187d620698a2
refs/heads/master
2021-06-29T17:31:06.888799
2017-09-15T23:05:38
2017-09-15T23:05:38
103,708,503
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6522811055183411, "alphanum_fraction": 0.6596794128417969, "avg_line_length": 26, "blob_id": "593e475324782a34e76c47dde06b91372834af9c", "content_id": "7082355a745298f3151e9670f581387752d24fdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 811, "license_type": "no_license", "max_line_length": 121, "num_lines": 30, "path": "/apps/random_word_app/views.py", "repo_name": "MarsX1e/random_word_Django", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.utils.crypto import get_random_string\nfrom django.shortcuts import render,redirect\n\ndef index(request):\n if 'number' in request.session:\n print '...'\n else:\n request.session[\"number\"]=1\n randomstr=get_random_string(length=32)\n context={\n \"number\":request.session['number'],\n \"str\":randomstr\n }\n return render(request, 'random_word_app/index.html',context)\n \ndef show(request):\n\n \n request.session[\"number\"]+=1\n \n return redirect('/')\ndef reset(request):\n request.session['number']=1\n return redirect('/')\n\n# Create your views here.\n# we use form action to redirect to another route(page) to run the function and redirectback so we don't run everythin at\n# index. \n" } ]
1
plasx/sanicgql
https://github.com/plasx/sanicgql
48a77bc3ca117be994c7cba413759a35e5967945
8025bbcda658ec2e400f663031d1a1db0920e931
c4470f5567aa8df1c2a9bc8727c543cd2de44ef1
refs/heads/master
2022-08-30T21:34:31.512015
2019-06-28T23:42:53
2019-06-28T23:42:53
181,251,427
0
0
null
2019-04-14T02:35:28
2019-06-28T23:43:03
2022-08-06T05:23:02
Python
[ { "alpha_fraction": 0.7933579087257385, "alphanum_fraction": 0.7952029705047607, "avg_line_length": 35.13333511352539, "blob_id": "800b58430ff5323a73487bffcc653660e009e2a8", "content_id": "8ffeafa50bd92f62bee12c143828b173e70059cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 542, "license_type": "no_license", "max_line_length": 212, "num_lines": 15, "path": "/architecture/ADR/ADR_0002.md", "repo_name": "plasx/sanicgql", "src_encoding": "UTF-8", "text": "# Angular Frontend\n\n\n## Status\nin the current state there is no framework chosen for the project, which mean's i'll have to use either the graphql explorer to utilze it.\n\n## Context\nno frontend framework implemented\n## Decision\n\nutilze the latest version of angular with apollo to consume the graphql sanic api\n\n## Consequences\n\nUsing a framework on the frontend enables us to utlize 3rd party libraries that integrate with angular such as apollo. Learning Angular will give some insight on pro/con descisions when it comes to using React.js\n" }, { "alpha_fraction": 0.5180412530899048, "alphanum_fraction": 0.7061855792999268, "avg_line_length": 16.636363983154297, "blob_id": "eb7741da8820248ede448b00c951e25b8173ca7e", "content_id": "c4945014bf7b5455c2f0decda62196fab667d4a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 388, "license_type": "no_license", "max_line_length": 26, "num_lines": 22, "path": "/requirements.txt", "repo_name": "plasx/sanicgql", "src_encoding": "UTF-8", "text": "aiofiles==0.4.0\naniso8601==3.0.2\ngraphene==2.1.3\ngraphene-sqlalchemy==2.1.1\ngraphql-core==2.1\ngraphql-relay==0.4.5\ngraphql-server-core==1.1.1\nhttptools==0.0.13\nMarkupSafe==1.1.1\nmultidict==4.5.2\npromise==2.2.1\npytest-runner==4.4\nRx==1.6.1\nsanic==19.3.1\nSanic-GraphQL==1.1.0\nsingledispatch==3.4.0.3\nsix==1.12.0\nSQLAlchemy==1.3.2\nujson==1.35\nuvloop==0.12.2\nwebsockets==6.0\nWerkzeug==0.15.2\n" }, { "alpha_fraction": 0.7941176295280457, "alphanum_fraction": 0.7941176295280457, "avg_line_length": 43.5625, "blob_id": "8369f64144143fbfca4065ed627278969a8229fc", "content_id": "770a6b307f327b4cb057fbb922cf021e8353d2a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 714, "license_type": "no_license", "max_line_length": 335, "num_lines": 16, "path": "/architecture/ADR/ADR_0001.md", "repo_name": "plasx/sanicgql", "src_encoding": "UTF-8", "text": "# Simple Sanic, GraphQL, and SQLAlchemy Application \n\n\n## Status\n\nSanic superseds flask as awsgi compatible web framework. In the current state of flask, it currently does not support ASGI and is not asynchronous friendly. \n\n## Context\nMainstream web frameworks not supporting asyncio/asgi out the box \n## Decision\n\nUtilize Sanic as a replacement for flask\n\n## Consequences\n\nWhile sanic enables us to utilize asgi and async event loops natively within the framework. we lose the vast amount of support and maturity that's behind flask. This means we will have to wait for more support or possibly take the risk of the framework not taking off and having no longer maintained legacy web framework in the future. \n" }, { "alpha_fraction": 0.6701754331588745, "alphanum_fraction": 0.6982455849647522, "avg_line_length": 24.909090042114258, "blob_id": "24bf8712489542f2c97570c4ed9be24370c65ee3", "content_id": "6c10d2c4c8a41b587003b88e2d3fe64d7d4220e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 285, "license_type": "no_license", "max_line_length": 76, "num_lines": 11, "path": "/app.py", "repo_name": "plasx/sanicgql", "src_encoding": "UTF-8", "text": "from sanic_graphql import GraphQLView\nfrom sanic import Sanic\nfrom schema import schema\n\napp = Sanic(__name__)\napp.debug = True\n\napp.add_route(GraphQLView.as_view(schema=schema, graphiql=True), '/graphql')\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8080, debug=True)\n" }, { "alpha_fraction": 0.6930803656578064, "alphanum_fraction": 0.7020089030265808, "avg_line_length": 22.578947067260742, "blob_id": "a5537485e108a061f64959a6722f68daffe84fd6", "content_id": "c7310549acd9c728cca1a6314320187f2c9319a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 896, "license_type": "no_license", "max_line_length": 110, "num_lines": 38, "path": "/readme.md", "repo_name": "plasx/sanicgql", "src_encoding": "UTF-8", "text": "# GraphQL + Sanic + SQLAlchemy\n\nI wanted to create a simple minimal starter utilizing SQLAlchemy, Sanic, and GraphQL.\n\n### Running locally\n\nTo run install the requirements.txt \n \n pip install -r requirements.txt\n\n\nthen run the application by running app.py\n\n python app.py\n\n# Sanic\n\n### Running with Docker\nExecute the docker compose file by doing the following:\n\n docker-compose -f docker-compose.yml build sanicgql\n docker-compose -f docker-compose.yml run --service-ports sanicgql\nThen visit the URL below in your browser to access the graphql explorer\n \n http://localhost:8080/graphql\n### Usage\n\n Upon running the application you'll be able to access the URL of GRAPHIQL at http://localhost:8080/graphql\n### Mutations\n you'll need to add something or else you'll have empty query\n### Query\n \n query{\n user\n }\n### Unit Tests\n \n WIP\n" } ]
5
PZiobro/ThinkPython
https://github.com/PZiobro/ThinkPython
96449345a549cf31e4a39a04f66fa3269fdfb46f
617122739d874b48777513c306d9e9118c99e4e8
00ee4ed899b39aef1bd73696e647fccd204b266d
refs/heads/master
2020-04-01T07:49:14.190489
2019-01-24T20:15:32
2019-01-24T20:15:32
153,004,957
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5421348214149475, "alphanum_fraction": 0.5463483333587646, "avg_line_length": 17.736841201782227, "blob_id": "a280e4e47f2de7ed076eb95b2e532e5288c06397", "content_id": "4ba87779936b147750dc45112935b839256a7a2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 712, "license_type": "no_license", "max_line_length": 42, "num_lines": 38, "path": "/Chapter14/Exercise14.3.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import os\n\n\ndef walk(dirname):\n file_list = list()\n for name in os.listdir(dirname):\n path = os.path.join(dirname, name)\n if os.path.isfile(path):\n file_list.append(path)\n else:\n walk(path)\n return file_list\n\n\ndef filter_files(names, suffix):\n t = list()\n for name in names:\n if name.endswith(suffix):\n t.append(name)\n return t\n\n\ndef compute_checksum(file):\n cmd = 'md5sum ' + file\n fp = os.popen(cmd)\n res = fp.read()\n stat = fp.close()\n return res\n\n\ndef main():\n t = walk(os.getcwd())\n t2 = filter_files(t, 'py')\n for file in t2:\n print(compute_checksum(file))\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4955555498600006, "alphanum_fraction": 0.5422222018241882, "avg_line_length": 20.380952835083008, "blob_id": "65abd8cacdb78cf209a1fd6522af8589f2f1ec44", "content_id": "056a086b4e23042ccdf0131ab41a305b524a6b8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 450, "license_type": "no_license", "max_line_length": 49, "num_lines": 21, "path": "/Chapter9/Exercise9.8.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef is_palindrom(number):\n return number == number[::-1]\n\n\ndef validated(number):\n return is_palindrom(str(number)[-4:]) and \\\n is_palindrom(str(number+1)[-5:]) and \\\n is_palindrom(str(number+2)[1:5]) \\\n and is_palindrom(str(number+3))\n\n\ndef main():\n number = 100000\n while number < 999996:\n if validated(number):\n print(number)\n number += 1\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4822334945201874, "alphanum_fraction": 0.5055837631225586, "avg_line_length": 19.93617057800293, "blob_id": "bec4f81ef71b0e7a77b9321d44c9fd28c56528d8", "content_id": "5e1282ada3489700cd1020f243f24143986363c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 985, "license_type": "no_license", "max_line_length": 69, "num_lines": 47, "path": "/Chapter12/Exercise12.3.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef make_dict():\n fin = open('words.txt')\n d = dict()\n for line in fin:\n word = line.strip()\n key = tuple(sorted(word))\n if key in d:\n d[key].append(word)\n else:\n d[key] = [word]\n return d\n\n\ndef find_anagram():\n d = make_dict()\n d2 = dict()\n fin = open('words.txt')\n for line in fin:\n sorted_word = tuple(sorted(line.strip()))\n if len(d[sorted_word]) > 1:\n d2[sorted_word] = d[sorted_word]\n return d2\n\n\ndef words_metric(word1, word2):\n count = 0\n for c1, c2, in zip(word1, word2):\n if c1 != c2:\n count += 1\n return count\n\n\ndef metathesis_pair(d):\n for anagrams in d.values():\n for word1 in anagrams:\n for word2 in anagrams:\n if word1 < word2 and words_metric(word1, word2) == 2:\n print(word1, word2)\n\n\ndef main():\n d = find_anagram()\n metathesis_pair(d)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.43913042545318604, "alphanum_fraction": 0.47826087474823, "avg_line_length": 16.461538314819336, "blob_id": "867cfc1cf7de20b2e68b99c4f4edf5253e25d670", "content_id": "75fd0a417bb3548d9a271b3610d1a8906fd5856c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 230, "license_type": "no_license", "max_line_length": 32, "num_lines": 13, "path": "/Chapter10/Exercise10.5.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef is_sorted(t):\n return t == sorted(t)\n\n\ndef main():\n print(is_sorted([1, 2, 2]))\n print(is_sorted([1, 2, 3]))\n print(is_sorted([4, 2, 2]))\n print(is_sorted(['b', 'a']))\n\n\nif __name__ == '__main__':\n main()\n\n\n" }, { "alpha_fraction": 0.542116641998291, "alphanum_fraction": 0.5464363098144531, "avg_line_length": 18.29166603088379, "blob_id": "4f05612b1df2c2d1043375d1bdc0475bd93a2abd", "content_id": "ab0730728309c05f13c9e99ff4d2fbceee73e3e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 463, "license_type": "no_license", "max_line_length": 80, "num_lines": 24, "path": "/Chapter13/Exercise13.1.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import string\n\n\ndef clean(word):\n clean_word = ''\n for letter in word:\n if letter not in string.punctuation and letter not in string.whitespace:\n clean_word += letter\n return clean_word.lower()\n\n\ndef lower_case(file):\n fin = open(file)\n for line in fin:\n word = line.strip()\n print(clean(word))\n\n\ndef main():\n print(clean('!\"#$%&\\'()*+,-./:;<=>?@[\\\\]AAAA \\t\\n\\r\\x0b\\x0c'))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.729411780834198, "alphanum_fraction": 0.729411780834198, "avg_line_length": 41.5, "blob_id": "8e128e626fce1d28ed396b28cfb0f752f6f939c1", "content_id": "f18c7b56c905a76da4bfd9f124404fa96e797713", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 85, "license_type": "no_license", "max_line_length": 73, "num_lines": 2, "path": "/Chapter5/Chapter5.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\nspeed = input('What...is the airspeed velocity of an unladen swallow?\\n')\nint(speed)" }, { "alpha_fraction": 0.4124700129032135, "alphanum_fraction": 0.4316546618938446, "avg_line_length": 18.809524536132812, "blob_id": "052a7a5f3ccc57418ebbeaa0971290e1ace1a589", "content_id": "b0dd5d30b11bb57c83727f0d7b115be6e5b75be7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 417, "license_type": "no_license", "max_line_length": 62, "num_lines": 21, "path": "/Chapter9/Exercise9.7.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef puzzler(word):\n i = 0\n while i < len(word) - 6:\n j = i+2\n k = i+4\n if word[i] == word[i+1] and \\\n word[j] == word[j+1] and word[k] == word[k+1]:\n return True\n i += 1\n return False\n\n\ndef main():\n fin = open('words.txt')\n for line in fin:\n if puzzler(line.strip()):\n print(line.strip())\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5068492889404297, "alphanum_fraction": 0.5251141786575317, "avg_line_length": 17.16666603088379, "blob_id": "f96f57a9e2b2df757c5b5138a0abe725e6fa72ee", "content_id": "a6a112e6177ac63b69a38719da69350d41bd8bd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 219, "license_type": "no_license", "max_line_length": 35, "num_lines": 12, "path": "/Chapter10/Exercise10.6.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef is_anagram(s1, s2):\n return sorted(s1) == sorted(s2)\n\n\ndef main():\n print(is_anagram('aa', 'aa'))\n print(is_anagram('ab', 'aa'))\n print(is_anagram('abc', 'cba'))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4938524663448334, "alphanum_fraction": 0.501024603843689, "avg_line_length": 22.80487823486328, "blob_id": "6df35a8792d673588e19741851f4df1d085e41cb", "content_id": "e3c8dc8bf74cc10199714127105d94e3fe93dc5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 976, "license_type": "no_license", "max_line_length": 80, "num_lines": 41, "path": "/Chapter13/Exercise13.2.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import string\n\n\ndef clean(word):\n clean_word = ''\n for letter in word:\n if letter not in string.punctuation and letter not in string.whitespace:\n clean_word += letter\n return clean_word.lower()\n\n\ndef lower_case(file):\n fin = open(file, encoding=\"utf8\")\n skip = True\n word_number = 0\n word_dict = dict()\n for line in fin:\n words = line.strip().split()\n if len(words) > 0:\n if words[0] == '***':\n skip = not skip\n continue\n if not skip:\n for word in words:\n cle = clean(word)\n if cle in word_dict.keys():\n word_dict[cle] += 1\n else:\n word_dict[cle] = 1\n word_number += 1\n print(word_dict)\n print('different words:', len(word_dict.keys()))\n return word_number\n\n\ndef main():\n print(lower_case('grapesofwrath.txt'))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4773869216442108, "alphanum_fraction": 0.5050251483917236, "avg_line_length": 17.045454025268555, "blob_id": "2b71e9d8a97753137277a47eb9f41db53f82a290", "content_id": "c1a82c66154d951db6d5e135f285f07cf33b4276", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 398, "license_type": "no_license", "max_line_length": 65, "num_lines": 22, "path": "/Chapter11/Exercise11.3.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\nknown = {}\n\n\ndef ackermann_memo(m,n):\n if m == 0:\n return n+1\n if n == 0:\n return ackermann_memo(m-1, 1)\n if (m, n) in known:\n return known[m, n]\n else:\n known[m, n] = ackermann_memo(m-1, ackermann_memo(m, n-1))\n return known[m, n]\n\n\ndef main():\n print(ackermann_memo(3, 4))\n print(ackermann_memo(3, 6))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5358724594116211, "alphanum_fraction": 0.5465013384819031, "avg_line_length": 20.711538314819336, "blob_id": "0a14fed7562a82d22d8dac7a9237a3f10485e53d", "content_id": "30c7072198ab6c18c9f9fea28733b877c169b787", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1129, "license_type": "no_license", "max_line_length": 69, "num_lines": 52, "path": "/Chapter10/Exercise10.12.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "def make_word_list():\n word_list = []\n fin = open('words.txt')\n for line in fin:\n word_list.append(line.strip())\n return word_list\n\n\ndef in_bisect(t, element):\n middle_index = len(t) // 2\n if len(t) == 0:\n return False\n if element == t[middle_index]:\n return True\n\n if len(t) == 1:\n if element == t[0]:\n return True\n else:\n return False\n\n left_list = t[:middle_index]\n right_list = t[middle_index+1:]\n if element < t[middle_index]:\n return in_bisect(left_list, element)\n else:\n return in_bisect(right_list, element)\n\n\ndef interlock(word, word_list):\n evens = word[::2]\n odds = word[1::2]\n return in_bisect(word_list, evens) and in_bisect(word_list, odds)\n\n\ndef interlock_general(word_list, word, n=3):\n for i in range(n):\n inter = word[i::n]\n if not in_bisect(word_list, inter):\n return False\n return True\n\n\ndef main():\n t = make_word_list()\n for word in t:\n if interlock(word, t):\n print(word, word[::2], word[1::2])\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4099099040031433, "alphanum_fraction": 0.44144144654273987, "avg_line_length": 14.785714149475098, "blob_id": "c286f5d0e86ee6d3cc42b72b6b825d16a3edcd17", "content_id": "dcd9a753cbcd58da17282bcbe062c136454be72f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 222, "license_type": "no_license", "max_line_length": 32, "num_lines": 14, "path": "/Chapter10/Exercise10.1.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef nested_sum(t):\n total = 0\n for i in range(len(t)):\n total += sum(t[i])\n return total\n\n\ndef main():\n t = [[1, 2], [3], [4, 5, 6]]\n print(nested_sum(t))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.44285714626312256, "alphanum_fraction": 0.4714285731315613, "avg_line_length": 14.217391014099121, "blob_id": "f5c128ac80b697236e36145a34bc5f5faaa8f544", "content_id": "550de6e1d752c3cb9897d797d59565f9ff3988e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 350, "license_type": "no_license", "max_line_length": 70, "num_lines": 23, "path": "/Chapter7/Exercise7.1.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import math\n\n\ndef mysqrt(a):\n x = a\n while True:\n y = (x + a/x) / 2\n if abs(y - x) < 0.00001:\n return y\n x = y\n\n\ndef test_square_root():\n for a in range(1, 10):\n print(a, mysqrt(a), math.sqrt(a), abs(mysqrt(a)-math.sqrt(a)))\n\n\ndef main():\n test_square_root()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.509036123752594, "alphanum_fraction": 0.5150602459907532, "avg_line_length": 16.421052932739258, "blob_id": "00f35efd8f3bcbb8edd772002ba668c4a7c54874", "content_id": "c02209267ffd48383319bd8ccf76bf8aebe677f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 332, "license_type": "no_license", "max_line_length": 44, "num_lines": 19, "path": "/Chapter9/Exercise9.5.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef uses_all(word, letters):\n for letter in letters:\n if letter not in word:\n return False\n return True\n\n\ndef main():\n fin = open('words.txt')\n count = 0\n for line in fin:\n if uses_all(line.strip(), 'aeiouy'):\n count += 1\n\n print(count)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.495356023311615, "alphanum_fraction": 0.5077399611473083, "avg_line_length": 17.941177368164062, "blob_id": "9811ff5a330eda4209620f5312a11bc59dfe3856", "content_id": "3e8e00660ed3117d6916924aec34e87e291408d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 323, "license_type": "no_license", "max_line_length": 47, "num_lines": 17, "path": "/Chapter11/Exercise11.2.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef invert_dict(d):\n invert_d = dict()\n for k in d:\n invert_d.setdefault(d[k], []).append(k)\n return invert_d\n\n\ndef main():\n d = dict(a=1, b=2, c=3, z=1)\n invert_d = invert_dict(d)\n for val in invert_d:\n keys = invert_d[val]\n print(val, keys)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5377777814865112, "alphanum_fraction": 0.5422222018241882, "avg_line_length": 16.230770111083984, "blob_id": "95dba09fb57f22f4cacc8d5c6792ab755d91e400", "content_id": "d73dba3b0576c766ad74f07340465466ce693e83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 225, "license_type": "no_license", "max_line_length": 33, "num_lines": 13, "path": "/Chapter8/Exercise8.3.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef is_palindrom(s):\n return s == s[::-1]\n\n\ndef main():\n print(is_palindrom('cat'))\n print(is_palindrom('dad'))\n print(is_palindrom('d'))\n print(is_palindrom('sassas'))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5230923891067505, "alphanum_fraction": 0.5261043906211853, "avg_line_length": 20.191490173339844, "blob_id": "a7f920cd4ccb912a108007854b9d6c1b1c71873c", "content_id": "5d84d100573d3d79b3c7a7564c6fa6850db8c3d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 996, "license_type": "no_license", "max_line_length": 80, "num_lines": 47, "path": "/Chapter13/Exercise13.4.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import string\n\n\ndef make_set(file):\n t = set()\n fin = open(file)\n for line in fin:\n word = line.strip()\n t.add(word)\n return t\n\n\ndef clean(word):\n clean_word = ''\n for letter in word:\n if letter not in string.punctuation and letter not in string.whitespace:\n clean_word += letter\n return clean_word.lower()\n\n\ndef find_other_words(file):\n english_set = make_set('words.txt')\n t = set()\n fin = open(file, encoding=\"utf8\")\n skip = True\n for line in fin:\n words = line.strip().split()\n if len(words) > 0:\n if words[0] == '***':\n skip = not skip\n continue\n if not skip:\n for word in words:\n if clean(word) not in english_set:\n t.add(clean(word))\n for item in t:\n print(item)\n\n\ndef main():\n #print(lower_case('grapesofwrath.txt'))\n find_other_words('grapesofwrath.txt')\n\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4882032573223114, "alphanum_fraction": 0.5226860046386719, "avg_line_length": 15.696969985961914, "blob_id": "f12a09c84663b23a219ed6c9bfdc3653b87da60a", "content_id": "def6cc0843b78cec542ae1d1c5d7a36cab57fc99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 551, "license_type": "no_license", "max_line_length": 43, "num_lines": 33, "path": "/Chapter10/Exercise10.8.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import random\n\n\ndef has_duplicates(t):\n t1 = sorted(t)\n for i in range(len(t1)-1):\n if t1[i] == t1[i+1]:\n return True\n i += 1\n return False\n\n\ndef random_birthdays(n):\n t = []\n for i in range(n):\n t.append(random.randint(1, 365))\n return t\n\n\ndef main():\n students_numb = 23\n simulations = 1000\n count = 0\n for i in range(simulations):\n t = random_birthdays(students_numb)\n if has_duplicates(t):\n count += 1\n\n print(count)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5123574137687683, "alphanum_fraction": 0.5133079886436462, "avg_line_length": 18.127273559570312, "blob_id": "7a6996ee3c37d0344678ad6b378e94878c8e3e57", "content_id": "5adf71ec86563094f1cf753db64a9e587fe51910", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1052, "license_type": "no_license", "max_line_length": 47, "num_lines": 55, "path": "/Chapter14/Exercise14.2.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import shelve\n\n\ndef make_dict(file):\n fin = open(file)\n d = dict()\n for line in fin:\n word = line.strip()\n t = list(word)\n t.sort()\n key = ''.join(t)\n if key in d:\n d[key].append(word)\n else:\n d[key] = [word]\n return d\n\n\ndef store_anagram(filename, anagram_map):\n shelf = shelve.open(filename, 'c')\n for k, words in anagram_map.items():\n shelf[k] = words\n shelf.close()\n\n\ndef read_anagrams(file, word):\n shelf = shelve.open(file)\n key = tuple(sorted(word))\n try:\n return shelf[key]\n except KeyError:\n return []\n\n\ndef find_anagram(file):\n d = make_dict(file)\n fin = open(file)\n for line in fin:\n word = line.strip()\n t = list(word)\n t.sort()\n key = ''.join(t)\n if len(d[key]) <= 1:\n del d[key]\n return d\n\n\ndef main():\n d = find_anagram('words.txt')\n #store_anagram('anagrams.db', d)\n print(read_anagrams('anagrams.db', 'file'))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.40893471240997314, "alphanum_fraction": 0.42611682415008545, "avg_line_length": 13.449999809265137, "blob_id": "5e0bb5b998a5878df9fe69a402d5bc7e210da887", "content_id": "6f7646385e946c07866a7f27f8ee9b5fff61c206", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 291, "license_type": "no_license", "max_line_length": 27, "num_lines": 20, "path": "/Chapter10/Exercise10.2.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef cumsum(t):\n if len(t) == 0:\n return []\n sub_total = 0\n for i in range(len(t)):\n sub_total += t[i]\n t[i] = sub_total\n\n return t\n\n\ndef main():\n t = []\n print(cumsum(t))\n t = [1, 2, 3]\n print(cumsum(t))\n\n\nif __name__ == '__main__':\n main()\n\n" }, { "alpha_fraction": 0.570652186870575, "alphanum_fraction": 0.570652186870575, "avg_line_length": 20.58823585510254, "blob_id": "c155b467f1b18db63ed5ddee70bcf8bc7caeaf73", "content_id": "fc2b5bea545bb61983cfe4a1e5aa37df39def7e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 368, "license_type": "no_license", "max_line_length": 61, "num_lines": 17, "path": "/Chapter9/Exercise9.3.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef avoids(word, forbidden):\n for letter in forbidden:\n if letter in word:\n return False\n return True\n\n\ndef main():\n forbidden = input('Give a string with forbidden letters')\n fin = open('words.txt')\n for line in fin:\n if avoids(line.strip(), forbidden):\n print(line.strip())\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.38955822587013245, "alphanum_fraction": 0.4457831382751465, "avg_line_length": 13.588234901428223, "blob_id": "aa2d94ea9a8edf964325425dc0211c78e3b2437d", "content_id": "bf8e00f2b5e5c9fa3eb116dda10e1387c54891cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 249, "license_type": "no_license", "max_line_length": 28, "num_lines": 17, "path": "/Chapter6/Exercise6.5.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef gcd(a, b):\n if b == 0:\n return a\n else:\n return gcd(b, a % b)\n\n\ndef main():\n print(gcd(81, 27))\n print(gcd(41, 7))\n print(gcd(82, 41))\n print(gcd(3, 7))\n print('lalla')\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5148248076438904, "alphanum_fraction": 0.5309972763061523, "avg_line_length": 18.473684310913086, "blob_id": "91a40aa7eaf21cf45ba4691e5b3a33e0ee9405c6", "content_id": "4f5879059166aa2f01aeaddaabc31f331260d7a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 371, "license_type": "no_license", "max_line_length": 37, "num_lines": 19, "path": "/Chapter6/Exercise6.3.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef is_palindrome(s):\n if len(s) in (0, 1):\n return True\n if s[0] == s[-1]:\n return is_palindrome(s[1:-1])\n else:\n return False\n\n\ndef main():\n print(is_palindrome('mom'))\n print(is_palindrome('a'))\n print(is_palindrome('mo'))\n print(is_palindrome('mm'))\n print(is_palindrome('rower'))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4680851101875305, "alphanum_fraction": 0.47340425848960876, "avg_line_length": 17.75, "blob_id": "6d9e71102289497ba3f54834d18648fdabc0c521", "content_id": "f483bcd89fd44a5a7e03a1ba302a1276aebd6765", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 376, "license_type": "no_license", "max_line_length": 40, "num_lines": 20, "path": "/Chapter12/Exercise12.1.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef most_frequent(word):\n d = dict()\n t = []\n for letter in word:\n if letter in d:\n d[letter] += 1\n else:\n d[letter] = 1\n for key, value in d.items():\n t.append((value, key))\n for k, v in sorted(t, reverse=True):\n print(v, k)\n\n\ndef main():\n most_frequent('abbcccdd')\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4833333194255829, "alphanum_fraction": 0.4833333194255829, "avg_line_length": 14.125, "blob_id": "8f54dcf058221fc55a5934bf0dc9ebdb537ac37f", "content_id": "d8dd36833a97a41d3b3549cb6360e819eef06690", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 120, "license_type": "no_license", "max_line_length": 29, "num_lines": 8, "path": "/Chapter8/Exercise8.2.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "def main():\n text = 'banana'\n a_count = text.count('a')\n print(a_count)\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.4736842215061188, "alphanum_fraction": 0.495356023311615, "avg_line_length": 16.83333396911621, "blob_id": "f0fd0a8230b605056873beedd7131362de4c673b", "content_id": "106fabbd25baad206de196b6bd04421ce8718d97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 323, "license_type": "no_license", "max_line_length": 36, "num_lines": 18, "path": "/Chapter11/Exercise11.4.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef has_duplicates(t):\n d = dict()\n for c in t:\n if c in d:\n return True\n d[c] = 1\n return False\n\n\ndef main():\n print(has_duplicates('aa'))\n print(has_duplicates([1, 2, 3]))\n print(has_duplicates([]))\n print(has_duplicates([1, 1, 1]))\n\n\nif __name__ == '__main__':\n main()\n\n" }, { "alpha_fraction": 0.6077210307121277, "alphanum_fraction": 0.6359485387802124, "avg_line_length": 22.617647171020508, "blob_id": "8ed13eb4d4dd4a4bc0d3b3e0e9dd699d12052cd7", "content_id": "e313bf7d43770f2b9a007207f257c1c2be77a977", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2409, "license_type": "no_license", "max_line_length": 70, "num_lines": 102, "path": "/Chapter15/Exercise15.1.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import math\n\n\nclass Point:\n x = None\n y = None\n\n\nclass Circle:\n center = Point()\n radius = None\n\n\nclass Rectangle:\n \"\"\"Represents a rectangle.\n attributes: width, height, corner.\n \"\"\"\n corner = Point()\n\n\ndef point_in_circle(circle, point):\n center_x = circle.center.x\n center_y = circle.center.y\n\n return math.pow(center_x-point.x, 2)+ \\\n math.pow(center_y-point.y, 2) <= math.pow(circle.radius, 2)\n\n\ndef rect_in_circle(circle, rectangle):\n # calculate all points and check whether are in circle\n point1 = point_in_circle(circle, rectangle.corner)\n\n point_2 = Point()\n point_2.x = rectangle.corner.x + rectangle.width\n point_2.y = rectangle.corner.y\n point2 = point_in_circle(circle, point_2)\n\n point_3 = Point()\n point_3.x = rectangle.corner.x + rectangle.width\n point_3.y = rectangle.corner.y + rectangle.height\n point3 = point_in_circle(circle, point_3)\n\n point_4 = Point()\n point_4.x = rectangle.corner.x\n point_4.y = rectangle.corner.y + rectangle.height\n point4 = point_in_circle(circle, point_4)\n\n return point1 and point2 and point3 and point4\n\n\ndef rect_circle_overlap(circle, rectangle):\n point1 = point_in_circle(circle, rectangle.corner)\n if point1:\n return True\n\n point_2 = Point()\n point_2.x = rectangle.corner.x + rectangle.width\n point_2.y = rectangle.corner.y\n point2 = point_in_circle(circle, point_2)\n if point2:\n return True\n\n point_3 = Point()\n point_3.x = rectangle.corner.x + rectangle.width\n point_3.y = rectangle.corner.y + rectangle.height\n point3 = point_in_circle(circle, point_3)\n if point3:\n return True\n\n point_4 = Point()\n point_4.x = rectangle.corner.x\n point_4.y = rectangle.corner.y + rectangle.height\n point4 = point_in_circle(circle, point_4)\n if point4:\n return True\n\n\ndef main():\n box = Rectangle()\n box.width = 100.0\n box.height = 200.0\n box.corner = Point()\n box.corner.x = 50.0\n box.corner.y = 50.0\n\n circle = Circle()\n circle.center = Point()\n circle.center.x = 150.0\n circle.center.y = 100.0\n circle.radius = 75.0\n\n print(circle.center.x)\n print(circle.center.y)\n print(circle.radius)\n\n print(point_in_circle(circle, box.corner))\n print(rect_in_circle(circle, box))\n print(rect_circle_overlap(circle, box))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5277777910232544, "alphanum_fraction": 0.5347222089767456, "avg_line_length": 19.571428298950195, "blob_id": "6b51c202f09c5ed1917edb285c8d49f62a4f26c3", "content_id": "f6b3c709ac9f65009e318ce2196bcdcc8fa538e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 720, "license_type": "no_license", "max_line_length": 60, "num_lines": 35, "path": "/Chapter11/Exercise11.5.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "def rotate_word(s, n):\n cypher = ''\n for c in s:\n start = ord('A') if c.isupper() else ord('a')\n cypher = cypher + chr(((ord(c)-start+n) % 26)+start)\n return cypher\n\n\ndef make_word_dict():\n d = dict()\n fin = open('words.txt')\n for line in fin:\n word = line.strip().lower()\n d[word] = None\n\n return d\n\n\ndef make_all_rotated_words(word):\n d = make_word_dict()\n # its enough to check only half of alphabet\n for i in range(1, 14):\n rotated = rotate_word(word, i)\n if rotated in d:\n print(word, i, rotated)\n\n\ndef main():\n d = make_word_dict()\n for word in d:\n make_all_rotated_words(word)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5287356376647949, "alphanum_fraction": 0.5517241358757019, "avg_line_length": 19.153846740722656, "blob_id": "2b3e23a0c7ea04c03242bfd30df099adf9985fef", "content_id": "8ee8d3ac88f43f8efd52e37cc6def24a76aab424", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "no_license", "max_line_length": 92, "num_lines": 13, "path": "/Chapter5/Exercise5.1.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import time\n\ndef main():\n seconds = time.time()\n minutes = seconds // 60\n hours = minutes // 60\n days = hours // 24\n print('days:{}, hours: {}, minutes:{}, seconds:{}'.format(days, hours,minutes, seconds))\n\n\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.4928571283817291, "alphanum_fraction": 0.5071428418159485, "avg_line_length": 18.928571701049805, "blob_id": "f9b2f48742d32755f55df9870a9d3951ca1a545a", "content_id": "c75b5ba1b17ddea1e011df95b95fbbb463494834", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 280, "license_type": "no_license", "max_line_length": 60, "num_lines": 14, "path": "/Chapter8/Exercise8.5.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef rotate_word(s, n):\n cypher = ''\n for c in s:\n start = ord('A') if c.isupper() else ord('a')\n cypher = cypher + chr(((ord(c)-start+n) % 26)+start)\n return cypher\n\n\ndef main():\n print(rotate_word('melon', -10))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4034653604030609, "alphanum_fraction": 0.448019802570343, "avg_line_length": 14.538461685180664, "blob_id": "5ad1ab87582a2449c155fab2453d16648e5e3dd5", "content_id": "53ba80fcfeef44078654aa7d9136396cfebe7d9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 808, "license_type": "no_license", "max_line_length": 27, "num_lines": 52, "path": "/Chapter5/Exercise5.6.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import turtle\nimport math\n\n\ndef main():\n bob = turtle.Turtle()\n #koch(bob, 3000)\n minkowski(bob, 1)\n turtle.mainloop()\n\n\ndef koch(t, x, angle):\n if x < 3:\n t.fd(x)\n else:\n koch(t, x/3, angle)\n t.lt(angle)\n koch(t, x/3, angle)\n t.rt(180-angle)\n koch(t, x/3, angle)\n t.lt(angle)\n koch(t, x/3, angle)\n\n\ndef snowflake(t, n):\n for i in range(3):\n koch(t, n, 60)\n t.rt(120)\n\n\ndef minkowski(t, n):\n for i in range(4):\n minko(t, n, 10)\n t.lt(90)\n\n\ndef minko(t, n, size):\n if n == 0:\n t.fd(size)\n else:\n t.rt(30)\n minko(t, n-1, size)\n t.lt(90)\n minko(t, n-1, size)\n t.rt(90)\n minko(t, n-1, size)\n t.lt(30)\n\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5068492889404297, "alphanum_fraction": 0.5068492889404297, "avg_line_length": 19.785715103149414, "blob_id": "4ba88519d77cf2cc67c46e0188a8b6735671b144", "content_id": "a6ecc2da66e9c08b9d909f59d418420e9fe8acb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 292, "license_type": "no_license", "max_line_length": 79, "num_lines": 14, "path": "/Chapter5/Exercise5.3.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef is_triangle(a, b, c):\n if a+b > c and a+c > b and b+c > a:\n print('Yes')\n else:\n print('No')\n\n\ndef main():\n a, b, c = input('Give three legths to check triangle condition \\n').split()\n is_triangle(int(a), int(b), int(c))\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5423855781555176, "alphanum_fraction": 0.5506376624107361, "avg_line_length": 22.803571701049805, "blob_id": "ef07dc97f31adc2b75e0b206fcb4be465efc1498", "content_id": "a10fd00a1c15697546288a434e1e496f2f9de007", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1333, "license_type": "no_license", "max_line_length": 80, "num_lines": 56, "path": "/Chapter13/Exercise13.8.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import string\nimport random\n\n\ndef clean(word):\n clean_word = ''\n for letter in word:\n if letter not in string.punctuation and letter not in string.whitespace:\n clean_word += letter\n return clean_word.lower()\n\n\ndef make_words_list(file):\n t = list()\n fin = open(file, encoding=\"utf8\")\n for line in fin:\n words = line.strip().split(sep=' ')\n for word in words:\n clean_word = clean(word)\n if clean_word != '':\n t.append(clean_word)\n return t\n\n\ndef markov_analysis(file, prefix_len=2):\n t = make_words_list(file)\n d = dict()\n for i in range(len(t)-prefix_len-1):\n pre = t[i] + ' ' + t[i+prefix_len-1]\n suf = t[i+prefix_len]\n if pre in d.keys():\n d[pre].append(suf)\n else:\n d[pre] = [suf]\n\n return d\n\n\ndef generate_text(markov_dict, prefix_len=2, text_len=10):\n pre = random.choice(list(markov_dict.keys()))\n sentence = pre\n for i in range(text_len):\n suf = random.choice(markov_dict[pre])\n sentence += ' ' + suf\n pre = pre.split(sep=' ')[prefix_len-1:] + ' ' + suf\n i += 1\n return sentence\n\n\ndef main():\n d = markov_analysis('grapesofwrath.txt', prefix_len=2)\n print(generate_text(d, prefix_len=2))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.34328359365463257, "alphanum_fraction": 0.38805970549583435, "avg_line_length": 10.083333015441895, "blob_id": "745082cc1ed84afdc875e42630e451ef5fe1a50a", "content_id": "0198e8e5bb744be60d30061c4844e3f0ef86e6a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 134, "license_type": "no_license", "max_line_length": 26, "num_lines": 12, "path": "/Chapter10/Exercise10.4.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef chop(t):\n del t[0], t[-1]\n\n\ndef main():\n t = [1, 2, 3, 4]\n chop(t)\n print(t)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4382716119289398, "alphanum_fraction": 0.4753086566925049, "avg_line_length": 15.947368621826172, "blob_id": "0f886a65af8d15a2af4d3e20268ff9dfa7758128", "content_id": "c6c5623739fac0877a2377fde14decb6ff77934e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 324, "license_type": "no_license", "max_line_length": 31, "num_lines": 19, "path": "/Chapter6/Exercise6.4.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef is_power(a, b):\n if a == b:\n return True\n if a % b != 0:\n return False\n else:\n return is_power(a/b, b)\n\n\ndef main():\n print(is_power(27, 3))\n print(is_power(3, 3))\n print(is_power(9, 3))\n print(is_power(7, 3))\n print(is_power(6, 2))\n\n\nif __name__ == '__main__':\n main()\n\n" }, { "alpha_fraction": 0.5872576236724854, "alphanum_fraction": 0.5872576236724854, "avg_line_length": 19.05555534362793, "blob_id": "6bedadd42fba3135cf9745ac6661dcb648dc4b7f", "content_id": "59b564e2b4c8e5a11c8732d726d071c8c69a6da4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 361, "license_type": "no_license", "max_line_length": 53, "num_lines": 18, "path": "/Chapter14/Exercise14.1.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef sed(pattern, replacement, read_file, write_file):\n\n fin = open(read_file, 'r')\n fout = open(write_file, 'w')\n for line in fin:\n line = line.replace(pattern, replacement)\n fout.write(line)\n fin.close()\n fout.close()\n\n\ndef main():\n pass\n #put your pattern, replacement and files here\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.5390625, "alphanum_fraction": 0.5390625, "avg_line_length": 17.14285659790039, "blob_id": "dc57ec893af685ea8fe5a8bb735f63c9f9d3f5a1", "content_id": "b9f205510d98c8b630190925d7d601d162185496", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "no_license", "max_line_length": 35, "num_lines": 14, "path": "/Chapter9/Exercise9.4.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef uses_only(word, letters):\n for letter in word:\n if letter not in letters:\n return False\n return True\n\n\ndef main():\n print(uses_only('mama', 'ma'))\n print(uses_only('dads', 'dan'))\n\n\nif __name__ == '__main__':\n main()\n\n" }, { "alpha_fraction": 0.49694502353668213, "alphanum_fraction": 0.505091667175293, "avg_line_length": 13.878787994384766, "blob_id": "5c4705ba7d9f48304d74c5aadefc75ee27729389", "content_id": "3cc12df5c3b5958ad360540c639db6fbd671d71b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 491, "license_type": "no_license", "max_line_length": 30, "num_lines": 33, "path": "/Chapter10/Exercise10.9.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import time\n\n\ndef build_list1():\n t = []\n fin = open('words.txt')\n for line in fin:\n t.append(line.strip())\n return t\n\n\ndef build_list2():\n t = []\n fin = open('words.txt')\n for line in fin:\n t = t + [line.strip()]\n return t\n\n\ndef main():\n start = time.time()\n build_list1()\n end = time.time()\n print(end - start)\n\n start = time.time()\n build_list2()\n end = time.time()\n print(end - start)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4657142758369446, "alphanum_fraction": 0.5028571486473083, "avg_line_length": 18.33333396911621, "blob_id": "b2d0d573592caa460a1a5c900a3b1cf6c04e0682", "content_id": "244ad4d7c8dfd02787b2d59fcbdc3c103aa5c651", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 350, "license_type": "no_license", "max_line_length": 36, "num_lines": 18, "path": "/Chapter10/Exercise10.7.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef has_duplicates(t):\n t1 = sorted(t)\n for i in range(len(t1)-1):\n if t1[i] == t1[i+1]:\n return True\n i += 1\n return False\n\n\ndef main():\n print(has_duplicates('aa'))\n print(has_duplicates([1, 2, 3]))\n print(has_duplicates([]))\n print(has_duplicates([1, 1, 1]))\n\n\nif __name__ == '__main__':\n main()\n\n" }, { "alpha_fraction": 0.4653846025466919, "alphanum_fraction": 0.4653846025466919, "avg_line_length": 15.1875, "blob_id": "b156552c6cd2697ddddb807d50dc568c59bf735d", "content_id": "7cc755688a4f82285d6690e04125e127b21624fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 260, "license_type": "no_license", "max_line_length": 30, "num_lines": 16, "path": "/Chapter7/Exercise7.2.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef eval_loop():\n result = None\n while True:\n text_in = input('>')\n if text_in == 'done':\n return result\n result = eval(text_in)\n print(result)\n\n\ndef main():\n eval_loop()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.542438268661499, "alphanum_fraction": 0.5856481194496155, "avg_line_length": 26.5744686126709, "blob_id": "cd7861627c84f7f557078c87635f5489480bfb9f", "content_id": "5773b292091ec4e1dfbbdb05c784d12986ffce7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1296, "license_type": "no_license", "max_line_length": 75, "num_lines": 47, "path": "/Chapter16/Exercise16.2.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import datetime\n\n\ndef calculate_n_day(date1, date2, n):\n d1 = min(date1, date2)\n d2 = max(date1, date2)\n\n return d2 + (d2-d1)/(n-1)\n\n\ndef main():\n # print day of week\n date = '2010-01-23'\n print(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%A'))\n # birthday = input('Give me date of your birthday! \\n')\n # birthday = datetime.datetime.strptime(birthday, '%Y-%m-%d')\n # today = datetime.datetime.now()\n # age = today.year - birthday.year\n # if today.month < birthday.month:\n # age -= 1\n # print('Your age is', age)\n # # next birthday\n # if birthday.month < today.month:\n # year = today.year+1\n # else:\n # year = today.year\n # next_birthday = datetime.datetime(year, birthday.month, birthday.day)\n #\n # duration_days = (next_birthday-today).days\n # print('To your next birthday left',\n # duration_days, 'days',\n # duration_days*24, 'hours',\n # duration_days*24*60, 'minutes')\n\n bday1 = datetime.datetime(day=11, month=5, year=1967)\n bday2 = datetime.datetime(day=11, month=10, year=2003)\n print(bday1)\n print(bday2)\n\n print(\"N Day is\")\n d1 = min(bday1, bday2)\n d2 = max(bday1, bday2)\n print(calculate_n_day(d1, d2, 3))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5204795002937317, "alphanum_fraction": 0.5254745483398438, "avg_line_length": 20.7608699798584, "blob_id": "d2b57afd5d2795d0ac62c47f72e7fcc97f4efe4d", "content_id": "9e1328e8c23828011087a303a458044c16b9c910", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1001, "license_type": "no_license", "max_line_length": 58, "num_lines": 46, "path": "/Chapter13/Exercise13.9.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import math\nimport matplotlib.pyplot as plt\n\n\ndef calculate_frequency(file):\n d = dict()\n fin = open(file, encoding=\"utf8\")\n for line in fin:\n words = line.strip().split(sep=' ')\n for word in words:\n l_word = word.lower()\n if l_word in d.keys():\n d[l_word] += 1\n else:\n d[l_word] = 1\n return d\n\n\ndef process_dict(freq_dict):\n log_f = list()\n log_r = list()\n d = sorted(freq_dict, key=freq_dict.get, reverse=True)\n i = 1\n for k in d:\n print(k, 'freq =', freq_dict[k], 'rank =', i)\n log_f.append(math.log(freq_dict[k]))\n log_r.append(math.log(i))\n i += 1\n return log_f, log_r\n\n\ndef draw_plot(x_data, y_data):\n plt.plot(x_data, y_data, 'ro')\n plt.xlabel('log rank')\n plt.ylabel('log frequency')\n plt.show()\n\n\ndef main():\n d = calculate_frequency('grapesofwrath.txt')\n x, y = process_dict(d)\n draw_plot(x, y)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5132275223731995, "alphanum_fraction": 0.5202822089195251, "avg_line_length": 20.769229888916016, "blob_id": "c4c1ef169d1d86b0416033ee32cabe25d8fc16be", "content_id": "421bd67784afb981fd2a352941a8f13b369e6f53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1134, "license_type": "no_license", "max_line_length": 49, "num_lines": 52, "path": "/Chapter12/Exercise12.2.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef make_dict():\n fin = open('words.txt')\n d = dict()\n for line in fin:\n word = line.strip()\n key = tuple(sorted(word))\n if key in d:\n d[key].append(word)\n else:\n d[key] = [word]\n return d\n\n\ndef find_anagram():\n d = make_dict()\n fin = open('words.txt')\n for line in fin:\n sorted_word = tuple(sorted(line.strip()))\n if len(d[sorted_word]) > 1:\n print(d[sorted_word])\n\n\ndef find_anagram_largest_to_smallest():\n d = make_dict()\n d2 = dict()\n for k in d:\n d[k].insert(0, len(d[k]))\n fin = open('words.txt')\n for line in fin:\n sorted_word = tuple(sorted(line.strip()))\n if len(d[sorted_word]) > 2:\n d2[sorted_word] = d[sorted_word]\n for v in sorted(d2.values(), reverse=True):\n print(v)\n return d2\n\n\ndef bingo():\n d = find_anagram_largest_to_smallest()\n for word, anagrams in d.items():\n if len(word) == 8:\n print(anagrams)\n\n\ndef main():\n #find_anagram()\n #find_anagram_largest_to_smallest()\n print(bingo())\n\n\nif __name__ == '__main__':\n main()\n\n" }, { "alpha_fraction": 0.38118812441825867, "alphanum_fraction": 0.42574256658554077, "avg_line_length": 12.399999618530273, "blob_id": "f874f80d4113651c5880d3d2c90a01cec966b7b8", "content_id": "cbda8e0b9a9ae1ba154d1ff6604aa7dd96b2f9d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 202, "license_type": "no_license", "max_line_length": 26, "num_lines": 15, "path": "/Chapter10/Exercise10.3.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef middle(t):\n return t[1:-1]\n\n\ndef main():\n t = []\n print(middle(t))\n t = [1, 2]\n print(middle(t))\n t = [1, 2, 3, 4, 5]\n print(middle(t))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4211764633655548, "alphanum_fraction": 0.4847058951854706, "avg_line_length": 19.238094329833984, "blob_id": "f3e6195a00cb8525f712ba9117bb328307c86090", "content_id": "230a34b717097a5e240fe0b8e3d5d2bb9f3f3f00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 425, "license_type": "no_license", "max_line_length": 66, "num_lines": 21, "path": "/Chapter7/Exercise7.3.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import math\n\n\ndef estimate_pi():\n k = 0\n pi = 0\n while True:\n item = (math.factorial(4*k) * (1103 + 26390*k)) / \\\n (math.pow(math.factorial(k), 4)*math.pow(396, 4*k))\n if abs(item) < 1e-15:\n return 9801/(2*math.sqrt(2)*pi)\n pi = pi + item\n k += 1\n\n\ndef main():\n print(estimate_pi(), math.pi, abs(estimate_pi()-math.pi))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5272952914237976, "alphanum_fraction": 0.5334987640380859, "avg_line_length": 20.783782958984375, "blob_id": "ee2b6299db827bce59980ff15e4294403a1e12d5", "content_id": "9c9349791944f3b35a56cdcbdef47410987c66fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 806, "license_type": "no_license", "max_line_length": 52, "num_lines": 37, "path": "/Chapter10/Exercise10.10.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "def make_word_list():\n word_list = []\n fin = open('words.txt')\n for line in fin:\n word_list.append(line.strip())\n return word_list\n\n\ndef in_bisect(t, element):\n middle_index = len(t) // 2\n if len(t) == 0:\n return False\n if element == t[middle_index]:\n return True\n\n if len(t) == 1:\n if element == t[0]:\n return True\n else:\n return False\n\n left_list = t[:middle_index]\n right_list = t[middle_index+1:]\n if element < t[middle_index]:\n return in_bisect(left_list, element)\n else:\n return in_bisect(right_list, element)\n\n\ndef main():\n t = make_word_list()\n for word in ['aa', 'alien', 'allen', 'zymurgy']:\n print(word, 'in list', in_bisect(t, word))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4571428596973419, "alphanum_fraction": 0.47428572177886963, "avg_line_length": 16.450000762939453, "blob_id": "53c8a996ae779da4546d8db611c727215e6c6728", "content_id": "99e097e5eadde4ae502bcf5a6a726c50ca50bf3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 350, "license_type": "no_license", "max_line_length": 40, "num_lines": 20, "path": "/Chapter9/Exercise9.6.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef is_abecedarian(word):\n i = 0\n while i < len(word)-1:\n if word[i+1] < word[i]:\n return False\n i += 1\n return True\n\n\ndef main():\n fin = open('words.txt')\n count = 0\n for line in fin:\n if is_abecedarian(line.strip()):\n count += 1\n print(count)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.8125, "alphanum_fraction": 0.8125, "avg_line_length": 39, "blob_id": "4493abe4384d3771818ec84c612cf0711a177a53", "content_id": "3b8be9b5e63496926c0896850a9f665627ecabd5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 80, "license_type": "no_license", "max_line_length": 65, "num_lines": 2, "path": "/README.md", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "# ThinkPython\nHere you can find my solution to exercises from book Think Python\n" }, { "alpha_fraction": 0.5692137479782104, "alphanum_fraction": 0.5747508406639099, "avg_line_length": 21.024391174316406, "blob_id": "0febde21700dcc2ecc3b854f3a928cf8427850ee", "content_id": "3364a867773007aa464985ff92ffe86357c84bd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 903, "license_type": "no_license", "max_line_length": 72, "num_lines": 41, "path": "/Chapter8/Exercise8.4.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "def any_lowercase1(s):\n \"\"\"This function works good.\n It checks whether string contains a lower char\"\"\"\n for c in s:\n if c.islower():\n return True\n else:\n return False\n\n\ndef any_lowercase2(s):\n \"\"\"This function always return True\n because 'c' is always lower char\"\"\"\n for c in s:\n if 'c'.islower():\n return 'True'\n else:\n return 'False'\n\n\ndef any_lowercase3(s):\n \"\"\"This function checks whether the last char in string is lower\"\"\"\n for c in s:\n flag = c.islower()\n return flag\n\n\ndef any_lowercase4(s):\n \"\"\"This function works fine!\"\"\"\n flag = False\n for c in s:\n flag = flag or c.islower()\n return flag\n\n\ndef any_lowercase5(s):\n \"\"\"This checks whether all letters are small. If not return False\"\"\"\n for c in s:\n if not c.islower():\n return False\n return True\n" }, { "alpha_fraction": 0.4972752034664154, "alphanum_fraction": 0.5081743597984314, "avg_line_length": 16.4761905670166, "blob_id": "d2346cfb0e67faf7fd3ee456f76b6d685b2e1efe", "content_id": "1e9ace534a4361b7e0e69a83acedcc0500d46296", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 734, "license_type": "no_license", "max_line_length": 47, "num_lines": 42, "path": "/Chapter13/Exercise13.5.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import random\n\n\ndef histogram(s):\n d = dict()\n for c in s:\n if c not in d:\n d[c] = 1\n else:\n d[c] += 1\n return d\n\n\ndef choose_from_hist(hist):\n #make a list with repetition from histogram\n t = list()\n for letter in hist:\n for i in range(hist[letter]):\n t.append(letter)\n return random.choice(t)\n\n\ndef test(hist):\n d = dict()\n for i in range(1000):\n letter = choose_from_hist(hist)\n if letter in d.keys():\n d[letter] += 1\n else:\n d[letter] = 1\n print(hist)\n print(d)\n\n\ndef main():\n hist = histogram('aaaaaabbbc')\n print(choose_from_hist(hist))\n test(hist)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5361595749855042, "alphanum_fraction": 0.5386533737182617, "avg_line_length": 21.33333396911621, "blob_id": "96036b50bc2985ff49984ece4edef8493dfb56b4", "content_id": "424eaec77d98331a2c558ef3f63a2361a7c5ef29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 401, "license_type": "no_license", "max_line_length": 77, "num_lines": 18, "path": "/Chapter5/Exercise5.2.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import math\n\n\ndef check_fermat(a, b, c, n):\n if n > 2 and math.pow(a,n)+math.pow(b,n)==math.pow(c,n):\n print('Holy smokes, Fermat was wrong!')\n else:\n print('No, that doesn`t work')\n\n\ndef main():\n a, b, c, n = \\\n input('Please give a, b, c and n to check Fermat theorem \\n').split()\n check_fermat(int(a), int(b), int(c), int(n))\n\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.4733542203903198, "alphanum_fraction": 0.4733542203903198, "avg_line_length": 17.705883026123047, "blob_id": "fa2247599c0307c2e1b06201e5f4b79a0e13d046", "content_id": "de246be73b1af71e400baea8ebbf892573a5e0d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 319, "license_type": "no_license", "max_line_length": 52, "num_lines": 17, "path": "/Chapter11/Exercise11.1.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef make_dic():\n d = dict()\n fin = open('words.txt')\n for line in fin:\n word = line.strip()\n d[word] = 'a'\n return d\n\n\ndef main():\n d = make_dic()\n for word in ['aa', 'alien', 'allen', 'zymurgy']:\n print(word, 'in list', word in d.keys())\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.3613445460796356, "alphanum_fraction": 0.4117647111415863, "avg_line_length": 14.800000190734863, "blob_id": "a5f8838b1e146049baf20be35bc996e0de8e625a", "content_id": "fa64d5d689df797385f49d8423097203c603184c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 238, "license_type": "no_license", "max_line_length": 36, "num_lines": 15, "path": "/Chapter6/Exercise6.2.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "\ndef ack(m, n):\n if m == 0:\n return n+1\n if m > 0 and n == 0:\n return ack(m-1, 1)\n if m > 0 and n > 0:\n return ack(m-1, ack(m, n-1))\n\n\ndef main():\n print(ack(4, 0))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5760936737060547, "alphanum_fraction": 0.6013554930686951, "avg_line_length": 17.03333282470703, "blob_id": "36e8c4d73fff032876706f24d66d963eeb475f08", "content_id": "ee7d9964835d5d7de8431c1d0ecf6d840f5d30ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1623, "license_type": "no_license", "max_line_length": 87, "num_lines": 90, "path": "/Chapter15/Exercise15.2.py", "repo_name": "PZiobro/ThinkPython", "src_encoding": "UTF-8", "text": "import turtle\nimport math\n\n\nclass Point:\n \"\"\"class represent point\"\"\"\n\n\nclass Rectangle:\n \"\"\"Represents a rectangle.\n attributes: width, height, corner.\n \"\"\"\n corner = Point()\n\n\nclass Circle:\n \"\"\"class represent circle\"\"\"\n center = Point()\n\n\ndef draw_circle(turtle, circle):\n turtle.pu()\n turtle.goto(circle.center.x, circle.center.y)\n turtle.fd(circle.radius)\n turtle.lt(90)\n turtle.pd()\n circ(turtle, circle.radius)\n\n\ndef draw_rect(turtle, rectangle):\n turtle.pu()\n turtle.goto(rectangle.corner.x, rectangle.corner.y)\n turtle.setheading(0)\n turtle.pd()\n for length in rectangle.width, rectangle.height, rectangle.width, rectangle.height:\n turtle.fd(length)\n turtle.rt(90)\n\n\ndef polygon(t, n, length):\n angle = 360 / n\n for i in range(n):\n t.fd(length)\n t.lt(angle)\n\n\ndef circ(t, r):\n circumference = 2 * math.pi * r\n n = 50\n length = circumference / n\n polygon(t, n, length)\n\n\n\ndef main():\n bob = turtle.Turtle()\n\n # draw the axes\n length = 400\n bob.fd(length)\n bob.bk(length)\n bob.lt(90)\n bob.fd(length)\n bob.bk(length)\n\n # draw a rectangle\n box = Rectangle()\n box.width = 100.0\n box.height = 200.0\n box.corner = Point()\n box.corner.x = 50.0\n box.corner.y = 50.0\n\n draw_rect(bob, box)\n\n # draw a circle\n circle = Circle\n circle.center = Point()\n circle.center.x = 150.0\n circle.center.y = 100.0\n circle.radius = 75.0\n\n draw_circle(bob, circle)\n\n # wait for the user to close the window\n turtle.mainloop()\n\n\nif __name__ == '__main__':\n main()\n" } ]
54
Microfish31/Car_Road_Detect
https://github.com/Microfish31/Car_Road_Detect
ad1dcb4487bc130c8418398b96c2082623cf1011
671eaaa010aa9bcb800c7bd19aca20ba38272703
a9faebc2fd460a6ac14896037de07173a35bee17
refs/heads/main
2023-07-04T23:46:58.347188
2021-09-02T06:05:42
2021-09-02T06:05:42
395,970,361
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5402272939682007, "alphanum_fraction": 0.5876978039741516, "avg_line_length": 29.15972137451172, "blob_id": "dfaf67198c12883980a411c83bef1bfe33b62063", "content_id": "7555bbecced182e8f3a5dfaea117276327fe66e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4623, "license_type": "no_license", "max_line_length": 118, "num_lines": 144, "path": "/0814_car_road_detect.py", "repo_name": "Microfish31/Car_Road_Detect", "src_encoding": "UTF-8", "text": "# instruction\r\nimport os\r\nimport cv2\r\nimport numpy as np \r\nfrom matplotlib import pyplot as plt\r\n\r\ndef getLineCoordinatesFromParameters(image, line_parameters):\r\n slope = line_parameters[0]\r\n intercept = line_parameters[1]\r\n y1 = image.shape[0] # since line will always start from bottom of image\r\n y2 = int(y1 * (3.4 / 5)) # some random point at 3/5\r\n x1 = int((y1 - intercept) / slope)\r\n x2 = int((y2 - intercept) / slope)\r\n if x1<0 :\r\n x1 = 0\r\n #print((x1,x2,y1,y2))\r\n return np.array([x1, y1, x2, y2])\r\n\r\ndef getSmoothLines(image, lines,threshold_slope):\r\n left_fit = [] # will hold m,c parameters for left side lines\r\n right_fit = [] # will hold m,c parameters for right side lines\r\n\r\n for line in lines:\r\n x1, y1, x2, y2 = line.reshape(4)\r\n parameters = np.polyfit((x1, x2), (y1, y2), 1)\r\n slope = parameters[0]\r\n intercept = parameters[1]\r\n #print(slope)\r\n if slope < -1*threshold_slope:\r\n left_fit.append((slope, intercept))\r\n elif slope > threshold_slope:\r\n right_fit.append((slope, intercept))\r\n \r\n if len(left_fit) == 0 or len(right_fit) == 0 :\r\n #print(\"in\")\r\n return \r\n\r\n # axis = 0?\r\n left_fit_average = np.average(left_fit, axis=0)\r\n right_fit_average = np.average(right_fit, axis=0)\r\n \r\n # now we have got m,c parameters for left and right line, we need to know x1,y1 x2,y2 parameters\r\n left_line = getLineCoordinatesFromParameters(image, left_fit_average)\r\n right_line = getLineCoordinatesFromParameters(image, right_fit_average)\r\n return np.array([left_line, right_line])\r\n\r\ndef canny_fun(image,sigma) :\r\n median = np.median(img_blur)\r\n lower = int(max(0, (1.0 - sigma) * median))\r\n upper = int(min(255, (1.0 + sigma) * median))\r\n\r\n return cv2.Canny(image, lower, upper)\r\n\r\ndef mask_fun(image) :\r\n # mask\r\n # create a zero array 假如有些情況下,我們已經有一個矩陣,我們想生成一個跟它具有相同尺寸的零矩陣,我們可以用傳統的方法來建立,\r\n stencil = np.copy(image)*0 #creating a blank to draw lines on\r\n\r\n # specify coordinates of the polygon\r\n polygon = np.array([[0,1080], [500,650], [1420,650], [1700,1080]])\r\n\r\n # fill polygon with ones 用来填充凸多边形\r\n cv2.fillConvexPoly(stencil, polygon, (255,255,255))\r\n\r\n return cv2.bitwise_and(image, image, mask=stencil)\r\n\r\n\r\ndef get_line(mask_image) :\r\n # HoughLinesP or not\r\n lines_canny_blur = cv2.HoughLinesP(mask_image, 0.3, np.pi/180, 60, np.array([]), minLineLength=50, maxLineGap=25) \r\n return getSmoothLines(mask_image,lines_canny_blur,0.25);\r\n\r\n\r\ndef display_line(image,lines) :\r\n for line in lines :\r\n x1,y1,x2,y2 = line\r\n cv2.line(image,(x1,y1),(x2,y2),(255,0,0),3);\r\n return image\r\n\r\n\r\npath = os.getcwd()\r\ninput_video_path = path + '\\\\影片偵測\\\\road_data_0709_Trim2.mp4'\r\ncap = cv2.VideoCapture(input_video_path)\r\nframe_list = []\r\n\r\nwhile cap.isOpened():\r\n ret, frame = cap.read()\r\n \r\n if ret == True :\r\n # read photo\r\n color_img = frame.copy()\r\n\r\n img = cv2.cvtColor(color_img, cv2.COLOR_BGR2GRAY)\r\n\r\n # blur\r\n img_blur = cv2.GaussianBlur(img,(5,5),0)\r\n\r\n # canny or not\r\n canny_blur = canny_fun(img_blur,0.95)\r\n\r\n # mask\r\n mask = mask_fun(canny_blur)\r\n\r\n mask_copy = mask.copy()\r\n\r\n lines = cv2.HoughLinesP(mask_copy, 0.3, np.pi/180, 60, np.array([]), minLineLength=50, maxLineGap=25) \r\n for line in lines :\r\n x1,y1,x2,y2 = line[0]\r\n cv2.line(mask_copy,(x1,y1),(x2,y2),(255,0,0),3);\r\n cv2.imwrite(path+'\\\\step_photo\\\\mask_copy.png',mask_copy)\r\n\r\n try :\r\n smooth_line = get_line(mask)\r\n final_img = display_line(color_img,smooth_line)\r\n \r\n # add green area\r\n x1,y1,x2,y2 = smooth_line[0]\r\n x3,y3,x4,y4 = smooth_line[1]\r\n\r\n polygon = np.array([[x1,y1], [x2,y2], [x4,y4],[x3,y3]])\r\n\r\n cv2.fillConvexPoly(final_img, polygon, (0,230,0))\r\n\r\n frame_list.append(final_img)\r\n except :\r\n final_img = color_img.copy()\r\n frame_list.append(final_img)\r\n else :\r\n break\r\n \r\ncap.release()\r\n\r\nfps = 15\r\nsize = (1920,1080)\r\n\r\n# write the video\r\nvideo_path = path + '\\\\影片偵測\\\\'\r\nout = cv2.VideoWriter(video_path + \"car_road_detect_0814.avi\",cv2.VideoWriter_fourcc(*'DIVX'), fps, size)\r\n\r\nfor i in range(len(frame_list)):\r\n # writing to a image array\r\n out.write(frame_list[i])\r\n\r\nout.release()\r\n" }, { "alpha_fraction": 0.7071428298950195, "alphanum_fraction": 0.7357142567634583, "avg_line_length": 27, "blob_id": "7bbaca06cdcd280af7c435d2cc9d33bd5f099fa8", "content_id": "cd2b53d5de217ca0e05e9da839393b759ff0de27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 280, "license_type": "no_license", "max_line_length": 80, "num_lines": 10, "path": "/README.md", "repo_name": "Microfish31/Car_Road_Detect", "src_encoding": "UTF-8", "text": "# Car_Road_Detect\n## Description \nTo find the lines on the road, so I wrote this program.\n\n## Tool\nOpencv\n\n## Result\n![image](https://github.com/Microfish31/Car_Road_Detect/blob/main/detect_01.png)\n![image](https://github.com/Microfish31/Car_Road_Detect/blob/main/detect_02.png)\n" } ]
2
JanSnobl/RockPaperScissors
https://github.com/JanSnobl/RockPaperScissors
2930a670e4044222a1a09ee8482eae9f80d93cb6
7399838c7c174f7b1059e88ebc3269a45810a1a0
06b07e820c21e41d0362f7fb338f6a6278c16ea2
refs/heads/master
2021-08-18T19:47:22.626636
2017-11-23T17:46:57
2017-11-23T17:46:57
111,836,916
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.652450680732727, "alphanum_fraction": 0.6632717847824097, "avg_line_length": 28.11111068725586, "blob_id": "bcb689590901dc6598d756bfdf15164fdd57e1ad", "content_id": "434b29bd1e016be60464a1b0136e838ce6d7c000", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1571, "license_type": "no_license", "max_line_length": 77, "num_lines": 54, "path": "/RockPaperScissors.py", "repo_name": "JanSnobl/RockPaperScissors", "src_encoding": "UTF-8", "text": "\"\"\"\nRock, Paper, Scissors\n1.Prompt the user to select either Rock, Paper, or Scissors\n2.Instruct the computer to randomly select either Rock, Paper, or Scissors\n3.Compare the user's choice and the computer's choice\n4.Determine a winner (the user or the computer)\n5.Inform the user who the winner is\nLet's begin!\n\"\"\"\n\nfrom random import randint\nfrom time import sleep\n\noptions = [\"R\", \"P\", \"S\"]\nLOS_MESSAGE = \"You lost!\"\nWIN_MESSAGE = \"You win!\"\n\n\ndef decide_winner(user_choice, computer_choice):\n print(\"You selected: %s\" % user_choice)\n print(\"Computer selecting...\")\n sleep(1)\n print(\"Computer selected: %s\" % computer_choice)\n user_choice_index = options.index(user_choice)\n computer_choice_index = options.index(computer_choice)\n if user_choice_index == computer_choice_index:\n print(\"It's a tie!\")\n\n elif user_choice_index == 0 and computer_choice_index == 2:\n print(\"You win!\")\n\n elif user_choice_index == 1 and computer_choice_index == 0:\n print(\"You win!\")\n\n elif user_choice_index == 2 and computer_choice_index == 1:\n print(\"You win!\")\n\n elif user_choice_index > 2:\n print(\"You chose wrong option. You must choose between 0 and two.\")\n return\n else:\n print(\"You lost!\")\n\n\ndef play_RPS():\n print(\"Rock, Paper or Scissors ?\")\n user_choice = input(\"Select R for Rock, P for Paper, or S for Scissors:\")\n user_choice = user_choice.upper()\n sleep(1)\n computer_choice = options[randint(0, len(options) - 1)]\n decide_winner(user_choice, computer_choice)\n\n\nplay_RPS()" } ]
1
PolyU-Mobility-AI/Adversarial-Diffusion-Attacks-on-Graph-based-Traffic-Prediction-Models
https://github.com/PolyU-Mobility-AI/Adversarial-Diffusion-Attacks-on-Graph-based-Traffic-Prediction-Models
86bc30f6416788b254409cd94a8c34e7fe6f79cb
dc29742b5173677663ddf81437eb454c7b2825e6
a2d375c7a2e4c79bec8cbb8fd3a675a3aa44e39a
refs/heads/main
2023-08-12T13:22:26.699050
2021-10-18T07:23:23
2021-10-18T07:23:23
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6006175875663757, "alphanum_fraction": 0.6176016330718994, "avg_line_length": 31.383333206176758, "blob_id": "d6468dfed74bf7b3a70a2817ca379d22c4619c6a", "content_id": "6fbbd9a179b7493ba95282f51bb2c20fc411e16e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2077, "license_type": "no_license", "max_line_length": 103, "num_lines": 60, "path": "/attack/model_attack/input_data.py", "repo_name": "PolyU-Mobility-AI/Adversarial-Diffusion-Attacks-on-Graph-based-Traffic-Prediction-Models", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\nimport numpy as np\nimport pandas as pd\n# import pickle as pkl\n\ndef load_sz_data(dataset):\n sz_adj = pd.read_csv(r'data/sz_adj.csv', header=None)\n adj = np.mat(sz_adj)\n sz_tf = pd.read_csv(r'data/sz_speed.csv')\n return sz_tf, adj\n\ndef load_los_data(dataset):\n los_adj = pd.read_csv(r'data/los_adj.csv', header=None)\n adj = np.mat(los_adj)\n los_tf = pd.read_csv(r'data/los_speed.csv')\n return los_tf, adj\n\ndef load_hk_data(dataset):\n hk_adj = pd.read_csv(r'data/hk_adj.csv', header=None)\n adj = np.mat(hk_adj)\n hk_tf = pd.read_csv(r'data/hk_speed.csv')\n return hk_tf, adj\n\ndef load_los_locations(dataset):\n los_locations = pd.read_csv(r'data/los_locations.csv', header=None)\n return np.array(los_locations)\n\ndef load_hk_locations(dataset):\n hk_locations = pd.read_csv(r'data/hk_locations.csv', header=None)\n return np.array(hk_locations)\n\n\ndef preprocess_data(data, time_len, rate, seq_len, pre_len):\n train_size = int(time_len * rate)\n train_data = data[0:train_size]\n test_data = data[train_size:time_len]\n\n trainX, trainY, testX, testY = [], [], [], []\n\n for i in range(len(train_data) - seq_len - pre_len):\n a = train_data[i: i + seq_len + pre_len]\n trainX.append(a[0: seq_len])\n trainY.append(a[seq_len: seq_len + pre_len]) # 切割a的后面部分,trainY增加一个元素(矩阵),代表预测的时间序列数据,长度pre_len\n for i in range(len(test_data) - seq_len - pre_len):\n b = test_data[i: i + seq_len + pre_len] # 同理构造训练集\n testX.append(b[0 : seq_len])\n testY.append(b[seq_len : seq_len + pre_len])\n\n # 三阶张量的训练数据trainX, trainY已经构造完毕\n # a=[], b[1,2,3], c[4,5,6], a.append(b) = [[1,2,3]], a.append(c) = [[1,2,3],[4,5,6]]\n # b.append(c) = [1,2,3,[4,5,6]]\n\n # 这里将矩阵转化为array数组?\n trainX1 = np.array(trainX)\n trainY1 = np.array(trainY)\n testX1 = np.array(testX)\n testY1 = np.array(testY)\n return trainX1, trainY1, testX1, testY1\n" }, { "alpha_fraction": 0.5208393335342407, "alphanum_fraction": 0.5328509211540222, "avg_line_length": 30.13953399658203, "blob_id": "2cfe8c69e525439fc9f455e299ebcb4790883171", "content_id": "ea25139e00312d3233894a7a236d7ca7126ffb06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6910, "license_type": "no_license", "max_line_length": 113, "num_lines": 215, "path": "/attack/model_attack/diffusion_attack_tool.py", "repo_name": "PolyU-Mobility-AI/Adversarial-Diffusion-Attacks-on-Graph-based-Traffic-Prediction-Models", "src_encoding": "UTF-8", "text": "import networkx as nx\r\nimport numpy as np\r\nfrom sklearn_extra.cluster import KMedoids\r\nimport copy\r\nimport math\r\n\r\n\r\ndef find_attack_set_by_degree(adj, b, B):\r\n G = nx.from_numpy_matrix(adj)\r\n D = G.degree()\r\n Degree = np.zeros(adj.shape[0])\r\n for i in range(adj.shape[0]):\r\n Degree[i] = D[i]\r\n # print(Degree)\r\n Dsort = Degree.argsort()[::-1]\r\n l = Dsort\r\n chosen_nodes = []\r\n i = 0\r\n k = 0\r\n while calculate_total_budget_of_attack_set(b, chosen_nodes) < B:\r\n while calculate_total_budget_of_attack_set(b, add_node([l[i]], chosen_nodes)) > B:\r\n i = i + 1\r\n if i == adj.shape[0]:\r\n k = 1\r\n break\r\n else:\r\n chosen_nodes.append(l[i])\r\n i = i + 1\r\n if i == adj.shape[0]:\r\n break\r\n if k == 1:\r\n break\r\n return np.array(chosen_nodes)\r\n\r\n\r\n\r\ndef add_node(set1, set2):\r\n intersection = list(set(set1).union(set(set2)))\r\n return np.array(intersection)\r\n\r\n\r\ndef find_neighbor(adj, attack_set, k):\r\n G = nx.from_numpy_matrix(adj)\r\n attack_num = attack_set.shape[0]\r\n target_set = []\r\n for i in range(attack_num):\r\n set1 = np.array([n for n in G.neighbors(attack_set[i])])\r\n target_set = add_node(target_set, set1)\r\n # print(set)\r\n\r\n return np.array(list(set(target_set).difference(set(attack_set))))\r\n\r\n\r\ndef calculate_goal(yp, pred):\r\n \"optimization goal: calculate the average difference between original prediction and prediction under attack\"\r\n difference = np.zeros(yp.shape[1])\r\n for i in range(yp.shape[1]):\r\n difference[i] = yp[0, i] - pred[0, i]\r\n return np.mean(difference)\r\n\r\n\r\ndef find_attack_set_by_kmedoids(locations, b, B):\r\n at_num = 1\r\n chosen_nodes = []\r\n temp = []\r\n while calculate_total_budget_of_attack_set(b, chosen_nodes) < B:\r\n chosen_nodes = []\r\n kmedoids = KMedoids(n_clusters=at_num, random_state=0).fit(locations)\r\n centers = kmedoids.cluster_centers_\r\n for i in range(at_num):\r\n for j in range(locations.shape[0]):\r\n if locations[j, 0] == centers[i, 0] and locations[j, 1] == centers[i, 1]:\r\n chosen_nodes.append(j)\r\n if calculate_total_budget_of_attack_set(b, chosen_nodes) < B:\r\n temp = copy.deepcopy(chosen_nodes) # record the chosen nodes in last iteration\r\n at_num = at_num + 1\r\n if at_num == b.shape[0]:\r\n break\r\n else:\r\n break\r\n return np.array(temp)\r\n\r\n\r\ndef find_attack_set_by_pagerank(adj, b, B):\r\n G = nx.from_numpy_matrix(adj)\r\n result = nx.pagerank(G)\r\n d_order = sorted(result.items(), key=lambda x: x[1], reverse=True)\r\n l = [x[0] for x in d_order] # The sequence produced by pagerank algorithm\r\n chosen_nodes = []\r\n i = 0\r\n k = 0\r\n while calculate_total_budget_of_attack_set(b, chosen_nodes) < B:\r\n while calculate_total_budget_of_attack_set(b, add_node([l[i]], chosen_nodes)) > B:\r\n i = i + 1\r\n if i == adj.shape[0]:\r\n k = 1\r\n break\r\n else:\r\n chosen_nodes.append(l[i])\r\n i = i + 1\r\n if i == adj.shape[0]:\r\n break\r\n if k == 1:\r\n break\r\n return np.array(chosen_nodes)\r\n\r\n\r\ndef find_attack_set_by_Kg_pagerank(adj, b, B):\r\n G = nx.from_numpy_matrix(adj)\r\n result = nx.pagerank(G)\r\n for i in range(adj.shape[0]):\r\n result[i] = result[i] / b[i]\r\n d_order = sorted(result.items(), key=lambda x: x[1], reverse=True)\r\n l = [x[0] for x in d_order] # The sequence produced by pagerank algorithm\r\n chosen_nodes = []\r\n i = 0\r\n k = 0\r\n while calculate_total_budget_of_attack_set(b, chosen_nodes) < B:\r\n while calculate_total_budget_of_attack_set(b, add_node([l[i]], chosen_nodes)) > B:\r\n i = i + 1\r\n if i == adj.shape[0]:\r\n k = 1\r\n break\r\n else:\r\n chosen_nodes.append(l[i])\r\n i = i + 1\r\n if i == adj.shape[0]:\r\n break\r\n if k == 1:\r\n break\r\n return np.array(chosen_nodes)\r\n\r\n\r\ndef find_attack_set_by_betweenness(adj, b, B):\r\n G = nx.from_numpy_matrix(adj)\r\n result = nx.betweenness_centrality(G)\r\n # print(result)\r\n d_order = sorted(result.items(), key=lambda x: x[1], reverse=True)\r\n l = [x[0] for x in d_order]\r\n chosen_nodes = []\r\n i = 0\r\n k = 0\r\n while calculate_total_budget_of_attack_set(b, chosen_nodes) < B:\r\n while calculate_total_budget_of_attack_set(b, add_node([l[i]], chosen_nodes)) > B:\r\n i = i + 1\r\n if i == adj.shape[0]:\r\n k = 1\r\n break\r\n else:\r\n chosen_nodes.append(l[i])\r\n i = i + 1\r\n if i == adj.shape[0]:\r\n break\r\n if k == 1:\r\n break\r\n return np.array(chosen_nodes)\r\n\r\n\r\ndef find_attack_set_by_Kg_betweenness(adj, b, B):\r\n G = nx.from_numpy_matrix(adj)\r\n result = nx.betweenness_centrality(G)\r\n # print(result)\r\n for i in range(adj.shape[0]):\r\n result[i] = result[i] / b[i]\r\n d_order = sorted(result.items(), key=lambda x: x[1], reverse=True)\r\n l = [x[0] for x in d_order]\r\n chosen_nodes = []\r\n i = 0\r\n k = 0\r\n while calculate_total_budget_of_attack_set(b, chosen_nodes) < B:\r\n while calculate_total_budget_of_attack_set(b, add_node([l[i]], chosen_nodes)) > B:\r\n i = i + 1\r\n if i == adj.shape[0]:\r\n k = 1\r\n break\r\n else:\r\n chosen_nodes.append(l[i])\r\n i = i + 1\r\n if i == adj.shape[0]:\r\n break\r\n if k == 1:\r\n break\r\n return np.array(chosen_nodes)\r\n\r\n\r\ndef find_k_hop_neighbor_of_single_node(adj, source, k):\r\n if k == 0:\r\n return k\r\n elif k > 0:\r\n G = nx.from_numpy_matrix(adj)\r\n k_hop_neighbor1 = nx.single_source_shortest_path_length(G, source, cutoff=k)\r\n k_hop_neighbor2 = nx.single_source_shortest_path_length(G, source, cutoff=k-1)\r\n k_hop_neighbor = k_hop_neighbor1.keys() - k_hop_neighbor2.keys()\r\n return np.array(list(k_hop_neighbor))\r\n\r\n\r\ndef calculate_degree_of_nodes_in_set(adj, nodes_set):\r\n nodes_set = np.array(nodes_set)\r\n corresponding_degree = np.zeros(nodes_set.shape)\r\n G = nx.from_numpy_matrix(adj)\r\n D = np.array(G.degree())\r\n # print(D)\r\n for i in range(len(nodes_set)):\r\n corresponding_degree[i] = D[nodes_set[i], 1]\r\n return corresponding_degree\r\n\r\n\r\ndef calculate_total_budget_of_attack_set(b, attack_set):\r\n budget = 0\r\n if attack_set is None: # empty list\r\n return 0\r\n else:\r\n for i in range(len(attack_set)):\r\n budget = budget + b[attack_set[i]]\r\n return budget\r\n" }, { "alpha_fraction": 0.49553877115249634, "alphanum_fraction": 0.503774881362915, "avg_line_length": 30.377777099609375, "blob_id": "fb0cec5bb3c169356e1d0b9eb4e48316bf8521d0", "content_id": "9d6091758ee10fdfc4aeb86c69e963d6dce58c08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2914, "license_type": "no_license", "max_line_length": 75, "num_lines": 90, "path": "/attack/model_train/sample.py", "repo_name": "PolyU-Mobility-AI/Adversarial-Diffusion-Attacks-on-Graph-based-Traffic-Prediction-Models", "src_encoding": "UTF-8", "text": "# coding=utf-8\r\nimport numpy as np\r\nimport scipy.sparse as sp\r\nfrom normalization import fetch_normalization\r\nfrom scipy.sparse import coo_matrix\r\n\r\ndef sparse_to_tuple(sparse_mx):\r\n \"\"\"Convert sparse matrix to tuple representation.\"\"\"\r\n def to_tuple(mx):\r\n if not sp.isspmatrix_coo(mx):\r\n mx = mx.tocoo()\r\n coords = np.vstack((mx.row, mx.col)).transpose()\r\n values = mx.data\r\n shape = mx.shape\r\n return coords, values, shape\r\n\r\n if isinstance(sparse_mx, list):\r\n for i in range(len(sparse_mx)):\r\n sparse_mx[i] = to_tuple(sparse_mx[i])\r\n else:\r\n sparse_mx = to_tuple(sparse_mx)\r\n\r\n return sparse_mx\r\n\r\n\r\nclass Sampler:\r\n \"\"\"Sampling the input graph data.\"\"\"\r\n def __init__(self, adj):\r\n adj = coo_matrix(adj)\r\n self.adj = adj\r\n self.train_adj = sparse_to_tuple(adj)\r\n\r\n def randomedge_sampler(self, percent):\r\n \"\"\"\r\n Randomly drop edge and preserve percent% edges.\r\n \"\"\"\r\n \"Opt here\"\r\n if percent >= 1.0:\r\n return self.adj\r\n\r\n nnz = len(self.train_adj[1])\r\n perm = np.random.permutation(nnz)\r\n preserve_nnz = int(nnz*percent)\r\n perm = perm[:preserve_nnz]\r\n test = self.train_adj[0][perm, 0]\r\n r_adj = sp.coo_matrix((self.train_adj[1][perm],\r\n (self.train_adj[0][perm, 0],\r\n self.train_adj[0][perm, 1])),\r\n shape=self.train_adj[2])\r\n\r\n return r_adj.todense()\r\n\r\n def randomvertex_sampler(self, percent):\r\n \"\"\"\r\n Randomly drop vertexes.\r\n \"\"\"\r\n if percent >= 1.0:\r\n return self.adj\r\n # print (\"start\")\r\n row = np.unique(self.train_adj[0][:, 0])\r\n data = self.train_adj[1]\r\n n_row = len(row)\r\n perm = np.random.permutation(n_row)\r\n preserve_row = int(n_row*percent)\r\n perm = perm[:preserve_row]\r\n preserve_row_set = set(row[perm])\r\n new_row = list()\r\n new_col = list()\r\n new_data = list()\r\n for i in range(len(self.train_adj[1])):\r\n # print (i)\r\n tmp_row = self.train_adj[0][i, 0]\r\n tmp_col = self.train_adj[0][i, 1]\r\n if tmp_row in preserve_row_set and tmp_col in preserve_row_set:\r\n new_row.append(tmp_row)\r\n new_col.append(tmp_col)\r\n new_data.append(self.train_adj[1][i])\r\n r_adj = sp.coo_matrix((new_data,\r\n (new_row,\r\n new_col)),\r\n shape=self.train_adj[2])\r\n return r_adj.todense()\r\n\r\n\r\n def degree_sampler(self, percent, normalization):\r\n \"\"\"\r\n Randomly drop edge wrt degree (high degree, low probility).\r\n \"\"\"\r\n print('not implemented yet')\r\n exit();\r\n" }, { "alpha_fraction": 0.5726179480552673, "alphanum_fraction": 0.6036077737808228, "avg_line_length": 31.727272033691406, "blob_id": "149159a38d86d362067ff28ddf293dc8debb5fad", "content_id": "7bb0eb3771376a7fbfcfbd4824c19b7d93de0d1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2162, "license_type": "no_license", "max_line_length": 71, "num_lines": 66, "path": "/attack/model_train/visualization.py", "repo_name": "PolyU-Mobility-AI/Adversarial-Diffusion-Attacks-on-Graph-based-Traffic-Prediction-Models", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\nimport matplotlib.pyplot as plt\n\ndef plot_result(test_result,test_label1,path):\n ##all test result visualization\n fig1 = plt.figure(figsize=(7, 1.5))\n# ax1 = fig1.add_subplot(1,1,1)\n a_pred = test_result[:, 0]\n a_true = test_label1[:, 0]\n plt.plot(a_pred, 'r-', label='prediction')\n plt.plot(a_true, 'b-', label='true')\n plt.legend(loc='best', fontsize=10)\n plt.savefig(path+'/test_all.png')\n plt.show()\n # oneday test result visualization\n fig1 = plt.figure(figsize=(7, 1.5))\n# ax1 = fig1.add_subplot(1,1,1)\n a_pred = test_result[0:96, 0]\n a_true = test_label1[0:96, 0]\n plt.plot(a_pred, 'r-', label=\"prediction\")\n plt.plot(a_true, 'b-', label=\"true\")\n plt.legend(loc='best', fontsize=10)\n plt.savefig(path+'/test_oneday.png')\n plt.show()\n \ndef plot_error(train_rmse,train_loss,test_rmse,test_acc,test_mae,path):\n # train_rmse & test_rmse\n fig1 = plt.figure(figsize=(5, 3))\n plt.plot(train_rmse, 'r-', label=\"train_rmse\")\n plt.plot(test_rmse, 'b-', label=\"test_rmse\")\n plt.legend(loc='best', fontsize=10)\n plt.savefig(path+'/rmse.png')\n plt.show()\n # train_loss & train_rmse\n fig1 = plt.figure(figsize=(5, 3))\n plt.plot(train_loss, 'b-', label='train_loss')\n plt.legend(loc='best', fontsize=10)\n plt.savefig(path+'/train_loss.png')\n plt.show()\n\n fig1 = plt.figure(figsize=(5, 3))\n plt.plot(train_rmse, 'b-', label='train_rmse')\n plt.legend(loc='best', fontsize=10)\n plt.savefig(path+'/train_rmse.png')\n plt.show()\n\n ### accuracy\n fig1 = plt.figure(figsize=(5, 3))\n plt.plot(test_acc, 'b-', label=\"test_acc\")\n plt.legend(loc='best', fontsize=10)\n plt.savefig(path+'/test_acc.png')\n plt.show()\n ### rmse\n fig1 = plt.figure(figsize=(5, 3))\n plt.plot(test_rmse, 'b-', label=\"test_rmse\")\n plt.legend(loc='best', fontsize=10)\n plt.savefig(path+'/test_rmse.png')\n plt.show()\n ### mae\n fig1 = plt.figure(figsize=(5, 3))\n plt.plot(test_mae, 'b-', label=\"test_mae\")\n plt.legend(loc='best', fontsize=10)\n plt.savefig(path+'/test_mae.png')\n plt.show()\n\n\n" }, { "alpha_fraction": 0.7482566237449646, "alphanum_fraction": 0.7656903862953186, "avg_line_length": 83.35294342041016, "blob_id": "bb9e46264b94bf2945a4d15b5fcc4f50eb3b9578", "content_id": "c1300c93553d0c52581237dc75ea67fa95463e4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1434, "license_type": "no_license", "max_line_length": 365, "num_lines": 17, "path": "/README.md", "repo_name": "PolyU-Mobility-AI/Adversarial-Diffusion-Attacks-on-Graph-based-Traffic-Prediction-Models", "src_encoding": "UTF-8", "text": "# Adversarial-Diffusion-Attacks-on-Graph-based-Traffic-Prediction-Models\nThe code includes two parts: model_train and model_attack.\n\nIn model_train, you could run the file \"main.py\" to train your model. Here we provide 3 types of models: st-gcn, t-gcn, a3t-gcn.\n(For t-gcn and a3t-gcn, the code is based on codes in https://github.com/lehaifeng/T-GCN.\n For st-gcn, the code is based on codes in https://github.com/VeritasYin/STGCN_IJCAI-18).\nYou can also train correspoding models with Dropout, Dropnode and Dropedge.\nThe model information is generated in folder \"model_train/out\".\n \nIn model_attack, you could run \"attack_algorithm_comparision.py\" to attack the models with different algorithms in our paper. Here we provide trained models in our Google drive https://drive.google.com/drive/folders/1sVoQxd7yH0PVR-g1Ni1HMM2vREjtp1l8?usp=sharing.\nIf you want to attack new models which are trained by yourself, you could train them in \"model_train/main.py\" file, then get results in \"model_train/out\" folder. You could copy this \"out\" folder from \"model_train/out\" to \"model_attack/out\", then run file \"attack_algorithm_comparision.py\". The file name should be the same if you want to restore models sucessfully.\n\nThe code of SPSA algorithm is based on https://github.com/TheBugger228/SPSA.\n \n \nOur paper is available at http://arxiv.org/abs/2104.09369.\nAuthor: Lyuyi Zhu ([email protected]), Kairui Feng ([email protected]), Ziyuan Pu ([email protected]), Wei Ma ([email protected]).\n" }, { "alpha_fraction": 0.5954875349998474, "alphanum_fraction": 0.6051571369171143, "avg_line_length": 27.86046600341797, "blob_id": "909a148677cfc64db1ae0143278c40ea9614dcb4", "content_id": "5354a6d6fabc5d2e2493b4d0208b60dd813e155e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1241, "license_type": "no_license", "max_line_length": 60, "num_lines": 43, "path": "/attack/model_train/input_data.py", "repo_name": "PolyU-Mobility-AI/Adversarial-Diffusion-Attacks-on-Graph-based-Traffic-Prediction-Models", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\nimport numpy as np\nimport pandas as pd\n# import pickle as pkl\n\n\ndef load_los_data(dataset):\n los_adj = pd.read_csv(r'data/los_adj.csv', header=None)\n adj = np.mat(los_adj)\n los_tf = pd.read_csv(r'data/los_speed.csv')\n return los_tf, adj\n\n\ndef load_hk_data(dataset):\n hk_adj = pd.read_csv(r'data/hk_adj.csv', header=None)\n adj = np.mat(hk_adj)\n hk_tf = pd.read_csv(r'data/hk_speed.csv')\n return hk_tf, adj\n\n\ndef preprocess_data(data, time_len, rate, seq_len, pre_len):\n train_size = int(time_len * rate)\n train_data = data[0:train_size]\n test_data = data[train_size:time_len]\n\n trainX, trainY, testX, testY = [], [], [], []\n\n for i in range(len(train_data) - seq_len - pre_len):\n a = train_data[i: i + seq_len + pre_len]\n trainX.append(a[0: seq_len])\n trainY.append(a[seq_len: seq_len + pre_len])\n for i in range(len(test_data) - seq_len - pre_len):\n b = test_data[i: i + seq_len + pre_len]\n testX.append(b[0 : seq_len])\n testY.append(b[seq_len : seq_len + pre_len])\n\n trainX1 = np.array(trainX)\n trainY1 = np.array(trainY)\n testX1 = np.array(testX)\n testY1 = np.array(testY)\n return trainX1, trainY1, testX1, testY1\n" }, { "alpha_fraction": 0.572862982749939, "alphanum_fraction": 0.5850746035575867, "avg_line_length": 38.92222213745117, "blob_id": "1fc28fd2571283822a36bc836ed10f746d3d84eb", "content_id": "48caadd9d88d880860766a16c2fc418618a29a07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3685, "license_type": "no_license", "max_line_length": 113, "num_lines": 90, "path": "/attack/model_train/gcn.py", "repo_name": "PolyU-Mobility-AI/Adversarial-Diffusion-Attacks-on-Graph-based-Traffic-Prediction-Models", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom tensorflow.python.platform import tf_logging as logging\r\nfrom utils import weight_variable_glorot, calculate_laplacian\r\n\r\nflags = tf.app.flags\r\nFLAGS = flags.FLAGS\r\n\r\n\r\nclass GCN(object):\r\n\r\n def __init__(self, num_units, tmp_adj, inputs, output_dim, out_keep_prob, activation=tf.nn.tanh,\r\n input_size=None, num_proj=None, reuse=None, **kwargs):\r\n super(GCN, self).__init__(**kwargs)\r\n if input_size is not None:\r\n logging.warn(\"%s: The input_size parameter is deprecated.\", self)\r\n self._num_units = num_units\r\n self._output_dim = output_dim\r\n self._inputs = inputs\r\n self._num_nodes = inputs.get_shape()[2].value\r\n self._input_dim = inputs.get_shape()[1].value\r\n self._batch_size = tf.shape(inputs)[0]\r\n self._tmp_adj = []\r\n self._tmp_adj.append(tmp_adj)\r\n self._activation = activation\r\n self._out_keep_prob = out_keep_prob\r\n self._gconv()\r\n\r\n\r\n @staticmethod\r\n def _build_sparse_matrix(L):\r\n L = L.tocoo()\r\n indices = np.column_stack((L.row, L.col))\r\n L = tf.SparseTensor(indices, L.data, L.shape)\r\n return tf.sparse_reorder(L)\r\n\r\n @property\r\n def output_size(self):\r\n output_size = self._num_units\r\n return output_size\r\n\r\n def init_state(self, batch_size):\r\n state = tf.zeros(shape=[batch_size, self._num_nodes * self._num_units], dtype=tf.float32)\r\n return state\r\n\r\n @staticmethod\r\n def _concat(x, x_):\r\n x_ = tf.expand_dims(x_, 0)\r\n return tf.concat([x, x_], axis=0)\r\n\r\n def _gconv(self, scope=None):\r\n ####[batch, num_nodes, seq]\r\n inputs = self._inputs\r\n inputs = tf.transpose(inputs, perm=[2, 0, 1])\r\n # print('0', inputs.get_shape())\r\n x0 = tf.reshape(inputs, shape=[self._num_nodes, self._batch_size * self._input_dim])\r\n\r\n scope = tf.get_variable_scope()\r\n with tf.variable_scope(scope):\r\n ####hidden1\r\n for adj in self._tmp_adj:\r\n x1 = tf.sparse_tensor_dense_matmul(adj, x0)\r\n x1 = tf.reshape(x1, shape=[self._num_nodes, self._batch_size, self._input_dim])\r\n x1 = tf.reshape(x1, shape=[self._num_nodes * self._batch_size, self._input_dim])\r\n weights1 = weight_variable_glorot(self._input_dim, self.output_size, name='weights1')\r\n self.hidden1 = self._activation(tf.matmul(x1, weights1))\r\n\r\n # dropout\r\n self.hidden1 = tf.nn.dropout(self. hidden1, self._out_keep_prob)\r\n\r\n ####hidden2\r\n self.hidden1 = tf.reshape(self.hidden1, shape=[self._num_nodes, self._batch_size * self.output_size])\r\n for adj in self._tmp_adj:\r\n x2 = tf.sparse_tensor_dense_matmul(adj, self.hidden1)\r\n x2 = tf.reshape(x2, shape=[self._num_nodes, self._batch_size, self.output_size])\r\n x2 = tf.reshape(x2, shape=[self._num_nodes * self._batch_size, self.output_size])\r\n\r\n weights2 = weight_variable_glorot(self.output_size, self._output_dim, name='weights2')\r\n self.hidden2 = self._activation(tf.matmul(x2, weights2))\r\n\r\n ####output\r\n self.output = self.hidden2\r\n self.output = tf.reshape(self.output, shape=[self._num_nodes, self._batch_size, self._output_dim])\r\n self.output = tf.transpose(self.output, perm=[1, 2, 0])\r\n self.output = tf.reshape(self.output, shape=[-1, self._num_nodes])\r\n return self.output\r\n\r\n" }, { "alpha_fraction": 0.5949301719665527, "alphanum_fraction": 0.6117560863494873, "avg_line_length": 38.969879150390625, "blob_id": "79413b4baa20b250b89bd1fa3adbfbc2baa8cd63", "content_id": "7626fa5113ca25de4e87eddd2e8909b51889b043", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13610, "license_type": "no_license", "max_line_length": 118, "num_lines": 332, "path": "/attack/model_train/main.py", "repo_name": "PolyU-Mobility-AI/Adversarial-Diffusion-Attacks-on-Graph-based-Traffic-Prediction-Models", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"The codes which contain 3 models: st-gcn, a3t-gcn, st-gcn,\r\nfor t-gcn and a3t-gcn, the codes are based on codes in https://github.com/lehaifeng/T-GCN.\r\nfor st-gcn, the codes are based on codes in https://github.com/VeritasYin/STGCN_IJCAI-18.\r\n\"\"\"\r\n# import pickle as pkl\r\nimport tensorflow as tf\r\nimport pandas as pd\r\nimport numpy as np\r\nimport math\r\nimport os\r\nimport numpy.linalg as la\r\nfrom input_data import preprocess_data, load_los_data, load_hk_data\r\nfrom tgcn import tgcnCell\r\nfrom sample import Sampler\r\nfrom utils import sparse_to_tuple\r\nfrom scipy import sparse\r\n#from gru import GRUCell\r\nfrom visualization import plot_result, plot_error\r\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\r\n#import matplotlib.pyplot as plt\r\nimport time\r\nfrom math_graph import scaled_laplacian, cheb_poly_approx\r\nfrom utils import calculate_laplacian\r\n\r\ntime_start = time.time()\r\n###### Settings ######\r\nflags = tf.app.flags\r\nFLAGS = flags.FLAGS\r\nflags.DEFINE_float('learning_rate', 0.001, 'Initial learning rate.')\r\nflags.DEFINE_integer('training_epoch', 1, 'Number of epochs to train.')\r\nflags.DEFINE_integer('gru_units', 100, 'hidden units of gru.')\r\nflags.DEFINE_integer('batch_size', 32, 'batch_size.')\r\nflags.DEFINE_integer('seq_len', 12, ' time length of inputs.')\r\nflags.DEFINE_float('train_rate', 0.8, 'rate of training set.')\r\nflags.DEFINE_string('dataset', 'hk', 'los or hk.')\r\nflags.DEFINE_string('model_name', 'stgcn', 'stgcn or tgcn or tgcn_att')\r\nflags.DEFINE_string('dropmode', 'out', 'node or edge or out')\r\nflags.DEFINE_float('out_keep_prob', 1.0, 'dropout keep rate') # if less than 1, ne_keep_prob should be 1\r\nflags.DEFINE_float('ne_keep_prob', 1.0, 'dropnode or dropedge keep rate') # if less than 1, out_keep_prob should be 1\r\nmodel_name = FLAGS.model_name\r\ndropmode = FLAGS.dropmode\r\ndata_name = FLAGS.dataset\r\ntrain_rate = FLAGS.train_rate\r\nseq_len = FLAGS.seq_len\r\nlr = FLAGS.learning_rate\r\ntraining_epoch = FLAGS.training_epoch\r\ngru_units = FLAGS.gru_units\r\nbatch_size = FLAGS.batch_size\r\nne_keep_prob = FLAGS.ne_keep_prob\r\nout_keep_prob = FLAGS.out_keep_prob\r\n\r\nif model_name == 'stgcn':\r\n pre_len = 1\r\nelif model_name == 'tgcn' or 'tgcn_att':\r\n pre_len = 3\r\n\r\noutput_dim = pre_len\r\n\r\nif dropmode == 'out':\r\n k = out_keep_prob # k is a marker of model file\r\nelif dropmode == 'node' or 'edge':\r\n k = ne_keep_prob\r\n\r\nblocks = [[1, 32, 64], [64, 32, 128]]\r\nKs = 3\r\nKt = 3\r\n\r\n###### load data ######\r\nif data_name == 'los':\r\n data, adj = load_los_data('los')\r\nif data_name == 'hk':\r\n data, adj = load_hk_data('hk')\r\n\r\nadj_sampler = Sampler(adj)\r\ntime_len = data.shape[0]\r\nnum_nodes = data.shape[1]\r\ndata1 = np.mat(data, dtype=np.float32)\r\n\r\n#### normalization\r\nmax_value = np.max(data1)\r\ndata1 = data1/max_value\r\ntrainX, trainY, testX, testY = preprocess_data(data1, time_len, train_rate, seq_len, pre_len)\r\ntotalbatch = int(trainX.shape[0]/batch_size)\r\ntraining_data_count = len(trainX)\r\n\r\ndef TGCN(_X, _weights, _biases, tmp_adj, keep_rate):\r\n ###\r\n tmp_adj = tf.sparse.from_dense(tmp_adj)\r\n cell_1 = tgcnCell(gru_units, tmp_adj, keep_rate, num_nodes=num_nodes)\r\n cell = tf.nn.rnn_cell.MultiRNNCell([cell_1], state_is_tuple=True)\r\n _X = tf.unstack(_X, axis=1)\r\n outputs, states = tf.nn.static_rnn(cell, _X, dtype=tf.float32)\r\n m = []\r\n for i in outputs:\r\n o = tf.reshape(i, shape=[-1, num_nodes, gru_units])\r\n o = tf.reshape(o, shape=[-1, gru_units])\r\n m.append(o)\r\n last_output = m[-1]\r\n output = tf.matmul(last_output, _weights['out']) + _biases['out']\r\n output = tf.reshape(output, shape=[-1, num_nodes, pre_len])\r\n output = tf.transpose(output, perm=[0, 2, 1])\r\n output = tf.reshape(output, shape=[-1, num_nodes])\r\n return output, m, states\r\n\r\ndef STGCN(_X, graph_kernel, keep_rate):\r\n # from math_graph import scaled_laplacian, cheb_poly_approx\r\n from base_model import build_model\r\n # W = np.array(tmp_adj).astype(np.float32)\r\n # print (tf.get_collection(\"tmp_adj\"))\r\n # W = np.array(tf.get_collection(\"tmp_adj\")[0]).astype(np.float32)\r\n # n = num_nodes\r\n n_his = seq_len\r\n # L = scaled_laplacian(W)\r\n # # Alternative approximation method: 1st approx - first_approx(W, n).\r\n # Lk = cheb_poly_approx(L, Ks, n)\r\n tf.add_to_collection(name='graph_kernel', value=tf.cast(graph_kernel, tf.float32))\r\n x = tf.expand_dims(_X, axis=3)\r\n train_loss, pred = build_model(x, n_his, Ks, Kt, blocks, keep_rate)\r\n pred = tf.transpose(pred, perm=[0, 2, 1])\r\n pred = tf.reshape(pred, shape=[-1, num_nodes])\r\n return train_loss, pred\r\n\r\ndef TGCN_att(_X, weights, biases, tmp_adj, keep_rate):\r\n ###\r\n tmp_adj = tf.sparse.from_dense(tmp_adj)\r\n cell_1 = tgcnCell(gru_units, tmp_adj, keep_rate, num_nodes=num_nodes)\r\n cell = tf.nn.rnn_cell.MultiRNNCell([cell_1], state_is_tuple=True)\r\n _X = tf.unstack(_X, axis=1)\r\n\r\n outputs, states = tf.nn.static_rnn(cell, _X, dtype=tf.float32)\r\n\r\n out = tf.concat(outputs, axis=0)\r\n out = tf.reshape(out, shape=[seq_len, -1, num_nodes, gru_units])\r\n out = tf.transpose(out, perm=[1, 0, 2, 3])\r\n\r\n last_output, alpha = self_attention1(out, weight_att, bias_att)\r\n\r\n output = tf.reshape(last_output, shape=[-1, seq_len])\r\n output = tf.matmul(output, weights['out']) + biases['out']\r\n output = tf.reshape(output, shape=[-1, num_nodes, pre_len])\r\n output = tf.transpose(output, perm=[0, 2, 1])\r\n output = tf.reshape(output, shape=[-1, num_nodes])\r\n\r\n return output, outputs, states\r\n\r\ndef self_attention1(x, weight_att, bias_att):\r\n x = tf.matmul(tf.reshape(x, [-1, gru_units]), weight_att['w1']) + bias_att['b1']\r\n f = tf.matmul(tf.reshape(x, [-1, num_nodes]), weight_att['w2']) + bias_att['b2']\r\n g = tf.matmul(tf.reshape(x, [-1, num_nodes]), weight_att['w2']) + bias_att['b2']\r\n h = tf.matmul(tf.reshape(x, [-1, num_nodes]), weight_att['w2']) + bias_att['b2']\r\n\r\n f1 = tf.reshape(f, [-1, seq_len])\r\n g1 = tf.reshape(g, [-1, seq_len])\r\n h1 = tf.reshape(h, [-1, seq_len])\r\n s = g1 * f1\r\n\r\n beta = tf.nn.softmax(s, dim=-1) # attention map\r\n\r\n context = tf.expand_dims(beta, 2) * tf.reshape(x, [-1, seq_len, num_nodes])\r\n\r\n context = tf.transpose(context, perm=[0, 2, 1])\r\n return context, beta\r\n\r\n###### placeholders ######\r\ninputs = tf.placeholder(tf.float32, shape=[None, seq_len, num_nodes], name='inputs')\r\nlabels = tf.placeholder(tf.float32, shape=[None, pre_len, num_nodes], name='labels')\r\ngraph_kernel = tf.placeholder(tf.float32, shape=[num_nodes, Ks * num_nodes], name='graph_kernel')\r\ntf_tmp_adj = tf.placeholder(tf.float32, shape=[num_nodes, num_nodes], name='tf_tmp_adj')\r\ntf_keep_prob = tf.placeholder(tf.float32, name='tf_keep_prob')\r\n\r\n\r\nif model_name == 'tgcn':\r\n # Graph weights\r\n weights = {\r\n 'out': tf.Variable(tf.random_normal([gru_units, pre_len], mean=1.0), name='weight_o')}\r\n biases = {\r\n 'out': tf.Variable(tf.random_normal([pre_len]), name='bias_o')}\r\n pred, ttts, ttto = TGCN(inputs, weights, biases, tf_tmp_adj, tf_keep_prob)\r\nelif model_name == 'stgcn':\r\n stgcn_loss, pred = STGCN(inputs, graph_kernel, tf_keep_prob)\r\nelif model_name == 'tgcn_att':\r\n # Graph weights\r\n weights = {\r\n 'out': tf.Variable(tf.random_normal([seq_len, pre_len], mean=1.0), name='weight_o')}\r\n bias = {\r\n 'out': tf.Variable(tf.random_normal([pre_len]), name='bias_o')}\r\n weight_att = {\r\n 'w1': tf.Variable(tf.random_normal([gru_units, 1], stddev=0.1), name='att_w1'),\r\n 'w2': tf.Variable(tf.random_normal([num_nodes, 1], stddev=0.1), name='att_w2')}\r\n bias_att = {\r\n 'b1': tf.Variable(tf.random_normal([1]), name='att_b1'),\r\n 'b2': tf.Variable(tf.random_normal([1]), name='att_b2')}\r\n pred, ttto, ttts = TGCN_att(inputs, weights, bias, tf_tmp_adj, tf_keep_prob)\r\n\r\n\r\ny_pred = pred\r\ntf.add_to_collection('y_pred', y_pred)\r\n\r\n\r\n###### optimizer ######\r\nlambda_loss = 0.0015\r\nLreg = lambda_loss * sum(tf.nn.l2_loss(tf_var) for tf_var in tf.trainable_variables())\r\nlabel = tf.reshape(labels, [-1, num_nodes])\r\n##loss\r\nloss = tf.reduce_mean(tf.nn.l2_loss(y_pred-label) + Lreg)\r\ntf.add_to_collection('loss', loss)\r\n##rmse\r\nerror = tf.sqrt(tf.reduce_mean(tf.square(y_pred-label)))\r\noptimizer = tf.train.AdamOptimizer(lr).minimize(loss)\r\n\r\n###### Initialize session ######\r\nvariables = tf.global_variables()\r\nsaver = tf.train.Saver(tf.global_variables())\r\n#sess = tf.Session()\r\ngpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)\r\nsess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\r\nsess.run(tf.global_variables_initializer())\r\n\r\nout = 'out/%s'%(model_name)\r\n#out = 'out/%s_%s'%(model_name,'perturbation')\r\npath1 = '%s_%s_pre%r_epoch%r_drop%s_%r' % (data_name, model_name, pre_len, training_epoch, dropmode, k)\r\npath = os.path.join(out, path1)\r\nif not os.path.exists(path):\r\n os.makedirs(path)\r\n\r\n###### evaluation ######\r\ndef evaluation(a,b):\r\n rmse = math.sqrt(mean_squared_error(a, b))\r\n mae = mean_absolute_error(a, b)\r\n F_norm = la.norm(a-b, 'fro')/la.norm(a, 'fro')\r\n r2 = 1-((a-b)**2).sum()/((a-a.mean())**2).sum()\r\n var = 1-(np.var(a-b))/np.var(a)\r\n return rmse, mae, 1-F_norm, r2, var\r\n\r\n\r\nx_axe, batch_loss, batch_rmse, batch_pred = [], [], [], []\r\ntest_loss, test_rmse, test_mae, test_acc, test_r2, test_var, test_pred = [], [], [], [], [], [], []\r\n\r\n# STGCN\r\nn = num_nodes\r\nn_his = seq_len\r\nkeep_rate = 1\r\ntotal_W = np.array(adj_sampler.adj.todense()).astype(np.float32)\r\nL = scaled_laplacian(total_W)\r\ntotal_LK = cheb_poly_approx(L, Ks, n)\r\n\r\n# TGCN or TGCN_att\r\nTGCN_total_adj = calculate_laplacian(adj_sampler.adj.todense()).toarray()\r\n\r\n\r\nfor epoch in range(training_epoch):\r\n if dropmode == 'node':\r\n tmp_adj = adj_sampler.randomedge_sampler(ne_keep_prob)\r\n elif dropmode == 'edge':\r\n tmp_adj = adj_sampler.randomvertex_sampler(ne_keep_prob)\r\n elif dropmode == 'out':\r\n tmp_adj = adj_sampler.adj.todense()\r\n\r\n W = np.array(tmp_adj).astype(np.float32)\r\n L = scaled_laplacian(W)\r\n # Alternative approximation method: 1st approx - first_approx(W, n).\r\n Lk = cheb_poly_approx(L, Ks, n)\r\n # tf.add_to_collection(name='graph_kernel', value=tf.cast(tf.constant(Lk), tf.float32))\r\n\r\n TGCN_tmp_adj = calculate_laplacian(tmp_adj).toarray()\r\n # print (type(TGCN_tmp_adj), TGCN_tmp_adj)\r\n # print (type(Lk))\r\n for m in range(totalbatch):\r\n mini_batch = trainX[m * batch_size: (m+1) * batch_size]\r\n mini_label = trainY[m * batch_size: (m+1) * batch_size]\r\n _, loss1, rmse1, train_output = sess.run([optimizer, loss, error, y_pred],\r\n feed_dict={inputs: mini_batch, labels: mini_label, graph_kernel: Lk,\r\n tf_tmp_adj: TGCN_tmp_adj, tf_keep_prob: out_keep_prob})\r\n batch_loss.append(loss1)\r\n batch_rmse.append(rmse1 * max_value)\r\n # Test completely at every epoch\r\n loss2, rmse2, test_output = sess.run([loss, error, y_pred],\r\n feed_dict={inputs: testX, labels: testY, graph_kernel: total_LK,\r\n tf_tmp_adj: TGCN_total_adj, tf_keep_prob: 1.0})\r\n # close drop when calculating test loss\r\n test_label = np.reshape(testY, [-1, num_nodes])\r\n rmse, mae, acc, r2_score, var_score = evaluation(test_label, test_output)\r\n test_label1 = test_label * max_value\r\n test_output1 = test_output * max_value\r\n test_loss.append(loss2)\r\n test_rmse.append(rmse * max_value)\r\n test_mae.append(mae * max_value)\r\n test_acc.append(acc)\r\n test_r2.append(r2_score)\r\n test_var.append(var_score)\r\n test_pred.append(test_output1)\r\n\r\n print('Iter:{}'.format(epoch),\r\n 'train_rmse:{:.4}'.format(batch_rmse[-1]),\r\n 'test_loss:{:.4}'.format(loss2),\r\n 'test_rmse:{:.4}'.format(rmse),\r\n 'test_acc:{:.4}'.format(acc))\r\n\r\n if (epoch % 300 == 0):\r\n saver.save(sess, path+'/model_100/%s_%s_pre_%r_epoch%r_drop%s_%r' % (data_name, model_name, pre_len,\r\n epoch, dropmode, k), global_step=epoch)\r\n mytxt = open('%s_%s_pre%r_epoch%r_drop%s_%r.txt' % (data_name, model_name, pre_len,\r\n training_epoch, dropmode, k), mode='a', encoding='utf-8')\r\n print('Iter:', epoch, 'train_rmse:', batch_rmse[-1], 'test_loss:', loss2,\r\n 'test_rmse:', rmse, 'test_acc:', acc, file=mytxt)\r\n mytxt.close()\r\n\r\n\r\ntime_end = time.time()\r\nprint(time_end-time_start, 's')\r\n\r\n############## visualization ###############\r\nb = int(len(batch_rmse)/totalbatch)\r\nbatch_rmse1 = [i for i in batch_rmse]\r\ntrain_rmse = [(sum(batch_rmse1[i*totalbatch:(i+1)*totalbatch])/totalbatch) for i in range(b)]\r\nbatch_loss1 = [i for i in batch_loss]\r\ntrain_loss = [(sum(batch_loss1[i*totalbatch:(i+1)*totalbatch])/totalbatch) for i in range(b)]\r\n\r\nindex = test_rmse.index(np.min(test_rmse))\r\ntest_result = test_pred[index]\r\nvar = pd.DataFrame(test_result)\r\nvar.to_csv(path+'/test_result.csv', index=False, header=False)\r\nplot_result(test_result, test_label1, path)\r\nplot_error(train_rmse, train_loss, test_rmse, test_acc, test_mae, path)\r\n\r\nprint('min_rmse:%r'%(np.min(test_rmse)),\r\n 'min_mae:%r'%(test_mae[index]),\r\n 'max_acc:%r'%(test_acc[index]),\r\n 'r2:%r'%(test_r2[index]),\r\n 'var:%r'%test_var[index])\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5061522126197815, "alphanum_fraction": 0.5213049054145813, "avg_line_length": 44.11909103393555, "blob_id": "822283399bf1d22ef96582c815819682c15e794b", "content_id": "8421c55d7871327a1e17d273b13fcdb250e219ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26436, "license_type": "no_license", "max_line_length": 162, "num_lines": 571, "path": "/attack/model_attack/attack_algorithm_comparision.py", "repo_name": "PolyU-Mobility-AI/Adversarial-Diffusion-Attacks-on-Graph-based-Traffic-Prediction-Models", "src_encoding": "UTF-8", "text": "\"\"\"\r\nThe codes are in https://github.com/LYZ98\r\n\"\"\"\r\n\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport copy\r\nfrom sample import Sampler\r\nfrom math_graph import scaled_laplacian, cheb_poly_approx\r\nfrom utils import calculate_laplacian\r\nfrom SPSA import SPSA\r\nimport random\r\nfrom SPSA import plot_progress\r\nfrom matplotlib import pyplot as plt\r\nimport seaborn as sns; sns.set()\r\nimport os\r\nfrom input_data import load_los_data, load_hk_data, load_hk_locations, load_los_locations\r\nfrom diffusion_attack_tool import calculate_goal, find_attack_set_by_degree, find_neighbor, \\\r\nfind_attack_set_by_kmedoids, find_attack_set_by_pagerank, \\\r\nfind_attack_set_by_betweenness, calculate_total_budget_of_attack_set, \\\r\ncalculate_degree_of_nodes_in_set, add_node, find_attack_set_by_Kg_pagerank, \\\r\nfind_attack_set_by_Kg_betweenness\r\n\r\n\r\n\r\n###### Settings ######\r\nflags = tf.app.flags\r\nFLAGS = flags.FLAGS\r\nflags.DEFINE_integer('training_epoch', 301, 'Number of epochs to train.')\r\nflags.DEFINE_integer('seq_len', 12, ' time length of inputs.')\r\n# flags.DEFINE_integer('pre_len', 3, 'time length of prediction.') # if choose 'stgcn' model, per_len have to be 1\r\nflags.DEFINE_string('dataset', 'los', 'los or hk.')\r\nflags.DEFINE_string('model_name', 'stgcn', 'stgcn or tgcn or tgcn_att')\r\nflags.DEFINE_string('dropmode', 'out', 'node or edge or out')\r\nflags.DEFINE_string('method', 'degree', 'spsa, Kg_spsa or degree or kmedoids or '\r\n 'pagerank or Kg_pagerank'\r\n 'or betweenness or Kg_betweenness or'\r\n 'or random')\r\nflags.DEFINE_float('out_keep_prob', 1.0, 'out keep') # if less than 1, ne_keep_prob should be 1. In our trained models, you could choose 0.9, 0.7, 0.5 or 1\r\nflags.DEFINE_float('ne_keep_prob', 1.0, 'node edge keep') # if less than 1, out_keep_prob should be 1. In our trained models, you could choose 0.9, 0.7, 0.5 or 1\r\nmodel_name = FLAGS.model_name\r\ndropmode = FLAGS.dropmode\r\ndata_name = FLAGS.dataset\r\nseq_len = FLAGS.seq_len\r\ntraining_epoch = FLAGS.training_epoch\r\nne_keep_prob = FLAGS.ne_keep_prob\r\nout_keep_prob = FLAGS.out_keep_prob\r\nmethod = FLAGS.method\r\n\r\nif model_name == 'stgcn':\r\n pre_len = 1\r\nelif model_name == 'tgcn' or 'tgcn_att':\r\n pre_len = 3\r\n\r\nif dropmode == 'out':\r\n k = out_keep_prob\r\nelif dropmode == 'node' or 'edge':\r\n k = ne_keep_prob\r\n\r\n# load model(here we have trained 3 models in file \"new_model\")\r\n# if load models, the file name should be the same as name in training\r\nout = 'out/%s'%(model_name)\r\npath1 = '%s_%s_pre%r_epoch%r_drop%s_%r' % (data_name, model_name, pre_len, training_epoch, dropmode, k)\r\npath = os.path.join(out, path1)\r\npath2 = '/model_100/%s_%s_pre_%r_epoch%r_drop%s_%r-%r.meta' % (data_name, model_name, pre_len, training_epoch -1, dropmode, k, training_epoch-1)\r\npath3 = '/model_100/%s_%s_pre_%r_epoch%r_drop%s_%r-%r' % (data_name, model_name, pre_len, training_epoch -1, dropmode, k, training_epoch -1)\r\nsess = tf.Session()\r\nnew_saver = tf.train.import_meta_graph(path + path2)\r\nnew_saver.restore(sess, path + path3)\r\ny_pred = tf.get_collection('y_pred')[0]\r\ngraph = tf.get_default_graph()\r\ninputs = graph.get_operation_by_name('inputs').outputs[0] # load placeholder\r\nlabels = graph.get_operation_by_name('labels').outputs[0]\r\ngraph_kernel = graph.get_operation_by_name('graph_kernel').outputs[0]\r\ntf_tmp_adj = graph.get_operation_by_name('tf_tmp_adj').outputs[0]\r\ntf_keep_prob = graph.get_operation_by_name('tf_keep_prob').outputs[0]\r\n\r\n# load data, include feature matrix, adjacency matrix,\r\n# and location matrix(include longitude and latitude of each node)\r\nif data_name == 'los':\r\n X2, A2 = load_los_data('los')\r\n locations = load_los_locations('los')\r\nelif data_name == 'hk':\r\n X2, A2 = load_hk_data('hk')\r\n locations = load_hk_locations('hk')\r\nelse:\r\n print('error!')\r\n\r\nblocks = [[1, 32, 64], [64, 32, 128]]\r\nKs = 3\r\nKt = 3\r\nadj_sampler = Sampler(A2)\r\nnode_num = A2.shape[0]\r\ntotal_W = np.array(adj_sampler.adj.todense()).astype(np.float32)\r\nL = scaled_laplacian(total_W)\r\ntotal_LK = cheb_poly_approx(L, Ks, node_num)\r\nGCN_total_adj = calculate_laplacian(adj_sampler.adj.todense()).toarray()\r\n\r\nX3 = np.mat(X2, dtype=np.float32)\r\nmax_value = np.max(X3) # max speed\r\n# min_value = np.min(X3)\r\n# print(\"max_speed:\", max_value, \"min_speed:\", min_value)\r\nX3 = X3 / max_value # normalize to 0~1\r\n\r\ntime_sample = [1890] # time sample from feature matrix, here we adopt the average as final result\r\nB = [50] # total budget\r\n# time_sample = [1890, 1910, 1930, 1950, 1970] # time sample from feature matrix, here we adopt the average as final result\r\n# B = [20, 50, 100, 150, 200] # total budget\r\nall_nodes = np.linspace(0, node_num-1, node_num)\r\nall_nodes = all_nodes.astype(np.int32)\r\nb = calculate_degree_of_nodes_in_set(A2, all_nodes) # a vector, denotes cost of each node\r\nw = np.ones(node_num) # a vector, denotes value weight of each node, here we set it equal\r\nattack_influence1 = np.zeros((len(time_sample), len(B)))\r\nattack_influence2 = np.zeros((len(time_sample), len(B)))\r\n\r\nfor time_step in range(len(time_sample)):\r\n X4 = X3[time_sample[time_step]: time_sample[time_step] + seq_len]\r\n label1 = X3[time_sample[time_step] + seq_len: time_sample[time_step] + seq_len + pre_len]\r\n _X = []\r\n _X.append(X4[0:seq_len])\r\n A = np.array(A2)\r\n X = np.array(_X)\r\n label = np.array(label1)\r\n # get a prediction \"pred\" of input from trained neural network in this iteration (the input is a time_sample)\r\n pred = sess.run(y_pred, feed_dict={inputs: X, graph_kernel: total_LK,\r\n tf_tmp_adj: GCN_total_adj, tf_keep_prob: 1.0})\r\n adj = copy.deepcopy(A)\r\n if model_name == 'stgcn':\r\n pred = np.squeeze(pred)\r\n pred = np.expand_dims(pred, 0)\r\n # here, pred is a pre_len*node_num matrix,\r\n # the element (i,j) in this matrix denotes the prediction speed after/\r\n # i interval(from the final time in choosen time_sample) of node j\r\n\r\n def find_attack_set_by_random(b, B):\r\n chosen_nodes = []\r\n k = random.randint(0, node_num-1)\r\n while calculate_total_budget_of_attack_set(b, add_node([k], chosen_nodes)) < B:\r\n chosen_nodes.append(k)\r\n k = random.randint(0, node_num - 1)\r\n return np.array(chosen_nodes)\r\n\r\n # def find_attack_set_by_spsa_step(l, m, u, iter, b, B, w):\r\n # chosen_nodes = []\r\n # total_score_matrix = np.zeros([node_num, node_num])\r\n # t = len(chosen_nodes)\r\n # k = 0\r\n # while calculate_total_budget_of_attack_set(b, chosen_nodes) < B:\r\n # score_matrix = np.zeros((node_num, node_num))\r\n # for i in range(node_num):\r\n # if i in chosen_nodes:\r\n # continue\r\n # else:\r\n # # 添加扰动\r\n # def add_perturbations(x):\r\n # Xp = copy.deepcopy(X)\r\n # Xp[0, :, i] = Xp[0, :, i] + x[0: seq_len]\r\n # for j in range(t):\r\n # Xp[0, :, chosen_nodes[j]] = Xp[0, :, chosen_nodes[j]] + x[(j + 1)*seq_len: (j+2)*seq_len]\r\n # return Xp\r\n #\r\n # def evaluation(x):\r\n # Xp = add_perturbations(x)\r\n # yp = sess.run(y_pred, feed_dict={inputs: Xp, graph_kernel: total_LK, tf_tmp_adj: GCN_total_adj, tf_keep_prob: 1.0}) # 扰动后的数据放入模型打标签\r\n # if model_name == 'stgcn':\r\n # yp = np.squeeze(yp)\r\n # yp = np.expand_dims(yp, 0)\r\n # goal = calculate_goal(yp, pred)\r\n # # sum = 0\r\n # # for i in chosen_nodes:\r\n # # sum = sum + yp[0, i] - pred[0, i]\r\n # # return (goal * node_num - sum) / (node_num - len(chosen_nodes))\r\n # return goal\r\n #\r\n # xh = []\r\n # xf = copy.deepcopy(X)\r\n # xc = xf[0, :, i]\r\n # xh.append(xc)\r\n # for j in range(t):\r\n # xh.append(xf[0, :, chosen_nodes[j]])\r\n # xh = np.array(xh)\r\n # xv = xh.flatten()\r\n # xl = l * xv\r\n # xi = m * xv\r\n # xu = u * xv\r\n #\r\n #\r\n # params, minimum, progress = SPSA(evaluation, xi, iter, report=False, theta_min=xl, theta_max=xu,\r\n # return_progress=10)\r\n #\r\n # Xp = add_perturbations(params)\r\n # yp = sess.run(y_pred, feed_dict={inputs: Xp, graph_kernel: total_LK, tf_tmp_adj: GCN_total_adj, tf_keep_prob: 1.0}) # 扰动后的数据放入模型打标签\r\n # if model_name == 'stgcn':\r\n # yp = np.squeeze(yp)\r\n # yp = np.expand_dims(yp, 0)\r\n # # w[i] = 0\r\n # weighted_score = np.multiply(w, yp[0, :] - pred[0, :])\r\n # # w[i] = 1\r\n # score_matrix[i, :] = weighted_score\r\n # # print('iter_node%r:%r' % (t, i))\r\n #\r\n # # mean_score = np.mean(score_matrix)\r\n # # con = min(mean_score, 0)\r\n # # score_matrix[np.where(score_matrix > con)] = 0\r\n # # print(score_matrix)\r\n # # np.save('score_matrix%r' % t, score_matrix)\r\n # new_score_vector = np.sum(score_matrix, axis=1) # total attack influence\r\n # # print(new_score_vector)\r\n # if t == 0:\r\n # final_score_vector = new_score_vector / b # marginal value of each node(if added to attack set), less than 0\r\n # else:\r\n # final_score_vector = (new_score_vector - total_score_matrix[t - 1, chosen_nodes[len(chosen_nodes) - 1]]) / b\r\n # # marginal value(the minimum is the best)\r\n # # total_score_matrix[...] denotes the influence on the whole system at iteration t-1.\r\n #\r\n # total_score_matrix[t, :] = new_score_vector\r\n # # np.save('total_score_matrix%r' % t, total_score_matrix)\r\n # # print('total_score_matrix%r:' % t, total_score_matrix)\r\n # sort_sequence = final_score_vector.argsort() # sequence produced by gcg\r\n # m = 0\r\n # while calculate_total_budget_of_attack_set(b, add_node([sort_sequence[m]], chosen_nodes)) > B \\\r\n # or sort_sequence[m] in chosen_nodes:\r\n # m = m + 1\r\n # if m == node_num:\r\n # k = 1\r\n # break\r\n # else:\r\n # if m == node_num:\r\n # break\r\n # chosen_nodes.append(sort_sequence[m])\r\n # # print('The %rth attack node is:' % t, sort_sequence[m])\r\n # t = t + 1\r\n #\r\n # if k == 1:\r\n # break\r\n #\r\n # # print('attack_set:', np.array(attack_set))\r\n # return np.array(chosen_nodes)\r\n\r\n def find_attack_set_by_spsa(l, m, u, iter, b, B, w):\r\n \"l: lower bound, -epsilon in paper\"\r\n \"m: initial value\"\r\n \"u: upper bound, +epsilon in paper\"\r\n \"iter: iteration for approximating influence of each node\"\r\n \"return vector: attack set\"\r\n\r\n chosen_nodes = []\r\n total_score_matrix = np.zeros([node_num, node_num])\r\n t = len(chosen_nodes)\r\n k = 0\r\n while calculate_total_budget_of_attack_set(b, chosen_nodes) < B:\r\n score_matrix = np.zeros((node_num, node_num))\r\n for i in range(node_num):\r\n if i in chosen_nodes:\r\n continue\r\n else:\r\n\r\n def add_perturbations(x):\r\n Xp = copy.deepcopy(X)\r\n Xp[0, :, i] = Xp[0, :, i] + x[0: seq_len]\r\n for j in range(t):\r\n Xp[0, :, chosen_nodes[j]] = Xp[0, :, chosen_nodes[j]] + x[(j + 1) * seq_len: (j + 2) * seq_len]\r\n return Xp\r\n\r\n def evaluation(x):\r\n Xp = add_perturbations(x)\r\n yp = sess.run(y_pred, feed_dict={inputs: Xp, graph_kernel: total_LK, tf_tmp_adj: GCN_total_adj,\r\n tf_keep_prob: 1.0})\r\n if model_name == 'stgcn':\r\n yp = np.squeeze(yp)\r\n yp = np.expand_dims(yp, 0)\r\n goal = calculate_goal(yp, pred)\r\n return goal\r\n\r\n xh = []\r\n xf = copy.deepcopy(X)\r\n xc = xf[0, :, i]\r\n xh.append(xc)\r\n for j in range(t):\r\n xh.append(xf[0, :, chosen_nodes[j]])\r\n xh = np.array(xh)\r\n xv = xh.flatten()\r\n xl = l * xv\r\n xi = m * xv\r\n xu = u * xv\r\n\r\n params, minimum, progress = SPSA(evaluation, xi, iter, report=False, theta_min=xl, theta_max=xu,\r\n return_progress=10)\r\n\r\n Xp = add_perturbations(params)\r\n yp = sess.run(y_pred, feed_dict={inputs: Xp, graph_kernel: total_LK, tf_tmp_adj: GCN_total_adj,\r\n tf_keep_prob: 1.0})\r\n if model_name == 'stgcn':\r\n yp = np.squeeze(yp)\r\n yp = np.expand_dims(yp, 0)\r\n weighted_score = np.multiply(w, yp[0, :] - pred[0, :])\r\n score_matrix[i, :] = weighted_score\r\n # print('iter_node%r:%r' % (t, i))\r\n\r\n new_score_vector = np.sum(score_matrix, axis=1) # total attack influence\r\n # print(new_score_vector)\r\n if t == 0:\r\n final_score_vector = new_score_vector # marginal value of each node(if added to attack set), less than 0\r\n else:\r\n final_score_vector = (new_score_vector - total_score_matrix[t - 1, chosen_nodes[len(chosen_nodes)-1]]) / b\r\n # marginal value(the minimum is the best)\r\n # total_score_matrix[...] denotes the influence on the whole system at iteration t-1.\r\n\r\n total_score_matrix[t, :] = new_score_vector\r\n # np.save('total_score_matrix%r' % t, total_score_matrix)\r\n # print('total_score_matrix%r:' % t, total_score_matrix)\r\n sort_sequence = final_score_vector.argsort() # sequence produced by spsa algorithm\r\n m = 0\r\n while calculate_total_budget_of_attack_set(b, add_node([sort_sequence[m]], chosen_nodes)) > B \\\r\n or sort_sequence[m] in chosen_nodes:\r\n m = m + 1\r\n if m == node_num:\r\n k = 1\r\n break\r\n else:\r\n if m == node_num:\r\n break\r\n chosen_nodes.append(sort_sequence[m])\r\n # print('The %rth attack node is:' % t, sort_sequence[m])\r\n t = t + 1\r\n\r\n if k == 1:\r\n break\r\n\r\n # print('attack_set:', np.array(attack_set))\r\n return np.array(chosen_nodes)\r\n\r\n def find_attack_set_by_Kg_spsa(l, m, u, iter, b, B, w):\r\n \"l: lower bound, -epsilon in paper\"\r\n \"m: initial value\"\r\n \"u: upper bound, +epsilon in paper\"\r\n \"iter: iteration for approximating influence of each node\"\r\n \"return vector: attack set\"\r\n\r\n chosen_nodes = []\r\n score_vector = np.zeros(node_num)\r\n # t = len(chosen_nodes)\r\n for i in range(node_num):\r\n\r\n # add perturbations on original input\r\n def add_perturbations(x):\r\n Xp = copy.deepcopy(X)\r\n Xp[0, :, i] = Xp[0, :, i] + x[0: seq_len]\r\n return Xp\r\n\r\n # define optimization goal\r\n def evaluation(x):\r\n Xp = add_perturbations(x)\r\n yp = sess.run(y_pred, feed_dict={inputs: Xp, graph_kernel: total_LK, tf_tmp_adj: GCN_total_adj,\r\n tf_keep_prob: 1.0})\r\n if model_name == 'stgcn':\r\n yp = np.squeeze(yp)\r\n yp = np.expand_dims(yp, 0)\r\n goal = calculate_goal(yp, pred)\r\n return goal\r\n\r\n # define the limits of perturbation\r\n xh = []\r\n xf = copy.deepcopy(X)\r\n xc = xf[0, :, i]\r\n xh.append(xc)\r\n xh = np.array(xh)\r\n xv = xh.flatten()\r\n xl = l * xv\r\n xi = m * xv\r\n xu = u * xv\r\n\r\n params, minimum, progress = SPSA(evaluation, xi, iter, report=False, theta_min=xl, theta_max=xu,\r\n return_progress=10)\r\n\r\n Xp = add_perturbations(params)\r\n yp = sess.run(y_pred, feed_dict={inputs: Xp, graph_kernel: total_LK, tf_tmp_adj: GCN_total_adj,\r\n tf_keep_prob: 1.0})\r\n if model_name == 'stgcn':\r\n yp = np.squeeze(yp)\r\n yp = np.expand_dims(yp, 0)\r\n weighted_score = np.multiply(w, yp[0, :] - pred[0, :])\r\n score_vector[i] = np.sum(weighted_score) / b[i]\r\n print('node%r:' % i)\r\n\r\n sort_sequence = score_vector.argsort() # sequence produced by Kg_spsa algorithm\r\n # print(sort_sequence)\r\n k = 0\r\n m = 0\r\n while calculate_total_budget_of_attack_set(b, chosen_nodes) < B:\r\n while calculate_total_budget_of_attack_set(b, add_node([sort_sequence[m]], chosen_nodes)) > B \\\r\n or sort_sequence[m] in chosen_nodes:\r\n m = m + 1\r\n if m >= node_num:\r\n k = 1\r\n break\r\n else:\r\n if m >= node_num:\r\n break\r\n elif sort_sequence[m] == 26: # an isolated node in dataset, could be ignored\r\n m = m + 1\r\n continue\r\n chosen_nodes.append(sort_sequence[m])\r\n m = m + 1\r\n print('The %rth attack node is:' % m, sort_sequence[m])\r\n\r\n if k == 1:\r\n break\r\n\r\n # print('attack set:', np.array(attack_set))\r\n return np.array(chosen_nodes)\r\n\r\n ############# diffusion attack on fixed attack_set\r\n def diffusion_attack(attack_set, l, m, u, iter):\r\n \"parameter l: lower bound, -epsilon in paper\"\r\n \"parameter m: initial value\"\r\n \"parameter u: upper bound, +epsilon in paper\"\r\n \"parameter iter: iteration for determine total influence of attack set\"\r\n \"return vector result1: degradation ratio of speed of each node, the average is AAIR in paper\"\r\n \"return vector result2: degradation(km/h) of speed of each node, the average is AAI in paper\"\r\n\r\n # add perturbations x on original input\r\n def add_perturbations(x):\r\n Xp = copy.deepcopy(X)\r\n for i in range(attack_set.shape[0]):\r\n Xp[0, :, attack_set[i]] = Xp[0, :, attack_set[i]] + x[i * seq_len: (i + 1) * seq_len] # 增加扰动\r\n return Xp # Xp is an adversarial sample\r\n\r\n # define the limits of perturbation\r\n xh = []\r\n for i in range(attack_set.shape[0]):\r\n Xf = copy.deepcopy(X)\r\n xc = Xf[0, :, attack_set[i]]\r\n xh.append(xc)\r\n xh = np.array(xh)\r\n xv = xh.flatten()\r\n xl = l * xv\r\n xi = m * xv\r\n xu = u * xv\r\n\r\n def evaluation(x): # evaluate the attack influence or optimization goal,\r\n # here we try to minimize it (degrade the speed in order to create traffic congestion)\r\n Xp = add_perturbations(x)\r\n # yp is a prediction matrix(the same size as the original output \"pred\") when the input is an adversarial sample Xp\r\n # in other word, yp denotes pertured speed of each node\r\n yp = sess.run(y_pred, feed_dict={inputs: Xp, graph_kernel: total_LK, tf_tmp_adj: GCN_total_adj, tf_keep_prob: 1.0}) # 扰动后的数据放入模型打标签\r\n if model_name == 'stgcn':\r\n yp = np.squeeze(yp)\r\n yp = np.expand_dims(yp, 0)\r\n goal = calculate_goal(yp, pred)\r\n return goal\r\n\r\n params, minimum, progress = SPSA(evaluation, xi, iter, report=100, theta_min=xl, theta_max=xu,\r\n return_progress=10)\r\n\r\n # if necessary, draw the optimization goal as iteration increase in spsa algorithm\r\n\r\n # print(f\"The parameters that minimise the function are {params}\\nThe minimum value of f is: {minimum}\")\r\n # plot_progress(progress, title=\"SPSA\", xlabel=r\"Iteration\", ylabel=r\"evaluation\")\r\n # plot_progress(progress, title=\"SPSA\", xlabel=r\"Iteration\", ylabel=r\"evaluation\",\r\n # moving_average=10)\r\n\r\n Xp = add_perturbations(params) # get an optimized adversarial sample\r\n yp = sess.run(y_pred, feed_dict={inputs: Xp, graph_kernel: total_LK,\r\n tf_tmp_adj: GCN_total_adj, tf_keep_prob: 1.0})\r\n if model_name == 'stgcn':\r\n yp = np.squeeze(yp)\r\n yp = np.expand_dims(yp, 0)\r\n\r\n difference = np.zeros(yp.shape[1])\r\n speed = np.zeros(yp.shape[1])\r\n\r\n for i in range(node_num):\r\n difference[i] = yp[0, i] - pred[0, i] # The difference of speed of node i between perturbed prediction and original prediction\r\n speed[i] = pred[0, i]\r\n\r\n difference = np.array(difference)\r\n speed = np.array(speed)\r\n\r\n result1 = difference / speed # This vector stores degradation ratio of speed of each node under attack\r\n result2 = difference * max_value # This vector stores degradation of speed of each node under attack (km/h)\r\n # attack_speed = (params + xv) * max_value\r\n np.set_printoptions(precision=2)\r\n return result1, result2\r\n\r\n for i in range(len(B)):\r\n print('time_step:', time_step, 'attack_budget:', B[i])\r\n if method == 'random':\r\n attack_set = find_attack_set_by_random(b, B[i])\r\n if method == 'degree':\r\n attack_set = find_attack_set_by_degree(A2, b, B[i])\r\n elif method == 'spsa':\r\n attack_set = find_attack_set_by_spsa(-1, 0, 0.5, 10, b, B[i], w)\r\n # elif method == 'spsa_step':\r\n # attack_set = find_attack_set_by_spsa_step(-1, 0, 0.5, 10, b, B[i], w)\r\n elif method == 'Kg_spsa':\r\n attack_set = find_attack_set_by_Kg_spsa(-1, 0, 0.5, 100, b, B[i], w)\r\n elif method == 'kmedoids':\r\n attack_set = find_attack_set_by_kmedoids(locations, b, B[i])\r\n elif method == 'pagerank':\r\n attack_set = find_attack_set_by_pagerank(A2, b, B[i])\r\n elif method == 'Kg_pagerank':\r\n attack_set = find_attack_set_by_Kg_pagerank(A2, b, B[i])\r\n elif method == 'betweenness':\r\n attack_set = find_attack_set_by_betweenness(A2, b, B[i])\r\n elif method == 'Kg_betweenness':\r\n attack_set = find_attack_set_by_Kg_betweenness(A2, b, B[i])\r\n\r\n attack_set = np.array(attack_set)\r\n result1, result2 = diffusion_attack(attack_set, -1, 0, 0.5, 30000)\r\n\r\n attack_influence1[time_step, i] = np.mean(result1)\r\n attack_influence2[time_step, i] = np.mean(result2)\r\n\r\n mytxt = open('%s_%s_%s_pre%r_epoch%r_drop%s_%r.txt' % (method, data_name, model_name, pre_len,\r\n training_epoch, dropmode, k), mode='a', encoding='utf-8')\r\n print('average rate:', np.mean(result1), 'average speed change:', np.mean(result2),\r\n 'attack set', attack_set, 'B:', B[i], 'time step:', time_sample[time_step],\r\n file=mytxt)\r\n mytxt.close()\r\n\r\n\r\n####### record of average of attack result in different time sample\r\nmytxt = open('%s_%s_%s_pre%r_epoch%r_drop%s_%r.txt' % (method, data_name, model_name, pre_len,\r\n training_epoch, dropmode, k), mode='a', encoding='utf-8')\r\nprint('\\n', file=mytxt)\r\nfor i in range(len(B)):\r\n print('final_average rate:', np.mean(attack_influence1[:, i]), 'final_average speed change:', np.mean(attack_influence2[:, i]),\r\n 'B:', B[i], file=mytxt)\r\nmytxt.close()\r\n\r\n\r\n############ visualisation\r\naxis_x = []\r\naxis_y = []\r\nfor i in range(len(attack_set)):\r\n axis_x.append(locations[attack_set[i], 0])\r\n axis_y.append(locations[attack_set[i], 1])\r\n\r\naxis_x = np.array(axis_x)\r\naxis_y = np.array(axis_y)\r\n\r\n# fig, axes = plt.subplots(2, 3, sharex=True, sharey=True, figsize=(16, 9), dpi=300)\r\n# plt.style.use('seaborn-poster')\r\nplt.scatter(axis_x, axis_y, c='black', s=400, alpha=0.4, marker='^')\r\nfor i in range(node_num):\r\n for j in range(node_num):\r\n if j >= i and A2[i, j] != 0:\r\n plt.plot([locations[i, 0], locations[j, 0]], [locations[i, 1], locations[j, 1]],\r\n color='#06470c', linewidth=0.2)\r\n\r\nresult1 = (result1-abs(result1))/2.0 # degradation ratio of speed of each node, less than 0\r\nresult1[np.where(result1 <= -1)] = -1 # for convenience, if degradation of speed less than -100%, we set it -100%\r\n\r\nif data_name == 'los':\r\n locations = np.delete(locations, 26, axis=0) # delete an isolated node in dataset\r\n result1 = np.delete(result1, 26, axis=0)\r\nprint(result1)\r\nsc = plt.scatter(locations[:, 0], locations[:, 1], c=-result1, s=40, cmap='RdYlGn_r', vmin=0, vmax=0.60)\r\n\r\ncbar = plt.colorbar(sc)\r\nticklabels = ['0.0', '0.2', '0.4', '0.6']\r\ncbar.set_ticks(np.linspace(0, 0.6, len(ticklabels)))\r\ncbar.set_ticklabels(ticklabels)\r\n\r\nplt.xlabel('Longitude', fontsize=15)\r\nplt.ylabel('Latitude', fontsize=15)\r\nplt.xticks(fontsize=11)\r\nplt.yticks(fontsize=11)\r\nplt.show()" } ]
9
dieg4231/MobileRobotSimulator
https://github.com/dieg4231/MobileRobotSimulator
dfb971ac90f73bf37b0d0199ed416f9123809c99
c9d50c531448b290c3433eba0e39a23c920fc910
7b2ebd7972cd7021bd4d59c76db8ccf3258d1a78
refs/heads/master
2023-05-11T05:56:07.809913
2023-05-08T15:31:57
2023-05-08T15:31:57
234,392,534
3
3
null
null
null
null
null
[ { "alpha_fraction": 0.5338361859321594, "alphanum_fraction": 0.5582973957061768, "avg_line_length": 30.030099868774414, "blob_id": "731ef2b95bcc6954d988e23069af6563ab397924", "content_id": "7260d722a3529cd011abd3b91b6a1c2f5eea6e5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9280, "license_type": "no_license", "max_line_length": 109, "num_lines": 299, "path": "/catkin_ws/src/simulator/src/action_planner/action_planner.h", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "/***********************************************\n* *\n* action_planner.h *\n* *\n* Jesus Savage *\n* Julio Cruz *\n* *\n* Bio-Robotics Laboratory *\n* UNAM, 2020 *\n* *\n* *\n************************************************/\n\n\n#include \"ros/ros.h\"\n#include \"simulator/simulator_find_obj.h\"\n#include \"simulator/simulator_manipulator.h\"\n#include <iostream>\n#include <vector>\n#include <ctime>\n#include <map>\n#include <sstream>\n#include <string>\n\n#ifndef PI\n#define PI 3.1415926535f\n#endif\n\n\n// It starts the communication with the CLIPS node\nint start_clips_node_action_planner(){\n\n bool init_kdb = false;\n std::string file;\n std::string result;\n\n std::cout << \"Starting CLIPS\" << std::endl;\n\n\n //This functions loads initial facts and rules from a file\n // The first parameter is a file that contains the names of CLIPS files *.clp\n // The second parameter indicates with false do not start executing the loaded files\n // The third parameter is a timeout\n //file = \"/src/expert_system/oracle.dat\";\n file = \"/src/action_planner/ViRBot_Cubes_ROS/ROS_cubes.dat\";\n init_kdb = SimuladorRepresentation::initKDB(file, false, 2000);\n if(!init_kdb){\n std::cout << \"CLIPS error file not found: \" << file << std::endl;\n return 0;\n }\n\n //Function to RESET CLIPS\n SimuladorRepresentation::resetCLIPS(true);\n\n //Function to print facts \n SimuladorRepresentation::factCLIPS(true);\n\n //Function to print the loaded rules' names\n SimuladorRepresentation::ruleCLIPS(true);\n\n //Function to start running Clips\n SimuladorRepresentation::runCLIPS(true);\n\n //Function to asserting a fact to the clips node to check if Clips is alive\n SimuladorRepresentation::strQueryKDB(\"(assert (alive clips))\", result, 10000);\n\n std::cout << \"CLIPS answer: \" << result << std::endl;\n\n}\n\n\n\n/*\nThis function is used to calculate the rotation angle for the Mvto command\n*/\nfloat get_angle(float ang,float c,float d,float X,float Y){\n float x,y;\n x=c-X;\n y=d-Y;\n if((x == 0) && (y == 0)) return(0);\n if(fabs(x)<0.0001) return((float) ((y<0.0f)? 3*PI/2 : PI/2) - ang );\n else{\n if(x>=0.0f&&y>=0.0f) return( (float)(atan(y/x)-ang) );\n else if(x< 0.0f&&y>=0.0f) return( (float)(atan(y/x)+PI-ang) );\n else if(x< 0.0f&&y<0.0f) return( (float)(atan(y/x)+PI-ang) );\n else return( (float)(atan(y/x)+2*PI-ang));\n }\n}\n\n\n\nvoid get_distance_theta(float x,float y,float angle,float x1,float y1,float *distance,float *theta){\n\n // it calculates the distance\n *distance=(float)sqrt((x-x1)*(x-x1)+(y-y1)*(y-y1));\n printf(\"Distance: %f\\n\",*distance);\n\n // it calculates the rotation angle\n *theta=get_angle(angle,x,y,x1,y1);\n printf(\"rotation angle: %f\\n\",*theta);\n\n}\n\n\n\nvoid action_planner(float px, float py, float theta, movement *movements){\n\n static int mini_sm=1;\n static char object_name[200];\n static int init_flg=1;\n std::string result;\n static int i=0,j=0,k=0;\n char str[300];\n char action[30];\n char ROS_System[30];\n char room[30];\n char zone[30];\n static float x,y,z=0.0;\n static char arm[30];\n static char object[100];\n static float distance=1.0;\n static float angle=0.0;\n\n movements->twist = 0.0;\n movements->advance = 0.0;\n\n if(init_flg==1){\n\n \t\t// It starts the communication with the Clips node\n \t\tstart_clips_node_action_planner();\n \t\tinit_flg=0;\n \t\tstrcpy(arm,\"manipulator\");\n\n \tSimuladorRepresentation::strQueryKDB(\"(assert (start action-planning))\", result, 10000);\n std::cout << \"CLIPS answer: \" << result << std::endl;\n }\n\n i++;\n sprintf(str,\"(assert (step %d ))\",i);\n printf(\"\\nSend fact %s\\n\",str);\n SimuladorRepresentation::strQueryKDB(str, result, 10000);\n printf(\"\\nCLIPS answer: %d %s\\n\",i,result.c_str());\n\n sscanf(result.c_str(),\"%s %s\",ROS_System,action);\n printf(\"ROS_System %s action %s\\n\",ROS_System,action);\n\n if(strcmp(action,\"goto\")==0){\n\n \t\t// ACT-PLN goto bedroom deposit 0.505 0.45 30000 4 \n \t\tsscanf(result.c_str(),\"%s %s %s %s %f %f\",ROS_System,action,room,zone,&x,&y);\n \t\tprintf(\"Room %s zone %s x %f y %f\\n\",room,zone,x,y);\n \t\tprintf(\"Pose x %f y %f theta %f\\n\",px,py,theta);\n\n\t\tget_distance_theta(x,y,theta,px,py,&distance,&angle);\n\t\tprintf(\"goto angle %f distance %f\\n\",angle,distance);\n\n\t\tmovements->twist = angle;\n movements->advance = distance;\n\n\n\t\t//answer ?sender command goto ?room ?zone ?x ?y ?flg\n\t\tsprintf(str,\"(assert (answer %s command %s %s %s %f %f 1))\",ROS_System,action,room,zone,x,y);\n \t\tprintf(\"\\nSend fact %s\\n\",str);\n \t\tSimuladorRepresentation::strQueryKDB(str, result, 10000);\n \t\tprintf(\"\\nCLIPS answer: %d %s\\n\",i,result.c_str());\n\n\n }\n\n \n if(strcmp(action,\"find_object\")==0){\n\n\t\t//ACT-PLN find_object blockB 30000 4 \n sscanf(result.c_str(),\"%s %s %s %f %f %f\",ROS_System,action,object,&x,&y,&z);\n printf(\"%s object %s x %f y %f z %f\\n\",action,object,x,y,z);\n\n\t\t //(answer ?sender command find_object ?block1 ?x ?y ?z ?arm 1)\n //sprintf(str,\"(assert (answer %s command %s %s %f %f %f %s 1))\",ROS_System,action,object,x,y,z,arm);\n //printf(\"\\nSend fact %s\\n\",str);\n \n\n ros::NodeHandle n;\n ros::ServiceClient client;\n simulator::simulator_find_obj srv;\n client = n.serviceClient<simulator::simulator_find_obj>(\"simulator_find_obj\"); //create the client\n\n srv.request.ROS_System = ROS_System;\n srv.request.action = action;\n srv.request.object = object;\n srv.request.x = x;\n srv.request.y = y;\n srv.request.z = z;\n srv.request.arm = arm;\n\n if (client.call(srv))\n {\n strcpy(str,srv.response.answer.c_str());\n }\n else\n {\n ROS_ERROR(\"Failed to call service simulator_find_obj\");\n }\n SimuladorRepresentation::strQueryKDB(str, result, 10000);\n printf(\"\\nCLIPS answer: %d %s\\n\",i,result.c_str());\n\n }\n\n \n\n if(strcmp(action,\"mv\")==0){\n\n\t // ACT-PLN mv 0.505 0.45 30000 4\n sscanf(result.c_str(),\"%s %s %f %f\",ROS_System,action,&x,&y);\n\n printf(\"%s %f %f\\n\",action,x,y);\n\t\t get_distance_theta(x,y,theta,px,py,&distance,&angle);\n printf(\"mv angle %f distance %f\\n\",angle,distance);\n\n movements->twist = angle;\n movements->advance = distance;\n\n\t\t//(answer ?sender command mv ?distance ?angle ?flg)\n sprintf(str,\"(assert (answer %s command %s %f %f 1))\",ROS_System,action,distance,angle);\n printf(\"\\nSend fact %s\\n\",str);\n SimuladorRepresentation::strQueryKDB(str, result, 10000);\n printf(\"\\nCLIPS answer: %d %s\\n\",i,result.c_str());\n\n\n }\n\n\n\n if(strcmp(action,\"grab\")==0 || strcmp(action,\"drop\")==0)\n {\n sscanf(result.c_str(),\"%s %s %s\",ROS_System,action,object);\n printf(\"%s object %s\\n\",action,object);\n\n ros::NodeHandle n;\n ros::ServiceClient client;\n simulator::simulator_manipulator srv;\n client = n.serviceClient<simulator::simulator_manipulator>(\"simulator_manipulator\"); //create the client\n\n srv.request.ROS_System = ROS_System;\n srv.request.action = action;\n srv.request.object = object;\n\n if (client.call(srv))\n {\n strcpy(str,srv.response.answer.c_str());\n }\n else\n {\n ROS_ERROR(\"Failed to call service simulator_manipulator\");\n }\n\n printf(\"\\nSend fact %s\\n\",str);\n SimuladorRepresentation::strQueryKDB(str, result, 10000);\n printf(\"\\nCLIPS answer: %d %s\\n\",i,result.c_str());\n }\n\n\n\n if(strcmp(action,\"go\")==0){\n\n // ACT-PLN go any 0.505 0.45 0.0 30000 4\n\t\t//ACT-PLN go storage 0.506491 0.875 1.541639 30000 4 \n \t\tsscanf(result.c_str(),\"%s %s %s %f %f %f\",ROS_System,action,room,&x,&y,&z);\n printf(\"%s %s %f %f %f\\n\",action,room,x,y,z);\n\n\t\tif(strcmp(room,\"any\")==0){\n\t\t\tj++;\n\t\t\t//if(j==3)j=1;\n\t\t\tmovements->twist = - 0.3*j;\n \tmovements->advance = 0.04*j;\n \tprintf(\"go j %d any angle %f distance %f\\n\",j,angle,distance);\n\t\t}\n\t\telse{\n\t\t\tk++;\n\t\t\tif(k==3)k=1;\n\t\t\tget_distance_theta(x,y,theta,px,py,&distance,&angle);\n\t\t\tmovements->twist = angle;\n\t\t\tmovements->advance = distance - 0.045*k;\n \tprintf(\"go k %d angle %f distance %f\\n\",k,angle,distance);\n\t\t}\n\n\n\n\t\t//(answer ?sender command go ?x ?y ?z ?flg)\n sprintf(str,\"(assert (answer %s command %s %f %f %f 1))\",ROS_System,action,x,y,z);\n printf(\"\\nSend fact %s\\n\",str);\n SimuladorRepresentation::strQueryKDB(str, result, 10000);\n printf(\"\\nCLIPS answer: %d %s\\n\",i,result.c_str());\n\n\n }\n\nprintf(\"movements->twist %f movements->advance %f \\n\",movements->twist,movements->advance);\n\n}\n\n\n" }, { "alpha_fraction": 0.7566371560096741, "alphanum_fraction": 0.7876105904579163, "avg_line_length": 36.66666793823242, "blob_id": "c10f241ba9f210317c2d8d6a403dcc24b381d181", "content_id": "bef8c69ea88888933199fd84bbc2757c440829da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 226, "license_type": "no_license", "max_line_length": 66, "num_lines": 6, "path": "/runSimulator.sh", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#!/bin/bash\nsource /opt/ros/melodic/setup.bash\nsource /home/$USER/MobileRobotSimulator/catkin_ws/devel/setup.bash\necho \"Exporting ROS MASTER since->$1\" \nexport ROS_MASTER_URI=http://$1:11311\nroslaunch simulator minibot.launch\n" }, { "alpha_fraction": 0.5637706518173218, "alphanum_fraction": 0.5743016004562378, "avg_line_length": 42.54777145385742, "blob_id": "ce3f1a77c036308c9c9871fa66d8df2c6998e4b8", "content_id": "8767b231235016c07d6cb5ddd94feb93097f5038", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13674, "license_type": "no_license", "max_line_length": 168, "num_lines": 314, "path": "/catkin_ws/src/simulator/src/turtlebot/move_minibot_node.cpp", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <geometry_msgs/Twist.h>\n#include <tf/transform_listener.h>\n#include <simulator/simulator_MoveRealRobot.h>\n\nros::Publisher pubCmdVel;\ntf::Quaternion q;\ntf::StampedTransform transform;\ntf::TransformListener* transformListener;\n\n\nfloat a, b, c, x, v_top;\n\n//PARAMETERS FOR ROBOT'S MOVEMENTS\nfloat max_speed = 0.12;\nfloat initial_speed = 0.04;\nfloat angle_tolerancy = 0.02;\nfloat distance_tolerancy = 0.004;\n\n//PARAMETERS FOR LINEAR MOVEMENTS\nfloat linear_alpha = 1.4;\nfloat linear_beta = 12.5;\nfloat linear_max_angular = 2.5;\n\n//PARAMETERS FOR ANGULAR MOVEMENTS\nfloat angular_alpha = 0.45;\nfloat angular_max_angular = 2.5;\n\nenum State{\n SM_INIT,\n SM_ROBOT_ACCEL,\n SM_ROBOT_DECCEL,\n SM_ROBOT_CORRECT_ANGLE,\n SM_ROBOT_FINISH\n};\n\nvoid load_parameters()\n{\n if(!ros::param::get(\"/max_speed\", max_speed)) {\n ROS_ERROR(\"/max_speed param did not loaded, check file: ~/MobileRobotSimulator/catkin_ws/src/simulator/src/data/control/control.yaml\"); \n std::cout << \"Loading default value for max_speed->\" << max_speed << std::endl;\n } else { std::cout << \"\\tmax_speed->\" << max_speed << std::endl; }\n \n if(!ros::param::get(\"/initial_speed\", initial_speed)){\n ROS_ERROR(\"/initial_speed param did not loaded, check file: ~/MobileRobotSimulator/catkin_ws/src/simulator/src/data/control/control.yaml\"); \n std::cout << \"Loading default value for initial_speed->\" << initial_speed << std::endl;\n } else { std::cout << \"\\tinitial_speed->\" << initial_speed << std::endl; }\n \n if(!ros::param::get(\"/angle_tolerancy\", angle_tolerancy)) {\n ROS_ERROR(\"/angle_tolerancy param did not loaded, check file: ~/MobileRobotSimulator/catkin_ws/src/simulator/src/data/control/control.yaml\"); \n std::cout << \"Loading default value for angle_tolerancy->\" << angle_tolerancy << std::endl;\n } else { std::cout << \"\\tangle_tolerancy->\" << angle_tolerancy << std::endl; }\n \n if(!ros::param::get(\"/distance_tolerancy\", distance_tolerancy)) {\n ROS_ERROR(\"/distance_tolerancy param did not loaded, check file: ~/MobileRobotSimulator/catkin_ws/src/simulator/src/data/control/control.yaml\"); \n std::cout << \"Loading default value for distance_tolerancy->\" << distance_tolerancy << std::endl;\n } else { std::cout << \"\\tdistance_tolerancy->\" << distance_tolerancy << std::endl; }\n \n if(!ros::param::get(\"/linear_alpha\", linear_alpha)) {\n ROS_ERROR(\"/linear_alpha param did not loaded, check file: ~/MobileRobotSimulator/catkin_ws/src/simulator/src/data/control/control.yaml\"); \n std::cout << \"Loading default value for linear_alpha->\" << linear_alpha << std::endl;\n } else { std::cout << \"\\tlinear_alpha->\" << linear_alpha << std::endl; }\n \n if(!ros::param::get(\"/linear_beta\", linear_beta)) {\n ROS_ERROR(\"/linear_beta param did not loaded, check file: ~/MobileRobotSimulator/catkin_ws/src/simulator/src/data/control/control.yaml\"); \n std::cout << \"Loading default value for linear_beta->\" << linear_beta << std::endl;\n } else { std::cout << \"\\tlinear_beta->\" << linear_beta << std::endl; }\n\n if(!ros::param::get(\"/linear_max_angular\", linear_max_angular)) {\n ROS_ERROR(\"/linear_max_angular param did not loaded, check file: ~/MobileRobotSimulator/catkin_ws/src/simulator/src/data/control/control.yaml\"); \n std::cout << \"Loading default value for /linear_max_angular->\" << linear_max_angular << std::endl;\n } else { std::cout << \"\\tlinear_max_angular->\" <<linear_max_angular << std::endl; }\n \n if(!ros::param::get(\"/angular_alpha\", angular_alpha)) {\n ROS_ERROR(\"/angular_alpha param did not loaded, check file: ~/MobileRobotSimulator/catkin_ws/src/simulator/src/data/control/control.yaml\"); \n std::cout << \"Loading default value for angular_alpha->\" << angular_alpha << std::endl;\n } else { std::cout << \"\\tangular_alpha->\" << angular_alpha << std::endl; }\n \n if(!ros::param::get(\"/angular_max_angular\", angular_max_angular)) {\n ROS_ERROR(\"/angular_max_angular param did not loaded, check file: ~/MobileRobotSimulator/catkin_ws/src/simulator/src/data/control/control.yaml\"); \n std::cout << \"Loading default value for /angular_max_angular->\" << angular_max_angular << std::endl;\n } else { std::cout << \"\\tangular_max_angular->\" <<angular_max_angular << std::endl; }\n}\n\ngeometry_msgs::Twist compute_speed(float robot_x, float robot_y, float robot_t, float goal_x, float goal_y,float robot_advance, bool backwards)\n{\n float speed = 3*a*pow(robot_advance, 2) + 2*b*robot_advance + c;\n speed = max_speed * speed / v_top;\n if(speed < 0) speed = 0;\n\n //PARAMETERS FOR LINEAR MOVEMENTS\n\tfloat alpha = linear_alpha;\n\tfloat beta = linear_beta;\n\tfloat max_angular = linear_max_angular;\n\n //Error calculation\n\tfloat angle_error = 0;\n\tif(backwards) angle_error = atan2(robot_y - goal_y, robot_x - goal_x) - robot_t;\n\telse angle_error = atan2(goal_y - robot_y, goal_x - robot_x) - robot_t;\n\tif(angle_error > M_PI) angle_error -= 2*M_PI;\n\tif(angle_error <= -M_PI) angle_error += 2*M_PI;\n \n if(backwards) speed *= -1;\n \n geometry_msgs::Twist _speed;\n _speed.linear.x = speed * exp(-(angle_error * angle_error) / alpha);\n _speed.linear.y = 0;\n _speed.angular.z = max_angular * (2 / (1 + exp(-angle_error / beta)) - 1);\n return _speed; \n\n}\n\ngeometry_msgs::Twist compute_speed(float goal_angle, float robot_angle)\n{\n\tfloat angle_error = goal_angle - robot_angle;\n if(angle_error > M_PI) angle_error -= 2*M_PI;\n if(angle_error <= -M_PI) angle_error += 2*M_PI;\n \n //PARAMETER FOR ANGULAR MOVEMENTS\n float alpha = angular_alpha;\n float max_angular = angular_max_angular;\n\n geometry_msgs::Twist speed;\n\tspeed.linear.x = 0;\n\tspeed.linear.y = 0;\n speed.angular.z = max_angular * (2 / (1 + exp(-angle_error / alpha)) - 1);\n\treturn speed;\n}\n\nvoid get_robot_position(tf::TransformListener* transformListener, float& robot_x, float& robot_y, float& robot_t)\n{\n double roll, pitch, yaw;\n\ttf::StampedTransform transform;\n\ttransformListener->lookupTransform(\"odom\", \"base_link\", ros::Time(0), transform);\n\trobot_x = transform.getOrigin().x();\n\trobot_y = transform.getOrigin().y();\n transform.getBasis().getRPY(roll, pitch, yaw);\n robot_t = yaw;\n\n\tif(robot_t > M_PI) robot_t -= 2*M_PI;\n\tif(robot_t <= -M_PI) robot_t += 2*M_PI;\n}\nvoid get_goal_position(tf::TransformListener* transformListener, float& robot_x, float& robot_y, float& robot_t, \n float goal_distance, float goal_angle, float& goal_x, float& goal_y, float& goal_t)\n{\n get_robot_position(transformListener, robot_x, robot_y, robot_t);\n\n goal_x = robot_x + goal_distance * cos(robot_t + goal_angle);\n\tgoal_y = robot_y + goal_distance * sin(robot_t + goal_angle);\n\tgoal_t = robot_t + goal_angle;\n\tif(goal_t > M_PI) goal_t -= 2*M_PI;\n\tif(goal_t <= -M_PI) goal_t += 2*M_PI;\n}\n\nbool simpleMoveCallback(simulator::simulator_MoveRealRobot::Request &req, simulator::simulator_MoveRealRobot::Response &res)\n{\n State state = SM_INIT;\n ros::Rate rate(50); \n \n float goal_x, goal_y, goal_t;\n float start_robot_x, start_robot_y;\n float goal_distance, distance_error, angle_error, last_error;\n float robot_x, robot_y, robot_t, robot_advance, robot_traveled;\n\n bool goal_reached = false;\n bool with_distance = false;\n int attempts = 0;\n \n geometry_msgs::Twist twist, stop_robot;\n\tstop_robot.linear.x = 0;\n\tstop_robot.linear.y = 0;\n\tstop_robot.angular.z = 0;\n \n while(ros::ok() && !goal_reached)\n {\n switch(state)\n {\n case SM_INIT:\n //std::cout<<\"ON INIT\"<<std::endl;\n get_goal_position(transformListener, robot_x, robot_y, robot_t, req.distance, req.theta, goal_x, goal_y, goal_t);\n start_robot_x = robot_x;\n start_robot_y = robot_y;\n goal_distance = fabs(req.distance);\n last_error = goal_distance + distance_tolerancy;\n \n x = goal_distance;\n if(goal_distance > distance_tolerancy){\n float xp_0 = 6*initial_speed / (max_speed +3*initial_speed);\n a = (xp_0 - 2)/pow(x, 2);\n b = (3 - 2*xp_0) / (x); \n c = xp_0;\n float x_inf = - b /(3*a);\n v_top = 3*a*pow(x_inf, 2) + 2*b*x_inf + c;\n }\n attempts = (int)((fabs(req.distance)+0.1)/0.5*400 + fabs(req.theta)/0.5*60);\n std::cout<<std::endl;\n std::cout << \"goal_distance.->\" << goal_distance << std::endl;\n std::cout<<\"-------------------------------\"<<std::endl;\n //std::cout<<std::setprecision(3)<<\"Start position: x-> \"<<robot_x<<\"\\ty-> \"<<robot_y<<\"\\t\\033[1;33mt->\\033[0m\"<<robot_t<<std::endl;\n state = State::SM_ROBOT_ACCEL;\n break;\n\n case SM_ROBOT_ACCEL:\n //std::cout << \"SM_ROBOT_ACCEL\" << std::endl;\n get_robot_position(transformListener, robot_x, robot_y, robot_t);\n distance_error = sqrt(pow(goal_x - robot_x, 2) + pow(goal_y - robot_y, 2));\n robot_traveled = sqrt(pow(robot_x - start_robot_x, 2) + pow(robot_y - start_robot_y, 2));\n\n angle_error = fabs(goal_t - robot_t);\n if(distance_error < distance_tolerancy && !with_distance)\n state = State::SM_ROBOT_CORRECT_ANGLE;\n else\n {\n if(fabs(req.theta) >= angle_tolerancy && !with_distance)\n {\n state = State::SM_ROBOT_CORRECT_ANGLE;\n with_distance = true;\n }\n else\n {\n if(distance_error > distance_tolerancy)\n {\n with_distance = true;\n \n robot_advance = goal_distance - distance_error;\n\n\n if(last_error < distance_error && distance_error < goal_distance / 2) {\n //std::cout <<\"\\t\\033[1;33mUps! I've exceeded the goal...\\033[0m\"<< std::endl;\n state = State::SM_ROBOT_FINISH;\n }\n //std::cout<< \"\\trobot_traveled.->\"<<robot_traveled<<\"\\trobot_advanced.->\"<<robot_advance<<\"\\tdistance_error.->\"<<distance_error<<std::endl;\n twist = compute_speed(robot_x, robot_y, robot_t, goal_x, goal_y, robot_advance, req.distance < 0);\n pubCmdVel.publish(twist);\n last_error = distance_error;\n }\n else\n state = State::SM_ROBOT_FINISH;\n }\n }\n\t\t\t\tif(--attempts <= 0)\n {\n\t\t\t\t\tstate = State::SM_ROBOT_FINISH;\n std::cout << \"\\t\\033[1;33mUps! I've exceeded the attempts...\\033[0m\" << std::endl;\n }//*/\n break;\n\n case SM_ROBOT_CORRECT_ANGLE:\n //std::cout << \"SM_ROBOT_CORRECT_ANGLE\" << std::endl;\n get_robot_position(transformListener, robot_x, robot_y, robot_t);\n angle_error = goal_t - robot_t;\n if(angle_error > M_PI) angle_error -= 2*M_PI;\n if(angle_error <= -M_PI) angle_error += 2*M_PI;\n\n if(fabs(angle_error) < angle_tolerancy) \n {\n if(!with_distance) state = State::SM_ROBOT_FINISH;\n else state = State::SM_ROBOT_ACCEL;\n }\n else {\n twist = compute_speed(goal_t, robot_t);\n pubCmdVel.publish(twist); //_speed.angular.z = 0;\n\n }\n break;\n\n case SM_ROBOT_FINISH:\n //std::cout << \"SM_ROBOT_FINISH\" << std::endl;\n std::cout << \"SimpleMove.->Successful moved with dist=\" << req.distance << \" angle=\" << req.theta << std::endl;\n goal_reached = true;\n pubCmdVel.publish(stop_robot);\n break;\n\n default:\n std::cout<<\"An unexpected error has occurred :O\"<<std::endl;\n break;\n }//FROM switch(state)\n \n ros::spinOnce();\n rate.sleep();\n }//FROM while(ros::ok())\n pubCmdVel.publish(stop_robot);\n get_robot_position(transformListener, robot_x, robot_y, robot_t);\n std::cout<<\"goal_t->\"<<goal_t<<\"\\trobot_t->\"<<robot_t<<\"\\tangle_error->\"<<angle_error<<\"\\t\\033[1;33mdistance_error\\033[0m.->\"<<distance_error<<std::endl;\n res.done = 1;\n return true;\n}//FROM bool simpleMoveCallback()\n\nint main(int argc, char ** argv){\n std::cout<<\"Starting move_minibot_node...\"<<std::endl;\n\tros::init(argc, argv, \"move_minibot_node\");\n\tros::NodeHandle nh;\n\tros::Rate rate(30);\n\n\tload_parameters();\n\tros::ServiceServer simpleMoveService = nh.advertiseService(\"simulator_move_RealRobot\", simpleMoveCallback);\n pubCmdVel = nh.advertise<geometry_msgs::Twist>(\"/cmd_vel\", 1);\n\t\n transformListener = new tf::TransformListener();\n try{\n\t\ttransformListener->waitForTransform(\"odom\", \"base_link\", ros::Time(0), ros::Duration(10.0));\n\t\ttransformListener->lookupTransform(\"odom\", \"base_link\", ros::Time(0), transform);\n }\n catch(...){\n std::cout << \"SimpleMove.->Cannot get transforms for robot's pose calculation... :'(\" << std::endl;\n\t\treturn -1;\n }\n \n\twhile(ros::ok()){\n \n\t\tros::spinOnce();\n\t\trate.sleep();\n\t}\n}\n" }, { "alpha_fraction": 0.5023961663246155, "alphanum_fraction": 0.5231629610061646, "avg_line_length": 27.454545974731445, "blob_id": "1bbf4c1780173033905e0f2bc9bd88a82a5ebee4", "content_id": "712d76c221b9abde81a71650166fe8043eaf2bbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1252, "license_type": "no_license", "max_line_length": 107, "num_lines": 44, "path": "/catkin_ws/src/simulator/src/simulator_physics/light_server.cpp", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <std_msgs/Int16MultiArray.h>\n#include <simulator/simulator_light.h>\n\nusing namespace std;\n\nfloat light_sensor[8];\n\nvoid light_callback(const std_msgs::Int16MultiArrayConstPtr& msg) {\n\n cout << \"[\" << msg->data[0] << \", \" <<\n msg->data[1] << \", \" <<\n msg->data[2] << \", \" <<\n msg->data[3] << \", \" <<\n msg->data[4] << \", \" <<\n msg->data[5] << \", \" <<\n msg->data[6] << \", \" <<\n msg->data[7] << \", \" <<\n \"] \" << endl;\n\n for(int i=0; i<8; i++) light_sensor[i] = ( msg->data[i]*40 ) / 1024;\n\n}\n\nbool get_intensities(simulator::simulator_light::Request &req, simulator::simulator_light::Response &res) {\n\n for(int i=0; i<8; i++) res.values[i] = light_sensor[i];\n\n return true;\n}\n\nint main(int argc, char **argv) {\n \n cout << \"Starting light_server by Luis Näva...\" << endl;\n ros::init(argc, argv, \"light_server\");\n ros::NodeHandle nh;\n\n ros::Subscriber sub_light_sensors = nh.subscribe(\"/light_sensors\", 10, light_callback);\n ros::ServiceServer service = nh.advertiseService(\"simulator_light_RealRobot\", get_intensities);\n\n ros::spin();\n\n return 0;\n}\n" }, { "alpha_fraction": 0.4356081783771515, "alphanum_fraction": 0.45483434200286865, "avg_line_length": 25.715499877929688, "blob_id": "7da9bb3903e03b27aa0e829da14770ae136f1742", "content_id": "3ced9c1c9a1b469ca49f4ac46b94d2424f4029c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12587, "license_type": "no_license", "max_line_length": 113, "num_lines": 471, "path": "/catkin_ws/src/simulator/src/state_machines/line_follower.h", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "/********************************************************\n * *\n * *\n * line_follower.h\t *\n * * \n * Miguel Sanchez *\n * FI-UNAM *\n * Agosto-2022 *\n * *\n ********************************************************/\n#include \"ros/ros.h\"\n#include \"dijkstralib.h\"\n#include<geometry_msgs/Twist.h>\n#include <math.h>\n#include<unistd.h>\n\n#define THRESHOLD 35\nfloat OBSTACLE_THRESHOLD=0.128;\nconst float dist_tolerancy = 0.1;\nconst float ang_tolerancy=0.2;\nconst float sleep_time = 5;\nint Kprop = 0;\nint node_dest=-1;\nint obstacles=-1;\nint lenght=0;\nint frec=4;\n\nros::Publisher pubCmdVel;\n\n\nint lines[3];\nfloat rx=0;\nfloat ry=0;\nfloat rtheta=0;\nbool battery_charging = false;\n\n\n\nenum State { MOVE_FOWARD, MOVE_BACKWARD, TURN_RIGHT, TURN_LEFT, ROBOT_STOP, TURN_RIGHT_FOWARD,TURN_LEFT_FOWARD };\n\ngeometry_msgs::Twist move_robot(int move){\n\n float lin_vel = 0.09 ;\n float ang_vel = 1.0 ;\n geometry_msgs::Twist speed;\n\n switch(move)\n {\n case ROBOT_STOP:\n speed.linear.x = 0.0;\n speed.linear.y = 0.0;\n speed.angular.z = 0.0; \n break;\n case MOVE_FOWARD:\n speed.linear.x = lin_vel;\n speed.linear.y = 0.0;\n speed.angular.z = 0.0; \n break;\n case MOVE_BACKWARD:\n speed.linear.x = -lin_vel;\n speed.linear.y = 0.0;\n speed.angular.z = 0.0; \n break;\n case TURN_LEFT:\n speed.linear.x = 0.0;\n speed.linear.y = 0.0;\n speed.angular.z = ang_vel; \n break;\n case TURN_RIGHT:\n speed.linear.x = 0.0;\n speed.linear.y = 0.0;\n speed.angular.z = -ang_vel; \n break;\n case TURN_RIGHT_FOWARD:\n //speed.linear.x = -(lin_vel*(1+(Kprop/1000000)));\n speed.linear.x = (lin_vel/15); \n speed.linear.y = 0.0;\n //speed.angular.z= -ang_vel;\n speed.angular.z = -(ang_vel*(1-(Kprop/10000))); \n //printf(\"lx: %f\\n\",-(lin_vel*(1+(Kprop/100000))));\n //printf(\"lx: %f\\n\",-(ang_vel*(1+(Kprop/100000))));\n break;\n case TURN_LEFT_FOWARD:\n speed.linear.x = -lin_vel;\n speed.linear.y = 0.0;\n speed.angular.z = ang_vel/2; \n break;\n \n default:\n printf(\"Error\\n\");\n }\n\n return speed;\n}\n\nvoid ParamsCallback(const simulator::Parameters::ConstPtr& paramss)\n{\n rx = paramss->robot_x;\n ry = paramss->robot_y;\n rtheta = paramss->robot_theta;\n}\n\nvoid lineSensCallback(const std_msgs::Int16MultiArray::ConstPtr& msg){\n lines[0] = msg->data[0];\n lines[1] = msg->data[1];\n lines[2] = msg->data[2];\n}\n\n\nint orient_to_node(int node_dest,ros::Rate lat)\n{\n float ang=0;\n ang=atan2f(nodes[node_dest].y-ry,nodes[node_dest].x-rx);\n printf(\"node: %d\\n\",node_dest);\n printf(\"Orientation goal: %f\\n\",ang*(180/3.141593));\n printf(\"Robot orientation %f\\n\",rtheta*(180/3.141593));\n \n if( abs(rtheta-ang) <= ang_tolerancy)\n {\n pubCmdVel.publish(move_robot(ROBOT_STOP));\n lat.sleep();\n printf(\"\\n\\t\\tRobot oriented\\n\\n\");\n return 1;\n }\n else if( (ang-rtheta) < 0)\n {\n printf(\"TURN_RIGHT\\n\");\n pubCmdVel.publish(move_robot(TURN_RIGHT));\n lat.sleep();\n\n }\n else if( (ang-rtheta) > 0)\n {\n printf(\"TURN_LEFT\\n\");\n pubCmdVel.publish(move_robot(TURN_LEFT));\n lat.sleep();\n }\n return 0;\n\n}\n\nint avoid_obst(ros::Rate lat)\n{\n \n obstacles=quantize_laser(lasers,lenght,OBSTACLE_THRESHOLD);\n \n //Mostrar mediciones laser \n /*for(int i=0; i<3;i++)\n {\n printf(\"l[%d]: %f\\n\",i,lasers[i]); \n \n }\n */\n if(lasers[1]<OBSTACLE_THRESHOLD)\n obstacles=3;\n if(!obstacles)\n { \n //printf(\"no obstacle\\n\"); \n }\n else\n {\n pubCmdVel.publish(move_robot(ROBOT_STOP));\n lat.sleep();\n if(obstacles==1)\n printf(\"obstacle in right\\n\"); \n \n if(obstacles==2)\n printf(\"obstacle in left\\n\");\n \n printf(\"obstacle detected, sorting obstacle\\n\");\n \n for(int i=0;i<10;i++)\n {\n pubCmdVel.publish(move_robot(MOVE_BACKWARD));\n lat.sleep();\n }\n \n\n pubCmdVel.publish(move_robot(ROBOT_STOP));\n lat.sleep();\n /*while(!orient_to_node(node_dest,lat))\n {\n printf(\"orienting to node to continue path\\n\");\n ros::spinOnce();\n lat.sleep();\n }*/\n }\n ros::spinOnce();\n}\n\n\n\nvoid findline(ros::Rate lat)\n{\n \n int rotation=-1;\n int sensor=-1;\n printf(\"RIGHT_FOWARD\\n\");\n int lineflag=0;\n do\n {\n //printf(\"l0 l1 l2\\n\");\n //printf(\"%d %d %d\\n\",lines[0],lines[1],lines[2]);\n pubCmdVel.publish(move_robot(TURN_RIGHT_FOWARD));\n lat.sleep();\n ros::spinOnce();\n avoid_obst(lat);\n \n //printf(\"l0 %d l1 %d l2 %d \\n\",lines[0],lines[1],lines[2]);\n if(lines[0] || lines[1] || lines[2])\n {\n printf(\"lines[0]: %d lines[1]: %d Lines [2]:: %d \\n\",lines[0],lines[1],lines[2]); \n pubCmdVel.publish(move_robot(ROBOT_STOP));\n lat.sleep();\n if(lines[0] && !lines[1])\n {\n rotation=2;//RIGHT\n sensor=0;\n }\n else if(!lines[0] && lines[1])\n {\n rotation=3;//LEFT\n sensor=1;\n }\n else if(lines[2])\n {\n rotation=4; //STOP\n sensor=2;\n }\n \n \n /*ros::spinOnce();\n printf(\"lines[0]: %d lines[1]: %d Lines [2]:: %d \\n\",lines[0],lines[1],lines[2]); \n if(lines[0] || lines[1] || lines[2])\n { \n lineflag=1;\n //scanf(\"%d\",&lineflag);\n }\n */\n lineflag=1;\n }\n Kprop++;\n \n }while(!lineflag);\n \n Kprop=0;\n \n printf(\"FOWARD\\n\");\n while(!lines[2])\n {\n pubCmdVel.publish(move_robot(MOVE_FOWARD));\n lat.sleep();\n \n ros::spinOnce();\n \n avoid_obst(lat);\n }\n pubCmdVel.publish(move_robot(ROBOT_STOP));\n lat.sleep();\n \n printf(\"TURN\\n\");\n printf(\"rotation: %d\\n\",rotation);\n printf(\"lines[%d]: %d\\n\",sensor,lines[sensor]);\n if(sensor != 2 && sensor !=-1)\n {\n while(lines[sensor])\n {\n pubCmdVel.publish(move_robot(rotation));\n //printf(\"move: %d\\n\",rotation);\n //printf(\"lines[%d]: %d\\n\",sensor,lines[sensor]);\n lat.sleep();\n ros::spinOnce();\n }\n }\n \n /*while(!orient_to_node(node_dest,lat))\n {\n printf(\"orienting to node find line\\n\");\n ros::spinOnce();\n lat.sleep();\n }\n \n */printf(\"\\n \\tline found\\n\");\n\n\n}\n\n\nint follow_line(ros::Rate lat){\n //printf(\"l0 %d l1 %d l2 %d \\n\",lines[0],lines[1],lines[2]);\n\n if(lines[2])\n {\n if (!lines[0] && !lines[1])\n {\n //*movements=generate_output(FORWARD,Mag_Advance,max_twist);\n pubCmdVel.publish(move_robot(MOVE_FOWARD));\n lat.sleep();\n //printf(\"FOWARD\\t\");\n }\n else if(lines[0] && !lines[1])\n { \n //*movements=generate_output(RIGHT,Mag_Advance,max_twist);\n pubCmdVel.publish(move_robot(TURN_RIGHT));\n lat.sleep();\n //printf(\"RIGHT\\t\");\n }\n else if(!lines[0] && lines[1])\n {\n //*movements=generate_output(LEFT,Mag_Advance,max_twist);\n pubCmdVel.publish(move_robot(TURN_LEFT));\n lat.sleep();\n //printf(\"LEFT\\t\");\n }\n else if(lines[0] && lines[1])\n {\n pubCmdVel.publish(move_robot(ROBOT_STOP));\n lat.sleep();\n //printf(\"STOP\\t\");\n return 1; \n }\n }\n \n else\n {\n findline(lat);\n /*while(!orient_to_node(node_dest,lat))\n {\n printf(\"orienting to node to find line\\n\");\n ros::spinOnce();\n avoid_obst(lat);\n lat.sleep();\n }\n while(!lines[2])\n {\n pubCmdVel.publish(move_robot(MOVE_FOWARD));\n printf(\"\\tmove foward\\n\");\n ros::spinOnce();\n avoid_obst(lat);\n lat.sleep();\n }\n */\n\n }\n \n return 0;\n}\n\nfloat calculateDistance(float x1,float y1, float x2, float y2){\nreturn sqrt(pow( x1 - x2 ,2) + pow( y1 - y2 ,2)); \n}\n\n\n\n//Behavior \nint line_follower(\n float *observations\n ,int obs\n ,int size\n ,float x_dest\n ,float y_dest\n ,float Mag_Advance \n ,float max_twist\n ,float robotx \n ,float roboty\n ,char *world_name\n )\n{\n ros::NodeHandle nh;\n ros::Rate lat(frec);\n pubCmdVel = nh.advertise<geometry_msgs::Twist>(\"/cmd_vel\", 10);\n ros::Subscriber subLineSensor = nh.subscribe(\"/line_sensors\", 1000, lineSensCallback);\n ros::Subscriber subPoseRobot = nh.subscribe(\"/simulator_parameters_pub\",0,ParamsCallback);\n \n int result=0,current_node=-1;\n obstacles=obs;\n lenght=size;\n char archivo[150];\n int i; \n int start = 0;\n std::string paths = ros::package::getPath(\"simulator\");\n strcpy(archivo,paths.c_str());\n strcat(archivo,\"/src/data/\");\n strcat(archivo,world_name);\n strcat(archivo,\"/\");\n strcat(archivo,world_name);\n strcat(archivo,\".top\");\n for(i = 0; i < MUM_NODES; i++)\n {\n nodes[i].flag='N';\n nodes[i].num_conections = 0;\n nodes[i].parent = -1;\n nodes[i].acumulado = 0;\n nodes[i].x=0.0;\n nodes[i].y=0.0;\n }\n\n num_nodes=read_nodes(archivo); // Se lee el arcivo .top\n\n for(i=0; i<num_nodes; i++)\n {\n if (calculateDistance(x_dest,y_dest,nodes[i].x,nodes[i].y) < dist_tolerancy)\n {\n node_dest=nodes[i].num_node;\n }\n }\n\n printf(\"\\nDestine Node: %d \\n\",node_dest);\n printf(\"Current Node: %d \\n\",current_node);\n printf(\"X_dest: %f \\n\",nodes[node_dest].x);\n printf(\"Y_dest: %f \\n\",nodes[node_dest].y);\n printf(\"Obstacle :%i\\n\",obs);\n printf(\"following line\\n\");\n while (current_node != node_dest) \n {\n //printf(\"l0 %d l1 %d l2 %d\\n\",lines[0],lines[1],lines[02]);\n \n if(rx!=0 && ry!=0)\n {\n result=follow_line(lat);\n //printf(\"debugging obst avoider\");\n //avoid_obst(lat);\n \n }\n //printf(\"RESULT %d\\n\",result); \n if(result)\n {\n for(i=0;i< num_nodes;i++)\n {\n if ((calculateDistance(rx,ry,nodes[i].x,nodes[i].y)) <= dist_tolerancy)\n {\n current_node=nodes[i].num_node;\n }\n }\n printf(\"\\nNode %d reached.\\n\\n\",current_node);\n if (current_node !=node_dest)\n {\n //*movements=generate_output(FORWARD,Mag_Advance,max_twist);\n while(lines[0] && lines[1] )\n {\n pubCmdVel.publish(move_robot(MOVE_FOWARD));\n ros::spinOnce();\n lat.sleep();\n }\n \n pubCmdVel.publish(move_robot(ROBOT_STOP));\n lat.sleep();\n\n while(orient_to_node(node_dest,lat)!=1)\n {\n printf(\"orienting to next node\\n\");\n ros::spinOnce();\n lat.sleep();\n }\n \n\n //printf(\"MOVE FORWARD\\n\");\n }\n \n \n }\n ros::spinOnce();\n avoid_obst(lat);\n lat.sleep();\n }\n\n pubCmdVel.publish(move_robot(ROBOT_STOP));\n lat.sleep();\n printf(\"Reached destine node\\n\\n\");\n return result;\n}\n\n\n\n\n" }, { "alpha_fraction": 0.34381288290023804, "alphanum_fraction": 0.35160964727401733, "avg_line_length": 36.82857131958008, "blob_id": "cb9dd922d4e9ea85e0bca2be0761ee65cef80254", "content_id": "8ba0e1364de18b0fe310e59223b6e106f964fc8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3976, "license_type": "no_license", "max_line_length": 120, "num_lines": 105, "path": "/catkin_ws/src/simulator/src/state_machines/sm_destination.h", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "/********************************************************\n * *\n * *\n * state_machine_destination.h \t\t*\n * *\n * Jesus Savage *\n * Diego Cordero *\n * FI-UNAM *\n * 13-2-2019 *\n * *\n ********************************************************/\n\n#define THRESHOLD_DEST 31.0\n\n\n// State Machine \nint sm_destination(float intensity, int dest,movement *movements ,int *next_state ,float Mag_Advance ,float max_twist)\n{\n\n int state = *next_state;\n int result=0;\n\n\n //printf(\"Present State: %d \\n\", state);\n //printf(\"intensity %f dest %d\\n\",intensity,dest);\n\n switch ( state ) {\n\n case 1:\n\n if (intensity > THRESHOLD_DEST){\n *movements=generate_output(STOP,Mag_Advance,max_twist);\n //printf(\"Present State: %d STOP\\n\", state);\n printf(\"\\n **************** Reached light source ******************************\\n\");\n *next_state = 1;\n result = 1;\n }\n else{\n *movements=generate_output(FORWARD,Mag_Advance,max_twist);\n //printf(\"Present State: %d FORWARD\\n\", state);\n *next_state = 2;\n }\n\n break;\n\n\n\tcase 2: // // check destination\n if (dest == 0){\n // go right\n *movements=generate_output(RIGHT,Mag_Advance,max_twist);\n //printf(\"Present State: %d RIGHT \\n\", state);\n *next_state = 3;\n }\n else if (dest == 1){\n // go left\n *movements=generate_output(LEFT,Mag_Advance,max_twist);\n //printf(\"Present State: %d LEFT\\n\", state);\n *next_state = 4;\n }\n else if (dest == 2){\n // go forward \n *movements=generate_output(FORWARD,Mag_Advance,max_twist);\n //printf(\"Present State: %d FORWARD\\n\", state);\n *next_state = 3;\n }\n else if (dest == 3){\n // go forward \n *movements=generate_output(FORWARD,Mag_Advance,max_twist);\n //printf(\"Present State: %d FORWARD\\n\", state);\n *next_state = 4;\n }\n else if (dest == 4){\n // go forward \n *movements=generate_output(FORWARD,Mag_Advance,max_twist);\n //printf(\"Present State: %d FORWARD\\n\", state);\n *next_state = 1;\n }\n break;\n\n\n case 3: // right turn\n *movements=generate_output(RIGHT,Mag_Advance,max_twist);\n //printf(\"Present State: %d TURN RIGHT\\n\", state);\n *next_state = 1;\n break;\n\n\n case 4: // left turn\n *movements=generate_output(LEFT,Mag_Advance,max_twist);\n //printf(\"Present State: %d TURN LEFT\\n\", state);\n *next_state = 1;\n break;\n\n default:\n //printf(\"State %d not defined used \", state);\n *movements=generate_output(STOP,Mag_Advance,max_twist);\n *next_state = 1;\n break;\n\n\n }\n\n return result;\n\n}\n\n\n\n\n" }, { "alpha_fraction": 0.7187391519546509, "alphanum_fraction": 0.7187391519546509, "avg_line_length": 33.369049072265625, "blob_id": "44a421e476b54b70312ac52bf6f516947281ca37", "content_id": "4017526d07a9b56eae6863333551a4f6ae17163a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2887, "license_type": "no_license", "max_line_length": 98, "num_lines": 84, "path": "/catkin_ws/src/clips_ros/src/clips_ros/SimuladorRepresentation.h", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#ifndef TOOLS_SIMULADOR_TOOLS_SRC_SIMULADORREPRESENTATION_H_\n#define TOOLS_SIMULADOR_TOOLS_SRC_SIMULADORREPRESENTATION_H_\n\n#include \"ros/ros.h\"\n\n#include <map>\n#include <vector>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n\n#include \"std_msgs/Bool.h\"\n#include \"std_msgs/String.h\"\n#include \"tf/transform_listener.h\"\n\n#include \"clips_ros/PlanningCmdClips.h\"\n#include \"clips_ros/planning_cmd.h\"\n#include \"clips_ros/StrQueryKDB.h\"\n#include \"clips_ros/InitKDB.h\"\n#include \"clips_ros/clearKDB.h\"\n\n#include <boost/algorithm/string/replace.hpp>\n#include <boost/filesystem/operations.hpp>\n#include <boost/filesystem/path.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\ntypedef struct movements_\n{\n\tfloat twist;\n\tfloat advance;\n}movements;\n\nclass SimuladorRepresentation {\n private:\n ros::NodeHandle * nh;\n\n\tstatic bool busy_clips;\n\tstatic movements output;\n\t\n static ros::Publisher * command_runCLIPS;\n static ros::Publisher * command_clearCLIPS;\n static ros::Publisher * command_resetCLIPS;\n static ros::Publisher * command_factCLIPS;\n static ros::Publisher * command_ruleCLIPS;\n static ros::Publisher * command_agendaCLIPS;\n static ros::Publisher * command_sendCLIPS;\n static ros::Publisher * command_loadCLIPS;\n static ros::Publisher * command_sendAndRunCLIPS;\n static ros::Publisher * command_response;\n\tstatic ros::Subscriber * subClipsToRos;\n static ros::ServiceClient * cliSpechInterpretation;\n static ros::ServiceClient * cliStringInterpretation;\n static ros::ServiceClient * cliStrQueryKDB;\n static ros::ServiceClient * cliInitKDB;\n\tstatic ros::ServiceClient * cliClearKDB;\n\n\n public:\n\n ~SimuladorRepresentation();\n\n static void setNodeHandle(ros::NodeHandle * nh);\n static void runCLIPS(bool enable);\n\tstatic void clearCLIPS(bool enable);\n static void resetCLIPS(bool enable);\n static void factCLIPS(bool enable);\n static void ruleCLIPS(bool enable);\n static void agendaCLIPS(bool enable);\n static void sendCLIPS(std::string command);\n static void loadCLIPS(std::string file);\n static void sendAndRunCLIPS(std::string command);\n static bool initKDB(std::string filePath, bool run, float timeout);\n static bool insertKDB(std::string nameRule, std::vector<std::string> params, int timeout);\n static bool clearKDB(int timeout);\n static bool strQueryKDB(std::string query, std::string &result, int timeout);\n\tstatic void callbackClipsToRos(const clips_ros::PlanningCmdClips::ConstPtr& msg);\n\tstatic bool get_movement(float& advance, float&twist);\n\tstatic void set_busy_clips(bool flag);\n\n};\n\n#endif /* TOOLS_SIMULADOR_TOOLS_SRC_SIMULADORREPRESENTATION_H_ */\n" }, { "alpha_fraction": 0.5477026700973511, "alphanum_fraction": 0.5728537440299988, "avg_line_length": 20.62310028076172, "blob_id": "b5c935df3dcc9983422585e79b04db81dbc72d94", "content_id": "f8b35935c2a2b0a4c0089e84a3393c40a34b5945", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7117, "license_type": "no_license", "max_line_length": 80, "num_lines": 329, "path": "/catkin_ws/src/simulator/src/utilities/random.h", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "/************************************************************************\n*\t\t\t\t\t\t\t\t\t*\n*\trandom.h\t\t\t\t\t\t\t*\n*\t\t\t\t\t\t\t\t\t*\n*\tThis program generates Uniform or Gaussian random numbers.\t*\n*\t\t\t\t\t\t\t\t\t*\n*\t\t\t\t\t\t\t\t\t*\n*\t\t\tJ. Savage \t\t\t\t\t*\n*\t\t\tDEPFI-UNAM\t11-2003\t\t\t\t*\n*\t\t\t\t\t\t\t\t\t*\n*************************************************************************/\t\t\t\t\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <math.h>\n\n#define Lmin 0.0\n#define Lmax 1.0\n#define PERCENTAGE_CHANGE 0.10\n#define MAX_NUM_SENSORS 1024\n\n\n\ntypedef struct _raw{\n int flag;\n int region;\n float x,y,theta[MAX_NUM_SENSORS],sensors[MAX_NUM_SENSORS];\n} Raw;\n\n\n\n// generates a uniform random variable\nfloat generaR(float Min,float Max){\n float n;\n //int BIG= 0x7FFFFFFF;\n int BIG= RAND_MAX;\n\n n=Min+ ((float) random()/(float) BIG ) *(Max-Min);\n\n return n;\n}\n\n\n\nfloat random_gaussian(float mean, float variance,float *gaussian){\n float u1,u2,v1,v2,w,y,sqrt_variance;\n\n sqrt_variance=(float) sqrt(variance);\n\n while(1){\n\n\t// it generates a uniform random variable between 0 to 1\n \tu1=generaR(Lmin,Lmax);\n \tu2=generaR(Lmin,Lmax);\n\n\t//printf(\"u1 %f u2 %f\",u1,u2);\n \tv1=2*u1-1;\n \tv2=2*u2-1;\n \tw=v1*v1+v2*v2;\n\n\t//printf(\" w %f \\n\",w);\n\tif(w < 1) {\n\t\ty=(float) sqrt( ((-2*log(w))/w));\n\t\tgaussian[1]=sqrt_variance*v1*y + mean;\n\t\tgaussian[2]=sqrt_variance*v2*y + mean;\n \t\treturn(1);\n \t}\n }\n\n}\n\n\n\n// it adds noise to the sensors' values\nvoid add_noise_obs(Raw *sensor_vector, int num_sensors, char *path){\n\n int k;\n float noise;\n float gaussian[3];\n float tmp1,tmp2;\n int j;\n FILE *fp;\n char file[300];\n static int flg=0;\n static float mean,variance;\n static float lmin,lmax;\n static int type;\n\n\n\n if(flg==0){\n // Initializes the random generator\n srandom((int)time((time_t *)NULL));\n sprintf(file,\"%srandom_settings_advance_angle_sensors.dat\",path);\n\t/* random_settings_advance_angle_sensors.dat, 0 Uniform PDF; 1 Gaussian PDF\n\t\t0 -0.004 0.004\n\t\t0 0.0 0.03927\n\t\t1 0.003 0.0003\n\t*/\n if((fp=fopen(file,\"r\")) == NULL){\n printf(\"File %s can not be open\\n\",file);\n exit(0);\n }\n printf(\"Random settings file %s\\n\",file);\n // it reads the settings for the advance noise\n // it reads the settings for the angle noise\n\tfor(j=1;j<7;j++){\n \tif( 0 < fscanf(fp,\"%f\",&tmp1))\n \t{}\n\t}\n\n\t// it reads the settings for the sensors noise\n if( 0 < fscanf(fp,\"%d\",&type)){}\n if( 0 < fscanf(fp,\"%f\",&tmp1)){}\n if( 0 < fscanf(fp,\"%f\",&tmp2)){}\n if(type==0){\n lmin=tmp1;\n lmax=tmp2;\n }\n else {\n mean=tmp1;\n variance=tmp2;\n }\n\n fclose(fp);\n flg=1;\n }\n\n \n //printf(\"random num_sensors %d\\n\",num_sensors);\n\n for( k=0; k< num_sensors; k++) {\n\n\tif(type==1) {\n \n\t\t// it generates a Gaussian random variable \n\t\trandom_gaussian(mean,variance,gaussian);\n \tnoise=gaussian[1];\n \t}\n \telse{\n \t// it generates a Uniform random variable\n \tnoise=generaR(lmin,lmax);\n \t}\n\n\t \n //printf(\"sensor(%d) = %f \\n\",k,sensor_vector[0].sensors[k]);\n\t//printf(\"noise %f\\n\",noise);\n sensor_vector[0].sensors[k]=sensor_vector[0].sensors[k]+ noise;\n //printf(\"noise+sensor(%d) = %f \\n\",k,sensor_vector[0].sensors[k]);\n\n }\n\n\n\n}\n\n\n\n\nvoid get_random_advance_angle(float *advance, float *angle, char *path)\n{\n\n float gaussian[3],uniform;\n float tmp1,tmp2;\n int i,dist,num_random;\n FILE *fp;\n char file[300];\n static int flg=0;\n static float mean_a,variance_a;\n static float lmin_a,lmax_a;\n static float mean_t,variance_t;\n static float lmin_t,lmax_t;\n static int type_a,type_t;\n\n\n printf(\"Path %s\\n\",path);\n if(flg==0){\n\t // Initializes the random generator\n \tsrandom((int)time((time_t *)NULL));\n\tsprintf(file,\"%srandom_settings_advance_angle_sensors.dat\",path);\n\tif((fp=fopen(file,\"r\")) == NULL){\n printf(\"File %s can not be open\\n\",file);\n exit(0);\n \t}\n printf(\"Random settings file %s\\n\",file);\n\t// it reads the settings for the advance noise\n if( 0 < fscanf(fp,\"%d\",&type_a)){}\n\tif( 0 < fscanf(fp,\"%f\",&tmp1)){}\n\tif( 0 < fscanf(fp,\"%f\",&tmp2)){}\n\tif(type_a==0){\n\t\tlmin_a=tmp1;\n\t\tlmax_a=tmp2;\n\t}\n\telse {\n\t\tmean_a=tmp1;\n\t\tvariance_a=tmp2;\n\t}\n\t// it reads the settings for the angle noise\n if( 0 < fscanf(fp,\"%d\",&type_t)){}\n\tif( 0 < fscanf(fp,\"%f\",&tmp1)){}\n\tif( 0 < fscanf(fp,\"%f\",&tmp2)){}\n\n\tif(type_t==0){\n\t\tlmin_t=tmp1;\n\t\tlmax_t=tmp2;\n\t}\n\telse {\n\t\tmean_t=tmp1;\n\t\tvariance_t=tmp2;\n\t}\n\n \tfclose(fp);\n\tflg=1;\n }\n\n\n if(type_a==1) {\n // it generates a Gaussian random variable \n\trandom_gaussian(mean_a,variance_a,gaussian);\n //printf(\"Gaussian %f %f\\n\",gaussian[1],gaussian[2]);\n\t*advance=gaussian[1];\n }\n else{\n\t// it generates a Uniform random variable\n uniform=generaR(lmin_a,lmax_a);\n //printf(\"Uniform %f\",uniform);\n\t*advance=uniform;\n }\n\n if(type_t==1) {\n // it generates a Gaussian random variable \n random_gaussian(mean_t,variance_t,gaussian);\n //printf(\"Gaussian %f %f\\n\",gaussian[1],gaussian[2]);\n *angle=gaussian[1];\n }\n else{\n // it generates a Uniform random variable\n uniform=generaR(lmin_t,lmax_t);\n //printf(\"Uniform %f\",uniform);\n *angle=uniform;\n }\n\n //printf(\"random noise advance %f angle %f\\n\",*advance,*angle);\n \n\n}\n\n\n\n\nfloat read_random_percentage(char *path){\n\n FILE *fp;\n char file[300];\n int j;\n float percentage = PERCENTAGE_CHANGE;\n float tmp1;\n int type;\n\n // Initializes the random generator\n srandom((int)time((time_t *)NULL));\n sprintf(file,\"%srandom_settings_advance_angle_sensors.dat\",path);\n if((fp=fopen(file,\"r\")) == NULL){\n printf(\"File %s can not be open\\n\",file);\n\t\t\treturn percentage;\n }\n printf(\"Random settings file %s\\n\",file);\n // it reads the settings for the advance noise\n // it reads the settings for the angle noise\n for(j=1;j<7;j++){\n \tif( 0 < fscanf(fp,\"%f\",&tmp1) ){}\n }\n\n // it reads the settings for the sensors noise\n if( 0 < fscanf(fp,\"%d\",&type)){}\n if( 0 < fscanf(fp,\"%f\",&tmp1)){}\n if( 0 < fscanf(fp,\"%f\",&tmp1)){}\n if( 0 < fscanf(fp,\"%f\",&percentage)){}\n\n fclose(fp);\n\n return percentage;\n\n}\n\n \n\n\n\n\nint change_bits_random(int value,int num_bits, char *path){\n\n int new_value;\n int num_bits_mutation;\n int i,j,k;\n int mask;\n float random;\n static float percentage;\n static int flg=1;\n\n if(flg == 1){\n \tpercentage=read_random_percentage(path);\n\tflg=0;\n }\n\n new_value=value;\n random = generaR(0.0,1.0);\n //printf(\"random %f percentage %f\\n\",random,percentage);\n\n if(random > percentage) return (new_value);\n\n num_bits_mutation=num_bits;\n k= (int) generaR(0.0,num_bits_mutation);\n //printf(\"Max. num_bits_change %d num_bits_change %d\\n\",num_bits_mutation,k+1);\n\n for(j=0;j<= k; j++){\n i= (int) generaR(0.0,num_bits);\n\tmask =(1 << i);\n\tif( (new_value & mask ) == 0) new_value = new_value | mask;\n\telse {\n\t\tnew_value = new_value & (~mask);\n\t} \n //printf(\"num %d bit_changed %d\\n\",j,i);\n }\n\n return(new_value);\n\n}\n\n\n\n" }, { "alpha_fraction": 0.5911789536476135, "alphanum_fraction": 0.6162001490592957, "avg_line_length": 52.5, "blob_id": "1461c4253857fc183c5d68b63d3351e02e077734", "content_id": "a52f8f64689323e97f350931d96c4d44e7ad61eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2358, "license_type": "no_license", "max_line_length": 151, "num_lines": 44, "path": "/catkin_ws/src/simulator/src/gui/environment.py", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "\n\n\nclass environment():\n\n\n\tdef print_topological_map(self): # It plots the topological map of the current map and show \"please wait\" message\n\t\twait_bg=w.create_rectangle(self.canvasX/2-30-120 ,self.canvasY/2-50 ,self.canvasX/2-30+120 ,self.canvasY/2+50 ,fill=\"white\")\n\t\twait = w.create_text(self.canvasX/2-30,self.canvasY/2,fill=\"darkblue\",font=\"Calibri 20 bold\",\n\t text=\"PLEASE WAIT ...\")\n\t\tself.w.update()\n\t\tself.print_topological_map_lines()\n\t\tself.w.delete(wait)\n\t\tself.w.delete(wait_bg)\n\t\tself.plot_robot()\n\n\tdef print_topological_map_lines(self): # It plots the topological map of the current map \n\t\tself.clear_topological_map();\n\t\tself.varShowNodes = True\n\t\t#self.w.delete(self.nodes_image)\t\n\t\tnodes_coords = []\n\t\timage = Image.new('RGBA', (self.canvasX, self.canvasY))\n\t\tdraw = ImageDraw.Draw(image)\n\t\tmap_file = open(self.rospack.get_path('simulator')+'/src/data/'+self.entryFile.get()+'/'+self.entryFile.get()+'.top','r') #Open file\n\t\tlines = map_file.readlines() #Split the file in lines\n\t\tfor line in lines: \t\t\t\t\t\t\t\t\t #To read line by line\n\t\t\twords = line.split()\t #To separate words \n\t\t\tif words:\t\t\t\t\t\t\t\t\t\t #To avoid empty lines\t\t\t\t\t\t\t\n\t\t\t\tif words[0] == \"(\":\t\t\t\t\t\t\t #To avoid coments\n\t\t\t\t\tif words[1] == \"num\":\t\t\t #To get world dimensions\n\t\t\t\t\t\tnumNode = float (words[3])\t\n\t\t\t\t\telif words[1] == \"node\":\t\t\t\t #to get polygons vertex\n\t\t\t\t\t\tnumNode = words[2]\n\t\t\t\t\t\tnodeXm = float (words[3]) * self.canvasX / self.mapX\n\t\t\t\t\t\tnodeYm = self.canvasY - ( float (words[4]) * self.canvasY) / self.mapY\n\t\t\t\t\t\tnodes_coords.append([nodeXm,nodeYm])\n\t\t\t\t\t\tdraw.ellipse((nodeXm - 3 ,nodeYm - 3 ,nodeXm + 3 ,nodeYm + 3), outline = '#9C4FDB', fill = '#9C4FDB')\n\t\t\t\t\t\tdraw.text( (nodeXm,nodeYm + 2) ,fill = \"darkblue\" ,text = str(numNode) )\n\t\t\t\t\telif words[1] == \"connection\":\t\t\t\t #to get polygons vertex\n\t\t\t\t\t\tc1 = int(words[2])\n\t\t\t\t\t\tc2 = int(words[3])\n\t\t\t\t\t\tdraw.line( (nodes_coords[c1][0],nodes_coords[c1][1] ,nodes_coords[c2][0] ,nodes_coords[c2][1] ) , fill = '#9C4FDB')\n\t\t\t\t\t\t\t\n\t\tmap_file.close()\n\t\timage.save(self.rospack.get_path('simulator')+'/src/gui/nodes.png')\n\t\tself.gif1 = PhotoImage( file = self.rospack.get_path('simulator')+'/src/gui/nodes.png')\n\t\tself.nodes_image = self.w.create_image(self.canvasX / 2, self.canvasY / 2, image = self.gif1)\n\n" }, { "alpha_fraction": 0.6518881916999817, "alphanum_fraction": 0.6570867896080017, "avg_line_length": 37.041046142578125, "blob_id": "89eb7e9f3d959d060e685c3307beea2b064d1baa", "content_id": "7f80b2e2ea2c00ba946af2ba0da381a838dd93a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10195, "license_type": "no_license", "max_line_length": 129, "num_lines": 268, "path": "/catkin_ws/src/clips_ros/src/SimuladorRepresentation.cpp", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "/***********************************************\n* *\n* SimuladorRepresentation.cpp *\n* *\n* Julio Cruz *\n* Jesus Savage *\n* *\n* Bio-Robotics Laboratory *\n* UNAM, 2019 *\n* *\n* *\n************************************************/\n\n\n#include \"clips_ros/SimuladorRepresentation.h\"\n\nros::Publisher * SimuladorRepresentation::command_runCLIPS;\nros::Publisher * SimuladorRepresentation::command_clearCLIPS;\nros::Publisher * SimuladorRepresentation::command_resetCLIPS;\nros::Publisher * SimuladorRepresentation::command_factCLIPS;\nros::Publisher * SimuladorRepresentation::command_ruleCLIPS;\nros::Publisher * SimuladorRepresentation::command_agendaCLIPS;\nros::Publisher * SimuladorRepresentation::command_sendCLIPS;\nros::Publisher * SimuladorRepresentation::command_loadCLIPS;\nros::Publisher * SimuladorRepresentation::command_sendAndRunCLIPS;\nros::Publisher * SimuladorRepresentation::command_response;\nros::Subscriber * SimuladorRepresentation::subClipsToRos;\nros::ServiceClient * SimuladorRepresentation::cliSpechInterpretation;\nros::ServiceClient * SimuladorRepresentation::cliStringInterpretation;\nros::ServiceClient * SimuladorRepresentation::cliStrQueryKDB;\nros::ServiceClient * SimuladorRepresentation::cliInitKDB;\nros::ServiceClient * SimuladorRepresentation::cliClearKDB;\n\nbool SimuladorRepresentation::busy_clips = false;\nmovements SimuladorRepresentation::output;\nusing namespace boost::algorithm;\n\nSimuladorRepresentation::~SimuladorRepresentation(){\n delete command_runCLIPS;\n delete command_clearCLIPS;\n delete command_resetCLIPS;\n delete command_factCLIPS;\n delete command_ruleCLIPS;\n delete command_agendaCLIPS;\n delete command_sendCLIPS;\n delete command_loadCLIPS;\n delete command_sendAndRunCLIPS;\n delete cliSpechInterpretation;\n delete cliStringInterpretation;\n delete cliStrQueryKDB;\n delete cliInitKDB;\n delete cliClearKDB;\n delete command_response;\n delete subClipsToRos;\n}\n\nvoid SimuladorRepresentation::setNodeHandle(ros::NodeHandle * nh) {\n command_runCLIPS = new ros::Publisher(nh->advertise<std_msgs::Bool>(\"/planning_rm/command_runCLIPS\", 1));\n command_clearCLIPS = new ros::Publisher(nh->advertise<std_msgs::Bool>(\"/planning_rm/command_clearCLIPS\", 1));\n command_resetCLIPS = new ros::Publisher(nh->advertise<std_msgs::Bool>(\"/planning_rm/command_resetCLIPS\", 1));\n command_factCLIPS = new ros::Publisher(nh->advertise<std_msgs::Bool>(\"/planning_rm/command_factCLIPS\", 1));\n command_ruleCLIPS = new ros::Publisher(nh->advertise<std_msgs::Bool>(\"/planning_rm/command_ruleCLIPS\", 1));\n command_agendaCLIPS = new ros::Publisher(nh->advertise<std_msgs::Bool>(\"/planning_rm/command_agendaCLIPS\", 1));\n command_sendCLIPS = new ros::Publisher(nh->advertise<std_msgs::String>(\"/planning_rm/command_sendCLIPS\", 1));\n command_loadCLIPS = new ros::Publisher(nh->advertise<std_msgs::String>(\"/planning_rm/command_loadCLIPS\", 1));\n command_sendAndRunCLIPS = new ros::Publisher(nh->advertise<std_msgs::String>(\"/planning_rm/command_sendAndRunCLIPS\", 1));\n cliSpechInterpretation = new ros::ServiceClient(nh->serviceClient<clips_ros::planning_cmd>(\"/planning_rm/spr_interpreter\"));\n cliStringInterpretation = new ros::ServiceClient(nh->serviceClient<clips_ros::planning_cmd>(\"/planning_rm/str_interpreter\"));\n cliStrQueryKDB = new ros::ServiceClient(nh->serviceClient<clips_ros::StrQueryKDB>(\"/planning_rm/str_query_KDB\"));\n cliInitKDB = new ros::ServiceClient(nh->serviceClient<clips_ros::InitKDB>(\"/planning_rm/init_kdb\"));\n cliClearKDB = new ros::ServiceClient(nh->serviceClient<clips_ros::clearKDB>(\"/planning_rm/clear_kdb\"));\n command_response = new ros::Publisher(nh->advertise<clips_ros::PlanningCmdClips>(\"/planning_rm/command_response\", 1));\n \n subClipsToRos = new ros::Subscriber(nh->subscribe(\"/planning_rm/clips_to_ros\", 1, callbackClipsToRos));\n}\n\nvoid SimuladorRepresentation::runCLIPS(bool enable){\n std_msgs::Bool msg;\n msg.data = enable;\n command_runCLIPS->publish(msg);\n boost::this_thread::sleep(boost::posix_time::milliseconds(400));\n}\n\nvoid SimuladorRepresentation::clearCLIPS(bool enable){\n std_msgs::Bool msg;\n msg.data = enable;\n command_clearCLIPS->publish(msg);\n boost::this_thread::sleep(boost::posix_time::milliseconds(400));\n}\n\nvoid SimuladorRepresentation::resetCLIPS(bool enable){\n std_msgs::Bool msg;\n msg.data = enable;\n command_resetCLIPS->publish(msg);\n boost::this_thread::sleep(boost::posix_time::milliseconds(400));\n}\n\nvoid SimuladorRepresentation::factCLIPS(bool enable){\n std_msgs::Bool msg;\n msg.data = enable;\n command_factCLIPS->publish(msg);\n boost::this_thread::sleep(boost::posix_time::milliseconds(400));\n}\n\nvoid SimuladorRepresentation::ruleCLIPS(bool enable){\n std_msgs::Bool msg;\n msg.data = enable;\n command_ruleCLIPS->publish(msg);\n boost::this_thread::sleep(boost::posix_time::milliseconds(400));\n}\n\nvoid SimuladorRepresentation::agendaCLIPS(bool enable){\n std_msgs::Bool msg;\n msg.data = enable;\n command_agendaCLIPS->publish(msg);\n boost::this_thread::sleep(boost::posix_time::milliseconds(400));\n}\n\nvoid SimuladorRepresentation::sendCLIPS(std::string command){\n std_msgs::String msg;\n msg.data = command;\n command_sendCLIPS->publish(msg);\n boost::this_thread::sleep(boost::posix_time::milliseconds(400));\n}\n\nvoid SimuladorRepresentation::loadCLIPS(std::string file)\n{\n std_msgs::String msg;\n msg.data = file;\n command_loadCLIPS->publish(msg);\n boost::this_thread::sleep(boost::posix_time::milliseconds(400));\n}\n\nvoid SimuladorRepresentation::sendAndRunCLIPS(std::string command){\n std_msgs::String msg;\n msg.data = command;\n command_sendAndRunCLIPS->publish(msg);\n boost::this_thread::sleep(boost::posix_time::milliseconds(400));\n}\n\nbool SimuladorRepresentation::strQueryKDB(std::string query, std::string &result, int timeout){\n clips_ros::StrQueryKDB srv;\n bool success = true;\n if(timeout > 0)\n success = ros::service::waitForService(\"/planning_rm/str_query_KDB\", timeout);\n if (success) {\n clips_ros::StrQueryKDB srv;\n srv.request.query = query;\n if (cliStrQueryKDB->call(srv)) {\n std::string queryResult = srv.response.result;\n std::cout << \"SimuladorRepresentation.->Query Result:\" << queryResult << std::endl;\n if(queryResult.compare(\"None\") == 0){\n std::cout << \"SimuladorRepresentation.->The query not success.\" << std::endl;\n result = \"\";\n return false;\n }\n result = queryResult;\n return true;\n }\n }\n std::cout << \"SimuladorRepresentation.->Failed to call service of str_query_kdb\" << std::endl;\n return false;\n}\n\nbool SimuladorRepresentation::clearKDB(int timeout){\n bool success = true;\n if(timeout > 0)\n success = ros::service::waitForService(\"/planning_rm/clear_kdb\", timeout);\n if (success) {\n clips_ros::clearKDB srv;\n srv.request.clear = true;\n if (cliClearKDB->call(srv)) {\n std::cout << \"SimuladorRepresentation.->Clear KDB\" << std::endl;\n return true;\n }\n }\n std::cout << \"SimuladorRepresentation.->Failed to call service of clear_kdb\" << std::endl;\n return false;\n}\n\nbool SimuladorRepresentation::initKDB(std::string filePath, bool run, float timeout){\n bool success = true;\n if(timeout > 0)\n success = ros::service::waitForService(\"/planning_rm/init_kdb\", timeout);\n if (success) {\n clips_ros::InitKDB srv;\n srv.request.filePath = filePath;\n srv.request.run = run;\n if (cliInitKDB->call(srv)) {\n std::cout << \"SimuladorRepresentation.->Init KDB\" << std::endl;\n return true;\n }\n }\n std::cout << \"SimuladorRepresentation.->Failed to call service of init_kdb\" << std::endl;\n return false;\n}\n\nbool SimuladorRepresentation::insertKDB(std::string nameRule, std::vector<std::string> params, int timeout){\n std::stringstream ss;\n std::string result;\n ss << \"(assert( \" << nameRule << \" \";\n for(int i = 0; i < params.size(); i++){\n ss << params[i] << \" \";\n }\n ss << \"1))\";\n bool success = SimuladorRepresentation::strQueryKDB(ss.str(), result, timeout);\n if(success)\n return true;\n return false;\n}\n\n\n\nvoid SimuladorRepresentation::callbackClipsToRos(const clips_ros::PlanningCmdClips::ConstPtr& msg){\n std::cout << \"--------- Clips to Ros-----\" << std::endl;\n std::cout << \"name: \" << msg->name << std::endl;\n std::cout << \"params: \" << msg->params << std::endl;\n \n int num;\n float status;\n float advance, rotation;\n char action[30];\n\n \n clips_ros::PlanningCmdClips responseMsg;\n responseMsg.name = msg->name;\n responseMsg.params = msg->params;\n responseMsg.id = msg->id;\n\n std::stringstream ss;\n std::vector<std::string> tokens;\n std::string str = responseMsg.params;\n split(tokens, str, is_any_of(\" \"));\n\n ss << tokens[0];\n for(int i=1 ; i<tokens.size(); i++)\n ss << \" \"<< tokens[i];\n\n std::cout << \"CLIPS Message: \" << ss.str() << std::endl;\n\n //Here you need to put your code for make an action, then send a response to CLIPS if succeeded or not\n sscanf(responseMsg.params.c_str(),\"%s%d%f%f%f\",action,&num,&rotation,&advance,&status);\n output.advance=advance;\n output.twist=rotation;\n\n \n //response to CLIPS\n responseMsg.params = \"ROS_RESPONSE\"; \n responseMsg.successful = 1;\n command_response->publish(responseMsg);\n busy_clips = false;\n\t\n\t\n}\n\nbool SimuladorRepresentation::get_movement(float& advance, float& twist){\n\tif (busy_clips)\n\t\treturn false;\n\n\tadvance = output.advance;\n\ttwist = output.twist;\t\n\n\treturn true;\n}\n\nvoid SimuladorRepresentation::set_busy_clips(bool flag){\n\tbusy_clips = flag;\n}\n" }, { "alpha_fraction": 0.4993261396884918, "alphanum_fraction": 0.5080862641334534, "avg_line_length": 31.604394912719727, "blob_id": "0d4773158fe97181f0a0f3409a6a02d3dc3a4087", "content_id": "e52e45f301bb4f6bc777aea1b1c28cf51b46b474", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2968, "license_type": "no_license", "max_line_length": 106, "num_lines": 91, "path": "/catkin_ws/src/simulator/src/simulator_physics/light_node.cpp", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "\n/***********************************************\n* *\n* light_node.cpp *\n* *\n* Jesus Savage *\n* Diego Cordero *\n* *\n* Bio-Robotics Laboratory *\n* UNAM, 2019 *\n* *\n* *\n************************************************/\n\n\n\n#include \"ros/ros.h\"\n#include \"simulator/Parameters.h\"\n#include \"../utilities/simulator_structures.h\"\n#include \"simulator/simulator_light.h\"\n\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\nparameters params;\n\nvoid paramsCallback(const simulator::Parameters::ConstPtr& paramss)\n{\n params.robot_x = paramss->robot_x ;\n params.robot_y = paramss->robot_y ;\n params.robot_theta = paramss->robot_theta ; \n params.robot_radio = paramss->robot_radio ; \n params.robot_max_advance = paramss->robot_max_advance ; \n params.robot_turn_angle = paramss->robot_turn_angle ; \n params.laser_num_sensors = paramss->laser_num_sensors ; \n params.laser_origin = paramss->laser_origin ; \n params.laser_range = paramss->laser_range ; \n params.laser_value = paramss->laser_value ; \n strcpy(params.world_name ,paramss -> world_name.c_str()); \n params.noise = paramss->noise ; \n params.run = paramss->run ; \n params.light_x = paramss->light_x;\n params.light_y = paramss->light_y;\n params.behavior = paramss->behavior; \n\n}\n\n\n\nbool get_intensities(simulator::simulator_light::Request &req ,simulator::simulator_light::Response &res)\n{\n \n\tfloat x,y;\n\tint sensor;\n\tfloat step = 3.1415/4; \n\tfloat values[8];\n\tint i;\n\n\tx = params.robot_radio * cos(params.robot_theta) + params.robot_x;\n y = params.robot_radio * sin( params.robot_theta ) + params.robot_y;\n res.values[0] = values[0] = 1 / sqrt( pow(x - params.light_x ,2) + pow(y - params.light_y,2));\n\n\tfor(int i = 1; i < 8; i++)\n\t{\n\t\tx = params.robot_radio * cos( params.robot_theta + i * step) + params.robot_x;\n\t\ty = params.robot_radio * sin( params.robot_theta + i * step) + params.robot_y;\n\t\tres.values[i] = values[i] = 1 / sqrt( pow(x - params.light_x ,2) + pow(y - params.light_y,2));\n\t}\n\tsensor = 0;\n\n\tfor(int i = 1; i < 8; i++)\n\t{\n\t\tif( values[i] > values[sensor])\n\t\t\tsensor = i;\n\t}\n\treturn true;\n}\n\n\n\n\nint main(int argc, char *argv[])\n{\t\n\tros::init(argc, argv, \"simulator_light_node\");\n\tros::NodeHandle n;\n\tros::ServiceServer service = n.advertiseService(\"simulator_light\",get_intensities);\n\tros::Subscriber params_sub = n.subscribe(\"simulator_parameters_pub\", 0, paramsCallback);\n\tros::spin();\n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.6795367002487183, "alphanum_fraction": 0.6843629479408264, "avg_line_length": 28.571428298950195, "blob_id": "b5461d58cc4414559214bccf21c72e1b7a224bb8", "content_id": "132e68eb8e8875c4a846ba9be37d9e02d04256e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1036, "license_type": "no_license", "max_line_length": 163, "num_lines": 35, "path": "/catkin_ws/src/simulator/src/simulator_physics/find_obj_node.cpp", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <tf/transform_broadcaster.h>\n#include <nav_msgs/Odometry.h>\n\n#include \"ros/ros.h\"\n#include <ros/package.h>\n#include \"simulator/Parameters.h\"\n#include \"../utilities/simulator_structures.h\"\n#include \"simulator/simulator_find_obj.h\"\n#include \"clips_ros/SimuladorRepresentation.h\"\n#include <string.h>\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\nbool find_object(simulator::simulator_find_obj::Request &req ,simulator::simulator_find_obj::Response &res)\n{\n\n char str[300];\n sprintf(str,\"(assert (answer %s command %s %s %f %f %f %s 1))\",req.ROS_System.c_str(),req.action.c_str(),req.object.c_str(),req.x,req.y,req.z,req.arm.c_str());\n printf(\"\\nSend fact %s\\n\",str);\n res.answer = str;\n\n return true;\n}\n\nint main(int argc, char *argv[])\n{\n ros::init(argc, argv, \"simulator_find_obj\");\n ros::NodeHandle n;\n SimuladorRepresentation::setNodeHandle(&n);\n ros::ServiceServer service = n.advertiseService(\"simulator_find_obj\", find_object);\n ros::spin();\n return 0;\n}\n\n" }, { "alpha_fraction": 0.5666459798812866, "alphanum_fraction": 0.5795876979827881, "avg_line_length": 23.076492309570312, "blob_id": "e6caa45804573eb88ef0177f180331c0909ec10f", "content_id": "7310da8f01b932d9f0f48fa511347020ee24e33c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12904, "license_type": "no_license", "max_line_length": 113, "num_lines": 536, "path": "/catkin_ws/src/simulator/src/motion_planner/motion_planner_utilities.h", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#include \"ros/ros.h\"\n#include \"simulator/Parameters.h\"\n#include \"simulator/Laser_values.h\"\n#include \"sensor_msgs/LaserScan.h\"\n#include \"simulator/simulator_set_light_position.h\"\n#include \"simulator/simulator_stop.h\"\n#include \"simulator/simulator_robot_step.h\"\n#include \"simulator/simulator_parameters.h\"\n#include \"simulator/simulator_robot_laser_values.h\"\n#include \"simulator/simulator_base.h\"\n#include \"simulator/simulator_laser.h\"\n#include \"simulator/simulator_light.h\"\n#include \"simulator/simulator_algorithm_result.h\"\n#include \"simulator/simulator_MoveRealRobot.h\"\n#include \"simulator/simulator_object_interaction.h\"\n#include <sensor_msgs/LaserScan.h>\n#include <std_msgs/Int16MultiArray.h>\n#include <string.h>\n\n#define GRASP 1\n#define RELEASE 0\n\n#define STOP 0\n#define FORWARD 1\n#define BACKWARD 2\n#define LEFT 3\n#define RIGHT 4\n\nnext_position next;\nparameters params;\nint new_simulation = 1;\nfloat lasers[512];\nint line_sensors[3];\n\nmovement generate_output(int out ,float advance ,float twist)\n{\n\n movement output;\n\n switch(out) {\n\n case 0: // Stop\n output.advance = 0.0f;\n output.twist = 0.0f;\n //printf(\"STOP\\n\");\n break;\n\n case 1: // Forward\n output.advance = advance;\n output.twist = 0.0f;\n //printf(\"FORWARD\\n\");\n break;\n\n case 2: // backward\n output.advance = -advance;\n output.twist = 0.0f;\n //printf(\"BACKWARD\\n\");\n break;\n\n case 3:// Turn left\n output.advance = 0.0f;\n output.twist = twist;\n //printf(\"LEFT\\n\");\n break;\n\n case 4: // Turn right\n output.advance = 0.0f;\n output.twist = -twist;\n printf(\"RIGHT %f\\n\",output.twist);\n break;\n\n default:\n printf(\"Output %d not defined used \", out);\n output.advance = 0.0f;\n output.twist = 0.0f;\n break;\n }\n\n return(output);\n\n}\n\n\nvoid parametersCallback(const simulator::Parameters::ConstPtr& paramss)\n{\n params.robot_x = paramss->robot_x ;\n params.robot_y = paramss->robot_y ;\n params.robot_theta = paramss->robot_theta ;\n params.robot_radio = paramss->robot_radio ;\n params.robot_max_advance = paramss->robot_max_advance ;\n params.robot_turn_angle = paramss->robot_turn_angle ;\n params.laser_num_sensors = paramss->laser_num_sensors ;\n params.laser_origin = paramss->laser_origin ;\n params.laser_range = paramss->laser_range ;\n params.laser_value = paramss->laser_value ;\n strcpy(params.world_name ,paramss -> world_name.c_str());\n params.noise = paramss->noise ;\n params.run = paramss->run ;\n params.light_x = paramss->light_x;\n params.light_y = paramss->light_y;\n params.behavior = paramss->behavior;\n params.steps = paramss->steps;\n params.useRealRobot = paramss->useRealRobot;\n params.useLidar = paramss->useLidar;\n params.useSArray = paramss->useSArray;\n\n}\n\n\n/// GUI interaction\n\n\nint stop()\n{\n ros::NodeHandle n;\n ros::ServiceClient client;\n simulator::simulator_stop srv;\n client = n.serviceClient<simulator::simulator_stop>(\"simulator_stop\");\n srv.request.stop = true;\n\n if ( !client.call(srv) )\n ROS_ERROR(\"Failed to call service simulator_stop\");\n\n return 1;\n}\n\nbool object_interaction(int action, char name[50])\n{\n ros::NodeHandle n;\n ros::ServiceClient client;\n simulator::simulator_object_interaction srv;\n client = n.serviceClient<simulator::simulator_object_interaction>(\"simulator_object_interaction\");\n std::string s;\n s=name;\n srv.request.name = s;\n srv.request.grasp = action;\n\n if( !client.call(srv) )\n {\n ROS_ERROR(\"Failed to call service simulator_object_interaction\");\n }\n printf(\"%d\\n\",srv.response.done );\n return srv.response.done;\n}\n\n\nint set_light_position(float x, float y)\n{\n ros::NodeHandle n;\n ros::ServiceClient client;\n simulator::simulator_set_light_position srv;\n client = n.serviceClient<simulator::simulator_set_light_position>(\"simulator_set_light_position\");\n srv.request.light_x = x;\n srv.request.light_y = y;\n\n if( !client.call(srv) )\n {\n ROS_ERROR(\"Failed to call service simulator_set_light_position\");\n }\n return 1;\n}\n\n\nint print_algorithm_graph (step *steps )\n{\n ros::NodeHandle n;\n ros::ServiceClient client;\n simulator::simulator_algorithm_result srv;\n client = n.serviceClient<simulator::simulator_algorithm_result>(\"simulator_print_graph\"); //create the client\n\n for(int i = 0; i < 200; i++)\n srv.request.nodes_algorithm[i] = steps[i].node;\n\n if( !client.call(srv) )\n ROS_ERROR(\"Failed to call service simulator_print_graph\");\n\n return 1;\n}\n\n//// Light Functions\n\nint get_light_values(float *intensity, float *values)\n{\n int sensor;\n ros::NodeHandle n;\n ros::ServiceClient client;\n simulator::simulator_light srv;\n client = n.serviceClient<simulator::simulator_light>(\"simulator_light\"); //create the client\n srv.request.req = 1;\n\n if ( client.call(srv) )\n {\n for(int i = 0; i < 8; i++)\n values[i] = srv.response.values[i];\n\n sensor = 0;\n\n for(int i = 1; i < 8; i++)\n {\n if( values[i] > values[sensor])\n sensor = i;\n }\n *intensity = values[sensor];\n }\n else\n {\n ROS_ERROR(\"Failed to call service simulator_light\");\n }\n}\n\nint get_light_values_RealRobot(float *intensity, float *values)\n{\n int sensor;\n ros::NodeHandle n;\n ros::ServiceClient client;\n simulator::simulator_light srv;\n client = n.serviceClient<simulator::simulator_light>(\"simulator_light_RealRobot\"); //create the client\n srv.request.req = 1;\n\n if ( client.call(srv) )\n {\n for(int i = 0; i < 8; i++)\n values[i] = srv.response.values[i];\n\n sensor = 0;\n\n for(int i = 1; i < 8; i++)\n {\n if( values[i] > values[sensor])\n sensor = i;\n }\n *intensity = values[sensor];\n }\n else\n {\n ROS_ERROR(\"Failed to call service simulator_light_RealRobot\");\n }\n}\n\nint quantize_light(float *light_values)\n{\n int sensor = 0;\n\n for(int i = 1; i < 8; i+=2 )\n {\n if( light_values[i] > light_values[sensor] )\n sensor = i;\n }\n //printf(\"biggest value sensor %d %f\\n\",sensor,light_values[sensor]);\n if(sensor == 0)\n return 2;\n else if(sensor == 1)\n return 3;\n else if(sensor == 3)\n return 1;\n else if(sensor == 5)\n return 0;\n else if(sensor == 7)\n return 2;\n else\n return 0;\n}\n\n\n//////LASER Functions\n\nint quantize_laser_noise(float *observations, int size, float laser_value )\n{\n /*\n It quantizes the inputs\n */\n int a,b,cta;\n int iz,de,salida;\n int j;\n\n iz = de = salida = 0;\n if( size % 2 != 0)\n {\n a = ( size - 1 ) / 2;\n b = a + 1;\n }\n else\n {\n a = b = size / 2;\n }\n\n cta = 0;\n for (int i = b; i < size ; i++ ) //izquierda\n {\n if( observations[i] < laser_value )\n cta++;\n if( cta >= size*.4 )\n {\n iz = 2;\n break;\n }\n }\n\n cta = 0;\n for (int i = 0; i < a ; i++ ) //derecha\n {\n if( observations[i] < laser_value )\n cta++;\n if( cta >= size*.4 )\n {\n de = 1;\n break;\n }\n }\n\n return iz + de ;\n}\n\nint quantize_laser(float *observations, int size, float laser_value )\n{\n /*\n It quantizes the inputs\n */\n int a,b;\n int iz,de,salida;\n int j;\n\n iz = de = salida = 0;\n if( size % 2 != 0)\n {\n a = ( size - 1 ) / 2;\n b = a + 1;\n }\n else\n {\n a = b = size / 2;\n }\n\n for (int i = b; i < size ; i++ ) //izquierda\n {\n if( observations[i] < laser_value )\n {\n iz = 2;\n break;\n }\n }\n\n for (int i = 0; i < a ; i++ ) //derecha\n {\n if( observations[i] < laser_value )\n {\n de = 1;\n break;\n }\n }\n\n return iz + de ;\n}\n\nvoid laserCallback(const sensor_msgs::LaserScan::ConstPtr& msg)\n{\n /*\n This functions returns the lidars value acoording to gui settings\n */\n double PI;\n double K1;\n double theta;\n double ranges;\n double inc_angle;\n double init_angle;\n double sensors[512];\n double complete_range;\n int index;\n int num_points;\n int range_laser;\n int num_sensors;\n\n if(params.useLidar)\n {\n num_points = 512;\n PI = 3.1415926535;\n range_laser = 360;//240;\n complete_range = range_laser * PI / 180;\n K1 = complete_range / num_points;\n num_sensors = params.laser_num_sensors;\n ranges = params.laser_range;\n init_angle = params.laser_origin;\n inc_angle = ranges / num_sensors;\n theta = init_angle;\n\n for(int j = 0, k = 1 ; j < num_sensors; j++, k++)\n {\n index = int ( ( theta * 256 ) / 1.5707 ) + 256;\n lasers[j] = float( msg->ranges[index] );\n theta = k * inc_angle + init_angle;\n }\n }else\n {\n for(int j = 0 ; j < params.laser_num_sensors ; j++)\n {\n lasers[j] = float( msg->ranges[j] );\n }\n }\n \n\n\n}\n\nvoid lineSensorsCallback(const std_msgs::Int16MultiArray::ConstPtr& msg){\n line_sensors[0] = msg->data[0];\n line_sensors[1] = msg->data[1];\n line_sensors[2] = msg->data[2];\n}\n\nint get_lidar_values(float *lasers, float robot_x ,float robot_y, float robot_theta, bool useRealRobot)\n{\n ros::NodeHandle n;\n ros::ServiceClient client;\n\n simulator::simulator_laser srv;\n client = n.serviceClient<simulator::simulator_laser>(\"simulator_laser_serv\"); //create the client\n\n srv.request.robot_x = robot_x;\n srv.request.robot_y = robot_y;\n srv.request.robot_theta = robot_theta;\n\n if (client.call(srv))\n {\n for(int i = 0; i < 512; i++)\n lasers[i] = srv.response.sensors[i];\n }\n else\n {\n ROS_ERROR(\"Failed to call service simulator_robot_laser_values\");\n }\n\n return 1;\n}\n\n\n/// BASE\n\nint move_gui(float angle ,float distance ,next_position *next,float lidar_readings[512] )\n{\n ros::NodeHandle n;\n ros::ServiceClient client;\n simulator::simulator_robot_step srv;\n client = n.serviceClient<simulator::simulator_robot_step>(\"simulator_robot_step\"); //create the client\n\n srv.request.theta = angle;\n srv.request.distance = distance;\n\n for(int i = 0; i < 512; i++ )\n srv.request.sensors[i] = lidar_readings[i];\n\n if (client.call(srv))\n {\n next->robot_x = srv.response.robot_x;\n next->robot_y = srv.response.robot_y;\n next->robot_theta =srv.response.theta;\n }\n else\n {\n ROS_ERROR(\"Failed to call service simulator_robot_step\");\n\n }\n\n return 1;\n}\n\n\nint move_RealRobot(float theta,float distance)\n{\n ros::NodeHandle n;\n ros::ServiceClient client;\n simulator::simulator_MoveRealRobot srv;\n client = n.serviceClient<simulator::simulator_MoveRealRobot>(\"simulator_move_RealRobot\");\n srv.request.theta = theta;\n srv.request.distance = distance;\n\n if (client.call(srv))\n {\n if(srv.response.done)\n printf(\"Robot move done \\n\");\n else\n printf(\"Robot move fail \\n\");\n }\n else\n {\n ROS_ERROR(\"Failed to call service simulator_move_RealRobot\");\n\n }\n\n return 1;\n}\n\n\n\nvoid check_collision(float theta ,float distance ,int new_simulation,float *final_theta,float *final_distance )\n{\n ros::NodeHandle n;\n ros::ServiceClient client;\n simulator::simulator_base srv;\n client = n.serviceClient<simulator::simulator_base>(\"simulator_base\"); //create the client\n\n srv.request.x1 = next.robot_x;\n srv.request.y1 = next.robot_y;\n srv.request.orientation = next.robot_theta;\n srv.request.theta = theta;\n srv.request.distance = distance;\n srv.request.new_simulation =new_simulation;\n\n if (client.call(srv))\n {\n *final_distance = srv.response.distance;\n *final_theta = srv.response.theta;\n\n //printf(\"TTTTTdistance: %f , req %f \\n\",srv.response.distance ,distance );\n }\n else\n {\n *final_distance = 0;\n *final_theta = 0;\n ROS_ERROR(\"Failed to call service simulator_base\");\n }\n\n \n}\n\n\nint move_robot(float theta,float advance,float lidar_readings[512] )\n{\n float final_distance,final_theta;\n check_collision(theta ,advance ,new_simulation,&final_theta,&final_distance);\n\n move_gui(final_theta ,final_distance ,&next,lidar_readings);\n if(params.useRealRobot)\n move_RealRobot(theta,advance);\n ros::spinOnce();\n return 1;\n}" }, { "alpha_fraction": 0.7916254997253418, "alphanum_fraction": 0.7930080890655518, "avg_line_length": 32.31578826904297, "blob_id": "6b0c73eeec39ff8d5121ec97fcbd9e2602f0b11c", "content_id": "e5ee2af96339df09d854be10000f5d67b92f05f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 5063, "license_type": "no_license", "max_line_length": 78, "num_lines": 152, "path": "/catkin_ws/src/simulator/CMakeLists.txt", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(simulator)\n\n## Compile as C++11, supported in ROS Kinetic and newer\nadd_compile_options(-std=c++11)\n\n\nfind_package(catkin REQUIRED COMPONENTS\n roscpp\n rospy\n std_msgs\n sensor_msgs\n nav_msgs\n geometry_msgs\n tf\n message_generation\n clips_ros\n joy\n image_transport\n)\n\n\nfind_package(CGAL REQUIRED COMPONENTS Core)\nfind_package(cv_bridge REQUIRED)\nfind_package(OpenCV REQUIRED)\nset(CGAL_DONT_OVERRIDE_CMAKE_FLAGS TRUE CACHE BOOL \"Don't override flags\")\nmessage(CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS})\ninclude(${CGAL_USE_FILE})\nmessage(CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS})\n\n## Generate messages in the 'msg' folder\n add_message_files(\n FILES\n poseCustom.msg\n PosesArray.msg\n Parameters.msg\n Laser_values.msg\n )\n\n## Generate services in the 'srv' folder\n add_service_files(\n FILES\n simulator_robot_step.srv\n simulator_parameters.srv\n simulator_base.srv\n simulator_laser.srv\n simulator_light.srv\n simulator_robot_laser_values.srv\n simulator_algorithm_result.srv\n simulator_stop.srv\n simulator_set_light_position.srv\n simulator_MoveRealRobot.srv\n simulator_object_interaction.srv\n simulator_find_obj.srv\n simulator_manipulator.srv\n auto_charge.srv\n line_follower.srv\n )\n\n## Generate added messages and services with any dependencies listed here\n generate_messages(\n DEPENDENCIES\n std_msgs\n sensor_msgs\n )\n\n\ncatkin_package(\n# INCLUDE_DIRS include\n# LIBRARIES simulator\n# CATKIN_DEPENDS roscpp rospy std_msgs clips\n# DEPENDS system_lib\n)\n\n###########\n## Build ##\n###########\n\n## Specify additional locations of header files\n## Your package locations should be listed before other locations\ninclude_directories(\n# include\n ${catkin_INCLUDE_DIRS}\n ${OpenCV_INCLUDE_DIRS}\n)\n\nadd_executable(motion_planner_node src/motion_planner/motion_planner_node.cpp)\ntarget_link_libraries(motion_planner_node ${catkin_LIBRARIES})\nadd_dependencies(motion_planner_node simulator_generate_messages_cpp)\n\nadd_executable(base_node src/simulator_physics/base_node.cpp)\ntarget_link_libraries(base_node ${catkin_LIBRARIES})\nadd_dependencies(base_node simulator_generate_messages_cpp)\n\nadd_executable(laser_node src/simulator_physics/laser_node.cpp)\ntarget_link_libraries(laser_node ${catkin_LIBRARIES})\nadd_dependencies(laser_node simulator_generate_messages_cpp)\n\nadd_executable(light_server src/simulator_physics/light_server.cpp)\ntarget_link_libraries(light_server ${catkin_LIBRARIES})\nadd_dependencies(light_server simulator_generate_messages_cpp)\n\nadd_executable(light_node src/simulator_physics/light_node.cpp)\ntarget_link_libraries(light_node ${catkin_LIBRARIES})\nadd_dependencies(light_node simulator_generate_messages_cpp)\n\nadd_executable(move_turtlebot_node src/turtlebot/move_turtlebot_node.cpp)\ntarget_link_libraries(move_turtlebot_node ${catkin_LIBRARIES})\nadd_dependencies(move_turtlebot_node simulator_generate_messages_cpp)\n\nadd_executable(move_minibot_node src/turtlebot/move_minibot_node.cpp)\ntarget_link_libraries(move_minibot_node ${catkin_LIBRARIES})\nadd_dependencies(move_minibot_node simulator_generate_messages_cpp)\n\nadd_executable(map_rviz_node src/visualization/map_rviz_node.cpp)\ntarget_link_libraries(map_rviz_node ${catkin_LIBRARIES})\nadd_dependencies(map_rviz_node simulator_generate_messages_cpp)\n\nadd_executable(objs_viz_node src/visualization/objs_viz_node.cpp)\ntarget_link_libraries(objs_viz_node ${catkin_LIBRARIES})\nadd_dependencies(objs_viz_node simulator_generate_messages_cpp)\n\nadd_executable(find_obj_node src/simulator_physics/find_obj_node.cpp)\ntarget_link_libraries(find_obj_node ${catkin_LIBRARIES})\nadd_dependencies(find_obj_node simulator_generate_messages_cpp)\n\nadd_executable(manipulator_node src/simulator_physics/manipulator_node.cpp)\ntarget_link_libraries(manipulator_node ${catkin_LIBRARIES})\nadd_dependencies(manipulator_node simulator_generate_messages_cpp)\n\nadd_executable(action_planner_node src/motion_planner/action_planner_node.cpp)\ntarget_link_libraries(action_planner_node ${catkin_LIBRARIES})\nadd_dependencies(action_planner_node simulator_generate_messages_cpp)\n\nadd_executable(auto_charge_server src/motion_planner/auto_charge_server.cpp)\ntarget_link_libraries(auto_charge_server ${catkin_LIBRARIES})\nadd_dependencies(auto_charge_server simulator_generate_messages_cpp)\n\nadd_executable(joy_teleop_node src/joy_teleop/joy_teleop_node.cpp)\ntarget_link_libraries(joy_teleop_node ${catkin_LIBRARIES})\n\nadd_executable(follow_line_server src/motion_planner/follow_line_server.cpp)\ntarget_link_libraries(follow_line_server ${catkin_LIBRARIES})\nadd_dependencies(follow_line_server simulator_generate_messages_cpp)\n\nadd_executable(follow_line_client src/motion_planner/follow_line_client.cpp)\ntarget_link_libraries(follow_line_client ${catkin_LIBRARIES})\nadd_dependencies(follow_line_client simulator_generate_messages_cpp)\n\nadd_executable(real_arena_viz src/visualization/real_arena_viz.cpp)\ntarget_link_libraries(real_arena_viz ${catkin_LIBRARIES} ${OpenCV_LIBRARIES})\nadd_dependencies(real_arena_viz simulator_generate_messages_cpp)" }, { "alpha_fraction": 0.7592592835426331, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 17, "blob_id": "c93b6d5ad792761ebe3487fd9f92677ae98c53c3", "content_id": "f9d01b9bb3ba17b4278e4bc291c8deb6548796aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 54, "license_type": "no_license", "max_line_length": 40, "num_lines": 3, "path": "/catkin_ws/src/simulator/src/gui/start_rviz.sh", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n roslaunch rob2w_description rviz.launch\n" }, { "alpha_fraction": 0.552970826625824, "alphanum_fraction": 0.5760112404823303, "avg_line_length": 26.377281188964844, "blob_id": "e2fa82621bb449c241b69adda2d14aecea67d393", "content_id": "f217eafd5b0fcbee1bdf3ff032ee0af12cad4150", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13498, "license_type": "no_license", "max_line_length": 283, "num_lines": 493, "path": "/catkin_ws/src/simulator/src/simulator_physics/base_node.cpp", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <tf/transform_broadcaster.h>\n#include <nav_msgs/Odometry.h>\n\n#include \"ros/ros.h\"\n#include <ros/package.h>\n#include \"simulator/Parameters.h\"\n#include \"../utilities/simulator_structures.h\"\n#include \"simulator/simulator_robot_step.h\"\n#include \"simulator/simulator_parameters.h\"\n#include \"simulator/simulator_base.h\"\n#include <string.h>\n\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\n#include <iterator>\n#include <random>\n\n#define MAX_NUM_POLYGONS 100\n#define NUM_MAX_VERTEX 10\n#define STRSIZ 300\n#define SIZE_LINE 10000\n\nfloat x2, y2, theta2;\n\nconst double mean = 0.0;\ndouble stddev_distance = 0.005;\ndouble stddev_theta = 0.05;\n\nstd::default_random_engine generator;\nstd::normal_distribution<double> noise_distance(mean, stddev_distance);\nstd::normal_distribution<double> noise_theta(mean, stddev_theta);\n\ntypedef struct Vertex_ {\n float x;\n float y;\n} Vertex;\n\ntypedef struct Polygon_ {\n char name[ STRSIZ ];\n char type[ STRSIZ ];\n int num_vertex;\n Vertex vertex[NUM_MAX_VERTEX];\n Vertex min,max;\n} Polygon;\n\nPolygon polygons_wrl[100];\nint num_polygons_wrl = 0;\nparameters params;\nchar actual_world[50];\nfloat dimensions_room_x,dimensions_room_y;\n\n// it reads the file that conteins the environment description\nint ReadPolygons(char *file,Polygon *polygons){\n\n\tFILE *fp;\n\tchar data[ STRSIZ ];\n\tint i;\n\tint num_poly = 0;\n\tint flg = 0;\n\tfloat tmp;\n\t\n\n\tfp = fopen(file,\"r\"); \n\t \n\tif( fp == NULL )\n\t{\n\t\tsprintf(data, \"File %s does not exist\\n\", file);\n\t\tprintf(\"File %s does not exist\\n\", file);\n\t\treturn(0);\n\t}\n\t//printf(\"World environment %s \\n\",file);\n\n\twhile( fscanf(fp, \"%s\" ,data) != EOF)\n\t{\n\t\tif( strcmp(\";(\", data ) == 0 )\n\t\t{\n\t\t\tflg = 1;\n\t\t\twhile(flg)\n\t\t\t{\n\t\t\t\tif( 0 < fscanf(fp, \"%s\", data));\n\t\t\t\tsscanf(data, \"%f\", &tmp);\n\t\t\t\tif(strcmp(\")\", data) == 0) flg = 0;\n\t\t\t}\n\t\t}\n\t\telse if((strcmp(\"polygon\", data ) == 0) && ( flg == 0 ) )\n\t\t{\n\t\t\tif( 0 < fscanf(fp, \"%s\", data));\n\t\t\tstrcpy(polygons[num_poly].type, data);\n\t\t\tif( 0 < fscanf(fp, \"%s\", data));\n\t\t\tstrcpy(polygons[num_poly].name, data);\n\t\t\ti = 0;\n\t\t\tflg = 1;\n\n\t\t\tpolygons[num_poly].max.x = 0;\n\t\t\tpolygons[num_poly].max.y = 0;\n\t\t\tpolygons[num_poly].min.x = 9999;\n\t\t\tpolygons[num_poly].min.y = 9999;\n\n\t\t\twhile(flg)\n\t\t\t{\n\t\t\t\tif( 0 < fscanf(fp, \"%s\", data));\n\t\t\t\tif(strcmp(\")\",data) == 0) \n\t\t\t\t{\n\t\t\t\t\tpolygons[num_poly].num_vertex = i - 1;\n\t\t\t\t\tpolygons[num_poly].vertex[i].x = polygons[num_poly].vertex[0].x; // to calculate intersecction range\n\t\t\t\t\tpolygons[num_poly].vertex[i].y = polygons[num_poly].vertex[0].y; // the first vertex its repeated on the last\n\t\t\t\t\tnum_poly++;\n\t\t\t\t\tflg = 0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tsscanf(data, \"%f\", &tmp);\n\t\t\t\t\tpolygons[num_poly].vertex[i].x = tmp;\n\t\t\t\t\tif( 0 < fscanf(fp, \"%s\", data));\n\t\t\t\t\tsscanf(data, \"%f\", &tmp);\n\t\t\t\t\tpolygons[num_poly].vertex[i].y = tmp;\n\t\t\t\t\t\n\t\t\t\t\tif(polygons[num_poly].vertex[i].x > polygons[num_poly].max.x) polygons[num_poly].max.x = polygons[num_poly].vertex[i].x;\n\t\t\t\t\tif(polygons[num_poly].vertex[i].y > polygons[num_poly].max.y) polygons[num_poly].max.y = polygons[num_poly].vertex[i].y;\n\t\t\t\t\tif(polygons[num_poly].vertex[i].x < polygons[num_poly].min.x) polygons[num_poly].min.x = polygons[num_poly].vertex[i].x;\n\t\t\t\t\tif(polygons[num_poly].vertex[i].y < polygons[num_poly].min.y) polygons[num_poly].min.y = polygons[num_poly].vertex[i].y;\n\t\n\t\t\t\t\t//printf(\"polygon vertex %d x %f y %f\\n\",i,polygons[num_poly].vertex[i].x,polygons[num_poly].vertex[i].y);\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if(strcmp(\"dimensions\", data) == 0 && (flg == 0) )\n\t\t{\n\t\t\tif( 0 < fscanf(fp, \"%s\", data));\n\t\t\tif( 0 < fscanf(fp, \"%s\", data));\n\t\t\tsscanf(data, \"%f\", &dimensions_room_x);\n\t\t\tif( 0 < fscanf(fp, \"%s\", data));\n\t\t\tsscanf(data, \"%f\", &dimensions_room_y);\n\t\t\t//printf(\"dimensions x %f y %f\\n\",dimensions_room_x,dimensions_room_y);\n\t\t}\n\t}\n\tfclose(fp);\n\treturn num_poly;\n}\n\nvoid read_environment(char *file, int debug)\n{\n\n \tint i; \n\tint j;\n\t// it reads the polygons \n\tstrcpy(polygons_wrl[0].name, \"NULL\");\n\tif(debug == 1) printf(\"\\nEnvironment file: %s\\n\", file);\n\tnum_polygons_wrl = ReadPolygons(file, polygons_wrl);\n\t\n\tif(num_polygons_wrl == 0)\n\t\tprintf(\"File doesnt exist %s \\n\",file);\n\telse \n\t\tprintf(\"Load: %s \\n\",file); \n\t// it prints the polygons\n\tif(debug == 1)\n\tfor(i = 0; i < num_polygons_wrl; i++)\n\t{\n\t\tprintf(\"\\npolygon[%d].name=%s\\n\",i,polygons_wrl[i].name);\n\t\tprintf(\"polygon[%d].type=%s\\n\",i,polygons_wrl[i].type);\n\t\tprintf(\"Num vertex polygon[%d].num_vertex=%d\\n\",i,polygons_wrl[i].num_vertex);\n\t printf(\"max x,y = (%f, %f) min x,y = (%f, %f) \\n\", polygons_wrl[i].max.x, polygons_wrl[i].max.y, polygons_wrl[i].min.x, polygons_wrl[i].min.y);\n\t //printf(\"self.w.create_rectangle(%f* self.canvasX/2, (self.canvasY-( %f* self.canvasY )/2) , (%f* self.canvasX)/2, (self.canvasY-(%f* self.canvasX)/2), outline='#000000', width=1)\\n\", polygons_wrl[i].max.x, polygons_wrl[i].max.y, polygons_wrl[i].min.x, polygons_wrl[i].min.y);\n\t\tfor(j = 0; j <= polygons_wrl[i].num_vertex+1 ; j++)\n\t\t{\n\t\t\tprintf(\"polygon[%d].vertex[%d] x=%f y=%f\\n\", i, j, polygons_wrl[i].vertex[j].x, polygons_wrl[i].vertex[j].y);\n\t\t\t//printf(\"polygon[%d].line[%d] m=%f b=%f\\n\", i, j, polygons_wrl[i].line[j].m, polygons_wrl[i].line[j].b);\n\t\t}\n\t}\n}\n\nfloat pDistance(float x,float y,float x1,float y1,float x2,float y2) {\n\n float A = x - x1;\n float B = y - y1;\n float C = x2 - x1;\n float D = y2 - y1;\n\n float dot = A * C + B * D;\n float len_sq = C * C + D * D;\n float param = -1;\n float dx,dy;\n float xx, yy;\n\n if (len_sq != 0) //in case of 0 length line\n param = dot / len_sq;\n\n if (param < 0) {\n xx = x1;\n yy = y1;\n }\n else if (param > 1) {\n xx = x2;\n yy = y2;\n }\n else {\n xx = x1 + param * C;\n yy = y1 + param * D;\n }\n\n dx = x - xx;\n dy = y - yy;\n float aux =(dx * dx + dy * dy );\n\n return sqrt( aux );\n}\n\n\nint sat(float robot_x, float robot_y, float robot_r)\n{\n\tint i,j;\n\tVertex r_max;\n\tVertex r_min;\n\n\tr_max.x = robot_x + robot_r; r_max.y = robot_y + robot_r;\n\tr_min.x = robot_x - robot_r; r_min.y = robot_y - robot_r;\n\t\n\tfor(i = 0; i < num_polygons_wrl; i++)\n\t\tif( (r_min.x < polygons_wrl[i].max.x && polygons_wrl[i].max.x < r_max.x) || ( r_min.x < polygons_wrl[i].min.x && polygons_wrl[i].min.x < r_max.x) || ( polygons_wrl[i].min.x < r_min.x && r_max.x < polygons_wrl[i].max.x ) )\n\t\t\tif( (r_min.y < polygons_wrl[i].max.y && polygons_wrl[i].max.y < r_max.y) || ( r_min.y < polygons_wrl[i].min.y && polygons_wrl[i].min.y < r_max.y) || ( polygons_wrl[i].min.y < r_min.y && r_max.y < polygons_wrl[i].max.y ) )\n\t\t\t\tfor(int j = 0; j <= polygons_wrl[i].num_vertex; j++)\n\t\t \t\t\t{\n\t\t \t\t\t\tif( pDistance(robot_x, robot_y, polygons_wrl[i].vertex[j].x, polygons_wrl[i].vertex[j].y, polygons_wrl[i].vertex[j + 1].x, polygons_wrl[i].vertex[j + 1].y) <= robot_r ) \n\t\t\t\t\t\t{\t\n\t\t\t\t\t\t return 1;\n\t\t \t\t\t\t}\n\t\t \t\t\t\t\t}\t\n\treturn 0;\n}\n\t\nbool check_path(simulator::simulator_base::Request &req ,simulator::simulator_base::Response &res)\n{\n\tfloat x1 = req.x1;\n\tfloat y1 = req.y1;\n\tfloat m;\n\n\t//theta2=req.theta; \n\tfloat x22, y22;\n\tfloat distance_final,distance_test;\n\tfloat theta_final;\n\tchar path[50];\n\n\t\t//res.theta = req.theta = req.theta ;//+ noise_theta(generator);\n\t\n\t//req.distance += noise_distance(generator);\n\tif( params.noise )\n\t\ttheta_final = req.theta + noise_theta(generator) ;\n\telse\n\t\ttheta_final = req.theta;\n\n\tres.theta = theta_final;\n\n\n\n\tif (req.distance == 0)\n\t{\n\t\tres.distance = 0; \n\t\treturn true;\n\t}\n\n\tm = tan(req.orientation + theta_final);\n\n\tif( params.noise )\n\t\tdistance_test = req.distance + noise_distance(generator);\n\telse\n\t\tdistance_test = req.distance;\n\n\n\tif(m > 1 || m < -1 )\n\t{\t\n\t\ty22 = distance_test * sin(req.orientation + theta_final) + y1;\n\t\tx2 = distance_test * cos(req.orientation + theta_final) + x1;\n\t\ty2 = 0;\n\n\t\tif(y22 > y1)\n\t\t{\t\n\t\t\tfor(y2 = y1; y2 <= y22; y2+=.005)\n\t\t\t{\n\t\t\t\tx2 = (y2 - y1) / m + x1 ;\n\t\t\t\t\n\t\t\t\tif(sat(x2, y2, params.robot_radio))\n\t\t\t\t{\n\t\t\t\tbreak;}\n\t\t\t}\n\t\t\tif(x2 != x1)\n\t\t\t{\t\n\t\t\t\ty2-=.005;\n\t\t\t\tx2 = (y2 - y1) / m + x1 ;\t\n\t\t\t}\n\t\t\t//printf(\"y1:%f x1:%f y2 %f x2 %f\\n\",y1,x1,y2,x2 );\n\t\t\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\t//printf(\"BBB\\n\");\n\t\t\tfor(y2 = y1; y2 >= y22; y2-=.005)\n\t\t\t{\n\t\t\t\t//y2 -y1= m ( x2 - x1)\n\t\t\t\tx2 = (y2 - y1) / m + x1 ;\n\t\t\t\tif(sat(x2, y2, params.robot_radio))\n\t\t\t\t{//printf(\"Fuera\\n\");\t\n\t\t\t\tbreak;}\n\t\t\t}\n\t\t\tif(x2 != x1)\n\t\t\t{\n\t\t\t\ty2+=.005;\n\t\t\t\tx2 = (y2 - y1) / m + x1 ;\n\t\t\t}\n\t\t}\n\n\t}\n\telse\n\t{\n\t\tx22 = distance_test * cos(req.orientation + theta_final ) + x1;\n\t\ty2 = distance_test * sin(req.orientation + theta_final ) + y1;\n\t\tx2 = 0;\n\n\t\tif(x22-x1 >= 0)\n\t\t{\n\t\t\t//printf(\"CCC\\n\");\n\t\t\tfor(x2 = x1; x2 <= x22; x2+=.005)\n\t\t\t{ \n\t\t\t\ty2 = m * (x2 - x1) + y1;\n\t\t\t\t//printf(\" x: %f y: %f\\n\",x2*600,y2*600 );\n\t\t\t\tif(sat(x2, y2, params.robot_radio))\n\t\t\t\t{//printf(\"Fuera\\n\");\n\t\t\t\tbreak;}\n\t\t\t}\n\t\t\tif(x2 != x1)\n\t\t\t{\n\t\t\t\tx2-=.005;\n\t\t\t\ty2 = m * (x2 - x1) + y1;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t//printf(\"DDD\\n\");\n\t\t\tfor(x2 = x1; x2 >= x22; x2-=.005)\n\t\t\t{\n\t\t\t\ty2 = m * (x2 - x1) + y1;\n\t\t\t\tif(sat(x2, y2, params.robot_radio))\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(x2 != x1)\n\t\t\t{\n\t\t\t\tx2+=.005;\n\t\t\t\ty2 = m * (x2 - x1) + y1;\n\t\t\t}\n\t\t}\n\t}\n\t\t\t\n \tdistance_final = sqrt( pow( x1-x2 ,2) + pow(y1-y2 ,2) );\n\n if (req.distance < 0)\n \tdistance_final = -distance_final;\n\n res.distance = distance_final/dimensions_room_x;\n\n //printf(\"====TTTTTdist reeq: %f , resp %f \\n\",req.distance ,res.distance );\n\n return true;\n}\n\n\nvoid paramsCallback(const simulator::Parameters::ConstPtr& paramss)\n{\n std::string paths = ros::package::getPath(\"simulator\");\n char path[500];\n\n\n params.robot_x = paramss->robot_x ;\n params.robot_y = paramss->robot_y ;\n params.robot_theta = paramss->robot_theta ; \n params.robot_radio = paramss->robot_radio ; \n params.robot_max_advance = paramss->robot_max_advance ; \n params.robot_turn_angle = paramss->robot_turn_angle ; \n params.laser_num_sensors = paramss->laser_num_sensors ; \n params.laser_origin = paramss->laser_origin ; \n params.laser_range = paramss->laser_range ; \n params.laser_value = paramss->laser_value ; \n strcpy(params.world_name ,paramss -> world_name.c_str()); \n params.noise = paramss->noise ; \n params.run = paramss->run ; \n params.light_x = paramss->light_x;\n params.light_y = paramss->light_y;\n params.behavior = paramss->behavior; \n\n if( strcmp( paramss->world_name.c_str(),actual_world) ) \n\t{\n\t\tstrcpy(path,paths.c_str());\n\t\tstrcat(path,\"/src/data/\");\n\t\tstrcat(path,paramss->world_name.c_str());\n\t\tstrcat(path,\"/\");\n\t\tstrcat(path,paramss->world_name.c_str());\n\t\tstrcat(path,\".wrl\");\n\t\tread_environment(path,0);\n\t\tstrcat(actual_world,paramss->world_name.c_str());\n\t\tstrcpy(actual_world,paramss->world_name.c_str());\n\t}\n\n}\n\nint main(int argc, char *argv[])\n{\t\n\tros::init(argc, argv, \"simulator_base_node\");\n\tros::NodeHandle n;\n\tros::ServiceServer service = n.advertiseService(\"simulator_base\", check_path);\n\tros::Subscriber params_sub = n.subscribe(\"simulator_parameters_pub\", 0, paramsCallback);\n\tros::spin();\n\t/*\t\n\tros::Publisher odom_pub = n.advertise<nav_msgs::Odometry>(\"odom\", 50);\n\ttf::TransformBroadcaster odom_broadcaster;\n\n \tdouble x = 0.0;\n \tdouble y = 0.0;\n \tdouble th = 0.0;\n\n \tdouble vx = 1.1;\n \tdouble vy = -1.1;\n \tdouble vth = 1.1;\n\n \tros::Time current_time, last_time;\n \tcurrent_time = ros::Time::now();\n \tlast_time = ros::Time::now();\n \n\n\tros::Rate r(2400.0);\n\t\n\twhile(n.ok())\n\t{\n\n ros::spinOnce(); // check for incoming messages\n \n current_time = ros::Time::now();\n\n //compute odometry in a typical way given the velocities of the robot\n double dt = (current_time - last_time).toSec();\n double delta_x = (vx * cos(th) - vy * sin(th)) * dt;\n double delta_y = (vx * sin(th) + vy * cos(th)) * dt;\n double delta_th = vth * dt;\n\n x += delta_x;\n y += delta_y;\n th += delta_th;\n\n //since all odometry is 6DOF we'll need a quaternion created from yaw\n geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(theta2);\n\n //first, we'll publish the transform over tf\n geometry_msgs::TransformStamped odom_trans;\n odom_trans.header.stamp = current_time;\n odom_trans.header.frame_id = \"map\";\n odom_trans.child_frame_id = \"base_link\";\n\n odom_trans.transform.translation.x = x2;\n odom_trans.transform.translation.y = y2;\n odom_trans.transform.translation.z = 0.0;\n odom_trans.transform.rotation = odom_quat;\n\n //send the transform\n odom_broadcaster.sendTransform(odom_trans);\n\n //next, we'll publish the odometry message over ROS\n nav_msgs::Odometry odom;\n odom.header.stamp = current_time;\n odom.header.frame_id = \"map\";\n\n //set the position\n odom.pose.pose.position.x = x2;\n odom.pose.pose.position.y = y2;\n odom.pose.pose.position.z = 0.0;\n odom.pose.pose.orientation = odom_quat;\n\n //set the velocity\n odom.child_frame_id = \"base_link\";\n odom.twist.twist.linear.x = vx;\n odom.twist.twist.linear.y = vy;\n odom.twist.twist.angular.z = 0;\n\n //publish the message\n odom_pub.publish(odom);\n\n last_time = current_time;\n \n r.sleep();\n }\n\t */\n\treturn 0;\n}\n\n" }, { "alpha_fraction": 0.6056456565856934, "alphanum_fraction": 0.6316735148429871, "avg_line_length": 40.00100326538086, "blob_id": "c659fed0b1eef2ff97efd7a16f736025a9d4bf44", "content_id": "740860f70dc2e6ffabfa5ef4fe4da56a3c78c435", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 81797, "license_type": "no_license", "max_line_length": 360, "num_lines": 1995, "path": "/catkin_ws/src/simulator/src/gui/MobileRobotSimulator.py", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#################################################\n#\t\t\t\t\t\t#\n#\tMobileRobotSimulator.py\t\t\t#\n#\t\t\t\t\t\t#\n#\t\tDiego Cordero\t\t\t#\n#\t\t\t\t\t\t#\n#\tBiorobotics Laboratory\t\t\t#\n# \t\tUNAM-2019\t\t\t#\n#\t\t\t\t\t\t#\n################################################# \n\nimport rospkg\nfrom Tkinter import *\nfrom tkFont import Font\nimport threading\nimport ttk\nimport time\nimport math\nfrom PIL import Image\nfrom PIL import ImageTk\nfrom PIL import ImageDraw\nimport tkMessageBox\nimport os\nimport numpy as np\nimport subprocess\n\n \nclass MobileRobotSimulator(threading.Thread):\n\t\n\tdef __init__(self):\n\t\t\n\t\tthreading.Thread.__init__(self)\n\t\tself.rospack = rospkg.RosPack()\n\t\tself.stopped = False \n\t\tself.isRunning = False\n\t\t# map size in meters\n\t\tself.mapX = 0 \n\t\tself.mapY = 0\n\t\t# canvas size in pixels\n\t\tself.canvasX= 400\n\t\tself.canvasY= 500\n\t\t\n\t\tself.defaultCanvasX = 600\n\t\tself.defaultCanvasY = 600\n\n\t\t# robot position and angle\n\t\tself.robot_theta=0\n\t\tself.robotX=-100\n\t\tself.robotY=-100\n\n\t\tself.p_giro=0\n\t\tself.p_distance=0\n\t\t\n\t\tself.polygonMap = []\n\t\tself.nodes_image = None\n\t\tself.light=-1\n\t\tself.light1=-1\n\t\tself.light2=-1\n\t\tself.robot=-1\n\n\t\tself.flagOnce=False\n\n\t\tself.light_x = 0\n\t\tself.light_y = 0\n\t\tself.startFlag = False\n\n\t\tself.lasers = []\n\t\tself.sensors_value = [None]*512;\n\t\tself.sensors_values = [None]*512;\n\t\tself.sensors_values_aux = [None]*512;\n\t\tself.sensors_values_aux_old = [None]*512;\n\t\t\n\t\t#for i in range(512):\n\t\t\t#self.sensors_value.append(0)\n\t\t#\tself.sensors_values.append(0)\n\t\t\t#self.sensors_values_aux.append(0)\n\n\n\t\tself.graph_list = [200]\n\t\tfor i in range(200):\n\t\t\tself.graph_list.append(0)\n\n\t\tself.rewind=[]\n\t\tself.trace_route= []\n\t\tself.varShowNodes = False\n\t\tself.grid =[]\n\t\tself.contador = 0;\n\t\tself.contador_ = 0;\n\t\tself.bandera = True\n\n\t\tself.X_pose = 0\n\t\tself.Y_pose = 0\n\n\t\tself.num_polygons = 0 #How many polygons exist in the field.\n\t\tself.polygons = []\t #Stors polygons vertexes\n\t\tself.polygons_mm = [] #Stors 2 vertexses for each polygon the maximum and minimum x and y points.\n\n\t\tself.objects_data = []\n\t\tself.grasp_id = False\n\t\tself.current_object = -1;\n\t\tself.current_object_name = -1;\n\n\t\tself.initX = 0\n\t\tself.initY = 0\n\t\tself.initR = 0\n\n\t\tself.steps_aux = 0\n\t\tself.posible_collision = [None] * 512;\n\t\tself.sensors_value = [None] * 512 \n\n\t\tself.movement = []\n\n\t\tself.start()\n\n\t\tself.play_record = False\n\t\tself.start_record = False\n\t\tself.finish_record = False\n\n\tdef kill(self): # When press (x) window\n\t\tself.stopped = True\n\t\tself.varTurtleBot.set(0)\n\t\tself.startFlag=False\n\t\tself.s_t_simulation(False)\n\t\tself.clear_topological_map()\n\t\tself.startFlag=False\n\t\tself.s_t_simulation(False)\n\t\ttime.sleep(2)\n\t\tself.root.quit()\n\t\tself.root.destroy()\n\n\n\n\tdef get_parameters(self): # It returns the parameters of simulation to be publish by a ROS topic\n\t\tparameters = []\n\n\t\ttry:\n\t\t\tparameters.append(self.robotX*self.mapX / self.canvasX )\n\t\texcept ValueError:\n\t\t\tparameters.append(0.0)\n\t\ttry:\n\t\t\tparameters.append( self.mapY - (self.robotY)*self.mapY / self.canvasY )\n\t\texcept ValueError:\n\t\t\tparameters.append(0.0)\n\t\ttry:\n\t\t\tparameters.append(self.robot_theta)\n\t\texcept ValueError:\n\t\t\tparameters.append(0.0)\n\t\ttry:\n\t\t\tparameters.append(float(self.entryRadio.get()))\n\t\texcept ValueError:\n\t\t\tparameters.append(0.0)\n\t\ttry:\n\t\t\tparameters.append( float(self.entryAdvance.get()))\n\t\texcept ValueError:\n\t\t\tparameters.append(0.0)\n\t\ttry:\n\t\t\tparameters.append( float(self.entryTurnAngle.get()))\n\t\texcept ValueError:\n\t\t\tparameters.append(0.0)\n\t\ttry:\n\t\t\tparameters.append( int(self.entryNumSensors.get()))\n\t\texcept ValueError:\n\t\t\tparameters.append(0)\n\t\ttry:\n\t\t\tparameters.append( float(self.entryOrigin.get()))\n\t\texcept ValueError:\n\t\t\tparameters.append(0.0)\n\t\ttry:\n\t\t\tparameters.append( float(self.entryRange.get()))\n\t\texcept ValueError:\n\t\t\tparameters.append(0.0)\n\t\ttry:\n\t\t\tparameters.append( float(self.entryValue.get()))\n\t\texcept ValueError:\n\t\t\tparameters.append(0.0)\n\t\ttry:\n\t\t\tparameters.append( str(self.entryFile.get()))\n\t\texcept ValueError:\n\t\t\tparameters.append(\"NOT FOUND\")\n\t\ttry:\n\t\t\tparameters.append( bool(self.varAddNoise.get() ))\n\t\texcept ValueError:\n\t\t\tparameters.append(False)\n\t\ttry:\n\t\t\tparameters.append( float(self.light_x))\n\t\texcept ValueError:\n\t\t\tparameters.append(0.0)\n\t\ttry:\n\t\t\tparameters.append( float(self.light_y))\n\t\texcept ValueError:\n\t\t\tparameters.append(0.0)\n\t\ttry:\n\t\t\tparameters.append( bool(self.startFlag ))\n\t\texcept ValueError:\n\t\t\tparameters.append(False)\n\t\ttry:\n\t\t\tparameters.append( int(self.entryBehavior.get() ))\n\t\texcept ValueError:\n\t\t\tparameters.append(-1)\n\t\ttry:\n\t\t\tparameters.append( bool(self.varTurtleBot.get()) )\n\t\texcept ValueError:\n\t\t\tif self.varTurtleBot.get()==1:\n\t\t\t\tparameters.append( True )\n\t\t\telse:\n\t\t\t\tparameters.append( False )\n\t\ttry:\n\t\t\tparameters.append( bool(self.varLidar.get()) )\n\t\texcept ValueError:\n\t\t\tif self.varLidar.get()==1:\n\t\t\t\tparameters.append( True )\n\t\t\telse:\n\t\t\t\tparameters.append( False )\n\t\ttry:\n\t\t\tparameters.append( bool(self.varSArray.get()) )\n\t\texcept ValueError:\n\t\t\tif self.varSArray.get()==1:\n\t\t\t\tparameters.append( True )\n\t\t\telse:\n\t\t\t\tparameters.append( False )\n\t\ttry:\n\t\t\tparameters.append( bool(self.varLight1.get()) )\n\t\texcept ValueError:\n\t\t\tif self.varLight1.get()==1:\n\t\t\t\tparameters.append( True )\n\t\t\telse:\n\t\t\t\tparameters.append( False )\n\t\ttry:\n\t\t\tparameters.append( bool(self.varLight2.get()) )\n\t\texcept ValueError:\n\t\t\tif self.varLight2.get()==1:\n\t\t\t\tparameters.append( True )\n\t\t\telse:\n\t\t\t\tparameters.append( False )\n\t\ttry:\n\t\t\tparameters.append(self.movement)\n\t\texcept ValueError:\n\t\t\tparameters.append([])\n\t\ttry:\n\t\t\tparameters.append(self.play_record)\n\t\texcept ValueError:\n\t\t\tparameters.append(False)\n\t\ttry:\n\t\t\tparameters.append(self.start_record)\n\t\texcept ValueError:\n\t\t\tparameters.append(False)\n\t\ttry:\n\t\t\tparameters.append(self.finish_record)\n\t\texcept ValueError:\n\t\t\tparameters.append(False)\n\n\t\treturn parameters\n\t\n\tdef restart_play_record(self):\n\t\tself.play_record = False\n\n\tdef restart_start_record(self):\n\t\tself.start_record = False\n\n\tdef restart_finish_record(self):\n\t\tself.finish_record = False\n\t\t\n\n\n##########################################\n##########################################\n#\n#\tEnvironment\n#\n##########################################\n##########################################\n\n\tdef print_graph(self,*args): # Plots graphs such as Dijkstra, DFS, A* and more (The graph is passed by a ROS service from motion_planner node)\n\t\t\tflagOnce=True;\n\t\t\tnumNode_=1\n\t\t\tself.w.delete(self.nodes_image)\t\n\t\t\tnodes_coords = []\n\t\t\timage = Image.new('RGBA', (self.canvasX, self.canvasY))\n\t\t\tdraw = ImageDraw.Draw(image)\n\t\t\tmap_file = open(self.rospack.get_path('simulator')+'/src/data/'+self.entryFile.get()+'/'+self.entryFile.get()+'.top','r') #Open file\n\t\t\tlines = map_file.readlines() #Split the file in lines\n\t\t\tfor line in lines: \t\t\t\t\t\t\t\t\t #To read line by line\n\t\t\t\twords = line.split()\t #To split words \n\t\t\t\tif words:\t\t\t\t\t\t\t\t\t\t #To avoid empty lines\t\t\t\t\t\t\t\n\t\t\t\t\tif words[0] == \"(\":\t\t\t\t\t\t\t #To avoid coments\n\t\t\t\t\t\tif words[1] == \"num\":\t\t\t #To get world dimensions\n\t\t\t\t\t\t\tnumNode = float (words[3])\t\n\t\t\t\t\t\t\tif numNode == 0:\n\t\t\t\t\t\t\t\tnumNode_=0\n\t\t\t\t\t\t\t\tmap_file.close()\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telif words[1] == \"node\":\t\t\t\t #to get polygons vertex\n\t\t\t\t\t\t\t#numNode = words[2]\n\t\t\t\t\t\t\tnodeXm = float (words[3]) * self.canvasX / self.mapX\n\t\t\t\t\t\t\tnodeYm = self.canvasY - ( float (words[4]) * self.canvasY) / self.mapY\n\t\n\t\t\t\t\t\t\tnodes_coords.append([nodeXm,nodeYm,numNode])\n\t\t\n\t\t\tif numNode_ != 0:\n\t\t\t\tsecuence = 0\n\t\t\t\tfor x in self.graph_list:\n\t\t\t\t\tif x != -1:\n\t\t\t\t\t\tif flagOnce:\n\t\t\t\t\t\t\tc1 = nodes_coords[x][0]\n\t\t\t\t\t\t\tc2 = nodes_coords[x][1]\n\t\t\t\t\t\t\tflagOnce = False\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tdraw.ellipse((nodes_coords[x][0] - 3 ,nodes_coords[x][1] - 3 ,nodes_coords[x][0] + 3 ,nodes_coords[x][1] + 3), outline = '#9C4FDB', fill = '#9C4FDB')\n\t\t\t\t\t\tdraw.text( (nodes_coords[x][0],nodes_coords[x][1] + 2) ,fill = \"darkblue\" ,text = str(secuence) )\n\t\t\t\t\t\tsecuence = secuence + 1\n\t\t\t\t\t\t\t#( connection 0 1 0.121195 )\n\t\t\t\t\t\tdraw.line( (c1,c2,nodes_coords[x][0],nodes_coords[x][1]), fill = '#9C4FDB')\n\t\t\t\t\t\tc1 = nodes_coords[x][0]\n\t\t\t\t\t\tc2 = nodes_coords[x][1]\n\n\t\t\t\tmap_file.close()\n\n\t\t\t\timage.save(self.rospack.get_path('simulator')+'/src/gui/nodes.png')\n\t\t\t\tself.gif1 = PhotoImage( file = self.rospack.get_path('simulator')+'/src/gui/nodes.png')\n\t\t\t\tself.nodes_image = self.w.create_image(self.canvasX / 2, self.canvasY / 2, image = self.gif1)\n\n#####################\n#####################\n#\n# Topological map\n#\n#####################\n#####################\n\tdef print_topological_map(self): # It plots the topological map of the current map and show \"please wait\" message\n\t\twait_bg=self.w.create_rectangle(self.canvasX/2-30-120 ,self.canvasY/2-50 ,self.canvasX/2-30+120 ,self.canvasY/2+50 ,fill=\"white\")\n\t\twait = self.w.create_text(self.canvasX/2-30,self.canvasY/2,fill=\"darkblue\",font=\"Calibri 20 bold\",\n text=\"PLEASE WAIT ...\")\n\t\tself.w.update()\n\t\tself.print_topological_map_lines()\n\t\tself.w.delete(wait)\n\t\tself.w.delete(wait_bg)\n\t\tself.plot_robot()\n\n\tdef clear_topological_map(self): # It removes topological_map\n\t\tif self.varShowNodes :\n\t\t\tself.w.delete(self.nodes_image)\t\n\t\t\tself.nodes=None\n\t\t\tself.w.update()\n\t\t\tself.varShowNodes = False\n\n\tdef print_topological_map_lines(self): # It plots the topological map of the current map \n\n\t\tself.clear_topological_map();\n\t\tself.varShowNodes = True\n\t\t#self.w.delete(self.nodes_image)\t\n\t\tnodes_coords = []\n\t\timage = Image.new('RGBA', (self.canvasX, self.canvasY))\n\t\tdraw = ImageDraw.Draw(image)\n\t\tmap_file = open(self.rospack.get_path('simulator')+'/src/data/'+self.entryFile.get()+'/'+self.entryFile.get()+'.top','r') #Open file\n\t\tlines = map_file.readlines() #Split the file in lines\n\t\tfor line in lines: \t\t\t\t\t\t\t\t\t #To read line by line\n\t\t\twords = line.split()\t #To separate words \n\t\t\tif words:\t\t\t\t\t\t\t\t\t\t #To avoid empty lines\t\t\t\t\t\t\t\n\t\t\t\tif words[0] == \"(\":\t\t\t\t\t\t\t #To avoid coments\n\t\t\t\t\tif words[1] == \"num\":\t\t\t #To get world dimensions\n\t\t\t\t\t\tnumNode = float (words[3])\t\n\t\t\t\t\telif words[1] == \"node\":\t\t\t\t #to get polygons vertex\n\t\t\t\t\t\tnumNode = words[2]\n\t\t\t\t\t\tnodeXm = float (words[3]) * self.canvasX / self.mapX\n\t\t\t\t\t\tnodeYm = self.canvasY - ( float (words[4]) * self.canvasY) / self.mapY\n\t\t\t\t\t\tnodes_coords.append([nodeXm,nodeYm])\n\t\t\t\t\t\tdraw.ellipse((nodeXm - 3 ,nodeYm - 3 ,nodeXm + 3 ,nodeYm + 3), outline = '#9C4FDB', fill = '#9C4FDB')\n\t\t\t\t\t\tdraw.text( (nodeXm,nodeYm + 2) ,fill = \"darkblue\" ,text = str(numNode) )\n\t\t\t\t\telif words[1] == \"connection\":\t\t\t\t #to get polygons vertex\n\t\t\t\t\t\tc1 = int(words[2])\n\t\t\t\t\t\tc2 = int(words[3])\n\t\t\t\t\t\tdraw.line( (nodes_coords[c1][0],nodes_coords[c1][1] ,nodes_coords[c2][0] ,nodes_coords[c2][1] ) , fill = '#9C4FDB')\n\t\t\t\t\t\t\n\t\tmap_file.close()\n\t\timage.save(self.rospack.get_path('simulator')+'/src/gui/nodes.png')\n\t\tself.gif1 = PhotoImage( file = self.rospack.get_path('simulator')+'/src/gui/nodes.png')\n\t\tself.nodes_image = self.w.create_image(self.canvasX / 2, self.canvasY / 2, image = self.gif1)\n\n##################################\n##################################\n# \n# MAP\n#\n##################################\n##################################\n\tdef map_change(self,event): \n\t\tself.w.delete(self.nodes_image)\t\n\t\tself.read_map()\n\t\tif self.varShowNodes:\n\t\t\tself.clear_topological_map()\n\t\tself.delete_robot()\n\t\tfor i in self.lasers:\n\t\t\tself.w.delete(i)\n\t\tself.lasers = []\n\t\tfor trace in self.trace_route :\n\t\t\tself.w.delete(trace)\n\t\tself.trace_route = []\n\t\tself.w.delete(self.light)\n\n\tdef read_map(self): # It reads maps from src/data/[map].wrl folder \n\t\tself.num_polygons=0\n\t\tfor polygon in self.polygonMap :\n\t\t\tself.w.delete(polygon)\n\t\tself.polygonMap = []\n\t\tself.polygons = []\t\n\t\tself.polygons_mm = []\n\t\ttry:\n\t\t\t#self.w.delete(\"all\")\n\t\t\tmap_file = open(self.rospack.get_path('simulator')+'/src/data/'+self.entryFile.get()+'/'+self.entryFile.get()+'.wrl','r') #Open file\n\t\t\tlines = map_file.readlines() #Split the file in lines\n\t\t\tfor line in lines: \t\t\t\t\t\t\t\t\t #To read line by line\n\t\t\t\twords = line.split()\t #To separate words \n\t\t\t\tif words:\t\t\t\t\t\t\t\t\t\t #To avoid empty lines\t\t\t\t\t\t\t\n\t\t\t\t\tif words[0] == \"(\":\t\t\t\t\t\t\t #To avoid coments\n\t\t\t\t\t\tif words[1] == \"dimensions\":\t\t\t #To get world dimensions\n\t\t\t\t\t\t\tself.mapX = float (words[3])\t\n\t\t\t\t\t\t\tself.mapY = float (words[4])\n\t\t\t\t\t\t\t\n self.canvasX = self.defaultCanvasX\n self.canvasY = self.defaultCanvasY\n\n if self.mapX > self.mapY: \n self.canvasX = ( self.mapX * self.canvasY ) / self.mapY\n if self.canvasX > self.screen_width_max:\n \t\t\t\tself.canvasX = self.screen_width_max\n self.canvasY = ( self.mapY * self.canvasX ) / self.mapX \n\n elif self.mapX < self.mapY:\n self.canvasY = ( self.mapY * self.canvasX ) / self.mapX\n if self.canvasY > self.screen_height_max:\n \t\t\t\tself.canvasY = self.screen_height_max\n self.canvasX = ( self.mapX * self.canvasY ) / self.mapY \n \t\n\n \n else:\n self.canvasX = self.canvasY\n self.canvasX = int(self.canvasX)\n\t\t\t\t\t\t\tself.canvasY = int(self.canvasY)\n self.w.configure(width = self.canvasX, height = self.canvasY)\n \n self.print_grid()\n\t\t\t\t\t\telif words[1] == \"polygon\":\t\t\t\t #to get polygons vertex\n\n\t\t\t\t\t\t\tvertex_x = [ ( ( self.canvasX * float(x) ) / self.mapX ) for x in words[4:len(words)-1:2]\t]\n\t\t\t\t\t\t\tvertex_y = [ ( self.canvasY - ( self.canvasY * float(y) ) / self.mapY ) for y in words[5:len(words)-1:2]\t]\n\t\t\t\t\t\t\tvertex_y_calculus = [ (( self.canvasY * float(y) ) / self.mapY ) for y in words[5:len(words)-1:2]\t]\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tvx = [ float(x)for x in words[4:len(words)-1:2] ]\t\n\t\t\t\t\t\t\tvy = [ float(y)for y in words[5:len(words)-1:2] ]\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tvertexs = ( zip( vertex_x , vertex_y) )\n\t\t\t\t\t\t\tself.polygons.append( zip( vertex_x , vertex_y_calculus))\n\t\t\t\t\t\t\tself.polygonMap.append(self.w.create_polygon(vertexs, outline=self.obstaclesOutlineColor, fill=self.obstacleInnerColor, width=1))\t\n\t\t\t\t\t\t\t#self.w.create_text( self.canvasX * float(words[4]) / self.mapX, self.canvasY - ( self.canvasY * float(words[5]) ) / self.mapY, text=str(pp))\n\t\t\t\t\t\t\tmax_x = 0;\n\t\t\t\t\t\t\tmax_y = 0;\n\t\t\t\t\t\t\tmin_x = 999;\n\t\t\t\t\t\t\tmin_y = 999;\n\n\t\t\t\t\t\t\tfor i in vertexs:\n\t\t\t\t\t\t\t\tif max_x < i[0]:\n\t\t\t\t\t\t\t\t\tmax_x = i[0]\n\t\t\t\t\t\t\t\tif min_x > i[0]:\n\t\t\t\t\t\t\t\t\tmin_x = i[0]\n\n\t\t\t\t\t\t\tfor i in vertexs:\n\t\t\t\t\t\t\t\tif max_y < i[1]:\n\t\t\t\t\t\t\t\t\tmax_y = i[1]\n\t\t\t\t\t\t\t\tif max_y > i[1]:\n\t\t\t\t\t\t\t\t\tmin_y = i[1]\n\t\t\t\t\t\t\tself.polygons_mm.append( [[max_x,max_y],[min_x,min_y] ] )\n\t\t\t\t\t\n\t\t\t\t\t\t\tself.num_polygons = self.num_polygons+1\n\t\t\tfor p in self.polygons:\n\t\t\t\tp.append(p[0])\n\t\texcept IOError:\n\t\t\ttkMessageBox.showerror(\"World erros \", \"World '\"+self.entryFile.get()+\"' doesn' t exist \\n Provide another file name \")\n\n\n\n\n\n#####################################\n#####################################\n#\n# Objects on the map\n#\n#####################################\n#####################################\n\tdef read_objects(self): \n\t\tfor polygon in self.objects_data:\n\t\t\tself.w.delete(polygon[3])\n\t\t\tself.w.delete(polygon[4])\n\n\t\tself.objects_data = []\n\t\tself.grasp_id = False\n\t\tif self.varLoadObjects.get():\n\t\t\ttry:\n\t\t\t\tmap_file = open(self.rospack.get_path('simulator')+'/src/data/objects/objects.txt','r') #Open file\n\t\t\t\tlines = map_file.readlines() #Split the file in lines\n\t\t\t\tfor line in lines: \t\t\t\t\t\t\t\t\t #To read line by line\n\t\t\t\t\twords = line.split()\t #To separate words \n\t\t\t\t\tif words:\t\t\t\t\t\t\t\t\t\t #To avoid empty lines\t\t\t\t\t\t\t\n\t\t\t\t\t\tself.objects_data.append([words[0],float(words[1]),float(words[2]) ,-1,-1] )\n\n\t\t\t\tfor i,objects_datas in enumerate(self.objects_data):\n\t\t\t\t\tobjects_datas[3] = self.w.create_rectangle( (objects_datas[1]*self.canvasX)/self.mapX -10, ( (self.mapY-objects_datas[2])*self.canvasY)/self.mapY -10 , (objects_datas[1]*self.canvasX)/self.mapX +10, ((self.mapY-objects_datas[2])*self.canvasY)/self.mapY +10 ,fill=\"#9FFF3D\",outline=\"#9FFF3D\")\n\t\t\t\t\tobjects_datas[4] = self.w.create_text((objects_datas[1]*self.canvasX)/self.mapX ,((self.mapY-objects_datas[2])*self.canvasY)/self.mapY , fill=\"#9E4124\",font=\"Calibri 10 bold\",text=objects_datas[0])\n\t\t\texcept IOError:\n\t\t\t\ttkMessageBox.showerror(\"Objects erros \", \"Ups! an error occurred. \\n Please check objects.txt syntax \")\n\t\telse:\n\t\t\tpass\n\tdef exist_object(self,name):\n\t\tfor obj in self.objects_data:\n\t\t\tif name == obj[0]:\n\t\t\t\treturn True\n\t\treturn False\n\n\tdef get_object(self,name):\n\t\tfor obj in self.objects_data:\n\t\t\tif name == obj[0]:\n\t\t\t\treturn obj\n\t\treturn False\n\n\tdef grasp_object(self,name):\n\t\tdistancia_min = 0.05\n\n\t\tif self.grasp_id==False :\n\t\t\tif self.exist_object(name) :\n\t\t\t\tobj = self.get_object(name)\n\t\t\t\tif math.sqrt(((self.robotX*self.mapX)/self.canvasX-obj[1])**2+(((self.canvasY-self.robotY)*self.mapY)/self.canvasY-obj[2])**2 ) < distancia_min:\n\t\t\t\t\tself.grasp_id = name\n\t\t\t\t\tself.w.delete(obj[3])\n\t\t\t\t\tself.w.delete(obj[4])\n\t\t\t\t\treturn True\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Distance to object \"+name+\" is more than \"+str(distancia_min))\n\t\t\telse:\n\t\t\t\tprint(\"Object \" + name + \" does not exist \")\n\t\telse:\n\t\t\tprint(\"I can not grasp more than one object\")\n\n\t\treturn False\n\n\tdef release_object(self):\n\t\tif self.grasp_id != False:\n\t\t\t\n\t\t\tfor obj in self.objects_data:\n\t\t\t\tif self.grasp_id == obj[0]:\n\t\t\t\t\tx=(self.robotX*self.mapX)/self.canvasX + (( (float(self.entryRadio.get()))*math.cos(float(self.entryAngle.get()))))\n\t\t\t\t\ty=((self.canvasY -self.robotY)*self.mapY)/self.canvasY + (((float(self.entryRadio.get()))*math.sin( float(self.entryAngle.get()) )))\n\t\t\t\t\t\n\t\t\t\t\tobj[1]= x\n\t\t\t\t\tobj[2]= y\n\n\t\t\t\t\tobj[3] = self.w.create_rectangle( (obj[1]*self.canvasX)/self.mapX -10, ((self.mapY-obj[2])*self.canvasY)/self.mapY -10 , (obj[1]*self.canvasX)/self.mapX +10, ((self.mapY-obj[2])*self.canvasY)/self.mapY +10 ,fill=\"#9FFF3D\",outline=\"#9FFF3D\")\n\t\t\t\t\tobj[4] = self.w.create_text((obj[1]*self.canvasX)/self.mapX ,((self.mapY-obj[2])*self.canvasY)/self.mapY , fill=\"#9E4124\",font=\"Calibri 10 bold\",text=obj[0])\n\t\t\tself.grasp_id = False\n\t\t\treturn True\n\t\telse:\n\t\t\tprint(\"Robot does not have an object\")\n\t\t\treturn False\n\n\n\n\n\n\n#####################################\n#####################################\n#\n#\tSimulacion\n#\n#######################################\n#######################################\n\n\tdef s_t_simulation(self,star_stop): # Button start simulation\n\t\t\n\t\tif star_stop :\n\t\t\tself.w.delete(self.nodes_image)\t\n\t\t\tself.denable('disabled')\n\t\t\tif not self.varTurtleBot.get:\n\t\t\t\tself.read_map()\n\t\t\tself.clear_topological_map() # To clear topological map\n\t\t\tself.startFlag=True\n\t\t\tself.steps_ = 0 ;\n\t\t\tself.steps_aux = int(self.entrySteps.get()) ;\n\t\t\tself.entrySteps.delete ( 0, END )\n\t\t\tself.entrySteps.insert ( 0, str(0) )\n\t\t\t\n\t\t\tself.rewind_x = self.robotX\n\t\t\tself.rewind_y = self.robotY\n\t\t\tself.rewind_angle = self.robot_theta\n\t\t\t\n\t\t\tself.rewind=[]\n\t\t\tfor trace in self.trace_route :\n\t\t\t\tself.w.delete(trace)\n\t\t\tself.trace_route = []\n\t\t\tself.isRunning = True\n\t\t\tself.start_record = True\n\n\t\telse: \n\t\t\tself.denable('normal')\n\t\t\tself.startFlag=False\n\t\t\tself.entrySteps.delete ( 0, END )\n\t\t\tself.entrySteps.insert ( 0, str(self.steps_aux) )\n\t\t\tself.isRunning = False\n\t\t\tself.finish_record = True\n\n\tdef rewindF(self): # When the \"Last simulation\" button is pressed\n\t\tself.denable('disabled')\n\t\tself.buttonStop.configure(state='disabled')\n\t\tself.robotX = self.rewind_x\n\t\tself.robotY = self.rewind_y\n\t\tself.robot_theta=self.rewind_angle\n\t\tcta=1\n\t\tfor i in self.rewind:\n\t\t\tself.p_giro = i[0]\n\t\t\tself.p_distance = i[1]\n\t\t\tself.entryStepsExcec.config(text=str(cta))\n\t\t\tcta = cta+1;\n\t\t\tself.move_robot(0)\n\t\tself.denable('normal')\n\t\tself.buttonStop.configure(state='normal')\n\n\tdef set_light_position(self,x,y): # Another way to start simulations, by plot the light ( goal point ).\n\t\tif self.light >0:\n\t\t\tself.w.delete(self.light)\n\t\ty1 = self.mapY - y \n\t\tself.light = self.w.create_image(x/self.mapX*self.canvasX, y1/self.mapY*self.canvasY, image = self.gif2)\n\t\tself.light_x = x \n\t\tself.light_y = y \n\t\tself.entryLightX.config(text=str(self.light_x)[:4])\n\t\tself.entryLightY.config(text=str(self.light_y)[:4])\n\t\t\n\tdef set_light_position1(self,x,y,visible): # Another way to start simulations, by plot the light ( goal point ).\n\t\tif self.light1 >0:\n\t\t\tself.w.delete(self.light1)\n\t\ty1 = self.mapY - y \n\t\tself.light1 = self.w.create_image(x/self.mapX*self.canvasX, y1/self.mapY*self.canvasY, image = self.gif2)\n\t\tif visible is False:\n\t\t\tself.w.delete(self.light1)\n\t\n\tdef set_light_position2(self,x,y,visible): # Another way to start simulations, by plot the light ( goal point ).\t\n\t\tif self.light2 >0:\n\t\t\tself.w.delete(self.light2)\n\t\ty1 = self.mapY - y \n\t\tself.light2 = self.w.create_image(x/self.mapX*self.canvasX, y1/self.mapY*self.canvasY, image = self.gif2)\n\t\tif visible is False:\n\t\t\tself.w.delete(self.light2)\n\n\tdef right_click(self,event): # Another way to start simulations, by plot the light ( goal point ).\n\t\tif not self.startFlag and not self.varTurtleBot.get():\n\t\t\tif self.light >0:\n\t\t\t\tself.w.delete(self.light)\n\t\t\tself.light = self.w.create_image(event.x, event.y, image = self.gif2)\n\t\t\tself.light_x = self.mapX*event.x / self.canvasX\n\t\t\tself.light_y = self.mapY - (( self.mapY * event.y ) / self.canvasY)\n\t\t\tself.entryLightX.config(text=str(self.light_x)[:4])\n\t\t\tself.entryLightY.config(text=str(self.light_y)[:4])\n\t\t\tself.s_t_simulation(True)\n\n\tdef left_click(self,event): # It plot the robot in the field\n\t\tif not self.varTurtleBot.get(): \n\t\t\tif self.robot > 0:\n\t\t\t\tself.delete_robot()\n\t\t\tself.robotX = event.x\n\t\t\tself.robotY = event.y\n\t\t\tself.plot_robot()\n\n\n\n\n\tdef object_interaction(self, *args):\n\t\tpass\n\n\n##################################################\n##################################################\n#\n# ROS\n#\n##################################################\n##################################################\n\tdef handle_simulator_object_interaction(self,grasp,name):\n\t\tif grasp == 1:\n\t\t\treturn self.grasp_object(name)\n\t\telse :\n\t\t\t\n\t\t\treturn self.release_object()\n\t\tself.d.set(1)\n\n\n\tdef handle_service(self,theta,distance):\n\t\tif not self.varTurtleBot.get():\n\t\t\tself.p_giro = theta\n\t\t\tself.p_distance = distance * self.canvasX \n\t\telse:\n\t\t\treturn\n\t\t\tself.p_giro = 0\n\t\t\tself.p_distance = 0\n\n\t\tself.steps_= self.steps_+1;\n\t\tself.entrySteps.delete ( 0, END )\n\t\t \n\t\tif self.startFlag:\n\t\t\tself.entrySteps.insert ( 0, str(self.steps_) )\n\t\telse:\n\t\t\tself.entrySteps.insert ( 0, str(self.steps_aux) )\n\n\t\tif self.steps_ == self.steps_aux:\n\t\t\tself.s_t_simulation(False)\n\t\t#elif( ( float(self.entryPoseX.get()) -self.light_x )**2 + ( float(self.entryPoseY.get()) - self.light_y )**2) < .05**2:\n\t\t\t#self.s_t_simulation(False)\n\t\telse:\n\t\t\tself.entryStepsExcec.config(text=str(self.steps_)[:4])\n\t\t\tself.rewind.append( [self.p_giro,self.p_distance])\n\t\t\tself.a.set(1)\n\n\tdef handle_print_graph(self,graph_list):\n\t\tself.graph_list = graph_list \n\t\tself.b.set(1)\n\n\tdef handle_hokuyo(self,sensors_values):\n\t\tself.sensors_values = sensors_values \t\t\n\t\tself.c.set(1)\n\n\tdef handlePoseByAruco(self,x,y,r):\n\n\t\tif self.varTurtleBot.get():\n\t\t\tself.robotX = self.convert_from_m_to_pixel( x * math.cos(self.initR) + y * math.sin(self.initR) - self.initX )\n\t\t\tself.robotY = self.canvasY- (y * self.canvasY / self.mapY)\n\n\t\t\tself.robot_theta = r \n\t\t\tself.d.set(1)\n\t\n\tdef handle_turtle(self,x,y,r):\n\n\t\tif self.varTurtleBot.get():\n\t\t\tself.robotX = self.convert_from_m_to_pixel( x * math.cos(self.initR) + y * math.sin(self.initR) - self.initX + 2.5)\n\t\t\tself.robotY = self.canvasY-self.convert_from_m_to_pixel( y * math.cos(self.initR) - x * math.sin(self.initR) - self.initY + 2.5 )\n\n\t\t\tself.robot_theta = r - self.initR\n\t\t\tself.d.set(1)\n\t\t\t#print(self.robotX,self.robotY,self.robot_theta)\n\t\telse:\n\t\t\tself.initX = x * math.cos(self.initR) + y * math.sin(self.initR)\n\t\t\tself.initY = y * math.cos(self.initR) - x * math.sin(self.initR)\n\t\t\tself.initR = r\n\t\t\t#print(x,y,r)\n\n\n####################################################\n####################################################\n#real robot\n####################################################\n####################################################\n\n\n\t\t\t\n\tdef print_real(self,*args):\n\t\tself.delete_robot()\n\t\tself.plot_robot2()\n\n\tdef print_hokuyo_values(self,*args):\n\n\t\t\"\"\"if self.startFlag:\n\n\t\t\toriginSensor = float( self.entryOrigin.get()) # -1.5707\n\t\t\trangeSensor = float( self.entryRange.get() ) # 240#3.1415\n\t\t\tnumSensor = int(self.entryNumSensors.get())\n\t\t\trx = self.robotX\n\t\t\try = self.robotY\n\t\t\tcolor = '#FF1008'\n\t\t\tx = 300#( float( self.entryValue.get() ) * self.canvasX ) / self.mapY\n\t\t\ty = ry\n\t\t\tangle =self.robot_theta\n\t\t\tf = angle + originSensor\n\t\t\tstep = float( float( rangeSensor ) / float( numSensor - 1 ) )\n\n\t\t\tfor i in self.lasers:\n\t\t\t\tself.w.delete(i)\n\t\t\tself.lasers = []\n\n\t\t\tfor i in range(0, numSensor):\t\n\t\t\t\t#if self.sensors_values[i] == float(\"inf\"):\n\t\t\t\t#\tcontinue\n\t\t\t\tq,w =self.get_ray(f ,rx ,ry ,(self.sensors_value[i]/4 * self.canvasX ) / self.mapY)\n\t\t\t\t#self.lasers.append(self.w.create_line(rx ,ry ,q ,w ,fill = self.laserColor) )\n\n\t\t\t\tif float(self.sensors_value[i]) < float(self.entryValue.get()) :\n\t\t\t\t\tself.lasers.append(self.w.create_oval(q-1 ,w-1,q+1 ,w+1 ,fill = color, outline =color ) )\t\n\t\t\t\tf = f + step\n\n\t\telse:\t\"\"\"\n\t\tif self.varTurtleBot.get() and not self.startFlag :\n\t\t\toriginSensor = -1.5707#-2.0944 #float( self.entryOrigin.get()) # -1.5707\n\t\t\trangeSensor = 3.1415#4.18879#float( self.entryRange.get() ) # 240#3.1415\n\t\t\tnumSensor = 512 #int(self.entryNumSensors.get())\n\t\t\trx = self.robotX\n\t\t\try = self.robotY\n\t\t\tcolor = '#FF1008'\n\t\t\tx = 300#( float( self.entryValue.get() ) * self.canvasX ) / self.mapY\n\t\t\ty = ry\n\t\t\tangle = self.robot_theta\n\t\t\tf = angle + originSensor\n\t\t\tstep = float( float( rangeSensor ) / float( numSensor - 1 ) )\n\n\t\t\tfor i in self.lasers:\n\t\t\t\tself.w.delete(i)\n\t\t\tself.lasers = []\n\n\t\t\tfor i in range(0, 512,1):\t\n\t\t\t\t#if self.sensors_values[i] == float(\"inf\"):\n\t\t\t\t#\tcontinue\n\t\t\t\tq,w =self.get_ray(f ,rx ,ry ,(self.sensors_values[i] * self.canvasX ) / self.mapY)\n\t\t\t\t#self.lasers.append(self.w.create_line(rx ,ry ,q ,w ,fill = self.laserColor) )\n\n\t\t\t\t#if float(self.sensors_values[i]/4) < float(self.entryValue.get()) :\n\n\t\t\t\tself.lasers.append(self.w.create_oval(q-1 ,w-1,q+1 ,w+1 ,fill = color, outline =color ) )\t\n\t\t\t\tf = f + step\n\n\tdef convert_from_m_to_pixel(self,m):\n\t\treturn m * self.canvasX / self.mapX\n\t\n\tdef use_s_array(self):\n\t\tif self.varSArray.get() :\n\t\t\tself.varLidar.set(0)\n\t\t\tself.entryNumSensors.delete ( 0, END )\n\t\t\tself.entryNumSensors.insert ( 0, '3')\n\t\telse:\n\t\t\tself.varLidar.set(1)\n\t\t\tself.entryNumSensors.delete ( 0, END )\n\t\t\tself.entryNumSensors .insert ( 0, '20')\n\n\tdef use_lidar(self):\n\t\tif self.varLidar.get():\n\t\t\tself.varSArray.set(0)\n\t\t\tself.entryNumSensors.delete ( 0, END )\n\t\t\tself.entryNumSensors .insert ( 0, '20')\n\t\telse:\n\t\t\tself.varSArray.set(1)\n\t\t\tself.entryNumSensors.delete ( 0, END )\n\t\t\tself.entryNumSensors .insert ( 0, '8')\n\n\n\tdef use_real_robot(self):\n\n\t\tif self.varTurtleBot.get() :\n\t\t\tif self.varSArray.get() :\n\t\t\t\tself.varLidar.set(0)\n\t\t\t\tself.entryNumSensors.delete ( 0, END )\n\t\t\t\tself.entryNumSensors.insert ( 0, '3')\n\t\t\telse:\n\t\t\t\tself.varLidar.set(0)\n\t\t\t\tself.varSArray.set(1)\n\t\t\t\tself.entryNumSensors.delete( 0, END )\n\t\t\t\tself.entryNumSensors.insert( 0, '3')\n\t\t\t\tself.entryOrigin.delete( 0, END)\n\t\t\t\tself.entryOrigin.insert( 0, '-0.7853')\n\t\t\t\tself.entryRange.delete( 0, END)\n\t\t\t\tself.entryRange.insert( 0, '1.5708')\n\t\t\t\tself.entryAdvance.delete( 0, END)\n\t\t\t\tself.entryAdvance.insert( 0, '0.03')\n\t\t\t\tself.entryValue.delete( 0, END)\n\t\t\t\tself.entryValue.insert( 0, '0.17')\n\t\t\t\tself.entryRadio.delete(0, END)\n\t\t\t\tself.entryRadio.insert(0, '0.05')\n\n\t\t\tself.checkLidar.configure(state=\"normal\")\n\t\t\tself.checkSArray.configure(state=\"normal\")\n\n\t\t\tself.entryNumSensors.delete( 0, END )\n\t\t\tself.entryNumSensors.insert( 0, '3')\n\t\t\tself.entryOrigin.delete( 0, END)\n\t\t\tself.entryOrigin.insert( 0, '-0.7853')\n\t\t\tself.entryRange.delete( 0, END)\n\t\t\tself.entryRange.insert( 0, '1.5708')\n\t\t\tself.entryAdvance.delete( 0, END)\n\t\t\tself.entryAdvance.insert( 0, '0.03')\n\t\t\tself.entryValue.delete( 0, END)\n\t\t\tself.entryValue.insert( 0, '0.17')\n\n\t\t\t#subprocess.Popen([self.rospack.get_path('simulator')+'/src/turtlebot/start_rviz_turtlebot.sh'])\n\t\t\tself.w.delete(self.nodes_image)\n\t\t\tstate='disabled'\n\t\t\tif self.flagOnce :\n\t\t\t\tself.delete_robot()\n\t\t\tself.flagOnce=True\n\n\t\t\tfor i in self.lasers:\n\t\t\t\tself.w.delete(i)\n\t\t\tself.clear_topological_map() # To clear topological map\n\t\t\tself.steps_ = 0 ;\n\t\t\tself.steps_aux = int(self.entrySteps.get()) ;\n\t\t\tself.entrySteps.delete ( 0, END )\n\t\t\tself.entrySteps.insert ( 0, str(100) )\n\t\t\t\n\t\t\tfor trace in self.trace_route :\n\t\t\t\tself.w.delete(trace)\n\t\t\tself.trace_route = []\n\n\t\t\tself.entryFile.delete(0, END)\n\t\t\tself.entryFile.insert(0, 'arena2')\n\t\t\tself.read_map()\n\n\t\t\t'''\n\t\t\tfor polygon in self.polygonMap :\n\t\t\t\tself.w.delete(polygon)\n\t\t\tself.polygonMap = []\n\t\t\tself.polygons = []\t\n\t\t\tself.polygons_mm = []\n\t\t\tself.mapX=5\n\t\t\tself.mapY=5\n\t\t\tself.entryRadio\n\t\t\tself.entryRadio.delete ( 0, END )\n\t\t\tself.entryRadio.insert ( 0, str(0.16) )\n\n\t\t\tself.buttonMapLess.configure(state=\"normal\")\n\t\t\tself.buttonMapMore.configure(state=\"normal\")\n\t\t\tself.print_grid(1)'''\n\t\t\t#self.robotX=self.canvasX/2\n\t\t\t#self.robotY=self.canvasY/2\n\t\t\t#self.robot_theta=0\n\t\t\t#self.delete_robot()\n\t\t\t#self.plot_robot2()\n\t\t\t\n\t\telse: \n\t\t\tself.entryNumSensors.delete ( 0, END )\n\t\t\tself.entryNumSensors .insert ( 0, '20')\n\t\t\tself.entryOrigin.delete( 0, END)\n\t\t\tself.entryOrigin.insert( 0, '-1.5707')\n\t\t\tself.entryRange.delete( 0, END)\n\t\t\tself.entryRange.insert( 0, '3.1415')\n\t\t\tself.entryAdvance.delete( 0, END)\n\t\t\tself.entryAdvance.insert( 0, '0.04')\n\t\t\tself.entryValue.delete( 0, END)\n\t\t\tself.entryValue.insert( 0, '0.05')\n\n\t\t\tself.checkLidar.configure(state=\"disabled\")\n\t\t\tself.checkSArray.configure(state=\"disabled\")\n\t\t\tself.buttonMapLess.configure(state=\"disabled\")\n\t\t\tself.buttonMapMore.configure(state=\"disabled\")\n\t\t\tstate='normal'\n\t\t\tself.entryRadio .configure(state=state)\n\t\t\tself.entryRadio.delete ( 0, END )\n\t\t\tself.entryRadio.insert ( 0, str(0.03) )\n\t\t\tself.entrySteps.delete ( 0, END )\n\t\t\tself.entrySteps.insert ( 0, str(self.steps_aux) )\n\t\t\tself.read_map()\n\t\t\tfor i in self.lasers:\n\t\t\t\tself.w.delete(i)\n\t\t\tself.lasers = []\n\n\t\t\tself.delete_robot()\n\n\t\tself.buttonRviz .configure(state=state) \n\t\tself.entryFile .configure(state=state) \n\t\t#self.entrySteps .configure(state=state) \n\t\t#self.buttonBehaviorLess .configure(state=state) \n\t\t#self.entryBehavior \t.configure(state=state) \n\t\t#self.buttonBehaviorMore .configure(state=state) \n\t\tself.checkFaster .configure(state=state) \n\t\tself.checkShowSensors .configure(state=state) \n\t\tself.checkAddNoise .configure(state=state) \n\t\tself.entryRobot .configure(state=state) \n\t\tself.entryPoseX .configure(state=state) \n\t\tself.entryPoseY .configure(state=state) \n\t\tself.entryAngle .configure(state=state) \n\t\tself.entryRadio .configure(state=state) \n\t\t#self.entryAdvance .configure(state=state) \n\t\t#self.entryTurnAngle .configure(state=state) \n\t\t#self.entryNumSensors .configure(state=state) \n\t\t#self.entryOrigin .configure(state=state) \n\t\t#self.entryRange .configure(state=state) \n\t\t#self.entryValue .configure(state=state)\n\t\tself.buttonLastSimulation.configure(state=state) \n\t\t#self.buttonRunSimulation.configure(state=state) \n\t\tself.buttonSetZero.configure(state=state) \n\t\tself.buttonPlotTopological.configure(state=state)\n\n\tdef turn_light(self):\n\t\tif self.varLight1.get():\n\t\t\tself.set_light_position1(0.8, 2.4, True)\n\t\t\t#print(\"Turn on light 1\")\n\t\telse:\n\t\t\tself.set_light_position1(0.8, 2.4, False)\n\t\t\t#print(\"Turn off light 1\")\n\t\tif self.varLight2.get():\n\t\t\tself.set_light_position2(0.46, 0.24, True)\n\t\t\t#print(\"Turn on light 2\")\n\t\telse:\n\t\t\tself.set_light_position2(0.46, 0.24, False)\n\t\t\t#print(\"Turn off light 2\")\n\t\t#print(\"---------------\")\n\n\t#####################################################################\n\t#####################################################################\n\t#####################################################################\n\t# Window Utilities\n\t# The following functions are for define buttons, texboxes, check boxes\n\t# And others functions to manage configurations\n\t#####################################################################\n\t#####################################################################\n\t#####################################################################\n\n\t###lidar utilities\n\n\tdef rotate_point(self,theta,ox,oy, x, y): \n\n\t\t# It rotates a point (x,y) from another point (ox,oy)\n\t\trotate = -theta\n\t\tnx = ( x - ox ) * math.cos( rotate ) - ( y - oy ) * math.sin(rotate) + ox\n\t\tny = ( x - ox ) * math.sin( rotate ) + ( y - oy ) * math.cos(rotate) + oy\n\t\treturn nx,ny\n\n\n\tdef line_intersection(self, p1, p2, p3 , p4, laser_value): \n\n\t\t#this function calculates the intersection point between two segments of lines.\n\t\t# p1,p2 are the points of the first segment\n\t\t# p1,p2 are the points of the second segment\n\n\t\tdenominadorTa = (p4[0]-p3[0])*(p1[1]-p2[1]) - (p1[0]-p2[0])*(p4[1]-p3[1])\n\t\tdenominadorTb = (p4[0]-p3[0])*(p1[1]-p2[1]) - (p1[0]-p2[0])*(p4[1]-p3[1])\n\t\t\n\t\tif denominadorTa == 0 or denominadorTb ==0 :\n\t\t\treturn laser_value\n\n\t\tta = ( (p3[1]-p4[1])*(p1[0]-p3[0]) + (p4[0]-p3[0])*(p1[1]-p3[1]) ) / float( denominadorTa )\n\t\ttb = ( (p1[1]-p2[1])*(p1[0]-p3[0]) + (p2[0]-p1[0])*(p1[1]-p3[1]) ) / float( denominadorTb )\n\t \n\t\tif 0 <= ta and ta <= 1 and 0 <= tb and tb <= 1 :\n\t\t\txi = p1[0] + ta * ( p2[0] - p1[0] ) \n\t\t\tyi = p1[1] + ta * ( p2[1] - p1[1] ) \n\t\t\treturn math.sqrt( (p1[0] - xi)**2 + (p1[1] - yi)**2 ) \t\n\t\telse:\n\t\t\treturn laser_value;\t\n\n\n\tdef calculate_ray_traicing(self): \n\n\t\t#It Calculates laser values Raycasting\n\t\tj=0;\n\t\tffl = False\n\t\tp1 = [None] * 2\n\t\tp2 = [None] * 2\n\n\t\tp3 = [None] * 2\n\t\tp4 = [None] * 2\n\n\t\tr_max = [None] * 2\n\t\tr_min = [None] * 2\n\n\t\tfour_lines = [None] * 4\n\n\t\tp1[0] = self.robotX;\n\t\tp1[1] = (self.canvasY-self.robotY);\n\n\t\tvalue = float(self.entryValue.get() ) * self.canvasX / self.mapX\n\n\t\tr_max[0] = p1[0] + float(value); \n\t\tr_max[1] = p1[1] + float(value);\n\t\tr_min[0] = p1[0] - float(value); \n\t\tr_min[1] = p1[1] - float(value);\n\n\t\t#self.w.create_line( r_max[0], r_max[1], r_max[0], r_min[1], fill = 'red')\n\t\t#self.w.create_line( r_max[0], r_min[1], r_min[0], r_min[1], fill = 'red')\n\t\t#self.w.create_line( r_min[0], r_min[1], r_min[0], r_max[1], fill = 'red')\n\t\t#self.w.create_line( r_min[0], r_max[1], r_max[0], r_max[1], fill = 'red')\n\t\t#self.w.create_oval( r_max[0]+1, r_max[1]+1, r_max[0]-1, r_max[1]-1 ,outline='green', fill='green', width=1)\n\t\t#self.w.create_oval( r_min[0]+1, r_min[1]+1, r_min[0]-1, r_min[1]-1 ,outline='black', fill='black', width=1)\n\n\t\tfour_lines[0] = [r_max[0], r_max[1], r_max[0], r_min[1]]\n\t\tfour_lines[1] = [r_max[0], r_min[1], r_min[0], r_min[1]]\n\t\tfour_lines[2] = [r_min[0], r_min[1], r_min[0], r_max[1]]\n\t\tfour_lines[3] = [r_min[0], r_max[1], r_max[0], r_max[1]]\n\n\n\t\tfor h in range(0,len(self.sensors_value)):\n\t\t\tself.sensors_value[h] = value\n\n\t\t\n\t\tfor p in range(0,4):\n\t\t\tself.posible_collision[p] = p\n\t\t\tj = j + 1\n\t\tfor i in range(0, self.num_polygons):\n\t\t\tffl = False\n\t\t\tfor k in four_lines:\n\t\t\t\tfor m in range(0, len(self.polygons[i] ) ):\n\t\t\t\t\tif ffl == True:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telse:\n\t\t\t\t\t\tif self.polygons[i][m][0] <= r_max[0] and self.polygons[i][m][0] >= r_min[0] and self.polygons[i][m][1] <= r_max[1] and self.polygons[i][m][1] >= r_min[1] :\n\n\t\t\t\t\t\t#if self.line_intersection([k[0],k[1]],[k[2],k[3]],self.polygons[i][m],self.polygons[i][m+1],value) != value:\n\t\t\t\t\t\t\tself.posible_collision[j] = i\n\t\t\t\t\t\t\tj = j + 1\n\t\t\t\t\t\t\tffl = True\n\n\t\t#print(str(j))\n\t\t#print(str(self.num_polygons))\n\n\t\tf = self.robot_theta + float(self.entryOrigin.get())\n\n\t\tstep = float(self.entryRange.get()) / ( float(self.entryNumSensors.get()) - 1 )\n\n\t\tfor k in range(0,int(self.entryNumSensors.get())):\n\t\t\tfor i in range(0,j):\n\t\t\t\tfor m in range(0, len(self.polygons[self.posible_collision[i]] )-1 ):\n\t\t\t\t\tp2[0] = float(value) * math.cos( f ) + float(p1[0]);\n\t\t\t\t\tp2[1] = float(value) * math.sin( f ) + float(p1[1]);\n\t\t\t\t\t\t\n\t\t\t\t\tif True:#self.ccw(p1,self.polygons[self.posible_collision[i]][m],self.polygons[self.posible_collision[i]][m+1]) != self.ccw(p2,self.polygons[ self.posible_collision[i] ][m],self.polygons[ self.posible_collision[i] ][m+1]) and self.ccw(p1,p2,self.polygons[ self.posible_collision[i] ][m]) != self.ccw(p1,p2,self.polygons[ self.posible_collision[i] ][m+1]):\n\t\t\t\t\t\taux = self.line_intersection(p1,p2,self.polygons[self.posible_collision[i]][m],self.polygons[ self.posible_collision[i] ][m+1],value);\n\t\t\t\t\t\tif self.sensors_value[k] > aux*self.mapX/ self.canvasX:\n\t\t\t\t\t\t\tself.sensors_value[k] = aux*self.mapX\t/ self.canvasX\t\t\n\t\t\tf = f + step\n\n\tdef ccw(self,A,B,C):\n\t\treturn (C[1]-A[1]) * (B[0]-A[0]) > (B[1]-A[1]) * (C[0]-A[0])\n\n\n\tdef plot_robot_values(self,color): \n\t\t#self.sensors_value = self.sensors_values_aux\n\t\tx = self.robotX\n\t\ty = self.robotY\n\t\tangle=self.robot_theta\n\n\t\ttry:\n\t\t\tself.entryPoseX.delete ( 0, END )\n\t\t\tself.entryPoseY.delete ( 0, END )\n\t\t\tself.entryAngle.delete ( 0, END )\n\t\t\tself.entryPoseX.insert ( 0, str(float(x)*self.mapX / self.canvasX) )\n\t\t\tself.entryPoseY.insert ( 0, str(self.mapY - (float(y)*self.mapY / self.canvasY ) )) \n\t\t\tif angle > math.pi*2 : \n\t\t\t\tangle = angle % (math.pi*2)\n\t\t\tif angle < 0 :\n\t\t\t\tangle = math.pi*2 - ( (angle * -1 ) % (math.pi*2) )\n\t\t\tself.robot_theta = angle\n\t\t\tself.entryAngle.insert ( 0, str( angle ) )\n\n\t\texcept ValueError:\n\t\t\tpass\n\n\t\tif self.flagOnce :\n\t\t\tself.delete_robot()\n\t\tself.flagOnce=True\n\n\t\tif self.varShowSensors.get():\n\t\t\tself.plot_sensors(angle,x,y,color)\t\n\n\t\tradio = ( float(self.entryRadio.get() ) * self.canvasX ) / self.mapX\n\t\tself.robot=self.w.create_oval(x-radio,y-radio, x+radio,y+radio , outline=self.robotColor, fill=self.robotColor, width=1)\n\t\tself.hokuyo=self.w.create_oval(x-radio/5,y-radio/5, x+radio/5,y+radio/5 ,outline=self.hokuyoColor, fill=self.hokuyoColor, width=1)\n\n\t\twheel1x1 = x - ( radio / 2 )\n\t\twheel1y1 = y - ( 5 * radio /6 )\n\t\twheel1x2 = x + radio / 2\n\t\twheel1y2 = y - ( 3 * radio / 6 )\n\t\twheel2y1 = y + ( 3 * radio / 6 )\n\t\twheel2y2 = y + ( 5 * radio / 6 )\n\t\twh1= []\n\t\twh2= []\n\t\twh1.append(self.rotate_point (angle ,x ,y ,wheel1x1 ,wheel1y1))\n\t\twh1.append(self.rotate_point (angle ,x ,y ,wheel1x2 ,wheel1y1))\n\t\twh1.append(self.rotate_point (angle ,x ,y ,wheel1x2 ,wheel1y2))\n\t\twh1.append(self.rotate_point (angle ,x ,y ,wheel1x1 ,wheel1y2))\n\t\twh2.append(self.rotate_point (angle ,x ,y ,wheel1x1 ,wheel2y1))\n\t\twh2.append(self.rotate_point (angle ,x ,y ,wheel1x2 ,wheel2y1))\n\t\twh2.append(self.rotate_point (angle ,x ,y ,wheel1x2 ,wheel2y2))\n\t\twh2.append(self.rotate_point (angle ,x ,y ,wheel1x1 ,wheel2y2))\n\t\tself.wheelL=self.w.create_polygon( wh1 ,outline = self.wheelColor, fill = self.wheelColor, width=1)\n\t\tself.wheelR=self.w.create_polygon( wh2 ,outline = self.wheelColor, fill = self.wheelColor, width=1)\n\t\thead = []\n\t\thead.append( self.rotate_point( angle ,x ,y ,x + ( 2 * radio / 3 ) ,y - ( radio / 3 ) ) )\n\t\thead.append( self.rotate_point( angle ,x ,y ,x + ( 2 * radio / 3 ) ,y + ( radio / 3 ) ) )\n\t\thead.append( self.rotate_point( angle ,x ,y ,x + ( 5 * radio / 6 ) ,y ))\n\t\tself.arrow=self.w.create_polygon( head , outline = self.arrowColor , fill = self.arrowColor , width = 1 )\n\t\tif self.grasp_id != False:\n\t\t\tself.current_object = self.w.create_rectangle(x-10, y -10 , x +10, y +10 ,fill=\"#9FFF3D\",outline=\"#9FFF3D\")\n\t\t\tself.current_object_name = self.w.create_text(x ,y , fill=\"#9E4124\",font=\"Calibri 10 bold\",text=self.grasp_id)\n\t\t\tfor obj in self.objects_data:\n\t\t\t\tif self.grasp_id == obj[0]:\n\t\t\t\t\tobj[1]= (self.robotX*self.mapX)/self.canvasX + (( (float(self.entryRadio.get()))*math.cos(float(self.entryAngle.get()))))\n\t\t\t\t\tobj[2]= ((self.canvasY -self.robotY)*self.mapY)/self.canvasY + (((float(self.entryRadio.get()))*math.sin( float(self.entryAngle.get()) )))\n\t\tself.w.update()\n\n\tdef plot_robot2(self):\n\n\t\tx = self.robotX\n\t\ty = self.robotY\n\t\tangle=self.robot_theta\n\n\t\tradio = ( float(self.entryRadio.get() ) * self.canvasX ) / self.mapX\n\t\tself.robot=self.w.create_oval(x-radio,y-radio, x+radio,y+radio , outline=self.robotColor, fill=self.robotColor, width=1)\n\t\tself.hokuyo=self.w.create_oval(x-radio/5,y-radio/5, x+radio/5,y+radio/5 ,outline=self.hokuyoColor, fill=self.hokuyoColor, width=1)\n\n\t\twheel1x1 = x - ( radio / 2 )\n\t\twheel1y1 = y - ( 5 * radio /6 )\n\t\twheel1x2 = x + radio / 2\n\t\twheel1y2 = y - ( 3 * radio / 6 )\n\t\twheel2y1 = y + ( 3 * radio / 6 )\n\t\twheel2y2 = y + ( 5 * radio / 6 )\n\t\twh1= []\n\t\twh2= []\n\t\twh1.append(self.rotate_point (angle ,x ,y ,wheel1x1 ,wheel1y1))\n\t\twh1.append(self.rotate_point (angle ,x ,y ,wheel1x2 ,wheel1y1))\n\t\twh1.append(self.rotate_point (angle ,x ,y ,wheel1x2 ,wheel1y2))\n\t\twh1.append(self.rotate_point (angle ,x ,y ,wheel1x1 ,wheel1y2))\n\t\twh2.append(self.rotate_point (angle ,x ,y ,wheel1x1 ,wheel2y1))\n\t\twh2.append(self.rotate_point (angle ,x ,y ,wheel1x2 ,wheel2y1))\n\t\twh2.append(self.rotate_point (angle ,x ,y ,wheel1x2 ,wheel2y2))\n\t\twh2.append(self.rotate_point (angle ,x ,y ,wheel1x1 ,wheel2y2))\n\t\tself.wheelL=self.w.create_polygon( wh1 ,outline = self.wheelColor, fill = self.wheelColor, width=1)\n\t\tself.wheelR=self.w.create_polygon( wh2 ,outline = self.wheelColor, fill = self.wheelColor, width=1)\n\t\thead = []\n\t\thead.append( self.rotate_point( angle ,x ,y ,x + ( 2 * radio / 3 ) ,y - ( radio / 3 ) ) )\n\t\thead.append( self.rotate_point( angle ,x ,y ,x + ( 2 * radio / 3 ) ,y + ( radio / 3 ) ) )\n\t\thead.append( self.rotate_point( angle ,x ,y ,x + ( 5 * radio / 6 ) ,y ))\n\t\tself.arrow=self.w.create_polygon( head , outline = self.arrowColor ,fill = self.arrowColor, width = 1 )\n\t\tif self.grasp_id != False:\n\t\t\tself.current_object = self.w.create_rectangle(x-10, y -10 , x +10, y +10 ,fill=\"#9FFF3D\",outline=\"#9FFF3D\")\n\t\t\tself.current_object_name = self.w.create_text(x ,y , fill=\"#9E4124\",font=\"Calibri 10 bold\",text=self.grasp_id)\n\t\t\tfor obj in self.objects_data:\n\t\t\t\tif self.grasp_id == obj[0]:\n\t\t\t\t\tobj[1]= (self.robotX*self.mapX)/self.canvasX + (( (float(self.entryRadio.get()))*math.cos(float(self.entryAngle.get()))))\n\t\t\t\t\tobj[2]= ((self.canvasY -self.robotY)*self.mapY)/self.canvasY + (((float(self.entryRadio.get()))*math.sin( float(self.entryAngle.get()) )))\n\t\tself.w.update()\n\t\ttime.sleep(.1)\n\t\t#self.laserColor = aux_color\n\t\n\n\tdef plot_robot(self):\n\t\t# It plots the robot on the field\n\t\t# The position and angle depend on the variables:\n\t\t# self.robotX, self.robotY and self.robot_theta\n\t\tself.calculate_ray_traicing()\n\t\tx = self.robotX\n\t\ty = self.robotY\n\t\tangle=self.robot_theta\n\n\t\ttry:\n\t\t\tself.entryPoseX.delete ( 0, END )\n\t\t\tself.entryPoseY.delete ( 0, END )\n\t\t\tself.entryAngle.delete ( 0, END )\n\t\t\tself.entryPoseX.insert ( 0, str(float(x)*self.mapX / self.canvasX) )\n\t\t\tself.entryPoseY.insert ( 0, str(self.mapY - (float(y)*self.mapX / self.canvasY ) )) \n\t\t\tif angle > math.pi*2 : \n\t\t\t\tangle = angle % (math.pi*2)\n\t\t\tif angle < 0 :\n\t\t\t\tangle = math.pi*2 - ( (angle * -1 ) % (math.pi*2) )\n\t\t\tself.robot_theta = angle\n\t\t\tself.entryAngle.insert ( 0, str( angle ) )\n\n\t\texcept ValueError:\n\t\t\tpass\n\n\t\tif self.flagOnce :\n\t\t\tself.delete_robot()\n\t\tself.flagOnce=True\n\n\t\tfor i in self.lasers:\n\t\t\t\tself.w.delete(i)\n\n\t\tif self.varShowSensors.get():\n\t\t\tif bool(self.varAddNoise.get() ) == True :\n\t\t\t\tself.plot_sensors(angle,x,y,\"#1dff0d\")\t\n\t\t\telse:\n\t\t\t\tself.plot_sensors(angle,x,y)\t\n\n\t\tradio = ( float(self.entryRadio.get() ) * self.canvasX ) / self.mapX\n\t\tself.robot=self.w.create_oval(x-radio,y-radio, x+radio,y+radio , outline=self.robotColor, fill=self.robotColor, width=1)\n\t\tself.hokuyo=self.w.create_oval(x-radio/5,y-radio/5, x+radio/5,y+radio/5 ,outline=self.hokuyoColor, fill=self.hokuyoColor, width=1)\n\n\t\twheel1x1 = x - ( radio / 2 )\n\t\twheel1y1 = y - ( 5 * radio /6 )\n\t\twheel1x2 = x + radio / 2\n\t\twheel1y2 = y - ( 3 * radio / 6 )\n\t\twheel2y1 = y + ( 3 * radio / 6 )\n\t\twheel2y2 = y + ( 5 * radio / 6 )\n\t\twh1= []\n\t\twh2= []\n\t\twh1.append(self.rotate_point (angle ,x ,y ,wheel1x1 ,wheel1y1))\n\t\twh1.append(self.rotate_point (angle ,x ,y ,wheel1x2 ,wheel1y1))\n\t\twh1.append(self.rotate_point (angle ,x ,y ,wheel1x2 ,wheel1y2))\n\t\twh1.append(self.rotate_point (angle ,x ,y ,wheel1x1 ,wheel1y2))\n\t\twh2.append(self.rotate_point (angle ,x ,y ,wheel1x1 ,wheel2y1))\n\t\twh2.append(self.rotate_point (angle ,x ,y ,wheel1x2 ,wheel2y1))\n\t\twh2.append(self.rotate_point (angle ,x ,y ,wheel1x2 ,wheel2y2))\n\t\twh2.append(self.rotate_point (angle ,x ,y ,wheel1x1 ,wheel2y2))\n\t\tself.wheelL=self.w.create_polygon( wh1 ,outline = self.wheelColor, fill = self.wheelColor, width=1)\n\t\tself.wheelR=self.w.create_polygon( wh2 ,outline = self.wheelColor, fill = self.wheelColor, width=1)\n\t\thead = []\n\t\thead.append( self.rotate_point( angle ,x ,y ,x + ( 2 * radio / 3 ) ,y - ( radio / 3 ) ) )\n\t\thead.append( self.rotate_point( angle ,x ,y ,x + ( 2 * radio / 3 ) ,y + ( radio / 3 ) ) )\n\t\thead.append( self.rotate_point( angle ,x ,y ,x + ( 5 * radio / 6 ) ,y ))\n\t\tif self.grasp_id != False:\n\t\t\tself.current_object = self.w.create_rectangle(x-10, y -10 , x +10, y +10 ,fill=\"#9FFF3D\",outline=\"#9FFF3D\")\n\t\t\tself.current_object_name = self.w.create_text(x ,y , fill=\"#9E4124\",font=\"Calibri 10 bold\",text=self.grasp_id)\n\t\t\tfor obj in self.objects_data:\n\t\t\t\tif self.grasp_id == obj[0]:\n\t\t\t\t\tobj[1]= (self.robotX*self.mapX)/self.canvasX + (( (float(self.entryRadio.get()))*math.cos(float(self.entryAngle.get()))))\n\t\t\t\t\tobj[2]= ((self.canvasY -self.robotY)*self.mapY)/self.canvasY + (((float(self.entryRadio.get()))*math.sin( float(self.entryAngle.get()) )))\n\t\tself.arrow=self.w.create_polygon( head , outline = self.arrowColor , fill = self.arrowColor , width = 1 )\n\t\tself.w.update()\n\n\t\n\n\tdef get_ray(self,angle,x,y,r):\n\t\treturn r * math.cos( angle ) + x ,r * ( - math.sin(angle) ) + y\n\n\t\n\tdef plot_sensors(self,angle,rx,ry,color = \"#FF0D0D\"):\n\t\t\n\t\toriginSensor = float( self.entryOrigin.get()) # -1.5707\n\t\trangeSensor = float( self.entryRange.get() ) # 240#3.1415\n\t\tnumSensor = int(self.entryNumSensors.get())\n\t\tx = rx\n\t\ty = ry\n\t\tf = angle + originSensor\n\t\tstep = float( float( rangeSensor ) / float( numSensor - 1 ) )\n\n\t\tfor i in self.lasers:\n\t\t\tself.w.delete(i)\n\t\tself.lasers = []\n\n\t\tfor i in range(0, numSensor):\t\n\t\t\tq,w =self.get_ray(f ,rx ,ry ,(self.sensors_value[i] * self.canvasX ) / self.mapX)\n\t\t\tself.lasers.append(self.w.create_line(rx ,ry ,q ,w ,fill = color) )\n\n\t\t\tif float(self.sensors_value[i]) < float(self.entryValue.get()) :\n\n\t\t\t\tself.lasers.append(self.w.create_oval(q-1 ,w-1,q+1 ,w+1 ,fill = color, outline =color ) )\n\t\t\tf = f + step\n\t\t\n\tdef delete_robot(self):\n\n\t\tself.w.delete(self.robot)\n\t\tself.w.delete(self.wheelL)\n\t\tself.w.delete(self.wheelR)\n\t\tself.w.delete(self.arrow)\n\t\tself.w.delete(self.hokuyo)\n\t\tself.w.delete(self.current_object)\n\t\tself.w.delete(self.current_object_name)\n\t\t\n\tdef move_robot(self,*args):\n\n\t\ttheta = float(self.p_giro)\n\t\tdistance = float(self.p_distance) \n\t\t\n\t\tinit_robotX = self.robotX\n\t\tinit_robotY = self.robotY\n\t\tinit_robotAngle = self.robot_theta\n\t\ti = self.robot_theta\n\n\t\tif self.varFaster.get() or self.varTurtleBot.get():\n\t\t\tself.plot_robot();\t\t\t\n\t\t\tself.robot_theta = init_robotAngle + theta\n\t\t\tself.robotX=distance * math.cos(self.robot_theta) + self.robotX\n\t\t\tself.robotY=-( distance * math.sin(self.robot_theta) )+ self.robotY\n\t\t\txf = self.robotX\n\t\t\tyf = self.robotY\n\n\t\telse:\n\t\t\tself.plot_robot();\n\t\t\t\n\t\t\tif theta ==0:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tif theta > 0 :\n\t\t\t\t\twhile i < init_robotAngle + theta:\n\t\t\t\t\t\ti = i + (0.0174533*2)*self.sliderVelocity.get()\n\t\t\t\t\t\tself.robot_theta = i\n\t\t\t\t\t\tself.plot_robot()\n\t\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\twhile i > init_robotAngle + theta:\n\t\t\t\t\t\ti = i - (0.0174533*2)*self.sliderVelocity.get()\n\t\t\t\t\t\tself.robot_theta = i\n\t\t\t\t\t\tself.plot_robot()\n\t\t\t\t\t\t\n\t\t\t\tself.robot_theta = init_robotAngle + theta\n\t\t\t\tself.plot_robot()\n\n\t\t\txf = distance * math.cos(self.robot_theta) + self.robotX\n\n\t\t\tyf = -( distance * math.sin(self.robot_theta) )+ self.robotY\n\n\n\t\t\tx = auxX = init_robotX\n\t\t\ty = auxY = init_robotY\n\t\t\tm = -math.tan(self.robot_theta)\n\n\t\t\tif xf==auxX :\n\t\t\t\tif yf <= auxY:\n\t\t\t\t\twhile y < yf:\n\t\t\t\t\t\ty = y - self.sliderVelocity.get()\n\t\t\t\t\t\tif(y > yf): \n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tself.robotY=y\n\t\t\t\t\t\tself.plot_robot()\n\t\t\t\telse:\n\t\t\t\t\twhile y > yf:\n\t\t\t\t\t\ty = y + self.sliderVelocity.get()\n\t\t\t\t\t\tif(y < yf): \n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tself.robotY=y\n\t\t\t\t\t\tself.plot_robot()\n\t\t\t\tself.robotY = yf\n\t\t\t\tself.plot_robot()\n\t\t\telse: # Calculos con punto pendiente y2 -y1= m ( x2 - x1)\n\t\t\t\tif m < -1 or m > 1 : # Si los angulos caen en este rango en vez de evaluar y evaluaremos x\n\n\t\t\t\t\tif yf > auxY:\n\t\t\t\t\t\twhile y < yf:\n\t\t\t\t\t\t\tx = -( (y - auxY) / math.tan(self.robot_theta) -auxX\t)\n\t\t\t\t\t\t\ty = y + self.sliderVelocity.get()\n\t\t\t\t\t\t\tif(y > yf): \n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tself.robotX=x\n\t\t\t\t\t\t\tself.robotY=y\n\t\t\t\t\t\t\tself.plot_robot()\t\n\t\t\t\t\telse:\n\t\t\t\t\t\twhile y > yf:\n\t\t\t\t\t\t\tx = -( (y - auxY) / math.tan(self.robot_theta) -auxX) \n\t\t\t\t\t\t\ty = y - self.sliderVelocity.get()\n\t\t\t\t\t\t\tif(y < yf): \n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tself.robotX=x\n\t\t\t\t\t\t\tself.robotY=y\n\t\t\t\t\t\t\tself.plot_robot()\t\n\t\t\t\telse:\n\n\t\t\t\t\tif xf > auxX:\n\t\t\t\t\t\twhile x < xf:\n\t\t\t\t\t\t\ty = -math.tan(self.robot_theta) * (x - auxX) + auxY\n\t\t\t\t\t\t\t#print(y)\n\t\t\t\t\t\t\tx = x + self.sliderVelocity.get()\n\t\t\t\t\t\t\tif(x > xf): \n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tself.robotX=x\n\t\t\t\t\t\t\tself.robotY=y\n\t\t\t\t\t\t\tself.plot_robot()\t\n \n\t\t\t\t\telse:\n\t\t\t\t\t\twhile x > xf:\n\t\t\t\t\t\t\ty = -math.tan(self.robot_theta) * (x - auxX) + auxY\n\t\t\t\t\t\t\tx = x - self.sliderVelocity.get()\n\t\t\t\t\t\t\tif(x < xf): \n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tself.robotX=x\n\t\t\t\t\t\t\tself.robotY=y\n\t\t\t\t\t\t\tself.plot_robot()\t\n\t\t\t\tself.robotX = xf\n\t\t\t\tself.robotY = yf\n\n\t\t\t\tself.plot_robot()\n\n\n\n\t\tself.trace_route.append(self.w.create_line(init_robotX ,init_robotY ,xf,yf,dash=(4, 4), fill=\"#AB1111\"))\n\t\n\n\tdef print_grid(self,line_per_m = 10):\n\t\tfor i in self.grid :\n\t\t\tself.w.delete(i)\n\t\tself.grid =[]\n\n\t\tfor i in range(0, int(self.mapX)*line_per_m):\n\t\t\tself.grid.append(self.w.create_line( i * self.canvasX/(self.mapX*line_per_m),0, i*self.canvasX/(self.mapX*line_per_m), self.canvasY, dash=(4, 4), fill=self.gridColor))\n\t\tfor i in range(0, int(self.mapY)*line_per_m):\n\t\t\tself.grid.append(self.w.create_line( 0, i*self.canvasY/(self.mapY*line_per_m),self.canvasX, i*self.canvasY/(self.mapY*line_per_m), dash=(4, 4), fill=self.gridColor))\n\n\tdef behavioLess(self): #Button behavior <\n\t\ttry:\n\t\t\tnewbehavior=int(self.entryBehavior.get())\n\t\t\tself.entryBehavior.delete ( 0, END )\n\t\t\tself.entryBehavior.insert ( 0, str(newbehavior-1) )\n\t\texcept ValueError:\n\t\t\tself.entryBehavior.delete ( 0, END )\n\t\t\tself.entryBehavior.insert ( 0, '1' )\n\t\n\tdef behavioMore(self): #Button behavior >\n\t\ttry:\n\t\t\tnewbehavior=int(self.entryBehavior.get())\n\t\t\tself.entryBehavior.delete ( 0, END )\n\t\t\tself.entryBehavior.insert ( 0, str(newbehavior+1) )\n\t\texcept ValueError:\n\t\t\tself.entryBehavior.delete ( 0, END )\n\t\t\tself.entryBehavior.insert ( 0, '1' )\n\tdef set_angle(self,foo): #\n\t\tself.robot_theta = float(self.entryAngle.get())\n\t\tself.plot_robot()\n\n\tdef moveBotFoward(self):\n\t\tself.movement = [1, 0, 0, 0]\n\n\tdef moveBotBackward(self):\n\t\tself.movement = [0, 1, 0, 0]\n\n\tdef moveBotLeft(self):\n\t\tself.movement = [0, 0, 1, 0]\n\t\t\n\tdef moveBotRight(self):\n\t\tself.movement = [0, 0, 0, 1]\n\n\tdef moveBotStop(self):\n\t\tself.movement = []\n\t\n\tdef viewArena(self):\n\t\tprint \"Open viewer\"\n\t\tos.system(\"rosparam set /show_image true\")\n\t\t\n\n\tdef compileMessage(self):\n\t\tstatus = os.system(\"cd ~/MobileRobotSimulator/catkin_ws && catkin_make\")\n\t\tif status == 0:\n\t\t\ttkMessageBox.showinfo(\"Code compilated\", \"Compilation Successful\")\n\t\telse:\n\t\t\ttkMessageBox.showerror(\"Compilation Error\", \"Code no compiled, there's an error in your code. :( \")\n\n\tdef playRecording(self):\n\t\tself.play_record = True\n\n\tdef startRecording(self):\n\t\tself.start_record = True\n\t\n\tdef stopRecording(self):\n\t\tself.finish_record = True\n\n\tdef set_zero_angle(self): #\n\t\tself.robot_theta = 0.0\n\t\tself.plot_robot()\t\n\n\tdef denable(self,state): # It disables some widgets when a simulation is running\n\t\tself.buttonPlotTopological.configure(state=state) \n\t\tself.entryFile .configure(state=state) \n\t\t#self.entrySteps .configure(state=state) \n\t\tself.buttonBehaviorLess .configure(state=state) \n\t\tself.entryBehavior \t.configure(state=state) \n\t\tself.buttonBehaviorMore .configure(state=state) \n\t\tself.checkFaster .configure(state=state) \n\t\tself.checkShowSensors .configure(state=state) \n\t\tself.checkAddNoise .configure(state=state) \n\t\tself.entryRobot .configure(state=state) \n\t\t#self.entryPoseX .configure(state=state) \n\t\t#self.entryPoseY .configure(state=state) \n\t\t#self.entryAngle .configure(state=state) \n\t\tself.entryRadio .configure(state=state) \n\t\tself.entryAdvance .configure(state=state) \n\t\tself.entryTurnAngle .configure(state=state) \n\t\tself.entryNumSensors .configure(state=state) \n\t\tself.entryOrigin .configure(state=state) \n\t\tself.entryRange .configure(state=state) \n\t\tself.entryValue .configure(state=state)\n\t\tself.buttonLastSimulation.configure(state=state) \n\t\tself.buttonRunSimulation.configure(state=state) \n\t\t#self.buttonStop \n\n\tdef mapMore(self):\n\t\tself.mapX = self.mapX-1 \n\t\tself.mapY = self.mapY-1 \n\t\tself.print_grid(1)\n\tdef mapLess(self):\n\t\tself.mapX = self.mapX+1 \n\t\tself.mapY = self.mapY+1\n\t\tself.print_grid(1)\n\n\tdef start_rviz(self):\n\t\tsubprocess.Popen([self.rospack.get_path('simulator')+'/src/gui/start_rviz.sh'])\n\t\t\n\n\tdef NewFile():\n\t\tprint (\"\")\n\tdef OpenFile():\n\t\tprint (\"\")\n\tdef About():\n\t\tprint (\"\")\n\t\n\n\tdef resizeCanvas(self,x,y):\n\t\tself.robotX = self.robotX * x / self.canvasX\n\t\tself.robotY = self.robotY * y / self.canvasY\n\t\tself.canvasX =x\n\t\tself.canvasY =y\n\t\tself.w.configure(width = self.canvasX, height = self.canvasY)\n\t\tself.changeTheme()\n\n\tdef changeTheme(self):\n\t\tself.w.configure(bg = self.canvasColor)\n\t\tself.print_grid()\n\t\tself.read_map()\n\t\tself.buttonBehaviorLess.configure(background=self.buttonColor, foreground = self.buttonFontColor)\n\t\tself.buttonBehaviorMore.configure(background=self.buttonColor, foreground = self.buttonFontColor)\n\t\tself.buttonRunSimulation.configure(background=self.buttonColor, foreground = self.buttonFontColor)\n\t\tself.buttonLastSimulation.configure(background=self.buttonColor, foreground = self.buttonFontColor)\n\t\tself.buttonPlotTopological.configure(background=self.buttonColor, foreground = self.buttonFontColor)\n\t\tself.buttonStop.configure(background=self.buttonColor, foreground = self.buttonFontColor)\n\t\tself.plot_robot()\n\n\tdef whiteTheme(self):\n\t\tself.obstacleInnerColor = '#447CFF'\n\t\tself.obstaclesOutlineColor=\"#216E7D\"#'#002B7A'\n\t\tself.buttonColor = \"#1373E6\"\n\t\tself.buttonFontColor = \"#FFFFFF\"\n\t\tself.canvasColor = \"#FFFFFF\"\n\t\tself.gridColor = \"#D1D2D4\"\n\t\tself.wheelColor = '#404000' \n\t\tself.robotColor = '#F7CE3F' \n\t\tself.hokuyoColor = '#4F58DB' \n\t\tself.arrowColor = '#1AAB4A' \n\t\tself.laserColor = \"#00DD41\" \n\t\tself.changeTheme()\n\n\tdef darkTheme(self):\n\t\tself.obstacleInnerColor = '#003B00'\n\t\tself.obstaclesOutlineColor=\"#00FF41\"#'#002B7A'\n\t\tself.buttonColor = \"#3F4242\"\n\t\tself.buttonFontColor = \"#FFFFFF\"\n\t\tself.canvasColor = \"#0D0208\"\n\t\tself.gridColor = \"#333333\"\n\t\tself.wheelColor = '#404000' \n\t\tself.robotColor = '#FF1008' \n\t\tself.hokuyoColor = '#006BFF' \n\t\tself.arrowColor = '#006BFF' \n\t\tself.laserColor = \"#08FFFB\" \n\t\tself.changeTheme()\n\n\tdef gui_init(self):\n\n\t\tself.backgroundColor = '#EDEDED';#\"#FCFCFC\";\n\t\tself.entrybackgroudColor = \"#FBFBFB\";##1A3A6D\";\n\t\tself.entryforegroundColor = '#37363A';\n\t\tself.titlesColor = \"#303133\"\n\t\tself.menuColor = \"#ECECEC\"\n\t\tself.menuButonColor = \"#375ACC\"\n\t\tself.menuButonFontColor = \"#FFFFFF\"\n\t\tself.obstacleInnerColor = '#447CFF'\n\t\tself.obstaclesOutlineColor=\"#216E7D\"#'#002B7A'\n\t\tself.buttonColor = \"#1373E6\"\n\t\tself.buttonFontColor = \"#FFFFFF\"\n\t\tself.canvasColor = \"#FFFFFF\"\n\t\tself.gridColor = \"#D1D2D4\"\n\t\tself.wheelColor = '#404000' \n\t\tself.robotColor = '#F7CE3F' \n\t\tself.hokuyoColor = '#4F58DB' \n\t\tself.arrowColor = '#1AAB4A' \n\t\tself.laserColor = \"#00DD41\" \n\t\tself.warnLightColor = '#F7FD2A'\n\t\tself.warnStrongColor = '#EEF511' \n\t\tself.errorLightColor = '#FA0A0A'\n\t\tself.errorStrongColor = \"#E10B0B\"\n\t\t\n\t\tself.root = Tk()\n\t\tself.root.protocol(\"WM_DELETE_WINDOW\", self.kill)\n\t\tself.root.title(\"Mobile Robot Simulator\")\n\t\tself.screen_width_max = self.root.winfo_screenwidth() - 650\n self.screen_height_max = self.root.winfo_screenheight() - 100\n\n\t\tself.barMenu = Menu(self.root)\n\t\tself.settingsMenu = Menu(self.barMenu, tearoff=0)\n\t\tself.submenuTheme = Menu(self.settingsMenu, tearoff=0)\n\t\tself.submenuCanvas = Menu(self.settingsMenu, tearoff=0)\n\t\tself.root.config(menu=self.barMenu )\n\t\tself.barMenu.config(background = self.menuColor)\n\n\t\t\n\t\tself.barMenu.add_cascade(label=\" Settings \", menu=self.settingsMenu,background = self.menuButonFontColor )\n\t\tself.settingsMenu.add_cascade(label=\" Canvas size \", menu=self.submenuCanvas,background = self.menuButonFontColor)\n\t\tself.settingsMenu.add_cascade(label=\" Theme \", menu=self.submenuTheme,background = self.menuButonFontColor)\n\t\tself.submenuTheme.add_command(label=\" White \", command=self.whiteTheme)\n\t\tself.submenuTheme.add_command(label=\" Dark \", command=self.darkTheme)\n\t\t\n\t\tself.submenuCanvas.add_command(label=\" 600 x 600 \", command= lambda : self.resizeCanvas(600,600) )\n\t\tself.submenuCanvas.add_command(label=\" 700 x 700 \", command= lambda : self.resizeCanvas(700,700) )\n\t\tself.submenuCanvas.add_command(label=\" 800 x 800 \", command= lambda : self.resizeCanvas(800,800) )\n\n\n\t\tself.helpMenu = Menu(self.barMenu, tearoff=0)\n\t\tself.helpMenu.add_command(label=\" Topological map \", command=self.NewFile)\n\t\tself.helpMenu.add_command(label=\" User guide \", command=self.OpenFile)\n\t\tself.helpMenu.add_command(label=\" ROS nodes \", command=self.root.quit)\n\t\tself.barMenu.add_cascade(label=\"Help\", menu=self.helpMenu,background = self.menuButonFontColor)\n\t\t\t\n\t\n\t\tself.content = Frame(self.root)\n\t\tself.frame = Frame(self.content,borderwidth = 5, relief = \"flat\", width = 600, height = 900 ,background = self.backgroundColor)\n\t\tself.rightMenu = Frame(self.content,borderwidth = 5, relief = \"flat\", width = 300, height = 900 ,background = self.backgroundColor)\n\t\tself.w = Canvas(self.frame, width = self.canvasX, height = self.canvasY, bg=self.canvasColor)\n\t\tself.w.pack()\n\t\t\n\t\tself.headLineFont = Font( family = 'Helvetica' ,size = 12, weight = 'bold')\n\t\tself.lineFont = Font( family = 'Helvetica' ,size = 10, weight = 'bold')\n\t\tself.buttonFont = Font( family = 'Helvetica' ,size = 8, weight = 'bold')\n\n\n\t\tself.lableEnvironment = Label(self.rightMenu ,text = \"Settings\" ,background = self.backgroundColor ,foreground = self.titlesColor ,font = self.headLineFont)\n\t\tself.labelFile = Label(self.rightMenu ,text = \"Environment:\" ,background = self.backgroundColor ,font = self.lineFont)\n\t\tself.labelSteps = Label(self.rightMenu ,text = \"Steps:\" ,background = self.backgroundColor ,font = self.lineFont)\n\t\tself.labelBehavior\t\t= Label(self.rightMenu ,text = \"Behavior:\" ,background = self.backgroundColor ,font = self.lineFont)\n\t\tself.labelLightX = Label(self.rightMenu ,text = \"Light X:\" ,background = self.backgroundColor ,font = self.lineFont)\n\t\tself.labelLightY = Label(self.rightMenu ,text = \"Light Y:\" ,background = self.backgroundColor ,font = self.lineFont)\n\t\tself.labelStepsExcec = Label(self.rightMenu ,text = \"Steps:\" ,background = self.backgroundColor ,font = self.lineFont)\n\t\tself.labelConfiguration = Label(self.rightMenu ,text = \"Configurations:\" ,background = self.backgroundColor ,font = self.lineFont)\n\t\t\t\n\t\tself.entryFile = Entry(self.rightMenu ,width = 15 ,foreground = self.entryforegroundColor ,background = self.entrybackgroudColor )\n\t\tself.entryFile.bind('<Return>', self.map_change)\n\t\tself.entrySteps = Entry(self.rightMenu ,width = 15 ,foreground = self.entryforegroundColor ,background = self.entrybackgroudColor )\n\n\t\tself.buttonBehaviorLess = Button(self.rightMenu ,width = 1, foreground = self.buttonFontColor, background = self.buttonColor , font = self.buttonFont ,text = \"<\" ,command = self.behavioLess)\n\t\tself.entryBehavior \t = Entry(self.rightMenu ,width = 4 ,foreground = self.entryforegroundColor ,background = self.entrybackgroudColor ,justify='center' )\n\t\tself.buttonBehaviorMore = Button(self.rightMenu ,width = 1, foreground = self.buttonFontColor, background = self.buttonColor , font = self.buttonFont, text = \">\" ,command = self.behavioMore)\n\t\t\n\t\tself.entryLightX = Label(self.rightMenu ,text = \"Click Right\" ,background = self.backgroundColor ,font = self.lineFont ,justify='center')\n\t\tself.entryLightY = Label(self.rightMenu ,text = \"Click Right\" ,background = self.backgroundColor ,font = self.lineFont ,justify='center')\n\t\tself.entryStepsExcec = Label(self.rightMenu ,text = \"0\" ,background = self.backgroundColor ,font = self.lineFont ,justify='center')\n\t\tself.entryFile.insert ( 0, 'arena2' )\n\t\tself.entrySteps.insert( 0, '100' )\n\t\tself.entryBehavior.insert ( 0, '4' )\n\n\t\tself.buttonMapLess = Button(self.rightMenu ,width = 5, foreground = self.buttonFontColor, background = self.buttonColor , font = self.buttonFont ,text = \"Zoom Out\" ,command = self.mapLess)\n\t\tself.buttonMapMore = Button(self.rightMenu ,width = 5, foreground = self.buttonFontColor, background = self.buttonColor , font = self.buttonFont, text = \"Zoom In \" ,command = self.mapMore)\n\n\t\t##### Rigth menu widgets declaration\n\n\t\t# Environment\n\n\t\tself.varFaster = IntVar()\n\t\tself.varShowSensors = IntVar()\n\t\tself.varAddNoise = IntVar()\n\t\tself.varLoadObjects = IntVar()\n\t\t\n\n\t\tself.checkFaster = Checkbutton(self.rightMenu ,text = 'Fast Mode' ,variable = self.varFaster ,onvalue = 1 ,offvalue = 0 ,background = self.backgroundColor)\n\t\tself.checkShowSensors = Checkbutton(self.rightMenu ,text = 'Show Sensors' ,variable = self.varShowSensors ,onvalue = 1 ,offvalue = 0 ,background = self.backgroundColor)\n\t\tself.checkAddNoise = Checkbutton(self.rightMenu ,text = 'Add Noise' ,variable = self.varAddNoise ,onvalue = 1 ,offvalue = 0 ,background = self.backgroundColor)\n\t\tself.checkLoadObjects = Checkbutton(self.rightMenu ,text = 'Load Objects' ,variable = self.varLoadObjects ,onvalue = 1 ,offvalue = 0 ,background = self.backgroundColor,command = self.read_objects)\n\t\t\n\t\trecord_img = Image.open(self.rospack.get_path('simulator')+'/src/gui/recording.png')\n\t\tstop_img = Image.open(self.rospack.get_path('simulator')+'/src/gui/stop.png')\n\t\tplay_img = Image.open(self.rospack.get_path('simulator')+'/src/gui/play.png')\n\n\t\trecord_img = record_img.resize((20,20), Image.ANTIALIAS)\n\t\tstop_img = stop_img.resize((20,20), Image.ANTIALIAS)\n\t\tplay_img = play_img.resize((20,20), Image.ANTIALIAS)\n\n\t\tself.recordImg = ImageTk.PhotoImage(record_img)\n\t\tself.stopImg = ImageTk.PhotoImage(stop_img)\n\t\tself.playImg = ImageTk.PhotoImage(play_img)\n\n\t\t#self.recordImg = PhotoImage( file = self.rospack.get_path('simulator')+'/src/gui/recording.png')\n\t\tself.checkFaster .deselect()\n\t\tself.checkShowSensors .select()\n\t\tself.checkAddNoise .deselect()\n\t\tself.checkLoadObjects .deselect()\n\t\n\t\t# Robot \n\n\t\tself.labelRobot = Label(self.rightMenu ,text = \"Robot\" ,background = self.backgroundColor ,foreground = self.titlesColor ,font = self.headLineFont )\n\t\tself.labelPoseX = Label(self.rightMenu ,text = \"Pose X:\" ,background = self.backgroundColor ,font = self.lineFont)\n\t\tself.labelPoseY = Label(self.rightMenu ,text = \"Pose Y:\" ,background = self.backgroundColor ,font = self.lineFont)\n\t\tself.labelAngle = Label(self.rightMenu ,text = \"Angle:\" ,background = self.backgroundColor ,font = self.lineFont)\n\t\tself.labelRadio = Label(self.rightMenu ,text = \"Radio:\" ,background = self.backgroundColor ,font = self.lineFont)\n\t\tself.labelAdvance = Label(self.rightMenu ,text = \"Magnitude Advance:\" ,background = self.backgroundColor ,font = self.lineFont)\n\t\tself.labelTurnAngle = Label(self.rightMenu ,text = \"Turn Angle:\" ,background = self.backgroundColor ,font = self.lineFont)\n\n\n\t\tself.entryRobot = Entry(self.rightMenu, width = 8 ,background = self.entrybackgroudColor ,foreground = self.entryforegroundColor)\n\t\tself.entryPoseX = Entry(self.rightMenu, width = 8 ,background = self.entrybackgroudColor ,foreground = self.entryforegroundColor)\n\t\tself.entryPoseY = Entry(self.rightMenu, width = 8 ,background = self.entrybackgroudColor ,foreground = self.entryforegroundColor)\n\t\tself.entryAngle = Entry(self.rightMenu, width = 8 ,background = self.entrybackgroudColor ,foreground = self.entryforegroundColor)\n\t\tself.buttonSetZero = Button(self.rightMenu ,width = 8, text = \"Angle Zero\", foreground = self.buttonFontColor ,background = self.buttonColor, font = self.buttonFont, command = self.set_zero_angle )\n\t\tself.entryRadio = Entry(self.rightMenu, width = 8 ,background = self.entrybackgroudColor ,foreground = self.entryforegroundColor)\n\t\tself.entryAdvance = Entry(self.rightMenu, width = 8 ,background = self.entrybackgroudColor ,foreground = self.entryforegroundColor)\n\t\tself.entryTurnAngle = Entry(self.rightMenu, width = 8 ,background = self.entrybackgroudColor ,foreground = self.entryforegroundColor)\n\n\t\tself.entryPoseX .insert ( 0, '0.5' )\n\t\tself.entryPoseY .insert ( 0, '200' )\n\t\tself.entryAngle .insert ( 0, '0.0' )\n\t\tself.entryAngle.bind('<Return>', self.set_angle)\n\t\tself.entryRadio .insert ( 0, '0.06' )\n\t\tself.entryAdvance .insert ( 0, '0.04' )\n\t\tself.entryTurnAngle .insert ( 0, '0.7857' )\n\n\t\tself.labelVelocity = Label(self.rightMenu ,text = \"Execution velocity:\" ,background = self.backgroundColor ,font = self.lineFont)\n\t\tself.sliderVelocity =Scale(self.rightMenu, from_=1, to=3, orient=HORIZONTAL ,length=150 ,background = self.backgroundColor ,font = self.lineFont)\n\t\t\n\n\t\t# Sensors\n\n\t\tself.lableSensors = Label(self.rightMenu, text = \"Sensors\" ,background = self.backgroundColor ,foreground = self.titlesColor ,font = self.headLineFont)\n\t\tself.labelNumSensors = Label(self.rightMenu, text = \"Num Sensors:\" ,background = self.backgroundColor ,font = self.lineFont)\n\t\tself.labelOrigin = Label(self.rightMenu, text = \"Origin angle:\" ,background = self.backgroundColor ,font = self.lineFont)\n\t\tself.labelRange = Label(self.rightMenu, text = \"Range:\" ,background = self.backgroundColor ,font = self.lineFont)\n\t\tself.labelValue = Label(self.rightMenu, text = \"Value:\" ,background = self.backgroundColor ,font = self.lineFont)\n\n\t\tself.entryNumSensors = Entry(self.rightMenu, width = 8 ,background = self.entrybackgroudColor ,foreground = self.entryforegroundColor)\n\t\tself.entryOrigin = Entry(self.rightMenu, width = 8 ,background = self.entrybackgroudColor ,foreground = self.entryforegroundColor)\n\t\tself.entryRange = Entry(self.rightMenu, width = 8 ,background = self.entrybackgroudColor ,foreground = self.entryforegroundColor)\n\t\tself.entryValue = Entry(self.rightMenu, width = 8 ,background = self.entrybackgroudColor ,foreground = self.entryforegroundColor)\n\n\t\tself.entryNumSensors .insert ( 0, '20')\n\t\tself.entryOrigin .insert ( 0, '-1.5707' )\n\t\tself.entryRange .insert ( 0, '3.1415' )\n\t\tself.entryValue .insert ( 0, '0.05' )\n\n\t\t# buttons\n\n\t\tself.lableSimulator = Label (self.rightMenu ,text = \"Simulator\" ,background = self.backgroundColor ,foreground = self.titlesColor ,font = self.headLineFont)\n\t\tself.buttonRviz = Button(self.rightMenu ,width = 20, text = \"Open Rviz\", foreground = self.buttonFontColor ,background = self.buttonColor, font = self.buttonFont, command = self.start_rviz )\n\t\tself.buttonPlotTopological = Button(self.rightMenu ,width = 20, text = \"Plot Topological\", foreground = self.buttonFontColor ,background = self.buttonColor, font = self.buttonFont ,command = self.print_topological_map )\n\t\tself.buttonLastSimulation = Button(self.rightMenu ,width = 20, text = \"Run last simulation\" ,state=\"disabled\", foreground = self.buttonFontColor ,background = self.buttonColor , font = self.buttonFont ,command = self.rewindF )\n\t\tself.buttonRunSimulation = Button(self.rightMenu ,width = 20, text = \"Run simulation\", foreground = self.buttonFontColor ,background = self.buttonColor,font = self.buttonFont,command = lambda: self.s_t_simulation(True) )\n\t\tself.buttonStop = Button(self.rightMenu ,width = 20, text = \"Stop\", foreground = self.buttonFontColor ,background = self.buttonColor, font = self.buttonFont, command = lambda: self.s_t_simulation(False) )\n\t\tself.labelBattery = Label(self.rightMenu ,text = \"Battery Charge:\", background = self.backgroundColor ,font = self.lineFont)\n\t\tself.batteryBar = ttk.Progressbar(self.rightMenu, orient=HORIZONTAL, mode='determinate', length=150)\n\t\tself.batteryBar['value'] = 0\n\t\tself.labelBattAdvertise = Label(self.rightMenu, text = \"Battery Low\", background = self.errorStrongColor, foreground = self.titlesColor, font = self.headLineFont)\n\t\tself.labelVideoNamed = Label(self.rightMenu, text = \"No video saved\", font = self.lineFont)\n\n\t\tself.lableTurtleBot = Label(self.rightMenu, text = \"Real robot\" ,background = self.backgroundColor ,foreground = self.titlesColor ,font = self.headLineFont)\n\t\tself.labelMoveBot = Label(self.rightMenu, text = \"Move robot\", background = self.backgroundColor ,font = self.lineFont)\n\t\tself.varTurtleBot = IntVar()\n\t\tself.varLidar = IntVar(value=1)\n\t\tself.varSArray = IntVar()\n\t\tself.varLight1 = IntVar()\n\t\tself.varLight2 = IntVar()\n\t\tself.checkTurtleBot = Checkbutton(self.rightMenu ,text = 'Use real robot' ,variable = self.varTurtleBot ,onvalue = 1 ,offvalue = 0 ,background = self.backgroundColor, command = self.use_real_robot )\n\t\tself.checkLidar = Checkbutton(self.rightMenu ,text = 'Use lidar' ,variable = self.varLidar ,onvalue = 1 ,offvalue = 0 ,background = self.backgroundColor, command = self.use_lidar )\n\t\tself.checkSArray = Checkbutton(self.rightMenu ,text = 'Sensors array' ,variable = self.varSArray ,onvalue = 1 ,offvalue = 0 ,background = self.backgroundColor, command = self.use_s_array )\n\t\tself.checkLight1 = Checkbutton(self.rightMenu, text = 'Turn on light 1', variable = self.varLight1, onvalue = 1, offvalue = 0, background = self.backgroundColor, command = self.turn_light)\n\t\tself.checkLight2 = Checkbutton(self.rightMenu, text = 'Turn on light 2', variable = self.varLight2, onvalue = 1, offvalue = 0, background = self.backgroundColor, command = self.turn_light)\n\t\tself.buttonMoveFoward = Button(self.rightMenu, width = 1, foreground = self.buttonFontColor, background = self.buttonColor , font = self.buttonFont, text = \"^\", command = self.moveBotFoward)\n\t\tself.buttonMoveLeft = Button(self.rightMenu, width = 1, foreground = self.buttonFontColor, background = self.buttonColor , font = self.buttonFont, text = \"<\", command = self.moveBotLeft)\n\t\tself.buttonMoveRight = Button(self.rightMenu, width = 1, foreground = self.buttonFontColor, background = self.buttonColor , font = self.buttonFont, text = \">\", command = self.moveBotRight)\n\t\tself.buttonMoveBackward = Button(self.rightMenu, width = 1, foreground = self.buttonFontColor, background = self.buttonColor , font = self.buttonFont, text = \"v\", command = self.moveBotBackward)\n\t\tself.buttonMoveStop = Button(self.rightMenu, width = 1, foreground = self.buttonFontColor, background = self.buttonColor , font = self.buttonFont, text =\"||\", command = self.moveBotStop)\n\t\tself.buttonCompile\t\t = Button(self.rightMenu, width = 8, height = 2, font = self.buttonFont, text =\"Compile\", command = self.compileMessage)\n\t\tself.buttonViewerArena\t = Button(self.rightMenu, width = 10, height = 2, foreground = self.buttonFontColor, background = self.buttonColor , font = self.buttonFont, text =\"View real\", command = self.viewArena)\n\t\tself.buttonReturnHome\t = Button(self.rightMenu, width = 10, height = 2, foreground = self.buttonFontColor, background = self.buttonColor , font = self.buttonFont, text =\"Return home\", command = self.viewArena)\n\n\t\tself.buttonStartRecording = Button(self.rightMenu, image = self.recordImg, width = 20, font = self.buttonFont, command = self.startRecording)\n\t\tself.buttonStopRecording = Button(self.rightMenu, image = self.stopImg, width = 20, font = self.buttonFont, command = self.stopRecording)\n\t\tself.buttonPlayRecording = Button(self.rightMenu, image = self.playImg, width = 20, font = self.buttonFont, command = self.playRecording)\n\t\t#### Right menu widgets grid\t\t\t\n\n\t\t# Environment\n\t\tself.lableEnvironment .grid(column = 0 ,row = 0 ,sticky = (N, W) ,padx = (5,5))\n\t\tself.labelFile .grid(column = 0 ,row = 1 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.labelSteps .grid(column = 0 ,row = 2 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.labelBehavior .grid(column = 0 ,row = 3 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.labelLightX .grid(column = 0 ,row = 4 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.labelLightY .grid(column = 0 ,row = 5 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.labelStepsExcec .grid(column = 0 ,row = 6 ,sticky = (N, W) ,padx = (10,5))\n\n\t\tself.labelConfiguration.grid(column = 0 ,row = 7 ,sticky = (N, W) ,padx = (10,5))\n\n\t\tself.entryFile .grid(column = 1 ,row = 1 ,columnspan = 2 ,sticky = (N, W) ,padx = 5)\n\t\tself.entrySteps\t\t .grid(column = 1 ,row = 2 ,columnspan = 2 ,sticky = (N, W) ,padx = 5)\t\n\t\t\n\t\tself.buttonBehaviorLess.grid(column = 1 ,row = 3 ,columnspan = 1 ,sticky = (N, W) ,padx = 5)\n\t\tself.entryBehavior .grid(column = 1 ,row = 3 ,columnspan = 1 ,padx = 50)\n\t\tself.buttonBehaviorMore.grid(column = 1 ,row = 3 ,columnspan = 1 ,sticky = (N, E) ,padx = 5)\n\t\t\n\t\tself.entryLightX.grid(column = 1 ,row = 4 ,columnspan = 2 ,sticky = (N, W) ,padx = 5)\n\t\tself.entryLightY.grid(column = 1 ,row = 5 ,columnspan = 2 ,sticky = (N, W) ,padx = 5)\n\t\tself.entryStepsExcec.grid(column = 1 ,row = 6 ,columnspan = 2 ,sticky = (N, W) ,padx = 5)\n\t\t\n\n\t\tself.checkFaster .grid(column = 1 ,row = 7 ,sticky = (N, W) ,padx = 5)\n\t\tself.checkShowSensors.grid(column = 1 ,row = 8 ,sticky = (N, W) ,padx = 5)\n\t\tself.checkAddNoise .grid(column = 1 ,row = 9 ,sticky = (N, W) ,padx = 5)\n\t\tself.checkLoadObjects .grid(column = 1 ,row = 10 ,sticky = (N, W) ,padx = 5)\n\t\t\n\t\t# Robot\n\n\t\tself.labelRobot .grid(column = 4 ,row = 0 ,sticky = (N, W) ,padx = (5,5)) \n\t\tself.labelPoseX .grid(column = 4 ,row = 1 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.labelPoseY .grid(column = 4 ,row = 2 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.labelAngle .grid(column = 4 ,row = 3 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.labelRadio .grid(column = 4 ,row = 5 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.labelAdvance .grid(column = 4 ,row = 6 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.labelTurnAngle .grid(column = 4 ,row = 7 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.labelVelocity\t.grid(column = 4 ,row = 8 ,sticky = (N, W) ,padx = (10,5))\n\t\t\n\t\tself.sliderVelocity .grid(column = 4 ,row = 9 ,columnspan = 2 ,rowspan = 2 ,sticky = (N, W), padx = 5)\n\n\t\tself.entryPoseX .grid(column = 5 ,row = 1 ,columnspan = 2 ,sticky = (N, W), padx = 5)\n\t\tself.entryPoseY .grid(column = 5 ,row = 2 ,columnspan = 2 ,sticky = (N, W), padx = 5)\n\t\tself.entryAngle .grid(column = 5 ,row = 3 ,columnspan = 2 ,sticky = (N, W), padx = 5)\n\t\tself.buttonSetZero .grid(column = 5 ,row = 4 ,columnspan = 2 ,sticky = (N, W), padx = 5)\n\t\tself.entryRadio .grid(column = 5 ,row = 5 ,columnspan = 2 ,sticky = (N, W), padx = 5)\n\t\tself.entryAdvance .grid(column = 5 ,row = 6 ,columnspan = 2 ,sticky = (N, W), padx = 5)\n\t\tself.entryTurnAngle .grid(column = 5 ,row = 7 ,columnspan = 2 ,sticky = (N, W), padx = 5)\n\t\t\n\t\t# Sensors\n\n\t\tself.lableSensors .grid(column = 0 ,row = 12 ,sticky = (N, W) ,padx = (5,5)) \n\t\tself.labelNumSensors .grid(column = 0 ,row = 13 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.labelOrigin .grid(column = 0 ,row = 14 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.labelRange .grid(column = 0 ,row = 15 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.labelValue .grid(column = 0 ,row = 16 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.labelMoveBot\t\t.grid(column = 0 ,row = 18 ,sticky = (N, W) ,padx = (20,5))\n\n\t\tself.entryNumSensors .grid(column = 1 ,row = 13 ,columnspan=2 ,sticky = (N, W) ,padx = 5)\n\t\tself.entryOrigin .grid(column = 1 ,row = 14 ,columnspan=2 ,sticky = (N, W) ,padx = 5)\n\t\tself.entryRange .grid(column = 1 ,row = 15 ,columnspan=2 ,sticky = (N, W) ,padx = 5)\n\t\tself.entryValue .grid(column = 1 ,row = 16 ,columnspan=2 ,sticky = (N, W) ,padx = 5)\n\n\t\tself.lableTurtleBot.grid(column = 0 ,row = 17 ,columnspan=2 ,sticky = (N, W) ,padx = 5)\n\t\tself.checkTurtleBot.grid(column = 1 ,row = 18 ,columnspan=2 ,sticky = (N, W) ,padx = 5)\n\t\tself.checkLidar.grid(column = 1 ,row = 19 ,columnspan=2 ,sticky = (N, W) ,padx = 5)\n\t\tself.checkSArray.grid(column = 1 ,row = 20 ,columnspan=2 ,sticky = (N, W) ,padx = 5)\n\t\tself.checkLight1.grid(column = 1, row = 22, columnspan=2, sticky = (N, W), padx = 5)\n\t\tself.checkLight2.grid(column = 1, row = 23, columnspan=2, sticky = (N, W), padx = 5)\n\t\tself.buttonMoveFoward .grid(column = 0, row = 19, columnspan = 2, sticky = (N, W), padx = 35)\n\t\tself.buttonMoveLeft .grid(column = 0, row = 20, columnspan = 2, sticky = (N, W), padx = 2)\n\t\tself.buttonMoveRight .grid(column = 0, row = 20, columnspan = 2, sticky = (N, W), padx = 68)\n\t\tself.buttonMoveBackward.grid(column = 0, row = 21, columnspan = 2, sticky = (N, W), padx = 35)\n\t\tself.buttonMoveStop .grid(column = 0, row = 20, columnspan = 2, sticky = (N, W), padx = 35)\n\t\tself.buttonCompile .grid(column = 0, row = 24, columnspan = 1, sticky = (N, W), padx = 5, pady = 10)\n\t\tself.buttonStartRecording .grid(column = 1, row = 24, columnspan = 1, sticky = (N, W),padx = (5,0), pady = 20)\n\t\tself.buttonStopRecording.grid(column = 1, row = 24, columnspan = 1, sticky = (N, W), padx = (35,0), pady = 20)\n\t\tself.buttonPlayRecording.grid(column = 1, row = 24, columnspan = 1, sticky = (N, W), padx = (65,0), pady = 20)\n\t\tself.buttonViewerArena .grid(column = 4, row = 24, columnspan = 3, sticky = (N, W), padx = (35,0), pady = 0)\n\t\tself.buttonReturnHome .grid(column = 4, row = 23, columnspan = 3, sticky = (N, W), padx = (35,0), pady = 0)\n\n\n\t\t#self.buttonMapLess.grid(column = 1 ,row = 19 ,columnspan=1 ,sticky = (N, W) ,padx = 5)\n\t\t#self.buttonMapMore.grid(column = 1 ,row = 19 ,columnspan=1 ,sticky = (N, E) ,padx = 5)\n\n\t\t# buttons\n\n\t\tself.lableSimulator .grid(column = 4 ,row = 12 ,sticky = (N, W) ,padx = (5,5))\n\t\tself.buttonRviz .grid(column = 4 ,row = 14 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.buttonPlotTopological .grid(column = 4 ,row = 15 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.buttonLastSimulation .grid(column = 4 ,row = 16 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.buttonRunSimulation.grid(column = 4 ,row = 17 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.buttonStop .grid(column = 4 ,row = 18 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.labelBattery\t\t.grid(column = 4 ,row = 20 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.batteryBar\t\t\t.grid(column = 4 ,row = 21 ,sticky = (N, W) ,padx = (10,5))\n\t\tself.labelBattAdvertise .grid(column = 4 ,row = 22 ,sticky = (N, W) ,padx = (20,5))\n\t\tself.labelVideoNamed\t\t.grid(column = 0 ,row = 24 ,sticky = (N, W) ,padx = 0, pady = 65,columnspan = 3)\n\n\t\tself.content .grid(column = 0 ,row = 0 ,sticky = (N, S, E, W))\n\t\tself.frame .grid(column = 0 ,row = 0 ,columnspan = 3 ,rowspan = 2 ,sticky = (N, S, E, W))\n\t\tself.rightMenu.grid(column = 3 ,row = 0 ,columnspan = 3 ,rowspan = 2 ,sticky = (N, S, E, W))\n\n\t\tself.root.columnconfigure(0, weight=1)\n\t\tself.root.rowconfigure(0, weight=1)\n\t\tself.content.columnconfigure(0, weight = 3)\n\t\tself.content.columnconfigure(1, weight = 3)\n\t\tself.content.columnconfigure(2, weight = 3)\n\t\tself.content.columnconfigure(3, weight = 1)\n\t\tself.content.columnconfigure(4, weight = 1)\n\t\tself.content.rowconfigure(1, weight = 1)\n\n\t\tself.gif2 = PhotoImage( file = self.rospack.get_path('simulator')+'/src/gui/light.png')\n\t\tself.gif2.zoom(50, 50)\n \n\t\tself.a = IntVar(value=3)\n\t\tself.a.trace(\"w\", self.move_robot)\n\t\t\n\t\tself.b = IntVar(value=3)\n\t\tself.b.trace(\"w\", self.print_graph)\n\n\t\tself.c = IntVar(value=3)\n\t\tself.c.trace(\"w\", self.print_hokuyo_values)\n\n\t\tself.d = IntVar(value=3)\n\t\tself.d.trace(\"w\", self.object_interaction)\n\n\t\tself.d = IntVar(value=3)\n\t\tself.d.trace(\"w\", self.print_real)\n\n\t\tself.w.bind(\"<Button-3>\", self.right_click)\n\t\tself.w.bind(\"<Button-1>\", self.left_click)\n\n\t\tself.buttonMapLess.configure(state=\"disabled\")\n\t\tself.buttonMapMore.configure(state=\"disabled\")\n\n\t\tself.checkLidar.configure(state=\"disabled\")\n\t\tself.checkSArray.configure(state=\"disabled\")\n\n\t\tself.labelBattAdvertise.grid_forget()\n\n\t\t\n\tdef run(self):\t\n\t\tself.gui_init()\n\t\tself.read_map()\n\t\tself.plot_robot2()\n\t\tself.root.mainloop()\n" }, { "alpha_fraction": 0.560606062412262, "alphanum_fraction": 0.5757575631141663, "avg_line_length": 7.375, "blob_id": "718e5ee688db4940511f79d837d527dd309be499", "content_id": "e2b726d87d43be7aaca4d1d3966e8287ed681c06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 66, "license_type": "no_license", "max_line_length": 18, "num_lines": 8, "path": "/catkin_ws/src/simulator/src/gui/p.c", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main()\n{\n\t\n\tprintf(\"Prros\");\n\treturn(0);\n}" }, { "alpha_fraction": 0.7632850408554077, "alphanum_fraction": 0.772946834564209, "avg_line_length": 33.5, "blob_id": "3522bc2f95ca11a5d057c7a71acabfb486fb9717", "content_id": "504cac8609889f9bead795af11cceffe99c02184", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 207, "license_type": "no_license", "max_line_length": 69, "num_lines": 6, "path": "/RobotScan.sh", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#!/bin/bash\nsource /opt/ros/melodic/setup.bash\npython3 /home/$USER/MobileRobotSimulator/message.py & PIDIOS=$!\npython3 /home/$USER/MobileRobotSimulator/robot_scanner.py & PIDMIX=$!\nwait $PIDIOS\nwait $PIDMIX\n" }, { "alpha_fraction": 0.434072345495224, "alphanum_fraction": 0.560093343257904, "avg_line_length": 26.645160675048828, "blob_id": "839befc71a477f0006130c1baaa612efab081f47", "content_id": "74991c10784a00e7081e6714546c3162152fa55e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 857, "license_type": "no_license", "max_line_length": 98, "num_lines": 31, "path": "/search_robots.py", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "import nmap, socket\n\nhosts = {'Minibot 1':'192.168.0.165',\n 'Minibot 2':'192.168.0.181',\n 'Minibot 3':'192.168.0.106',\n 'Minibot 4':'192.168.0.195',\n 'Minibot 5':'192.168.0.110'}\n\n#hosts['Streamer PC'] = '192.168.0.193'\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKCYAN = '\\033[96m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n\nprint(\"\\n\\nSearching minibots connections...\\n\")\n\nscanner = nmap.PortScanner()\nfor hostName in sorted(hosts.keys()):\n scanner.scan(hosts[hostName], '1', '-v')\n if(scanner[hosts[hostName]].state() == \"up\"):\n print(bcolors.OKGREEN + bcolors.BOLD + hostName + '->' + ' ' + 'Available' + bcolors.ENDC)\n else:\n print hostName + '->' + ' ' + 'Not available'\n" }, { "alpha_fraction": 0.4027634561061859, "alphanum_fraction": 0.4134873151779175, "avg_line_length": 36.8671875, "blob_id": "4600d81cc9d02b731d1049ba171518100e2cfcc5", "content_id": "33399fd580f4281e29adadd0ddaad8479693c03c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4849, "license_type": "no_license", "max_line_length": 136, "num_lines": 128, "path": "/catkin_ws/src/simulator/src/state_machines/sm_avoidance.h", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "/********************************************************\n * *\n * *\n * state_machine_avoidance.h\t *\n * *\n * Jesus Savage *\n * Diego Cordero *\n * Miguel Sanchez *\n * FI-UNAM *\n * 5-2-2019 *\n * *\n ********************************************************/\n\n\n\n// Function to get next state\n#define THRESHOLD 35\n#define LIDAR_THRESHOLD 0.15\n// State Machine \nvoid sm_avoid_obstacles(float *observations,int size,int obs ,movement *movements ,int *next_state ,float Mag_Advance ,float max_twist)\n{\n//Function to use in real robot, comment to use in simulation \nobs=quantize_laser(observations,size,LIDAR_THRESHOLD);\nprintf(\"Obstacle :%i\\n\",obs);\n int state = *next_state;\n\n //printf(\"Next state %d \\n\",state );\n\n switch ( state ) \n {\n\n case 0:\n printf(\"Obstacle: %i\", obs);\n if (obs == 0){\n // there is not obstacle\n *movements=generate_output(FORWARD,Mag_Advance,max_twist);\n //printf(\"Present State: %d FORWARD\\n\", state);\n *next_state = 0;\n }\n else{\n *movements=generate_output(STOP,Mag_Advance,max_twist);\n //printf(\"Present State: %d STOP\\n\", state);\n\n if (obs == 1){\n // obtacle in the right\n *next_state = 1;\n }\n else if (obs == 2){\n // obstacle in the left\n *next_state = 3;\n }\n else if (obs == 3){\n // obstacle in the front\n *next_state = 5;\n }\n }\n\n break;\n\n case 1: // Backward, obstacle in the right\n *movements=generate_output(BACKWARD,Mag_Advance,max_twist);\n //printf(\"Present State: %d BACKWARD, obstacle RIGHT\\n\", state);\n *next_state = 2;\n break;\n\n case 2: // left turn\n *movements=generate_output(LEFT,Mag_Advance,max_twist);\n //printf(\"Present State: %d TURN LEFT\\n\", state);\n *next_state = 0;\n break;\n\n case 3: // Backward, obstacle in the left\n *movements=generate_output(BACKWARD,Mag_Advance,max_twist);\n //printf(\"Present State: %d BACKWARD, obstacle LEFT\\n\", state);\n *next_state = 4;\n break;\n\n case 4: // right turn\n *movements=generate_output(RIGHT,Mag_Advance,max_twist);\n //printf(\"Present State: %d TURN RIGHT\\n\", state);\n *next_state = 0;\n break;\n case 5: // Backward, obstacle in front\n\n *movements=generate_output(BACKWARD,Mag_Advance,max_twist);\n //printf(\"Present State: %d BACKWARD, obstacle FRONT\\n\", state);\n *next_state = 6;\n break;\n\n case 6: /// Left turn\n *movements=generate_output(LEFT,Mag_Advance,max_twist);\n //printf(\"Present State: %d TURN 1 LEFT\\n\", state);\n *next_state = 7;\n break;\n\n case 7:// Left turn\n *movements=generate_output(LEFT,Mag_Advance,max_twist);\n //printf(\"Present State: %d TURN 2 LEFT\\n\", state);\n *next_state = 8;\n break;\n\n case 8: // Forward\n *movements=generate_output(FORWARD,Mag_Advance,max_twist);\n //printf(\"Present State: %d 1 FORWARD\\n\", state);\n *next_state = 9;\n break;\n\n case 9: // Forward\n *movements=generate_output(FORWARD,Mag_Advance,max_twist);\n //printf(\"Present State: %d 2 FORWARD\\n\", state);\n *next_state = 10;\n break;\n\n case 10: // Right turn\n *movements=generate_output(RIGHT,Mag_Advance,max_twist);\n //printf(\"Present State: %d TURN 1 RIGHT\\n\", state);\n *next_state = 11;\n break;\n\n case 11: // Right turn\n *movements=generate_output(RIGHT,Mag_Advance,max_twist);\n //printf(\"Present State: %d TURN 2 RIGHT\\n\", state);\n *next_state = 0;\n break;\n }\n\n\n}\n\n\n" }, { "alpha_fraction": 0.5292197465896606, "alphanum_fraction": 0.5523996353149414, "avg_line_length": 24.747900009155273, "blob_id": "2cea13b6ca4e751130707b71882acf53b61923f2", "content_id": "749e2a0e810244d114acbe48244e73358f1ff7af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3063, "license_type": "no_license", "max_line_length": 103, "num_lines": 119, "path": "/catkin_ws/src/simulator/src/motion_planner/follow_line_server.cpp", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#include<ros/ros.h>\n#include<geometry_msgs/Twist.h>\n#include<simulator/line_follower.h>\n#include<sensor_msgs/LaserScan.h>\n#include<std_msgs/Int16MultiArray.h>\n\nusing namespace std;\n\nros::Publisher pubCmdVel;\n\nint line_sensor[2];\nbool finished = false;\nbool flagOnce = false;\n\nenum State { FOWARD, BACKWARD, TURN_RIGHT, TURN_LEFT, STOP };\n\ngeometry_msgs::Twist move_robot(int move){\n\n geometry_msgs::Twist speed;\n\n switch(move)\n {\n case STOP:\n speed.linear.x = 0.0;\n speed.linear.y = 0.0;\n speed.angular.z = 0.0; \n break;\n case FOWARD:\n speed.linear.x = 0.08;\n speed.linear.y = 0.0;\n speed.angular.z = 0.0; \n break;\n case BACKWARD:\n speed.linear.x = -0.08;\n speed.linear.y = 0.0;\n speed.angular.z = 0.0; \n break;\n case TURN_LEFT:\n speed.linear.x = 0.0;\n speed.linear.y = 0.0;\n speed.angular.z = 1.2; \n break;\n case TURN_RIGHT:\n speed.linear.x = 0.0;\n speed.linear.y = 0.0;\n speed.angular.z = -1.2; \n break;\n default:\n cout << \"An unexpected error has occurred :(\" << endl;\n }\n\n return speed;\n}\n\nvoid follow_line(){\n cout << \"{ \" << line_sensor[0] << \", \" << line_sensor[1] << \", \" << line_sensor[2] << \" }\" << endl;\n if(line_sensor[0] == 1 && line_sensor[1] == 1 && !flagOnce)\n pubCmdVel.publish(move_robot(FOWARD));\n else if(line_sensor[0] == 0 && line_sensor[1] == 0) {\n pubCmdVel.publish(move_robot(FOWARD));\n flagOnce = true;\n }\n else if(line_sensor[0] == 1 && line_sensor[1] == 0) {\n pubCmdVel.publish(move_robot(TURN_RIGHT));\n flagOnce = true;\n }\n else if(line_sensor[0] == 0 && line_sensor[1] == 1) {\n pubCmdVel.publish(move_robot(TURN_LEFT));\n flagOnce = true;\n }\n else {\n pubCmdVel.publish(move_robot(STOP));\n finished = true;\n }\n \n}\n\nbool startFollow(simulator::line_follower::Request &req, simulator::line_follower::Response &res){\n ros::Rate rate(50);\n\n /*while(ros::ok()){\n follow_line();\n if(finished) break;\n \n ros::spinOnce();\n rate.sleep();\n }//*/\n\n res.response = \"Ok\";\n\n return true;\n}\n\nvoid lineSensorsCallback(const std_msgs::Int16MultiArray::ConstPtr& msg){\n line_sensor[0] = msg->data[0];\n line_sensor[1] = msg->data[1];\n}\n\n\nint main(int argc, char **argv){\n cout << \"Starting follow_line_server by Luis Nava\" << endl;\n ros::init(argc, argv, \"follow_line_server\");\n ros::NodeHandle nh;\n ros::Rate loop(20);\n\n pubCmdVel = nh.advertise<geometry_msgs::Twist>(\"/cmd_vel\", 10);\n ros::ServiceServer service = nh.advertiseService(\"follow_line\", startFollow);\n ros::Subscriber subLineSensor = nh.subscribe(\"/line_sensors\", 1000, lineSensorsCallback);\n \n \n pubCmdVel.publish(move_robot(STOP));\n \n while(ros::ok()){\n\t//follow_line();\n\tros::spinOnce();\n }\n\n return 0;\n}" }, { "alpha_fraction": 0.5811688303947449, "alphanum_fraction": 0.5821428298950195, "avg_line_length": 33.617977142333984, "blob_id": "9a5ae8728db64d88405bffa3bcfc319cba9a45cd", "content_id": "439fc67d2df97b4e228abf865e340a3f5bdf6055", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3080, "license_type": "no_license", "max_line_length": 108, "num_lines": 89, "path": "/catkin_ws/src/simulator/src/utilities/utilities.h", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#include \"simulator/simulator_robot_step.h\"\n#include \"simulator/simulator_parameters.h\"\n\n\nparameters get_params()\n{\n parameters params;\n\n ros::NodeHandle n;\n ros::ServiceClient client;\n simulator::simulator_parameters srv;\n client = n.serviceClient<simulator::simulator_parameters>(\"simulator_get_parameters\"); //create the client\n \n srv.request.request=1;\n params.run=0;\n\n if (client.call(srv))\n {\n params.robot_x = srv.response.robot_x ;\n params.robot_y = srv.response.robot_y ;\n params.robot_theta = srv.response.robot_theta ; \n params.robot_radio = srv.response.robot_radio ; \n params.robot_max_advance = srv.response.robot_max_advance ; \n params.robot_turn_angle = srv.response.robot_turn_angle ; \n params.laser_num_sensors = srv.response.laser_num_sensors ; \n params.laser_origin = srv.response.laser_origin ; \n params.laser_range = srv.response.laser_range ; \n params.laser_value = srv.response.laser_value ; \n strcpy(params.world_name,srv.response.world_name.c_str()); \n params.noise = srv.response.noise ; \n params.run = srv.response.run ; \n params.light_x = srv.response.light_x;\n params.light_y = srv.response.light_y;\n params.behavior = srv.response.behavior; \n params.steps = srv.response.steps;\n }\n else\n {\n ROS_ERROR(\"Failed to call service get_parameters\");\n \n }\n \n\n printf(\"Inicial parameters:\\n\" );\n printf(\"robot_x %f \\n\",params.robot_x ) ; \n printf(\"robot_y %f \\n\",params.robot_y ) ;\n printf(\"robot_theta %f \\n\",params.robot_theta );\n printf(\"robot_radio %f \\n\",params.robot_radio );\n printf(\"robot_max_advance %f \\n\",params.robot_max_advance ); \n printf(\"robot_turn_angle %f \\n\",params.robot_turn_angle ); \n printf(\"laser_num_sensors %d \\n\",params.laser_num_sensors); \n printf(\"laser_origin %f \\n\",params.laser_origin ) ; \n printf(\"laser_range %f \\n\",params.laser_range ); \n printf(\"laser_value %f \\n\",params.laser_value ); \n printf(\"world_name %s \\n\",params.world_name); \n printf(\"noise %d \\n\",params.noise ); \n printf(\"run %d \\n\",params.run ) ; \n printf(\"light_x %f \\n\",params.light_x );\n printf(\"light_y %f \\n\",params.light_y );\n printf(\"behavior %d \\n\",params.behavior ); \n\n return params;\n}\n\n\nint move_gui(float angle ,float distance)\n{\n \n ros::NodeHandle n;\n ros::ServiceClient client;\n simulator::simulator_robot_step srv;\n client = n.serviceClient<simulator::simulator_robot_step>(\"simulator_robot_step\"); //create the client\n \n srv.request.theta=angle;\n srv.request.distance=distance;\n \n if (client.call(srv))\n {\n printf(\"%s\\n\",\"Echo\" );\n }\n else\n {\n ROS_ERROR(\"Failed to call service get_parameters\");\n \n }\n \n\n return 1;\n}" }, { "alpha_fraction": 0.5400493741035461, "alphanum_fraction": 0.552165150642395, "avg_line_length": 27.0125789642334, "blob_id": "5395540ad4938ac7bcd1aa9bf811c0bb99db307a", "content_id": "05bf3b50ab42262896e6ed6112783fe1d93c7ff5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4457, "license_type": "no_license", "max_line_length": 111, "num_lines": 159, "path": "/catkin_ws/src/simulator/src/behaviors/oracle.h", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "\n/***********************************************\n* *\n* oracle.h\t *\n* *\n* Jesus Savage *\n* Julio Cruz *\n* *\n* Bio-Robotics Laboratory *\n* UNAM, 2019 *\n* *\n* *\n************************************************/\n\n\n\n#include \"ros/ros.h\"\n#include <iostream>\n#include <vector>\n#include <ctime>\n#include <map>\n#include <sstream>\n#include <string>\n\n\n// It starts the communication with the CLIPS node\nint start_clips(){\n\n bool init_kdb = false;\n std::string file;\n std::string result;\n\n std::cout << \"Starting CLIPS\" << std::endl;\n\n\n //This functions loads initial facts and rules from a file\n // The first parameter is a file that contains the names of CLIPS files *.clp\n // The second parameter indicates with false do not start executing the loaded files\n // The third parameter is a timeout\n file = \"/src/expert_system/oracle.dat\";\n init_kdb = SimuladorRepresentation::initKDB(file, false, 2000);\n if(!init_kdb){\n std::cout << \"CLIPS error file not found: \" << file << std::endl;\n return 0;\n }\n\n //Function to RESET CLIPS\n SimuladorRepresentation::resetCLIPS(true);\n\n //Function to print facts \n SimuladorRepresentation::factCLIPS(true);\n\n //Function to print the loaded rules' names\n SimuladorRepresentation::ruleCLIPS(true);\n\n //Function to start running Clips\n SimuladorRepresentation::runCLIPS(true);\n\n //Function to asserting a fact to the clips node to check if Clips is alive\n SimuladorRepresentation::strQueryKDB(\"(assert (alive clips))\", result, 10000);\n\n std::cout << \"CLIPS answer: \" << result << std::endl;\n\n\n}\n\n\nfloat oracle_clips(float intensity, int dest,int obs ,movement *movements,float Max_Advance ,float Max_Twist){\n\n static int j=1;\n char str[300];\n static int init_flg=1;\n std::string result;\n char accion[20];\n float rotation,advance;\n int num;\n float status = 0.0;\n\n\n\n if(init_flg==1){\n\n // It starts the communication with the Clips node\n start_clips();\n\n // It loads the maximum rotation and advance of the robot\n strcpy(str,\"(assert (max-advance \");\n sprintf(str,\"%s %f max-rotation %f\",str,Max_Advance,Max_Twist);\n strcat(str,\"))\");\n printf(\"Send fact %s\\n\",str);\n SimuladorRepresentation::strQueryKDB(str, result, 10000);\n printf(\"CLIPS answer: %d %s\\n\",j,result.c_str());\n rotation = 0.0;\n advance = 0.0;\n init_flg=0;\n }\n else{\n\n // It loads to the Clips node as a fact the quantized sensory data\n strcpy(str,\"(assert (step \");\n sprintf(str,\"%s %d intensity %f obs %d dest %d\",str,j,intensity,obs,dest);\n strcat(str,\"))\");\n printf(\"Send fact %s\\n\",str);\n SimuladorRepresentation::strQueryKDB(str, result, 10000);\n printf(\"CLIPS answer: %d %s\\n\",j,result.c_str());\n j++;\n\n sscanf(result.c_str(),\"%s%d%f%f%f\",accion,&num,&rotation,&advance,&status);\n //printf(\"rotation %f advance %f\\n\",rotation,advance);\n \n if (status == 1.0){\n printf(\"\\n **************** Reached light source ******************************\\n\");\n }\n\n }\n\t\n movements->advance=advance;\n movements->twist=rotation;\n\n return status;\n\n}\n\n\nint ros_clips(int dest,int obs ,movement *movements ,int *next_state ,float Mag_Advance ,float max_twist){\n\n static int j=1;\n char str[300];\n char accion[20],rotation[20],advance[20];\n int num;\n float status;\n\tstatic int init_flg=1;\n\n\n\tif(init_flg==1){\n\n \t\t// It starts the communication with the Clips node\n \t\tstart_clips();\n\t\tstrcpy(str,\"(assert (init))\");\n \tprintf(\"Send fact %s\\n\",str);\n \tSimuladorRepresentation::sendAndRunCLIPS(str);\n\n \t\tinit_flg=0;\n \t}\n \telse{\n\n \tstrcpy(str,\"(assert (ros step \");\n \tsprintf(str,\"%s %d obs %d dest %d advance %f twist %f\",str,j,obs,dest, Mag_Advance, max_twist);\n \tstrcat(str,\"))\");\n \tprintf(\"Send fact %s\\n\",str);\n \tSimuladorRepresentation::sendAndRunCLIPS(str);\n\t\t//set busy clips flag and wait for a CLIPS response\n \t \tSimuladorRepresentation::set_busy_clips(true);\n\t\n \tj++;\n\n }\n\n\n}\n\n\n" }, { "alpha_fraction": 0.3957552909851074, "alphanum_fraction": 0.4051186144351959, "avg_line_length": 25.79660987854004, "blob_id": "5d9d1114cb9daf63fe730d36eb6b83d3d658c94b", "content_id": "b23753abe8e398e7cc317cfd0dcfe5bfec3e5bd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1602, "license_type": "no_license", "max_line_length": 121, "num_lines": 59, "path": "/catkin_ws/src/simulator/src/state_machines/user_sm.h", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "/********************************************************\n * *\n * *\n * user_sm.h\t\t\t \t*\n * *\n *\t\t\t\t\t\t\t*\n *\t\tFI-UNAM\t\t\t\t\t*\n *\t\t17-2-2019 *\n * *\n ********************************************************/\n\n\n\n// State Machine \nvoid user_sm(float intensity, float *light_values, float *observations, int size, float laser_value, int dest, int obs ,\n\t\t\t\t\tmovement *movements ,int *next_state ,float Mag_Advance ,float max_twist)\n{\n\n int state = *next_state;\n int i;\n\n printf(\"intensity %f\\n\",intensity);\n printf(\"quantized destination %d\\n\",dest);\n printf(\"quantized obs %d\\n\",obs);\n\n for(int i = 0; i < 8; i++)\n printf(\"light_values[%d] %f\\n\",i,light_values[i]);\n for (int i = 0; i < size ; i++ ) \n printf(\"laser observations[%d] %f\\n\",i,observations[i]);\n\n\n switch ( state ) {\n\n case 0:\n\n\t\t*movements=generate_output(FORWARD,Mag_Advance,max_twist);\n *next_state = 1;\n\n \tbreak;\n\n case 1:\n *movements=generate_output(LEFT,Mag_Advance,max_twist);\n *next_state = 0;\n break;\n\n\n\tdefault:\n\t\t//printf(\"State %d not defined used \", state);\n *movements=generate_output(STOP,Mag_Advance,max_twist);\n *next_state = 0;\n break;\n\n \n }\n\n printf(\"Next State: %d\\n\", *next_state);\n\n\n}\n\n\n\n \n" }, { "alpha_fraction": 0.5470264554023743, "alphanum_fraction": 0.5687713027000427, "avg_line_length": 20.44382095336914, "blob_id": "008ba35f5b817dd87f867ca8160e2bd3339b30ff", "content_id": "4984b189085e7304feb3a029db7827bd3830cf0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3817, "license_type": "no_license", "max_line_length": 105, "num_lines": 178, "path": "/catkin_ws/src/simulator/src/state_machines/dfs.cpp", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct conection_\n{\n\tint node;\n\tfloat cost;\n} conection;\n\ntypedef struct nodo_\n{\n\tchar flag;\n\tint num_node;\n\tfloat x;\n\tfloat y;\n\tint num_conections;\n\tconection conections[100];\n\n\tint parent;\n\tfloat acumulado;\n} nodo;\n\nnodo nodes[250];\nint num_nodes = 0;\n\n// it reads the file that conteins the environment description\nint read_nodes(char *file)\n{\n\tFILE *fp;\n\n\tchar data[ 100 ];\n\tint i=0;\n\tint flg = 0;\n\tfloat tmp;\n\tfloat dimensions_room_x,dimensions_room_y;\n\n\n\tint node_index,node_connection,cost;\n\n\tfp = fopen(file,\"r\"); \n\t \n\tif( fp == NULL )\n\t{\n\t\tsprintf(data, \"File %s does not exists\\n\", file);\n\t\tprintf(\"File %s does not exists\\n\", file);\n\t\treturn(0);\n\t}\n\t//printf(\"World environment %s \\n\",file);\n\n\twhile( fscanf(fp, \"%s\" ,data) != EOF)\n\t{\n\t\tif( strcmp(\";(\", data ) == 0 )\n\t\t{\n\t\t\tflg = 1;\n\t\t\twhile(flg)\n\t\t\t{\n\t\t\t\tfscanf(fp, \"%s\", data);\n\t\t\t\tsscanf(data, \"%f\", &tmp);\n\t\t\t\tif(strcmp(\")\", data) == 0) flg = 0;\n\t\t\t}\n\t\t}\n\t\telse if((strcmp(\"node\", data ) == 0) && ( flg == 0 ) )\n\t\t{\n\t\t\t//( node 0 0.309586 0.61346 )\n\t\t\tfscanf(fp, \"%s\" ,data);\n\t\t\tnodes[i].num_node = atoi(data);\n\t\t\tfscanf(fp, \"%s\" ,data);\n\t\t\tnodes[i].x = atof(data);\n\t\t\tfscanf(fp, \"%s\" ,data);\n\t\t\tnodes[i++].y = atof(data);\n\t\t}\n\t\telse if((strcmp(\"connection\", data ) == 0) && ( flg == 0 ) )\n\t\t{\n\t\t\t//( node 0 0.309586 0.61346 )\n\t\t\t//( connection 0 4 0.112605 )\n\t\t\tfscanf(fp, \"%s\" ,data);\n\t\t\tnode_index = atoi(data);\n\t\t\t\n\t\t\tfscanf(fp, \"%s\" ,data);\n\t\t\tnode_connection = atoi(data);\n\n\t\t\tnodes[node_index].conections[nodes[node_index].num_conections].node = node_connection;\n\n\t\t\tfscanf(fp, \"%s\" ,data);\n\t\t\tnodes[node_index].conections[nodes[node_index].num_conections].cost = atof(data);\n\t\t\tnodes[node_index].num_conections++;\n\t\t}\n\t}\n\tfclose(fp);\n\treturn i;\n}\n\n\n\nvoid printNode(int i)\n{\n\tprintf(\"\\n\\n\");\n \tprintf(\"# %d x %f y %f\\n\",nodes[i].num_node,nodes[i].x,nodes[i].y );\n \tprintf(\"flag: %c parent: %d acumulado: %f \\n\",nodes[i].flag,nodes[i].parent,nodes[i].acumulado );\n \tprintf(\"num_conections %d \\n\",nodes[i].num_conections);\n \tfor(int j=0 ; j < nodes[i].num_conections; j++ )\n \t\tprintf( \"%d %f \\n\",nodes[i].conections[j].node,nodes[i].conections[j].cost );\n \n}\n\n\nint stack[250];\nint sp=0;\nvoid push(int v){stack[sp++] = v;}\nvoid pop(){sp--;}\nvoid print_stack(){\n\tprintf(\"\\nstack: \");\n for(int i=0; i < sp; i++)\n {\n \tprintf(\" %d \",stack[i]);\n }\n printf(\"\\n\");\n}\n\nvoid dfs(int D ,int L)\n{\n\tint menor,flagOnce;\n\tint contador=0;\n\tint node_actual = D;\n\tint flagPush;\n\n\twhile(node_actual != L)\n\t{\t\n\t\tprint_stack();\n\t\tflagPush = 1;\n\t\t//printf(\"aa %d \\n\",nodes[node_actual].num_conections );\n\t\tfor( int j = 0; j < nodes[node_actual].num_conections; j++)\n \t\t{\n \t\t\t//printf(\"** %c** \\n\",nodes[nodes[node_actual].conections[j].node].flag );\n \t\t\tif(nodes[nodes[node_actual].conections[j].node].flag == 'N')\n \t\t\t{\n \t\t\t\t//printf(\"Node actual %d \\n\",node_actual);\n \t\t\t\tnodes[nodes[node_actual].conections[j].node].flag = 'Y';\n \t\t\t\tpush(node_actual);\n \t\t\t\tnode_actual = nodes[node_actual].conections[j].node;\n \t\t\t\t//printf(\"Node actual %d \\n\",node_actual);\n \t\t\t\tflagPush = 0;\n \t\t\t\tbreak;\t\n \t\t\t}\n \t\t}\n \t\t\n \t\tif( flagPush==1 )\n \t\t{\t\n \t\t\tpop();\n \t\t\tnode_actual = sp - 1;\n\t\t}\n\t}\n\tpush(node_actual);\n}\n\nint main(int argc, char ** argv)\n{\n char archivo[]=\"../data/obstacles/obstacles.top\";\n \n for(int i=0; i<200; i++)\n {\n \t\tnodes[i].flag='N';\n \t\tnodes[i].num_conections = 0;\n \t\tnodes[i].parent = -1;\n \t\tnodes[i].acumulado = 0;\n }\n printf(\"NUmero de nodos #: %d \\n\",num_nodes=read_nodes(archivo));\n\n //for(int i=0; i<num_nodes; i++)\n //\tprintNode(i);\n \n printf(\"%d %d \\n\",atoi(argv[1]),atoi(argv[2]) );\n dfs(atoi(argv[1]),atoi(argv[2]));\n printf(\"Final Stack\\n\");\n print_stack();\n\treturn 0;\n} " }, { "alpha_fraction": 0.44182077050209045, "alphanum_fraction": 0.45021337270736694, "avg_line_length": 38.494380950927734, "blob_id": "c286d117090e5455e03b14275215bffe4b05d4f6", "content_id": "2cccc24d2f20159565d1c76c35d7b07312263954", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14060, "license_type": "no_license", "max_line_length": 214, "num_lines": 356, "path": "/catkin_ws/src/simulator/src/motion_planner/action_planner_node.cpp", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "/***********************************************\n* *\n* motion_planner_node.cpp *\n* *\n* Jesus Savage *\n* Diego Cordero *\n* *\n* Bio-Robotics Laboratory *\n* UNAM, 17-2-2020 *\n* *\n* *\n************************************************/\n\n#include \"ros/ros.h\"\n#include \"../utilities/simulator_structures.h\"\n#include \"../utilities/random.h\"\n#include \"motion_planner_utilities.h\"\n#include \"../state_machines/light_follower.h\"\n#include \"../state_machines/sm_avoidance.h\"\n#include \"../state_machines/sm_avoidance_destination.h\"\n#include \"../state_machines/sm_destination.h\"\n#include \"../state_machines/user_sm.h\"\n#include \"../state_machines/dijkstra.h\"\n#include \"../state_machines/dfs.h\"\n#include \"clips_ros/SimuladorRepresentation.h\"\n#include \"../behaviors/oracle.h\"\n#include \"../action_planner/action_planner.h\"\n\n\nint main(int argc ,char **argv)\n{\n ros::init(argc ,argv ,\"simulator_action_planner_node\");\n ros::NodeHandle n;\n ros::Subscriber params_sub = n.subscribe(\"simulator_parameters_pub\",0, parametersCallback);\n ros::Subscriber sub = n.subscribe(\"/scan\", 10, laserCallback);\n SimuladorRepresentation::setNodeHandle(&n);\n ros::Rate r(20);\n\n\n float lidar_readings[512];\n float light_readings[8];\n \n int i;\n int tmp;\n int sensor;\n int est_sig;\n int q_light;\n int q_inputs;\n int flagOnce;\n int flg_finish;\n int mini_sm=1;\n int cta_steps;\n int flg_result;\n int flg_noise=0;\n \n float result;\n float final_x;\n float final_y;\n float intensity;\n float max_advance;\n float max_turn_angle;\n float noise_advance;\n float noise_angle;\n \n char path[100];\n char object_name[20];\n\n\n movement movements;\n step steps[200];\n step graph_steps[200];\n\n // it sets the environment's path\n strcpy(path,\"./src/simulator/src/data/\");\n\n while( ros::ok() )\n {\n flagOnce = 1;\n cta_steps = 0;\n mini_sm =1;\n\n while( params.run )\n {\n // it gets sensory data\n ros::spinOnce();\n\n if (!params.useRealRobot)\n {\n get_light_values(&intensity,light_readings); // function in ~/catkin_ws/src/simulator/src/motion_planner/motion_planner_utilities.h\n\n get_lidar_values(lidar_readings,params.robot_x,\n params.robot_y,params.robot_theta,params.useRealRobot); // function in ~/catkin_ws/src/simulator/src/motion_planner/motion_planner_utilities.h\n }\n else\n {\n get_light_values_RealRobot(&intensity,light_readings); // function in ~/catkin_ws/src/simulator/src/motion_planner/motion_planner_utilities.h\n for( i = 0; i < 512; i++)\n lidar_readings[i] = lasers[i];\n }\n\n // it quantizes the sensory data\n q_light = quantize_light(light_readings); // function in ~/catkin_ws/src/simulator/src/motion_planner/motion_planner_utilities.h\n \n if(params.noise )\n q_inputs = quantize_laser_noise(lidar_readings,params.laser_num_sensors,params.laser_value); // function in ~/catkin_ws/src/simulator/src/motion_planner/motion_planner_utilities.h\n else\n q_inputs = quantize_laser(lidar_readings,params.laser_num_sensors,params.laser_value); // function in ~/catkin_ws/src/simulator/src/motion_planner/motion_planner_utilities.h\n\n\n max_advance = params.robot_max_advance;\n max_turn_angle = params.robot_turn_angle;\n\n switch ( params.behavior)\n {\n\n case 1:\n // This function sends light sensory data to a function that follows a light source and it issues\n // the actions that the robot needs to perfom.\n // It is located in ~/catkin_ws/src/simulator/src/state_machines/light_follower.h\n flg_result = light_follower(intensity, light_readings,&movements,max_advance,max_turn_angle);\n if(flg_result == 1) stop();\n break;\n\n case 2:\n // This function sends light sensory data to an state machine that follows a light source and it issues\n // the actions that the robot needs to perfom.\n // It is located in ~/catkin_ws/src/simulator/src/state_machines/sm_destination.h\n if(flagOnce)\n {\n est_sig = 1;\n flagOnce = 0;\n }\n flg_result = sm_destination(intensity,q_light,&movements,&est_sig,params.robot_max_advance,params.robot_turn_angle);\n if(flg_result == 1) stop();\n\n break;\n\n case 3:\n // This function sends quantized sensory data to an state machine that avoids obstacles and it issues\n // the actions that the robot needs to perfom.\n // It is located in ~/catkin_ws/src/simulator/src/state_machines/sm_avoidance.h\n if(flagOnce)\n {\n est_sig = 0;\n flagOnce = 0;\n }\n sm_avoid_obstacles(lidar_readings,params.laser_num_sensors,q_inputs,&movements,&est_sig ,params.robot_max_advance ,params.robot_turn_angle);\n break;\n\n case 4:\n // This function sends quantized sensory data to an state machine that follows a light source and avoids obstacles\n // and it issues the actions that the robot needs to perfom.\n // It is located in ~/catkin_ws/src/simulator/src/state_machines/sm_avoidance_destination.h\n if(flagOnce)\n {\n est_sig = 0;\n flagOnce = 0;\n }\n flg_result=sm_avoidance_destination(lidar_readings,params.laser_num_sensors,intensity,q_light,q_inputs,&movements,&est_sig,\n params.robot_max_advance ,params.robot_turn_angle);\n\n if(flg_result == 1) stop();\n break;\n\n case 5:\n // This function sends the intensity and the quantized sensory data to a Clips node and it receives the actions that\n // the robot needs to perfom to avoid obstacles and reach a light source according to first order logic\n // It is located in ~/catkin_ws/src/simulator/src/behaviors/oracle.h\n result=oracle_clips(intensity,q_light,q_inputs,&movements,max_advance ,max_turn_angle);\n if(result == 1.0) stop();\n break;\n\n\n case 6:\n // it finds a path from the origen to a destination using depth first search\n if(flagOnce)\n {\n for(i = 0; i < 200; i++) steps[i].node = -1;\n\n // it finds a path from the origen to a destination using first search\n dfs(params.robot_x ,params.robot_y ,params.light_x ,params.light_y ,params.world_name,steps);\n print_algorithm_graph (steps);\n i = 0;\n final_x = params.light_x;\n final_y = params.light_y;\n set_light_position(steps[i].x,steps[i].y);\n printf(\"New Light %d: x = %f y = %f \\n\",i,steps[i].x,steps[i].y);\n flagOnce = 0;\n flg_finish=0;\n est_sig = 0;\n movements.twist=0.0;\n movements.advance =0.0;\n }\n else\n {\n //flg_result=sm_avoidance_destination(intensity,q_light,q_inputs,&movements,&est_sig, //params.robot_max_advance ,params.robot_turn_angle);\n flg_result = oracle_clips(intensity,q_light,q_inputs,&movements,max_advance ,max_turn_angle);\n\n if(flg_result == 1)\n {\n if(flg_finish == 1)\n stop();\n else\n {\n if(steps[i].node != -1)\n {\n set_light_position(steps[i].x,steps[i].y);\n printf(\"New Light %d: x = %f y = %f \\n\",i,steps[i].x,steps[i].y);\n printf(\"Node %d\\n\",steps[i].node);\n i++;\n //printf(\"type a number \\n\");\n //scanf(\"%d\",&tmp);\n }\n else\n {\n set_light_position(final_x,final_y);\n printf(\"New Light %d: x = %f y = %f \\n\",i,final_x,final_y);\n flg_finish = 1;\n }\n }\n }\n }\n\n break;\n\n case 7:\n if(flagOnce)\n {\n for(i = 0; i < 200; i++)steps[i].node=-1;\n // it finds a path from the origen to a destination using the Dijkstra algorithm\n dijkstra(params.robot_x ,params.robot_y ,params.light_x ,params.light_y ,params.world_name,steps);\n print_algorithm_graph (steps);\n i=0;\n final_x=params.light_x;\n final_y= params.light_y;\n set_light_position(steps[i].x,steps[i].y);\n printf(\"New Light %d: x = %f y = %f \\n\",i,steps[i].x,steps[i].y);\n flagOnce = 0;\n flg_finish=0;\n est_sig = 0;\n movements.twist=0.0;\n movements.advance =0.0;\n }\n else\n {\n flg_result=sm_avoidance_destination(lidar_readings,params.laser_num_sensors,intensity,q_light,q_inputs,&movements,&est_sig,\n params.robot_max_advance ,params.robot_turn_angle);\n\n if(flg_result == 1)\n {\n if(flg_finish == 1) stop();\n else\n {\n if(steps[i].node != -1)\n {\n set_light_position(steps[i].x,steps[i].y);\n printf(\"New Light %d: x = %f y = %f \\n\",i,steps[i].x,steps[i].y);\n printf(\"Node %d\\n\",steps[i].node);\n i++;\n //printf(\"type a number \\n\");\n //scanf(\"%d\",&tmp);\n }\n else\n {\n set_light_position(final_x,final_y);\n printf(\"New Light %d: x = %f y = %f \\n\",i,final_x,final_y);\n flg_finish=1;\n }\n }\n }\n }\n break;\n\n case 8:\n // Here it goes your code for selection 8\n if(flagOnce)\n {\n est_sig = 0;\n flagOnce = 0;\n }\n user_sm(intensity,light_readings, lidar_readings, params.laser_num_sensors,params.laser_value,\n q_light,q_inputs,&movements,&est_sig ,params.robot_max_advance ,params.robot_turn_angle);\n break;\n\n case 9:\n\n flg_result=light_follower(intensity, light_readings,&movements,max_advance,max_turn_angle);\n if(flg_result == 1)\n set_light_position(.5,.25);\n\n break;\n\n \n case 10:\n\n\t\t action_planner(params.robot_x, params.robot_y,params.robot_theta,&movements);\n\n break;\n\n case 11:\n movements.twist = 0;\n movements.advance = .05;\n if (mini_sm==1)\n {\n\n mini_sm++;\n }\n else if(mini_sm==2)\n {\n object_interaction(GRASP,\"blockA\");\n mini_sm++;\n }\n else if(mini_sm==3)\n {\n mini_sm++;\n }\n else if(mini_sm==4)\n {\n\n mini_sm++;\n }\n else if(mini_sm==5)\n {\n mini_sm++;\n }\n\n \n \n\n break;\n\n default:\n printf(\" ******* SELECTION NO DEFINED *******\\n\");\n movements.twist = 3.1416/4;\n movements.advance = .03;\n break;\n }\n\n ros::spinOnce();\n printf(\"\\n\\n MOTION PLANNER \\n________________________________\\n\");\n printf(\"Light: x = %f y = %f \\n\",params.light_x,params.light_y);\n printf(\"Robot: x = %f y = %f \\n\",params.robot_x,params.robot_y);\n printf(\"Step: %d \\n\",cta_steps++);\n printf(\"Movement: twist: %f advance: %f \\n\" ,movements.twist ,movements.advance );\n\n flg_noise = params.noise;\n\n move_robot(movements.twist,movements.advance,lidar_readings);\n ros::spinOnce();\n new_simulation = 0;\n r.sleep();\n }\n ros::spinOnce();\n r.sleep();\n }\n}\n" }, { "alpha_fraction": 0.5089936852455139, "alphanum_fraction": 0.5226057171821594, "avg_line_length": 21.866666793823242, "blob_id": "4e878e3f70c6a3d6f7627e7db93de5f934139206", "content_id": "04c01742f0f16bdf39caf6b7763dcaa9968b10c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2057, "license_type": "no_license", "max_line_length": 95, "num_lines": 90, "path": "/catkin_ws/src/simulator/src/state_machines/dijkstralib.h", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#ifndef DIJSTRALIB_H\n#define DIJSTRALIB_H\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ros/package.h>\n#define MUM_NODES 250\n\ntypedef struct conection_\n{\n int node;\n float cost;\n} conection;\n\ntypedef struct nodo_\n{\n char flag;\n int num_node;\n float x;\n float y;\n int num_conections;\n conection conections[100];\n int parent;\n float acumulado;\n} nodo;\n\nnodo nodes[MUM_NODES];\nint num_nodes = 0;\n\n// it reads the file that conteins the environment description\nint read_nodes(char *file)\n{\n FILE *fp;\n char data[ 100 ];\n int i=0;\n int flg = 0;\n float tmp;\n float dimensions_room_x,dimensions_room_y;\n int node_index,node_connection,cost;\n\n fp = fopen(file,\"r\"); \n \n if( fp == NULL )\n {\n sprintf(data, \"File %s does not exists\\n\", file);\n printf(\"File %s does not exists\\n\", file);\n return(0);\n }\n\n while( fscanf(fp, \"%s\" ,data) != EOF)\n {\n if( strcmp(\";(\", data ) == 0 )\n {\n flg = 1;\n while(flg)\n {\n if( 0 < fscanf(fp, \"%s\", data));\n sscanf(data, \"%f\", &tmp);\n if(strcmp(\")\", data) == 0) flg = 0;\n }\n }\n else if((strcmp(\"node\", data ) == 0) && ( flg == 0 ) )\n {\n if( 0 < fscanf(fp, \"%s\", data));\n nodes[i].num_node = atoi(data);\n if( 0 < fscanf(fp, \"%s\", data));\n nodes[i].x = atof(data);\n if( 0 < fscanf(fp, \"%s\", data));\n nodes[i++].y = atof(data);\n }\n else if((strcmp(\"connection\", data ) == 0) && ( flg == 0 ) )\n {\n if( 0 < fscanf(fp, \"%s\", data));\n node_index = atoi(data);\n \n if( 0 < fscanf(fp, \"%s\", data));\n node_connection = atoi(data);\n\n nodes[node_index].conections[nodes[node_index].num_conections].node = node_connection;\n\n if( 0 < fscanf(fp, \"%s\", data));\n nodes[node_index].conections[nodes[node_index].num_conections].cost = atof(data);\n nodes[node_index].num_conections++;\n }\n }\n fclose(fp);\n return i;\n}\n#endif" }, { "alpha_fraction": 0.553795337677002, "alphanum_fraction": 0.5694350600242615, "avg_line_length": 30.027196884155273, "blob_id": "9f0daf734333ee492ac8c2493a4c6b9575695e5e", "content_id": "398f492314e72962c80f5b13c10da684613bdc3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14834, "license_type": "no_license", "max_line_length": 284, "num_lines": 478, "path": "/catkin_ws/src/simulator/src/visualization/map_rviz_node.cpp", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "// ROS\n#include <geometry_msgs/Point.h>\n#include <ros/package.h>\n#include \"simulator/Parameters.h\"\n#include \"simulator/simulator_parameters.h\"\n#include \"../utilities/simulator_structures.h\"\n#include <ros/ros.h>\n\n// For visualizing things in rviz\n#include <functional>\n\n//#include <rviz_visual_tools/rviz_visual_tools.h>\n#include <visualization_msgs/Marker.h>\n// C++\n#include <string>\n#include <vector>\n\n//CGAL for triangulation\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Partition_traits_2.h>\n#include <CGAL/partition_2.h>\n#include <cassert>\n#include <list>\n\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Partition_traits_2<K> Traits;\ntypedef Traits::Point_2 Point_2;\ntypedef std::vector<Point_2> Point_list;\ntypedef Traits::Polygon_2 Polygon_2;\ntypedef std::list<Polygon_2> Polygon_list;\n\nPoint_2 aux,aux2;\nPoint_list point_list;\n\n\n#define MAX_NUM_POLYGONS 100\n#define NUM_MAX_VERTEX 10\n#define STRSIZ 300\n#define SIZE_LINE 10000\n\n\n\ntypedef struct Vertex_ {\n float x;\n float y;\n} Vertex;\n\ntypedef struct Polygon_ {\n char name[ STRSIZ ];\n char type[ STRSIZ ];\n int num_vertex;\n Vertex vertex[NUM_MAX_VERTEX];\n Vertex min,max;\n} Polygon;\n\nPolygon polygons_wrl[100];\nint num_polygons_wrl = 0;\nparameters params;\nchar actual_world[50];\nfloat dimensions_room_x,dimensions_room_y;\n\n\n// it reads the file that conteins the environment description\nint ReadPolygons(char *file,Polygon *polygons){\n\n FILE *fp;\n char data[ STRSIZ ];\n int i;\n int num_poly = 0;\n int flg = 0;\n float tmp;\n \n\n fp = fopen(file,\"r\"); \n \n if( fp == NULL )\n {\n sprintf(data, \"File %s does not exist\\n\", file);\n printf(\"File %s does not exist\\n\", file);\n return(0);\n }\n //printf(\"World environment %s \\n\",file);\n\n while( fscanf(fp, \"%s\" ,data) != EOF)\n {\n if( strcmp(\";(\", data ) == 0 )\n {\n flg = 1;\n while(flg)\n {\n if( 0 < fscanf(fp, \"%s\", data));\n sscanf(data, \"%f\", &tmp);\n if(strcmp(\")\", data) == 0) flg = 0;\n }\n }\n else if((strcmp(\"polygon\", data ) == 0) && ( flg == 0 ) )\n {\n if( 0 < fscanf(fp, \"%s\", data));\n strcpy(polygons[num_poly].type, data);\n if( 0 < fscanf(fp, \"%s\", data));\n strcpy(polygons[num_poly].name, data);\n i = 0;\n flg = 1;\n\n polygons[num_poly].max.x = 0;\n polygons[num_poly].max.y = 0;\n polygons[num_poly].min.x = 9999;\n polygons[num_poly].min.y = 9999;\n\n while(flg)\n {\n if( 0 < fscanf(fp, \"%s\", data));\n if(strcmp(\")\",data) == 0) \n {\n polygons[num_poly].num_vertex = i - 1;\n polygons[num_poly].vertex[i].x = polygons[num_poly].vertex[0].x; // to calculate intersecction range\n polygons[num_poly].vertex[i].y = polygons[num_poly].vertex[0].y; // the first vertex its repeated on the last\n num_poly++;\n flg = 0;\n }\n else\n {\n sscanf(data, \"%f\", &tmp);\n polygons[num_poly].vertex[i].x = tmp;\n if( 0 < fscanf(fp, \"%s\", data));\n sscanf(data, \"%f\", &tmp);\n polygons[num_poly].vertex[i].y = tmp;\n \n if(polygons[num_poly].vertex[i].x > polygons[num_poly].max.x) polygons[num_poly].max.x = polygons[num_poly].vertex[i].x;\n if(polygons[num_poly].vertex[i].y > polygons[num_poly].max.y) polygons[num_poly].max.y = polygons[num_poly].vertex[i].y;\n if(polygons[num_poly].vertex[i].x < polygons[num_poly].min.x) polygons[num_poly].min.x = polygons[num_poly].vertex[i].x;\n if(polygons[num_poly].vertex[i].y < polygons[num_poly].min.y) polygons[num_poly].min.y = polygons[num_poly].vertex[i].y;\n \n //printf(\"polygon vertex %d x %f y %f\\n\",i,polygons[num_poly].vertex[i].x,polygons[num_poly].vertex[i].y);\n i++;\n }\n }\n }\n else if(strcmp(\"dimensions\", data) == 0 && (flg == 0) )\n {\n if( 0 < fscanf(fp, \"%s\", data));\n if( 0 < fscanf(fp, \"%s\", data));\n sscanf(data, \"%f\", &dimensions_room_x);\n if( 0 < fscanf(fp, \"%s\", data));\n sscanf(data, \"%f\", &dimensions_room_y);\n //printf(\"dimensions x %f y %f\\n\",dimensions_room_x,dimensions_room_y);\n }\n }\n fclose(fp);\n return num_poly;\n}\n\nvoid read_environment(char *file, int debug)\n{\n\n int i; \n int j;\n // it reads the polygons \n strcpy(polygons_wrl[0].name, \"NULL\");\n if(debug == 1) printf(\"\\nEnvironment file: %s\\n\", file);\n num_polygons_wrl = ReadPolygons(file, polygons_wrl);\n \n if(num_polygons_wrl == 0)\n printf(\"File doesnt exist %s \\n\",file);\n else \n printf(\"Load: %s \\n\",file); \n // it prints the polygons\n if(debug == 1)\n for(i = 0; i < num_polygons_wrl; i++)\n {\n printf(\"\\npolygon[%d].name=%s\\n\",i,polygons_wrl[i].name);\n printf(\"polygon[%d].type=%s\\n\",i,polygons_wrl[i].type);\n printf(\"Num vertex polygon[%d].num_vertex=%d\\n\",i,polygons_wrl[i].num_vertex);\n printf(\"max x,y = (%f, %f) min x,y = (%f, %f) \\n\", polygons_wrl[i].max.x, polygons_wrl[i].max.y, polygons_wrl[i].min.x, polygons_wrl[i].min.y);\n //printf(\"self.w.create_rectangle(%f* self.canvasX/2, (self.canvasY-( %f* self.canvasY )/2) , (%f* self.canvasX)/2, (self.canvasY-(%f* self.canvasX)/2), outline='#000000', width=1)\\n\", polygons_wrl[i].max.x, polygons_wrl[i].max.y, polygons_wrl[i].min.x, polygons_wrl[i].min.y);\n for(j = 0; j <= polygons_wrl[i].num_vertex+1 ; j++)\n {\n printf(\"polygon[%d].vertex[%d] x=%f y=%f\\n\", i, j, polygons_wrl[i].vertex[j].x, polygons_wrl[i].vertex[j].y);\n //printf(\"polygon[%d].line[%d] m=%f b=%f\\n\", i, j, polygons_wrl[i].line[j].m, polygons_wrl[i].line[j].b);\n }\n }\n}\n\n\n\nvoid paramsCallback(const simulator::Parameters::ConstPtr& paramss)\n{\n std::string paths = ros::package::getPath(\"simulator\");\n char path[500];\n int k;\n Polygon_2 polygon;\n Polygon_list partition_polys;\n\n\n params.robot_x = paramss->robot_x ;\n params.robot_y = paramss->robot_y ;\n params.robot_theta = paramss->robot_theta ; \n params.robot_radio = paramss->robot_radio ; \n params.robot_max_advance = paramss->robot_max_advance ; \n params.robot_turn_angle = paramss->robot_turn_angle ; \n params.laser_num_sensors = paramss->laser_num_sensors ; \n params.laser_origin = paramss->laser_origin ; \n params.laser_range = paramss->laser_range ; \n params.laser_value = paramss->laser_value ; \n strcpy(params.world_name ,paramss -> world_name.c_str()); \n params.noise = paramss->noise ; \n params.run = paramss->run ; \n params.light_x = paramss->light_x;\n params.light_y = paramss->light_y;\n params.behavior = paramss->behavior; \n\n if( strcmp( paramss->world_name.c_str(),actual_world) ) \n {\n strcpy(path,paths.c_str());\n strcat(path,\"/src/data/\");\n strcat(path,paramss->world_name.c_str());\n strcat(path,\"/\");\n strcat(path,paramss->world_name.c_str());\n strcat(path,\".wrl\");\n read_environment(path,0);\n strcat(actual_world,paramss->world_name.c_str());\n strcpy(actual_world,paramss->world_name.c_str());\n\n point_list.clear();\n\n for(int i = 0; i < num_polygons_wrl; i++)\n {\n polygon.clear();\n partition_polys.clear();\n for(int j = 0; j <= polygons_wrl[i].num_vertex; j++ )\n polygon.push_back(Point_2(polygons_wrl[i].vertex[j].x, polygons_wrl[i].vertex[j].y));\n\n CGAL::approx_convex_partition_2(polygon.vertices_begin(),\n polygon.vertices_end(),\n std::back_inserter(partition_polys));\n for( Polygon_list::iterator vi = partition_polys.begin(); vi != partition_polys.end(); ++vi) \n { k = 0; \n for( Polygon_2::Vertex_iterator vert = vi->vertices_begin(); vert != vi->vertices_end(); ++vert,k++) \n {\n if(k == 0)\n aux = *vert;\n else if(k == 1)\n {\n aux2 = *vert;\n }\n else\n {\n point_list.push_back(aux); \n point_list.push_back(aux2); \n point_list.push_back(*vert); \n aux2 = *vert;\n\n }\n }\n } \n }\n\n }\n}\n\n\nint main(int argc, char** argv)\n{\n ros::init(argc, argv, \"visual_tools_demo\");\n ros::NodeHandle n;\n ros::Subscriber params_sub = n.subscribe(\"simulator_parameters_pub\", 0, paramsCallback);\n\n\n ros::Publisher vis_pub = n.advertise<visualization_msgs::Marker>( \"map_marker\", 0 );\n ros::Publisher goal_pub = n.advertise<visualization_msgs::Marker>( \"goal_marker\", 0 );\n ros::Publisher goal_base_pub = n.advertise<visualization_msgs::Marker>( \"goal_marker_base\", 0 );\n\n\nvisualization_msgs::Marker goal;\ngoal.header.frame_id = \"map\";\ngoal.header.stamp = ros::Time();\ngoal.ns = \"my_namespace2\";\ngoal.id = 0;\ngoal.type = visualization_msgs::Marker::SPHERE;\ngoal.action = visualization_msgs::Marker::ADD;\ngoal.lifetime = ros::Duration(1);\ngoal.pose.position.x = 0;\ngoal.pose.position.y = 0;\ngoal.pose.position.z = 0.1;\ngoal.pose.orientation.x = 0.0;\ngoal.pose.orientation.y = 0.0;\ngoal.pose.orientation.z = 0.0;\ngoal.pose.orientation.w = 1.0;\ngoal.scale.x = .05;\ngoal.scale.y = .05;\ngoal.scale.z = .05;\ngoal.color.a = 1.0; // Don't forget to set the alpha!\ngoal.color.r = 1.0;\ngoal.color.g = 0.8;\ngoal.color.b = 0.0;\n\n\nvisualization_msgs::Marker goal_base;\ngoal_base.header.frame_id = \"map\";\ngoal_base.header.stamp = ros::Time();\ngoal_base.ns = \"my_namespace3\";\ngoal_base.id = 1;\ngoal_base.type = visualization_msgs::Marker::CYLINDER;\ngoal_base.action = visualization_msgs::Marker::ADD;\ngoal_base.lifetime = ros::Duration(1);\ngoal_base.pose.position.x = 0;\ngoal_base.pose.position.y = 0;\ngoal_base.pose.position.z = 0.05;\ngoal_base.pose.orientation.x = 0.0;\ngoal_base.pose.orientation.y = 0.0;\ngoal_base.pose.orientation.z = 0.0;\ngoal_base.pose.orientation.w = 1.0;\ngoal_base.scale.x = .01;\ngoal_base.scale.y = .01;\ngoal_base.scale.z = .1;\ngoal_base.color.a = 1.0; // Don't forget to set the alpha!\ngoal_base.color.r = 1.0;\ngoal_base.color.g = 0.8;\ngoal_base.color.b = 0.0;\n\n\ngeometry_msgs::Point pt;\n\nvisualization_msgs::Marker marker;\nmarker.header.frame_id = \"map\";\nmarker.header.stamp = ros::Time();\nmarker.ns = \"my_namespace\";\nmarker.id = 2;\nmarker.type = visualization_msgs::Marker::TRIANGLE_LIST;\nmarker.action = visualization_msgs::Marker::ADD;\nmarker.lifetime = ros::Duration(1);\nmarker.pose.position.x = 0;\nmarker.pose.position.y = 0;\nmarker.pose.position.z = 0;\nmarker.pose.orientation.x = 0.0;\nmarker.pose.orientation.y = 0.0;\nmarker.pose.orientation.z = 0.0;\nmarker.pose.orientation.w = 1.0;\nmarker.scale.x = 1;\nmarker.scale.y = 1;\nmarker.scale.z = 1;\nmarker.color.a = 1.0; // Don't forget to set the alpha!\nmarker.color.r = 0.1;\nmarker.color.g = 0.5;\nmarker.color.b = 1.0;\n\n\nstd_msgs::ColorRGBA color;\n\ncolor.r = 0;\ncolor.g = 0;\ncolor.b = 50;\ncolor.a = 1;\n\n\n ros::Rate r(10.0);\n \n while(n.ok())\n {\n \n marker.points.clear();\n marker.colors.clear();\n\n for(int i = 0; i < num_polygons_wrl; i++)\n {\n for(int j = 1; j <= polygons_wrl[i].num_vertex; j++ )\n {\n pt.x = polygons_wrl[i].vertex[j-1].x;\n pt.y = polygons_wrl[i].vertex[j-1].y;\n pt.z = 0;\n marker.points.push_back(pt);\n marker.colors.push_back(color);\n\n pt.x = polygons_wrl[i].vertex[j].x;\n pt.y = polygons_wrl[i].vertex[j].y;\n pt.z = 0;\n marker.points.push_back(pt);\n marker.colors.push_back(color);\n\n pt.x = polygons_wrl[i].vertex[j-1].x;\n pt.y = polygons_wrl[i].vertex[j-1].y;\n pt.z = .06;\n marker.points.push_back(pt);\n marker.colors.push_back(color);\n\n pt.x = polygons_wrl[i].vertex[j].x;\n pt.y = polygons_wrl[i].vertex[j].y;\n pt.z = 0;\n marker.points.push_back(pt);\n marker.colors.push_back(color);\n\n pt.x = polygons_wrl[i].vertex[j].x;\n pt.y = polygons_wrl[i].vertex[j].y;\n pt.z = .06;\n marker.points.push_back(pt);\n marker.colors.push_back(color);\n\n pt.x = polygons_wrl[i].vertex[j-1].x;\n pt.y = polygons_wrl[i].vertex[j-1].y;\n pt.z = .06;\n marker.points.push_back(pt);\n marker.colors.push_back(color);\n }\n\n pt.x = polygons_wrl[i].vertex[polygons_wrl[i].num_vertex].x;\n pt.y = polygons_wrl[i].vertex[polygons_wrl[i].num_vertex].y;\n pt.z = 0;\n marker.points.push_back(pt);\n marker.colors.push_back(color);\n\n pt.x = polygons_wrl[i].vertex[0].x;\n pt.y = polygons_wrl[i].vertex[0].y;\n pt.z = 0;\n marker.points.push_back(pt);\n marker.colors.push_back(color);\n\n pt.x = polygons_wrl[i].vertex[polygons_wrl[i].num_vertex].x;\n pt.y = polygons_wrl[i].vertex[polygons_wrl[i].num_vertex].y;\n pt.z = .06;\n marker.points.push_back(pt);\n marker.colors.push_back(color);\n\n pt.x = polygons_wrl[i].vertex[0].x;\n pt.y = polygons_wrl[i].vertex[0].y;\n pt.z = 0;\n marker.points.push_back(pt);\n marker.colors.push_back(color);\n\n pt.x = polygons_wrl[i].vertex[0].x;\n pt.y = polygons_wrl[i].vertex[0].y;\n pt.z = .06;\n marker.points.push_back(pt);\n marker.colors.push_back(color);\n\n pt.x = polygons_wrl[i].vertex[polygons_wrl[i].num_vertex].x;\n pt.y = polygons_wrl[i].vertex[polygons_wrl[i].num_vertex].y;\n pt.z = .06;\n marker.points.push_back(pt);\n marker.colors.push_back(color);\n }\n\n for(int k =0; k < point_list.size(); k++)\n {\n pt.x = point_list[k].x();\n pt.y = point_list[k].y();\n pt.z = .06;\n marker.points.push_back(pt);\n marker.colors.push_back(color);\n }\n\n for(int k =0; k < point_list.size(); k++)\n {\n pt.x = point_list[k].x();\n pt.y = point_list[k].y();\n pt.z = .0;\n marker.points.push_back(pt);\n marker.colors.push_back(color);\n }\n\n vis_pub.publish( marker );\n goal.pose.position.x = params.light_x;\n goal.pose.position.y = params.light_y;\n goal_pub.publish( goal );\n goal_base.pose.position.x = params.light_x;\n goal_base.pose.position.y = params.light_y;\n goal_base_pub.publish( goal_base );\n\n\n ros::spinOnce(); \n r.sleep();\n\n }\n\n ROS_INFO_STREAM(\"Shutting down.\");\n\n return 0;\n}\n\n\n\n" }, { "alpha_fraction": 0.7476949095726013, "alphanum_fraction": 0.7502095699310303, "avg_line_length": 21.50943374633789, "blob_id": "6d3d5b400fe6c0a1b8cdf2f6f8353d833b555bca", "content_id": "1bc870eb9ebe94e77dfc9ee85c47b50705d2e559", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1193, "license_type": "no_license", "max_line_length": 103, "num_lines": 53, "path": "/catkin_ws/src/clips_ros/CMakeLists.txt", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(clips_ros)\n\n## Find catkin macros and libraries\n## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)\n## is used, also find other catkin packages\nfind_package(catkin REQUIRED COMPONENTS\n roscpp\n rospy\n roslib \n std_msgs\n std_srvs\n message_generation\n geometry_msgs \n)\n\n\n## Generate messages in the 'msg' folder\nfile(GLOB MESSAGE_FILES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}/msg ${CMAKE_CURRENT_SOURCE_DIR}/msg/*.msg)\nadd_message_files(FILES ${MESSAGE_FILES})\n\n## Generate services in the 'srv' folder\nfile(GLOB SERVICE_FILES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}/srv ${CMAKE_CURRENT_SOURCE_DIR}/srv/*.srv)\nadd_service_files(FILES ${SERVICE_FILES})\n\ngenerate_messages(\n DEPENDENCIES\n std_msgs\n geometry_msgs\n )\n\ncatkin_package(\n INCLUDE_DIRS src\n LIBRARIES clips_ros\n CATKIN_DEPENDS geometry_msgs roscpp rospy std_msgs std_srvs\n# DEPENDS system_lib\n)\n\ninclude_directories(\n src \n ${catkin_INCLUDE_DIRS}\n)\n\nadd_library(clips_ros\n src/SimuladorRepresentation.cpp\n)\n\nadd_dependencies(clips_ros ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n\ntarget_link_libraries(clips_ros\n ${catkin_LIBRARIES}\n\n)\n" }, { "alpha_fraction": 0.6895634531974792, "alphanum_fraction": 0.7072634100914001, "avg_line_length": 27.54450225830078, "blob_id": "1f29a80945210efeb46a38d8ae1f9ae5ace7565f", "content_id": "0ea7b9cb47c5d11f04a29bcd316da2db1078194b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10904, "license_type": "no_license", "max_line_length": 163, "num_lines": 382, "path": "/catkin_ws/src/simulator/src/gui/simulator_node.py", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom MobileRobotSimulator import *\nfrom simulator.srv import *\nfrom minibot_msgs.srv import *\nfrom simulator.msg import Parameters\nfrom simulator.msg import PosesArray\nfrom simulator.msg import poseCustom\nfrom sensor_msgs.msg import LaserScan\nfrom nav_msgs.msg import Odometry\nfrom tf.transformations import euler_from_quaternion \nimport os\nimport tf\nimport time\nimport rospy\nfrom geometry_msgs.msg import Point, Pose, Quaternion, Twist, Vector3, PoseStamped\nfrom std_msgs.msg import Int8MultiArray\nimport tkMessageBox\n\n\ngui=MobileRobotSimulator()\n\nbattery_low = False\nbattery_charging = False\n\nvideo_name = \"\"\nvideo_path = \"/home/\" + os.environ.get(\"USERNAME\") + \"/MobileRobotSimulator/catkin_ws/recordings/\"\n#video_path = \"/home/\" + 'admin' + \"/MobileRobotSimulator/catkin_ws/recordings/\"\n\ndef handlePoseByAruco(msg):\n\tquaternion = (\n msg.pose.orientation.x,\n msg.pose.orientation.y,\n msg.pose.orientation.z,\n msg.pose.orientation.w)\n\n\teuler = euler_from_quaternion(quaternion)\n\troll = euler[0]\n\tpitch = euler[1]\n\tyaw = euler[2]\n\tgui.handlePoseByAruco(msg.pose.position.x,msg.pose.position.y,yaw)\n\n\ndef turtle_odometry(msg):\n\tquaternion = (\n msg.pose.pose.orientation.x,\n msg.pose.pose.orientation.y,\n msg.pose.pose.orientation.z,\n msg.pose.pose.orientation.w)\n\n\teuler = euler_from_quaternion(quaternion)\n\troll = euler[0]\n\tpitch = euler[1]\n\tyaw = euler[2]\n\tgui.handle_turtle(msg.pose.pose.position.x,msg.pose.pose.position.y,yaw)\n\t#msg.pose.pose.position\n\t\ndef handle_simulator_object_interaction(req):\n\tprint(req)\n\tresp = simulator_object_interactionResponse()\n\tresp.done = gui.handle_simulator_object_interaction(req.grasp,req.name)\n\tprint(gui.objects_data)\n\treturn resp\n\ndef convertArray2Pose(objects_data):\n\tarrayPosesObjs = PosesArray();\n\tfor obj in objects_data:\n\t\ttmp = poseCustom()\n\t\ttmp.name = obj[0]\n\t\ttmp.x = obj[1]\n\t\ttmp.y = obj[2]\n\t\tarrayPosesObjs.posesArray.append(tmp)\n\treturn arrayPosesObjs\n\ndef update_value(msg):\n\tgui.handle_hokuyo(msg.ranges)\n\tranges=msg.ranges\n\ndef handle_simulator_set_light_position(req):\n\n\tresp = simulator_set_light_positionResponse()\n\tgui.set_light_position(req.light_x,req.light_y)\n\treturn resp\n\ndef handle_simulator_stop(req):\n\n\tresp = simulator_stopResponse()\n\tgui.s_t_simulation(False)\n\treturn resp\n\n\ndef handle_robot_step(req):\n\n\tresp = simulator_robot_stepResponse()\n\tgui.sensors_values_aux = req.sensors;\n\tgui.handle_service(req.theta,req.distance)\n\tparameters = gui.get_parameters()\n\tresp.robot_x = parameters[0]\n\tresp.robot_y = parameters[1]\n\tresp.theta = parameters[2]\n\treturn resp\n\ndef handle_print_graph(req):\n\n\tresp = simulator_algorithm_resultResponse()\n\tgui.handle_print_graph(req.nodes_algorithm)\n\tresp.success=1;\n\treturn resp\n\ndef turn_lights(lights_array):\n\n\tlights = Int8MultiArray()\n\tlights.data = lights_array\n\tlights_pub.publish(lights)\n\ndef publish_movement(move):\n\trate = rospy.Rate(1.2)\n\tmove_cmd = Twist()\n\n\ttry:\n\t\tif move[0] == 1:\n\t\t\tmove_cmd.linear.x = 0.5\n\t\t\tmove_cmd.angular.z = 0\n\t\t\tmove_pub.publish(move_cmd)\n\t\t\trate.sleep()\n\n\t\telif move[1] == 1:\n\t\t\tmove_cmd.linear.x = -0.5\n\t\t\tmove_cmd.angular.z = 0\n\t\t\tmove_pub.publish(move_cmd)\n\t\t\trate.sleep()\n\n\t\telif move[2] == 1:\n\t\t\tmove_cmd.linear.x = 0\n\t\t\tmove_cmd.angular.z = 2.4\n\t\t\tmove_pub.publish(move_cmd)\n\t\t\trate.sleep()\n\n\t\telif move[3] == 1:\n\t\t\tmove_cmd.linear.x = 0\n\t\t\tmove_cmd.angular.z = -2.4\n\t\t\tmove_pub.publish(move_cmd)\n\t\t\trate.sleep()\n\n\t\telse:\n\t\t\tmove_cmd.linear.x = 0\n\t\t\tmove_cmd.angular.z = 0\n\t\t\tmove_pub.publish(move_cmd)\n\texcept:\n\t\t\tmove_cmd.linear.x = 0\n\t\t\tmove_cmd.angular.z = 0\n\t\t\tmove_pub.publish(move_cmd)\n\ndef battery_charge():\n\ttry:\n\t\tget_batt_perc = rospy.ServiceProxy('/battery_perc', GetBattPerc)\n\t\tgui.batteryBar['value'] = get_batt_perc().batt_percentage\n\texcept rospy.ServiceException as e:\n\t\tgui.batteryBar['value'] = 0\n\t\ndef battery_advertise(message, color):\n\tgui.labelBattAdvertise.grid_forget()\n\tgui.labelBattAdvertise.config( text = message , bg = color )\n\tgui.labelBattAdvertise.grid(column = 4 ,row = 22 ,sticky = (N, W) ,padx = (10,5))\n\t\ndef play_recording():\n\tos.system('mplayer ' + video_path + video_name)\n\tprint(\"playing video: \" + video_path + video_name)\n\ndef transfer_video():\n\ttkMessageBox.showinfo(\"Video loading\", \"Loading video...\" + video_name )\n\ttime.sleep(6)\n\ttry:\n\t\tvideo_transfer = rospy.ServiceProxy('/transfer_file', TransferFile)\n\t\tif(video_transfer(video_name).status == \"ok\"):\n\t\t\trospy.loginfo(\"Video transfered correctly\")\n\t\telse:\n\t\t\trospy.logerr(\"Video was not found\")\n\texcept:\n\t\tprint(\"/transfer_file service couldnt get response\")\n\t\ttkMessageBox.showerror(\"Video loading\", \"There was an error loading video\" )\n\ndef start_recording():\n\tglobal video_name\n\ttry:\n\t\tstart_recording = rospy.ServiceProxy('/start_recording', StartRecording)\n\t\tvideo_name = start_recording(os.environ.get(\"USER\")).video_name\n\n\t\tif(video_name != \"\"):\t\t\n\t\t\tgui.labelVideoNamed = Label(gui.rightMenu, text = \"File: \" + video_name, font = gui.lineFont)\n\t\t\tgui.labelVideoNamed.grid(column = 0 ,row = 24 ,sticky = (N, W) ,padx = 0, pady = 65,columnspan = 3)\n\t\t\ttkMessageBox.showinfo(\"Video recording\", \"Video recording has started\")\n\n\texcept rospy.ServiceException as e:\n\t\tprint(\"/start_recording service couldnt get response\")\n\t\ttkMessageBox.showerror(\"Video recording\", \"There was an errro recording video\")\n\ndef stop_recording():\n\ttry:\n\t\tstop_recording = rospy.ServiceProxy('/finish_recording', FinishRecording)\n\t\tprint(stop_recording().video_status)\n\t\ttransfer_video()\n\texcept rospy.ServiceException as e:\n\t\tprint(\"/finish_recording service couldnt get response\")\n\ndef get_params():\n\tglobal battery_low, battery_charging\n\tif rospy.has_param('/battery_low'):\n\t\tbattery_low = rospy.get_param(\"/battery_low\")\n\tif rospy.has_param('/battery_charging'):\n\t\tbattery_charging = rospy.get_param(\"/battery_charging\")\n\ndef ros():\n\tglobal lights_pub, move_pub\n\trospy.init_node('simulator_gui_node')\n\ta = rospy.Service('simulator_robot_step', simulator_robot_step, handle_robot_step)\n\tb = rospy.Service('simulator_print_graph', simulator_algorithm_result, handle_print_graph)\n\tc = rospy.Service('simulator_stop', simulator_stop, handle_simulator_stop)\n\td = rospy.Service('simulator_set_light_position', simulator_set_light_position, handle_simulator_set_light_position)\n\te = rospy.Service('simulator_object_interaction', simulator_object_interaction, handle_simulator_object_interaction)\n\t\n\t#rospy.Subscriber('/scan',LaserScan,update_value,queue_size=1)\n\t#rospy.Subscriber('/odom',Odometry, turtle_odometry ,queue_size=1)\n\trospy.Subscriber('/robotPoseByAruco',PoseStamped, handlePoseByAruco ,queue_size=1)\n\todom_pub = rospy.Publisher(\"/odom_simul\", Odometry, queue_size=50)\n\tobjPose_pub = rospy.Publisher(\"/objectsPose\", PosesArray, queue_size=5)\n\todom_broadcaster = tf.TransformBroadcaster()\n\tlights_pub = rospy.Publisher(\"/turn_lights\", Int8MultiArray, queue_size=5)\n\tmove_pub = rospy.Publisher(\"/cmd_vel\", Twist, queue_size=10)\n\n\t\n\tx = 0.0\n\ty = 0.0\n\tth = 0.0\n\n\tvx = 0.1\n\tvy = -0.1\n\tvth = 0.1\n\tcurrent_time = rospy.Time.now()\n\tlast_time = rospy.Time.now()\n\n\tlights_array = [0, 0]\n\tlast_movement = []\n\n\tpub_params = rospy.Publisher('simulator_parameters_pub', Parameters, queue_size = 0)\n\t#rospy.Subscriber(\"simulator_laser_pub\", Laser_values, callback)\n\n\tget_params()\n\tbattery_charge()\n\n\tmsg_params = Parameters()\n\trate = rospy.Rate(100)\n\t\n\n\tstart = time.time()\n\tlabelColor = gui.warnLightColor\n\n\trobot_selected = 'No selected'\n\n\tif rospy.has_param('/robot_selected'):\n\t\trobot_selected = rospy.get_param(\"/robot_selected\")\n\n\tgui.labelRobot = Label(gui.rightMenu ,text = \"Robot: \" + robot_selected, background = gui.backgroundColor, foreground = gui.titlesColor ,font = gui.headLineFont )\n\tgui.labelRobot.grid(column = 4 ,row = 0 ,sticky = (N, W) ,padx = (5,5)) \n\n\twhile not gui.stopped:\n\t\tparameters = gui.get_parameters()\n\t\tmsg_params.robot_x = parameters[0]\n\t\tmsg_params.robot_y = parameters[1]\n\t\tmsg_params.robot_theta = parameters[2]\n\t\tmsg_params.robot_radio = parameters[3]\n\t\tmsg_params.robot_max_advance = parameters[4]\n\t\tmsg_params.robot_turn_angle = parameters[5]\n\t\tmsg_params.laser_num_sensors = parameters[6]\n\t\tmsg_params.laser_origin = parameters[7]\n\t\tmsg_params.laser_range = parameters[8]\n\t\tmsg_params.laser_value = parameters[9]\n\t\tmsg_params.world_name = parameters[10]\n\t\tmsg_params.noise = parameters[11]\n\t\tmsg_params.light_x = parameters[12]\n\t\tmsg_params.light_y = parameters[13]\n\t\tmsg_params.run = parameters[14]\n\t\tmsg_params.behavior = parameters[15]\n\t\tmsg_params.steps = parameters[16]\n\t\tmsg_params.useRealRobot = parameters[16]\n\t\tmsg_params.useLidar = parameters[17]\n\t\tmsg_params.useSArray = parameters[18]\n\t\tmsg_params.realLights = [parameters[19], parameters[20], 0, 0, 0, 0]\n\t\t#msg_params.play_record = parameters[21]\n\t\t#msg_params.start_record = parameters[22]\n\t\t#msg_params.finish_record = parameters[23]\n\n\t\tpub_params.publish(msg_params)\n\n\t\tx = parameters[0]\n\t\ty = parameters[1]\n\t\tth = parameters[2]\n\t\todom_quat = tf.transformations.quaternion_from_euler(0, 0, th)\n\n\t\todom_broadcaster.sendTransform(\n\t\t\t(x, y, 0.),\n\t\t\todom_quat,\n\t\t\tcurrent_time,\n\t\t\t\"base_link_rob2w\",\n\t\t\t\"map\"\n\t\t\t\n\t\t)\n\n\t\todom = Odometry()\n\t\todom.header.stamp = current_time\n\t\todom.header.frame_id = \"map\"\n\t\todom.pose.pose = Pose(Point(x, y, 0.), Quaternion(*odom_quat))\n\t\todom.child_frame_id = \"base_link_rob2w\"\n\t\todom.twist.twist = Twist(Vector3(0, 0, 0), Vector3(0, 0, 0))\n\t\todom_pub.publish(odom)\n\n\n\t\tobjPose_pub.publish(convertArray2Pose(gui.objects_data))\t\t \n\t\t\n\t\tif lights_array != [parameters[19], parameters[20]]:\n\t\t\tlights_array = [parameters[19], parameters[20]]\n\t\t\tturn_lights(lights_array)\n\t\t\n\t\tif last_movement != parameters[21]:\n\t\t\tpublish_movement(parameters[21])\n\t\t\tlast_movement = parameters[21]\n\t\t\tgui.movement = [0, 0, 0, 0]\n\t\t\n\t\tif(gui.isRunning is False):\n\t\t\tbattery_charge()\n\n\t\trate.sleep()\n\n\n\t\tget_params()\n\t\tend = time.time()\n\t\t\n\t\tif(end - start > 0.5):\n\t\t\tstart = time.time()\t\n\t\t\tif battery_charging:\n\t\t\t\tif labelColor == gui.warnLightColor:\n\t\t\t\t\tlabelColor = gui.warnStrongColor\n\t\t\t\telse:\n\t\t\t\t\tlabelColor = gui.warnLightColor\n\n\t\t\t\tbattery_advertise('Battery charging...', labelColor)\n\t\t\n\t\t\telif battery_low:\n\t\t\t\tif labelColor == gui.errorLightColor:\n\t\t\t\t\tlabelColor = gui.errorStrongColor\n\t\t\t\telse:\n\t\t\t\t\tlabelColor = gui.errorLightColor\n\n\t\t\t\tbattery_advertise('Battery low :,O', labelColor)\n\t\t\telse: \n\t\t\t\tgui.labelBattAdvertise.grid_forget()\n\n\t\t#print(str(parameters[22]) + \", \" + str(parameters[23]) + \", \" + str(parameters[24]))\n\t\t\n\t\tif(parameters[22]):\n\t\t\tplay_recording()\n\t\t\tgui.restart_play_record()\n\t\tif(parameters[23]):\n\t\t\tstart_recording()\n\t\t\tgui.restart_start_record()\n\t\tif(parameters[24]):\n\t\t\tstop_recording()\n\t\t\tgui.restart_finish_record()\n\t\t\n\t\t#print(gui.stopped)\n\t\n\tfor _ in range(20):\n\t\tmsg_params.run = False\n\t\tpub_params.publish(msg_params)\n\t\trate.sleep()\n\n\nif __name__ == \"__main__\":\n\ttime.sleep(5) #\n\tros()\n\tturn_lights([0, 0, 0, 0, 0, 0])\n\tprint(\"Finishing...\")\n" }, { "alpha_fraction": 0.5433303713798523, "alphanum_fraction": 0.5658089518547058, "avg_line_length": 26.721311569213867, "blob_id": "49a4e269823104ed37d75d5dc29dba71a589e3b1", "content_id": "9feed2aaa93e09989333302e2b6e12437d3c7574", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3381, "license_type": "no_license", "max_line_length": 96, "num_lines": 122, "path": "/catkin_ws/src/simulator/src/motion_planner/auto_charge_server.cpp", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#include<ros/ros.h>\n#include<geometry_msgs/Twist.h>\n#include<simulator/auto_charge.h>\n#include<sensor_msgs/LaserScan.h>\n#include<std_msgs/Int16MultiArray.h>\n\nusing namespace std;\n\nros::Publisher pubCmdVel;\n\nint line_sensor[2];\nfloat obstacle_distance = 1, obstacle_threshold = 0.1300;\nbool battery_charging = false;\n\nenum State { FOWARD, BACKWARD, TURN_RIGHT, TURN_LEFT, STOP };\n\ngeometry_msgs::Twist move_robot(int move){\n\n geometry_msgs::Twist speed;\n\n switch(move)\n {\n case STOP:\n speed.linear.x = 0.0;\n speed.linear.y = 0.0;\n speed.angular.z = 0.0; \n break;\n case FOWARD:\n speed.linear.x = 0.08;\n speed.linear.y = 0.0;\n speed.angular.z = 0.0; \n break;\n case BACKWARD:\n speed.linear.x = -0.08;\n speed.linear.y = 0.0;\n speed.angular.z = 0.0; \n break;\n case TURN_LEFT:\n speed.linear.x = 0.0;\n speed.linear.y = 0.0;\n speed.angular.z = 1.2; \n break;\n case TURN_RIGHT:\n speed.linear.x = 0.0;\n speed.linear.y = 0.0;\n speed.angular.z = -1.2; \n break;\n default:\n cout << \"An unexpected error has occurred :(\" << endl;\n }\n\n return speed;\n}\n\nvoid follow_line(){\n //cout << \"{ \" << line_sensor[0] << \", \" << line_sensor[1] << \" }\" << endl;\n if(line_sensor[0] == 0 && line_sensor[1] == 0) \n pubCmdVel.publish(move_robot(FOWARD));\n else if(line_sensor[0] == 1 && line_sensor[1] == 0) \n pubCmdVel.publish(move_robot(TURN_RIGHT));\n else if(line_sensor[0] == 0 && line_sensor[1] == 1) \n pubCmdVel.publish(move_robot(TURN_LEFT));\n else\n pubCmdVel.publish(move_robot(STOP));\n \n /*if(obstacle_distance < obstacle_threshold){\n pubCmdVel.publish(move_robot(BACKWARD));\n\tcout << \"Obstacle\" << endl;\n }//*/\n}\n\nbool startCharging(simulator::auto_charge::Request &req, simulator::auto_charge::Response &res){\n ros::Rate rate(50);\n\n while(ros::ok()){\n follow_line();\n \n if(ros::param::get(\"/battery_charging\", battery_charging))\n if(battery_charging){\n cout << \"battery charging\" << endl;\n pubCmdVel.publish(move_robot(STOP));\n break;\n }\n\n ros::spinOnce();\n rate.sleep();\n }\n\n return true;\n}\n\nvoid lineSensorsCallback(const std_msgs::Int16MultiArray::ConstPtr& msg){\n line_sensor[0] = msg->data[0];\n line_sensor[1] = msg->data[1];\n}\n\nvoid scanCallback(const sensor_msgs::LaserScan::ConstPtr& msg){\n obstacle_distance = msg->ranges[1]; \n //cout << msg->ranges[1] << endl;\n}\n\nint main(int argc, char **argv){\n cout << \"Starting auto_charge_server by Luis Nava\" << endl;\n ros::init(argc, argv, \"auto_charge_server\");\n ros::NodeHandle nh;\n ros::Rate loop(20);\n\n pubCmdVel = nh.advertise<geometry_msgs::Twist>(\"/cmd_vel\", 10);\n ros::ServiceServer service = nh.advertiseService(\"auto_charge\", startCharging);\n ros::Subscriber subScan = nh.subscribe(\"/scan\",10, scanCallback);\n ros::Subscriber subLineSensor = nh.subscribe(\"/line_sensors\", 1000, lineSensorsCallback);\n \n \n pubCmdVel.publish(move_robot(STOP));\n \n while(ros::ok()){\n\t//follow_line();\n\tros::spinOnce();\n }\n\n return 0;\n}" }, { "alpha_fraction": 0.32871124148368835, "alphanum_fraction": 0.34910276532173157, "avg_line_length": 22.132076263427734, "blob_id": "b2e14acf575786ba6f54b072abeedd7316c6aa64", "content_id": "2b254277479bd9447bd4167dddc4d4fa1d7d3ce2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1226, "license_type": "no_license", "max_line_length": 115, "num_lines": 53, "path": "/catkin_ws/src/simulator/src/state_machines/light_follower.h", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "/***********************************************\n* *\n* light_follower.h\t *\n* *\n* Diego Cordero *\n* Jesus Savage\t\t\t *\n*\t\t\t\t\t *\n* *\n* Bio-Robotics Laboratory *\n* UNAM, 2019 *\n* *\n* *\n************************************************/\n\n\n#define THRESHOLD_FOLLOWER 31\n \n\nint light_follower(float intensity,float *light_values,movement *movements,float max_advance, float max_turn_angle)\n{\n\n int sensor = 0;\n int i;\n int result = 0;\n\n\n if(intensity > THRESHOLD_FOLLOWER)\n {\n\n\tmovements->twist = 0.0;\n \tmovements->advance = 0.0;\n\tresult = 1;\n\tprintf(\"\\n **************** Reached light source ******************************\\n\");\n }\n else\n {\n \tfor(i = 1; i < 8; i++) \n \t{\n\t if( light_values[i] > light_values[sensor])\n\t\tsensor = i;\n \t}\n \t\n \tif(sensor > 4)\n\t sensor = -(8 - sensor);\t\n\n\n\tmovements->twist = sensor * 3.1315 / 16;\n \tmovements->advance = max_advance/2;\n }\n\n return result;\n\n}\n" }, { "alpha_fraction": 0.5801064372062683, "alphanum_fraction": 0.6054322123527527, "avg_line_length": 28.29032325744629, "blob_id": "4209f0c00b2728037d9974c05f002a3251744003", "content_id": "a479434b9ebf8e6fccc81f6895493b72bd6d23d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5449, "license_type": "no_license", "max_line_length": 109, "num_lines": 186, "path": "/robot_scanner.py", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "import nmap\nimport time\nimport paramiko\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import messagebox as MessageBox\nfrom pexpect import pxssh\nfrom PIL import Image, ImageTk\nimport os\nimport rosgraph\nimport shlex\nfrom psutil import Popen\nimport threading\nimport subprocess\n\n\nhosts = ['192.168.0.165',\n '192.168.0.181',\n '192.168.0.106',\n '192.168.0.195',\n '192.168.0.110',\n '192.168.0.189'\n ]\n\nips_scanned = 0\nscanner = nmap.PortScanner()\nrobot_selected = \"No robot selected\"\nip_available = [False, False, False, False, False, False]\nroot = tk.Tk()\n\n#user = 'remote_laboratory'\n#passw = 'pumaspumas'\nuser = 'pi'\npassw = 'raspberry'\n\nuserName = os.environ.get(\"USERNAME\")\n\ndef launch_simulator(ip):\n os.environ[\"ROS_MASTER_URI\"]=\"http://\" + ip + \":11311\"\n if(rosgraph.is_master_online()):\n process = subprocess.check_call(['/home/' + userName\n + '/MobileRobotSimulator/./runSimulator.sh', ip])\n\n print(\"Process finished\")\n #process.kill()\n\ndef ros_finder(ip):\n os.environ[\"ROS_MASTER_URI\"]=\"http://\" + ip + \":11311\"\n print('.', end='', flush=True)\n if(rosgraph.is_master_online()):\n print(\"ROS MASTER FOUND AT->\" + ip)\n return True\n \n return False\n\ndef connect_host(ip):\n print('Connecting with->' + ip)\n\n try:\n ssh = paramiko.SSHClient()\n\n # Load SSH host keys.\n ssh.load_system_host_keys()\n # Add SSH host key automatically if needed.\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\n # Connect to router using username/password authentication.\n ssh.connect(ip, username=user, password=passw, look_for_keys=False, timeout=10)\n transport = ssh.get_transport()\n channel = transport.open_session()\n\n channel.exec_command('~/Minibot/start.sh')\n #MessageBox.showinfo(\"Connecting\", \"Please wait...\")\n print(\"Searching ROS MASTER...\")\n while True:\n if(ros_finder(ip)):\n break\n launch_simulator(ip)\n\n print(\"Killing rosmaster for Minibot\")\n ssh.exec_command('killall rosmaster')\n #channel.exec_command('killall rosmaster')\n channel.close()\n ssh.close()\n\n except Exception as e:\n print(e)\n MessageBox.showerror(\"Error message\", \"Cannot connect with robot\")\n \n\n \ndef event(i):\n global robot_selected\n robot_selected = \"Selected->\" + \" Minibot \" + str(i)\n connect_host(hosts[i-1])\n\n selected_label = ttk.Label(root, text = robot_selected, font='Helvetica 11 bold')\n selected_label.grid(column=1, row=len(hosts)+1, sticky=tk.W, padx=5, pady=5)\n\ndef scan_ip(ip, id):\n global ips_scanned, ip_available\n scanner.scan(ip, '1', '-v')\n ips_scanned += 1\n if(scanner[ip].state() == \"up\"):\n ip_available[id] = True\n \ndef scan_all():\n global ips_scanned, robot_selected\n id=0\n robot_selected = \"No robot selected \"\n start = time.time()\n print(\"\\nScanning...\")\n for host in hosts:\n thread = threading.Thread(target=scan_ip, args=(host, id, ))\n thread.start()\n id += 1\n \n while(ips_scanned < len(hosts)):\n wait = True\n\n end = time.time()\n scaning_time = end-start\n print(\"Scanned in->\", end = ' ')\n print(scaning_time, end= ' ')\n print(\"seconds\") \n ips_scanned = 0\n\n selected_label = ttk.Label(root, text = robot_selected, font='Helvetica 11 bold')\n selected_label.grid(column=1, row=len(hosts)+1, sticky=tk.W, padx=5, pady=5)\n\ndef render_gui():\n root.geometry(\"400x360\")\n root.title('Robots scanner')\n root.resizable(0, 0)\n\n # configure the grid\n root.columnconfigure(0, weight=1)\n root.columnconfigure(1, weight=3)\n\n err_image = Image.open('/home/remotelab/MobileRobotSimulator/error.png').resize((25,25), Image.ANTIALIAS)\n ok_image = Image.open('/home/remotelab/MobileRobotSimulator/ok.png').resize((25,25), Image.ANTIALIAS)\n\n label = ttk.Label(root, text=\"Status\", font='Helvetica 11 bold')\n label.grid(column=0, row=0, sticky=tk.W, padx=(20,0), pady=5)\n\n i = 1\n for ip in hosts:\n if(ip_available[i-1]):\n status = \"Available\"\n icon_status = ImageTk.PhotoImage(ok_image)\n button = ttk.Button(root, text=\"Connect\", command=lambda m = i: event(m))\n else:\n status = \"Not available\"\n icon_status = ImageTk.PhotoImage(err_image)\n button = ttk.Button(root, text=\"Connect\" , state= tk.DISABLED)\n\n label = ttk.Label(root, image = icon_status)\n label.image = icon_status\n label.grid(row=i)\n\n minibot_label = ttk.Label(root, text=\"Minibot \" + str(i) + \": \" + status)\n minibot_label.grid(column=1, row=i, sticky=tk.W, padx=5, pady=5)\n button.grid(column=2, row=i, sticky=tk.W, padx=(0,10), pady=5)\n \n i += 1\n\n button_refresh = ttk.Button(root, text=\"Refresh\", command=scan_all)\n button_refresh.grid(column=0, row=i, sticky=tk.W, padx=5, pady=5)\n\n selected_label = ttk.Label(root, text = robot_selected, font='Helvetica 11 bold')\n selected_label.grid(column=1, row=i, sticky=tk.W, padx=5, pady=5)\n\n root.mainloop()\n\n\ndef main():\n scan_all()\n render_gui()\n \nif __name__ == '__main__':\n try:\n main()\n except:\n pass\n finally:\n print(\"Finishing robot_scanner.py...\")\n\n" }, { "alpha_fraction": 0.5983145833015442, "alphanum_fraction": 0.6019663214683533, "avg_line_length": 31.953702926635742, "blob_id": "a5ad84a6eb6d988f88d1903ea10c93fb62f79c37", "content_id": "1e6f4366c8c1cdb2c92f57459c94f73cc60b1099", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3560, "license_type": "no_license", "max_line_length": 181, "num_lines": 108, "path": "/catkin_ws/src/simulator/src/simulator_physics/manipulator_node.cpp", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#include \"ros/ros.h\"\n#include <ros/package.h>\n#include \"simulator/Parameters.h\"\n#include \"../utilities/simulator_structures.h\"\n#include \"simulator/simulator_manipulator.h\"\n#include \"simulator/simulator_object_interaction.h\"\n#include <string.h>\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#define GRASP 1\n#define RELEASE 0\nparameters params;\n\nbool object_interaction(int action, const char name[50])\n{\n ros::NodeHandle n;\n ros::ServiceClient client;\n simulator::simulator_object_interaction srv;\n client = n.serviceClient<simulator::simulator_object_interaction>(\"simulator_object_interaction\");\n std::string s;\n s=name;\n srv.request.name = s;\n srv.request.grasp = action;\n\n if( !client.call(srv) )\n {\n ROS_ERROR(\"Failed to call service simulator_object_interaction\");\n }\n printf(\"%d\\n\",srv.response.done );\n return srv.response.done;\n}\n\nbool manipulator(simulator::simulator_manipulator::Request &req ,simulator::simulator_manipulator::Response &res)\n{\n char str[300];\n //sscanf(result.c_str(),\"%s %s %s\",ROS_System,action,object);\n //printf(\"%s object %s\\n\",action,object);\n\n if( strcmp(req.action.c_str(),\"grab\") == 0 )\n {\n if(object_interaction(GRASP,req.object.c_str()))\n {\n printf(\"object %s grasped\\n\",req.object.c_str());\n }\n else\n {\n printf(\"object %s not grasped\\n\",req.object.c_str());\n }\n\n sprintf(str,\"(assert (answer %s command %s %s 1))\",req.ROS_System.c_str(),req.action.c_str(),req.object.c_str());\n res.answer = str;\n }\n else if(strcmp(req.action.c_str(),\"drop\")==0)\n {\n\n if(object_interaction(RELEASE,req.object.c_str()))\n {\n printf(\"object %s released\\n\",req.object.c_str());\n }\n else\n {\n printf(\"object %s not released\\n\",req.object.c_str());\n }\n\n sprintf(str,\"(assert (answer %s command %s %s %f %f %f 1))\",req.ROS_System.c_str(),req.action.c_str(),req.object.c_str(),params.robot_x ,params.robot_y ,params.robot_theta);\n res.answer = str;\n } \n else\n {\n ROS_ERROR(\"Operation unknow\");\n res.answer = \"FAIL\";\n }\n\n\n return true;\n}\n\n\nvoid paramsCallback(const simulator::Parameters::ConstPtr& paramss)\n{\n params.robot_x = paramss->robot_x ;\n params.robot_y = paramss->robot_y ;\n params.robot_theta = paramss->robot_theta ; \n params.robot_radio = paramss->robot_radio ; \n params.robot_max_advance = paramss->robot_max_advance ; \n params.robot_turn_angle = paramss->robot_turn_angle ; \n params.laser_num_sensors = paramss->laser_num_sensors ; \n params.laser_origin = paramss->laser_origin ; \n params.laser_range = paramss->laser_range ; \n params.laser_value = paramss->laser_value ; \n strcpy(params.world_name ,paramss -> world_name.c_str()); \n params.noise = paramss->noise ; \n params.run = paramss->run ; \n params.light_x = paramss->light_x;\n params.light_y = paramss->light_y;\n params.behavior = paramss->behavior; \n}\n\nint main(int argc, char *argv[])\n{\t\n ros::init(argc, argv, \"simulator_manipulator\");\n ros::NodeHandle n;\n ros::ServiceServer service = n.advertiseService(\"simulator_manipulator\", manipulator);\n ros::Subscriber params_sub = n.subscribe(\"simulator_parameters_pub\", 0, paramsCallback);\n ros::spin();\n return 0;\n}\n\n" }, { "alpha_fraction": 0.6075731515884399, "alphanum_fraction": 0.6144578456878662, "avg_line_length": 21.384614944458008, "blob_id": "68d260a5e5e05c02adcfea88f08ff1b42854652e", "content_id": "b94e1bdd6af35ab150554543f7885b16b9d2d39e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 581, "license_type": "no_license", "max_line_length": 90, "num_lines": 26, "path": "/catkin_ws/src/simulator/src/motion_planner/follow_line_client.cpp", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#include<ros/ros.h>\n#include<simulator/line_follower.h>\n\nusing namespace std;\n\nint main(int argc, char **argv){\n cout << \"Starting follow_line_client by Luis Nava\" << endl;\n ros::init(argc, argv, \"follow_line_client\");\n ros::NodeHandle nh;\n ros::Rate loop(20);\n\n ros::ServiceClient client = nh.serviceClient<simulator::line_follower>(\"follow_line\");\n\n simulator::line_follower srv;\n \n\n if(client.call(srv)) {\n cout << \"Ok\" << endl;\n }\n else {\n ROS_ERROR(\"Failed to call service line_follow_server\");\n return 1;\n }\n\n return 0;\n}" }, { "alpha_fraction": 0.6931937336921692, "alphanum_fraction": 0.6952879428863525, "avg_line_length": 58.625, "blob_id": "ded0c206a9e3b18fd8137287802ca2fd42f10663", "content_id": "8a346ddcdbc692e9563a821fbcf9db68325a32b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 955, "license_type": "no_license", "max_line_length": 93, "num_lines": 16, "path": "/catkin_ws/start.sh", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#Script to start the ros simulations \nxterm -hold -e \". devel/setup.bash && roscore\" &\nxterm -hold -e \". devel/setup.bash && roscd simulator/src/gui/ && python simulator_node.py\" &\nsleep 3\nxterm -hold -e \". devel/setup.bash && rosrun simulator light_node\" &\nxterm -hold -e \". devel/setup.bash && rosrun simulator laser_node\" &\nxterm -hold -e \". devel/setup.bash && rosrun simulator base_node\" &\nxterm -hold -e \". devel/setup.bash && rosrun clips_ros ros_pyclips_node.py\" & \nxterm -hold -e \". devel/setup.bash && rosrun simulator find_obj_node\" & \nxterm -hold -e \". devel/setup.bash && rosrun simulator manipulator_node\" & \nxterm -hold -e \". devel/setup.bash && rosrun simulator objs_viz_node\" & \nsleep 3\nxterm -hold -e \". devel/setup.bash && rosrun simulator motion_planner_node\" \nxterm -hold -e \". devel/setup.bash && rosrun simulator action_planner_node\" \n#xterm -hold -e \". devel/setup.bash && rosrun simulator move_turtlebot_node\" \n" }, { "alpha_fraction": 0.5728273987770081, "alphanum_fraction": 0.5938647389411926, "avg_line_length": 32.6041145324707, "blob_id": "ebf275056bf5309320528804ccc91fc40ecee822", "content_id": "7f809cac67f06e878889023772db2ef3fd869ac7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13072, "license_type": "no_license", "max_line_length": 283, "num_lines": 389, "path": "/catkin_ws/src/simulator/src/simulator_physics/laser_node.cpp", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#include \"ros/ros.h\"\n#include <ros/package.h>\n#include \"simulator/Parameters.h\"\n//#include \"simulator/Laser_values.h\"\n#include \"simulator/simulator_laser.h\"\n#include \"../utilities/simulator_structures.h\"\n#include \"simulator/simulator_robot_step.h\"\n#include \"simulator/simulator_parameters.h\"\n#include \"sensor_msgs/LaserScan.h\"\n#include \"std_msgs/Header.h\"\n//#include \"simulator/simulator_base.h\"\n#include <string.h>\n\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <iterator>\n#include <random>\n\n#include <boost/thread/thread.hpp> \n\n#define MAX_NUM_POLYGONS 100\n#define NUM_MAX_VERTEX 10\n#define STRSIZ 300\n\nstd::default_random_engine generator;\ndouble stddev = 0.015;\nstd::normal_distribution<double> noise(0, stddev);\n\ntypedef struct Vertex_ {\n float x;\n float y;\n} Vertex;\n\ntypedef struct Polygon_ {\n char name[ STRSIZ ];\n char type[ STRSIZ ];\n int num_vertex;\n Vertex vertex[NUM_MAX_VERTEX];\n Vertex min,max;\n} Polygon;\n\nPolygon polygons_wrl[100];\nint num_polygons_wrl = 0;\nfloat sensors[512];\nfloat X_pose,Y_pose;\nchar actual_world[50];\ndouble robot_x;\ndouble robot_y;\ndouble robot_theta;\nparameters params;\n\n// it reads the file that conteins the environment description\nint ReadPolygons(char *file,Polygon *polygons){\n\n\tFILE *fp;\n\tchar data[ STRSIZ ];\n\tint i;\n\tint num_poly = 0;\n\tint flg = 0;\n\tfloat tmp;\n\tfloat dimensions_room_x,dimensions_room_y;\n\n\tfp = fopen(file,\"r\"); \n\t \n\tif( fp == NULL )\n\t{\n\t\tsprintf(data, \"File %s does not exist\\n\", file);\n\t\tprintf(\"File %s does not exist\\n\", file);\n\t\treturn(0);\n\t}\n\t//printf(\"World environment %s \\n\",file);\n\n\twhile( fscanf(fp, \"%s\" ,data) != EOF)\n\t{\n\t\tif( strcmp(\";(\", data ) == 0 )\n\t\t{\n\t\t\tflg = 1;\n\t\t\twhile(flg)\n\t\t\t{\n\t\t\t\tif( 0 < fscanf(fp, \"%s\", data));\n\t\t\t\tsscanf(data, \"%f\", &tmp);\n\t\t\t\tif(strcmp(\")\", data) == 0) flg = 0;\n\t\t\t}\n\t\t}\n\t\telse if((strcmp(\"polygon\", data ) == 0) && ( flg == 0 ) )\n\t\t{\n\t\t\tif( 0 < fscanf(fp, \"%s\", data));\n\t\t\tstrcpy(polygons[num_poly].type, data);\n\t\t\tif( 0 < fscanf(fp, \"%s\", data));\n\t\t\tstrcpy(polygons[num_poly].name, data);\n\t\t\ti = 0;\n\t\t\tflg = 1;\n\n\t\t\tpolygons[num_poly].max.x = 0;\n\t\t\tpolygons[num_poly].max.y = 0;\n\t\t\tpolygons[num_poly].min.x = 9999;\n\t\t\tpolygons[num_poly].min.y = 9999;\n\n\t\t\twhile(flg)\n\t\t\t{\n\t\t\t\tif( 0 < fscanf(fp, \"%s\", data));\n\t\t\t\tif(strcmp(\")\",data) == 0) \n\t\t\t\t{\n\t\t\t\t\tpolygons[num_poly].num_vertex = i - 1;\n\t\t\t\t\tpolygons[num_poly].vertex[i].x = polygons[num_poly].vertex[0].x; // to calculate intersecction range\n\t\t\t\t\tpolygons[num_poly].vertex[i].y = polygons[num_poly].vertex[0].y; // the first vertex its repeated on the last\n\t\t\t\t\tnum_poly++;\n\t\t\t\t\tflg = 0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tsscanf(data, \"%f\", &tmp);\n\t\t\t\t\tpolygons[num_poly].vertex[i].x = tmp;\n\t\t\t\t\tif( 0 < fscanf(fp, \"%s\", data));\n\t\t\t\t\tsscanf(data, \"%f\", &tmp);\n\t\t\t\t\tpolygons[num_poly].vertex[i].y = tmp;\n\t\t\t\t\t\n\t\t\t\t\tif(polygons[num_poly].vertex[i].x > polygons[num_poly].max.x) polygons[num_poly].max.x = polygons[num_poly].vertex[i].x;\n\t\t\t\t\tif(polygons[num_poly].vertex[i].y > polygons[num_poly].max.y) polygons[num_poly].max.y = polygons[num_poly].vertex[i].y;\n\t\t\t\t\tif(polygons[num_poly].vertex[i].x < polygons[num_poly].min.x) polygons[num_poly].min.x = polygons[num_poly].vertex[i].x;\n\t\t\t\t\tif(polygons[num_poly].vertex[i].y < polygons[num_poly].min.y) polygons[num_poly].min.y = polygons[num_poly].vertex[i].y;\n\t\t\t\t\t//printf(\"polygon vertex %d x %f y %f\\n\",i,polygons[num_poly].vertex[i].x,polygons[num_poly].vertex[i].y);\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if(strcmp(\"dimensions\", data) == 0 && (flg == 0) )\n\t\t{\n\t\t\tif( 0 < fscanf(fp, \"%s\", data));\n\t\t\tif( 0 < fscanf(fp, \"%s\", data));\n\t\t\tsscanf(data, \"%f\", &dimensions_room_x);\n\t\t\tif( 0 < fscanf(fp, \"%s\", data));\n\t\t\tsscanf(data, \"%f\", &dimensions_room_y);\n\t\t\t//printf(\"dimensions x %f y %f\\n\",dimensions_room_x,dimensions_room_y);\n\t\t}\n\t}\n\tfclose(fp);\n\treturn num_poly;\n}\n\nvoid read_environment(char *file, int debug)\n{\n \tint i; \n\tint j;\n\t/* it reads the polygons */\n\tstrcpy(polygons_wrl[0].name, \"NULL\");\n\tif(debug == 1) printf(\"\\nEnvironment file: %s\\n\", file);\n\tnum_polygons_wrl = ReadPolygons(file, polygons_wrl);\n\tif(num_polygons_wrl == 0)\n\t\tprintf(\"File doesnt exist %s \\n\",file);\n\telse \n\t\tprintf(\"Load: %s \\n\",file);\n \n\t// it prints the polygons\n\tif(debug == 1)\n\tfor(i = 0; i < num_polygons_wrl; i++)\n\t{\n\t\tprintf(\"\\npolygon[%d].name=%s\\n\",i,polygons_wrl[i].name);\n\t\tprintf(\"polygon[%d].type=%s\\n\",i,polygons_wrl[i].type);\n\t\tprintf(\"Num vertex polygon[%d].num_vertex=%d\\n\",i,polygons_wrl[i].num_vertex);\n\t printf(\"max x,y = (%f, %f) min x,y = (%f, %f) \\n\", polygons_wrl[i].max.x, polygons_wrl[i].max.y, polygons_wrl[i].min.x, polygons_wrl[i].min.y);\n\t //printf(\"self.w.create_rectangle(%f* self.canvasX/2, (self.canvasY-( %f* self.canvasY )/2) , (%f* self.canvasX)/2, (self.canvasY-(%f* self.canvasX)/2), outline='#000000', width=1)\\n\", polygons_wrl[i].max.x, polygons_wrl[i].max.y, polygons_wrl[i].min.x, polygons_wrl[i].min.y);\n\t\tfor(j = 0; j <= polygons_wrl[i].num_vertex+1 ; j++)\n\t\t{\n\t\t\tprintf(\"polygon[%d].vertex[%d] x=%f y=%f\\n\", i, j, polygons_wrl[i].vertex[j].x, polygons_wrl[i].vertex[j].y);\n\t\t\t//printf(\"polygon[%d].line[%d] m=%f b=%f\\n\", i, j, polygons_wrl[i].line[j].m, polygons_wrl[i].line[j].b);\n\t\t}\n\t}\n}\n\nfloat getValue(Vertex p1, Vertex p2, Vertex p3 ,Vertex p4, float laser_value)\n{\n\n\tfloat denominadorTa,ta,xi;\n\tfloat denominadorTb,tb,yi;\n \n\tdenominadorTa =(p4.x-p3.x)*(p1.y-p2.y) - (p1.x-p2.x)*(p4.y-p3.y);\n\tdenominadorTb =(p4.x-p3.x)*(p1.y-p2.y) - (p1.x-p2.x)*(p4.y-p3.y);\n\t\n\tif( denominadorTa == 0 || denominadorTb ==0 )\n\t\treturn laser_value;\n\n\tta = ( (p3.y-p4.y)*(p1.x-p3.x) + (p4.x-p3.x)*(p1.y-p3.y) ) / ( denominadorTa );\n\ttb = ( (p1.y-p2.y)*(p1.x-p3.x) + (p2.x -p1.x)*(p1.y-p3.y) ) / ( denominadorTb );\n \n //printf(\"TTT %f %f \\n\",ta,tb );\n // printf(\"1 %f %f \\n\",p1.x,p1.y );\n \t//printf(\"2 %f %f \\n\",p2.x,p2.y );\n \t//printf(\"3 %f %f \\n\",p3.x,p3.y );\n \t//printf(\"4 %f %f \\n\",p4.x,p4.y );\n\tif( 0 <= ta && ta <=1 && 0 <= tb && tb <=1 )\n\t{\n\t\txi = p1.x + ta * ( p2.x - p1.x ) ;\n\t\tyi = p1.y + ta * ( p2.y - p1.y ) ;\n\t\t//printf(\"%s x %f y% f \\n\",\"holaa\",xi,yi );\n\t\t//printf(\"x1 %f y1 %f x2 %f y2%f \\n\",p1.x,p1.y,p2.x,p2.y );\t\n\t\t//printf(\"x3 %f y3 %f x4 %f y4%f \\n\",p3.x,p3.y,p4.x,p4.y );\n\t\treturn sqrt( pow(p1.x-xi,2) + pow(p1.y-yi,2) ) ;\n\t}\t\t\n\telse\n\t\treturn laser_value;\n\t//resa=[p1.x p1.y] + ta*( [p2.x p2.y]- [p1.x p1.y\n\t//resb= [p3.x p3.y] + tb*( [p4.x p4.y]- [p3.x p3.y] )\n\n}\n\nint getValues(float laser_num_sensors, float laser_origin, float laser_range,float laser_value,float robot_x ,float robot_y ,float robot_theta, float *values)\n{\n\tint i,j,k,m;\n\tfloat f,step,aux;\n\tVertex r_max;\n\tVertex r_min;\n\n\tVertex p1;\n\tVertex p2;\n\tp1.x = robot_x;\n\tp1.y = robot_y;\n\n\tr_max.x = robot_x + laser_value; r_max.y = robot_y + laser_value;\n\tr_min.x = robot_x - laser_value; r_min.y = robot_y - laser_value;\n\n\tint posible_collision[512];\n\t //printf(\"self.w.create_rectangle(%f* self.canvasX, (self.canvasY-( %f* self.canvasY )) , (%f* self.canvasX), (self.canvasY-(%f* self.canvasX)), outline='#000000', width=1)\\n\", r_max.x, r_max.y, r_min.x, r_min.y);\n\t\n\tfor (i=0;i < 512;i++)\n\t\tposible_collision[i]=-1;\n\tj=0;\n\n\tfor (i=0;i < laser_num_sensors;i++)\n\t\tvalues[i]=laser_value;\t\n\n\tfor(i = 0; i < num_polygons_wrl; i++)\n\t\tif( (r_min.x < polygons_wrl[i].max.x && polygons_wrl[i].max.x < r_max.x) || ( r_min.x < polygons_wrl[i].min.x && polygons_wrl[i].min.x < r_max.x) || ( polygons_wrl[i].min.x < r_min.x && r_max.x < polygons_wrl[i].max.x ) )\n\t\t\tif( (r_min.y < polygons_wrl[i].max.y && polygons_wrl[i].max.y < r_max.y) || ( r_min.y < polygons_wrl[i].min.y && polygons_wrl[i].min.y < r_max.y) || ( polygons_wrl[i].min.y < r_min.y && r_max.y < polygons_wrl[i].max.y ) )\n\t\t\t\t//printf(\"%i Aa\\n\",\n\t\t\t\tposible_collision[j++]=i;// );\n\n f = robot_theta + laser_origin;\n\n step = laser_range / ( laser_num_sensors - 1 );\n\n for ( k = 0; k < laser_num_sensors; k++)\n \t{\n \t\tfor(i = 0; i < j; i++)\n\t\t\t{\n\t\t\t\tfor( m = 0; m <= polygons_wrl[posible_collision[i]].num_vertex; m++)\n\t\t\t\t{\n\t\t\t\t\tp2.x = laser_value * cos( f ) + p1.x;\n\t\t\t\t\tp2.y = laser_value * sin( f ) + p1.y;\n\t\t\t\t\t//printf(\"Laser: %d Poligon: %d Valu: %f \\n\",k,i,values[k] );\n\t\t\t\t\taux = getValue(p1,p2,polygons_wrl[posible_collision[i]].vertex[m],polygons_wrl[ posible_collision[i] ].vertex[m+1],laser_value);\n\t\t\t\t\t//printf(\"Laser: %d Poligon: %d Valu: %f \\n\",k,i,values[k] );\n\t\t //printf(\"x1 %f y1 %f x2 %f y2%f \\n\",p1.x,p1.y,p2.x,p2.y );\t\n\t\t //printf(\"x3 %f y3 %f x4 %f y4%f \\n\\n\",polygons_wrl[i].vertex[m].x,polygons_wrl[i].vertex[m].y,polygons_wrl[i].vertex[m+1].x,polygons_wrl[i].vertex[m+1].y );\n\t\t\n\t\t\t\t\tif(values[k] > aux)\n\t\t\t\t\t\tvalues[k] = aux;\n\n\t\t\t\t\t}\n\t\t\t}\n\t\t\tf += step;\n }\n\treturn 0;\n}\n\n\n\nvoid paramsCallback(const simulator::Parameters::ConstPtr& paramss)\n{\n\t std::string paths = ros::package::getPath(\"simulator\");\n \t char path[500];\n\n\t params.robot_x = paramss->robot_x ;\n\t params.robot_y = paramss->robot_y ;\n\t params.robot_theta = paramss->robot_theta ; \n\t params.robot_radio = paramss->robot_radio ; \n\t params.robot_max_advance = paramss->robot_max_advance ; \n\t params.robot_turn_angle = paramss->robot_turn_angle ; \n\t params.laser_num_sensors = paramss->laser_num_sensors ; \n\t params.laser_origin = paramss->laser_origin ; \n\t params.laser_range = paramss->laser_range ; \n\t params.laser_value = paramss->laser_value ; \n\t strcpy(params.world_name ,paramss -> world_name.c_str()); \n\t params.noise = paramss->noise ; \n\t params.run = paramss->run ; \n\t params.light_x = paramss->light_x;\n\t params.light_y = paramss->light_y;\n\t params.behavior = paramss->behavior; \n\n\tif( strcmp( paramss->world_name.c_str(),actual_world) ) \n\t{\n\t\tstrcpy(path,paths.c_str());\n\t\tstrcat(path,\"/src/data/\");\n\t\tstrcat(path,paramss->world_name.c_str());\n\t\tstrcat(path,\"/\");\n\t\tstrcat(path,paramss->world_name.c_str());\n\t\tstrcat(path,\".wrl\");\n\t\tread_environment(path,0);\n\t\tstrcpy(actual_world,paramss->world_name.c_str());\n\t}\n}\n\n\nbool laserCallback(simulator::simulator_laser::Request &req ,simulator::simulator_laser::Response &res)\n{\n\tfloat valores1[512];\n\tfloat valores2[50];\n\tint j=0;\n\tgetValues(params.laser_num_sensors ,params.laser_origin ,params.laser_range ,params.laser_value ,req.robot_x ,req.robot_y ,req.robot_theta ,valores1);\n\t\n\tif(params.noise)\n\t\tfor (int i =0 ; i<params.laser_num_sensors;i++,j++)\n\t\t\tres.sensors[i] = valores1[i] + noise(generator);\n\telse\n\t\tfor (int i =0 ; i<params.laser_num_sensors;i++,j++)\n\t\t\tres.sensors[i] = valores1[i];\n\n\n\t//boost::thread first (getValues,params.laser_num_sensors/2 ,params.laser_origin ,params.laser_range/2 ,params.laser_value ,req.robot_x ,req.robot_y ,req.robot_theta ,valores1);\n\t//boost::thread second (getValues,params.laser_num_sensors/2 ,params.laser_origin + params.laser_range/2 ,params.laser_range/2 ,params.laser_value ,req.robot_x ,req.robot_y ,req.robot_theta ,valores2);\n\t//first.join();\n\t//second.join();\n\t//for (int i =0 ; i<params.laser_num_sensors/2;i++,j++)\n\t//\tres.sensors[j] = valores1[i];\n\n\t//for (int i =0 ; i<params.laser_num_sensors/2;i++,j++)\n\t//\tres.sensors[j] = valores2[i];\n\n\treturn true;\n}\n\n\nint main(int argc, char *argv[])\n{\t\n\tros::init(argc, argv, \"simulator_laser_node\");\n\tros::NodeHandle n;\n\tros::Subscriber params_sub = n.subscribe(\"simulator_parameters_pub\", 0, paramsCallback);\n\tros::ServiceServer service = n.advertiseService(\"simulator_laser_serv\", laserCallback);\n\t//ros::spin();\n\n\t\n\tros::Publisher pubLaseScan = n.advertise<sensor_msgs::LaserScan>(\"/scan_simul\", 1);\n\t\n\tactual_world[0] = '\\0';\n\t\n\tstd::string paths = ros::package::getPath(\"simulator\");\n \t\n\tchar a[200];\n\ta[0] ='\\0'; \n\tstrcat(a,paths.c_str());\n\tstrcat(a,\"/src/data/random_2/random_2.wrl\");\n\t\n\tread_environment(a,0);\n\tfloat valores1[512];\n\tfloat valores2[50];\n std_msgs::Header header;\n sensor_msgs::LaserScan msg;\n ros::Rate loop_rate(50);\n\n\twhile (ros::ok())\n\t{\n\t\t\n\theader.frame_id = \"base_link_rob2w\";\n\tmsg.header = header;\n\tmsg.angle_min = params.laser_origin;\n\tmsg.angle_max = params.laser_origin + params.laser_range;\n\tmsg.angle_increment = (double)params.laser_range / (double)params.laser_num_sensors;\n\tmsg.range_min = 0.0;\n\tmsg.range_max = params.laser_value;\n\tmsg.ranges.resize(params.laser_num_sensors);\n\n\n\tgetValues(params.laser_num_sensors ,params.laser_origin ,params.laser_range ,params.laser_value ,params.robot_x ,params.robot_y ,params.robot_theta ,valores1);\n\t\n\tfor (int i =0 ; i<params.laser_num_sensors;i++)\n\t\t//printf(\"%f \\n\",valores1[i] );\n\t\tmsg.ranges[i] = valores1[i];\n\n\t\tpubLaseScan.publish(msg);\n\t \n\t ros::spinOnce();\n\t loop_rate.sleep();\n\n\t}\n\t\n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.760613203048706, "alphanum_fraction": 0.7641509175300598, "avg_line_length": 24.727272033691406, "blob_id": "569cff815b25e5b54ce8e3eecf18f450a50e6166", "content_id": "5b059b3755879297c4d57799e11f26e37e4f1e58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 848, "license_type": "no_license", "max_line_length": 103, "num_lines": 33, "path": "/catkin_ws/src/minibot_msgs/CMakeLists.txt", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(minibot_msgs)\n\nfind_package(catkin REQUIRED COMPONENTS\n roscpp\n rospy\n std_msgs\n message_generation\n)\n\nadd_service_files(FILES GetBattPerc.srv)\nadd_service_files(FILES StartRecording.srv)\nadd_service_files(FILES FinishRecording.srv)\nadd_service_files(FILES TransferFile.srv)\n\n## Generate added messages and services with any dependencies listed here\ngenerate_messages(\n DEPENDENCIES\n std_msgs\n)\n\ninclude_directories(\n# include\n ${catkin_INCLUDE_DIRS}\n)\n\n# add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n# add_executable(${PROJECT_NAME}_node src/minibot_msgs_node.cpp)\n# add_dependencies(${PROJECT_NAME}_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n\n# target_link_libraries(${PROJECT_NAME}_node\n# ${catkin_LIBRARIES}\n# )" }, { "alpha_fraction": 0.7023041248321533, "alphanum_fraction": 0.7170506715774536, "avg_line_length": 15.179104804992676, "blob_id": "1f05bfe9128f4656a39e75b04196c8b9d5f262fa", "content_id": "d7579eb5641eb06104cffad561582d2443d2bcc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1085, "license_type": "no_license", "max_line_length": 196, "num_lines": 67, "path": "/README.md", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "# Mobile Robot Simulation Biorobotics UNAM\n\n\n![GUI](https://raw.githubusercontent.com/dieg4231/MobileRobotSimulator/master/screenshot.png)\n\n## Getting Started\n\nThese instructions will get you a copy of the project up and running on your local machine.\n\n### Prerequisites\n\nThe things you need to install:\n\n- [ROS Melodic](http://wiki.ros.org/melodic/Installation/Ubuntu)\n- [Ubuntu 18.04](http://releases.ubuntu.com/18.04/)\n\n\n### Installing\n\n- Clone this repo\n```\ngit clone https://github.com/dieg4231/MobileRobotSimulator.git\n\n```\n\n\n- Go to catkin_ws folder\n\n```\ncd MobileRobotSimulator/catkin_ws\n\n```\n\n- run the script install.sh\n\n```\n./install.sh\n```\n\nand then\n\n```\ncatkin_make\n```\n\n\n### Run\n\n- The \"source\" command can be used to load any functions file into the current shell script or a command prompt, in this case the file catkin_ws/devel/setup.bash. Inside catkin_ws folder execute:\n```\nsource devel/setup.bash\n\n```\n\n\n- Launch simulator:\n\n```\n roslaunch simulator simulator.launch \n\n```\n\n- Or execute start.sh (this option open a xterminal for each node)\n\n```\n./start.sh\n```\n\n" }, { "alpha_fraction": 0.6256809234619141, "alphanum_fraction": 0.6295719742774963, "avg_line_length": 25.183673858642578, "blob_id": "9e1ad8e6007baa9c06fa8e1622e365928138fafb", "content_id": "7e2dc59bd0ddbe2bd48a4ed64bbafb60887759ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1285, "license_type": "no_license", "max_line_length": 93, "num_lines": 49, "path": "/catkin_ws/src/simulator/src/visualization/real_arena_viz.cpp", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <image_transport/image_transport.h>\n#include <opencv2/highgui/highgui.hpp>\n#include <cv_bridge/cv_bridge.h>\n\nbool show_image;\nbool dispayed = false;\nbool last_status = false;\n\nvoid imageCallback(const sensor_msgs::CompressedImageConstPtr& msg)\n{\n ros::param::get(\"/show_image\", show_image);\n \n \n if(show_image) {\n try\n {\n //std::cout << \"Display image.->\" << dispayed << std::endl;\n cv::Mat image = cv::imdecode(cv::Mat(msg->data),1);\n\n if(cv::getWindowProperty(\"real_time_view\", cv::WND_PROP_AUTOSIZE) > 0) dispayed = true;\n else dispayed = false;\n\n if(!dispayed && last_status) ros::param::set(\"/show_image\", false);\n\n cv::imshow(\"real_time_view\", image);\n cv::waitKey(1);\n last_status = dispayed;\n }\n catch (cv_bridge::Exception& e)\n {\n ROS_ERROR(\"Could not convert to image!\");\n }\n }\n else {\n cv::destroyAllWindows();\n }\n}\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"real_arena_viz\");\n ros::NodeHandle nh;\n std::cout << \"Starting real_arena_viz by Luis Nava...\" << std::endl;\n nh.setParam(\"/show_image\", show_image);\n image_transport::ImageTransport it(nh);\n ros::Subscriber sub = nh.subscribe(\"/camera/image/compressed\", 1, imageCallback);\n ros::spin();\n} " }, { "alpha_fraction": 0.5655199289321899, "alphanum_fraction": 0.5811750888824463, "avg_line_length": 31.337499618530273, "blob_id": "ac36559b7a91bfb895cc1b347786d1be63d7bc3c", "content_id": "2ac91888acaeaaf1d46f22e35d973c8d5aa82134", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5174, "license_type": "no_license", "max_line_length": 180, "num_lines": 160, "path": "/catkin_ws/src/simulator/src/turtlebot/move_turtlebot_node.cpp", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <ros/ros.h>\n#include <tf/tf.h>\n#include <geometry_msgs/Twist.h>\n#include <geometry_msgs/Pose2D.h>\n#include <nav_msgs/Odometry.h>\n#include \"simulator/simulator_MoveRealRobot.h\"\n#include <math.h>\n\ngeometry_msgs::Pose2D current_pose;\nros::Publisher movement_pub;\nint once;\n\nvoid odomCallback(const nav_msgs::OdometryConstPtr& msg)\n{\n // linear position\n current_pose.x = msg->pose.pose.position.x;\n current_pose.y = msg->pose.pose.position.y;\n \n // quaternion to RPY conversion\n tf::Quaternion q(\n msg->pose.pose.orientation.x,\n msg->pose.pose.orientation.y,\n msg->pose.pose.orientation.z,\n msg->pose.pose.orientation.w);\n tf::Matrix3x3 m(q);\n double roll, pitch, yaw;\n m.getRPY(roll, pitch, yaw);\n current_pose.theta = yaw;\n //printf(\"YAW: %f ,X %f ,Y %f \\n\", yaw,current_pose.x,current_pose.y) ; \n // angular position\n once =1;\n}\n\n\nbool move_turtle(simulator::simulator_MoveRealRobot::Request &req, simulator::simulator_MoveRealRobot::Response &res)\n{\n double dist = req.distance;\n double angle = req.theta;//M_PI;//1.5707;\n double x,y,x_goal,y_goal,angle_goal;\n double q = M_PI/2;\n double quadrant;\n geometry_msgs::Twist move;\n\n ros::Rate rate(100);\n\n ROS_INFO(\"--NEW GOAL--\");\n ROS_INFO(\" Angular Move:\");\n ros::Time start = ros::Time::now();\n while(!once)\n {\n ros::spinOnce();\n rate.sleep();\n };\n\n angle_goal = current_pose.theta + angle;\n angle_goal = fmod( angle_goal , M_PI*2 );\n\n if( angle_goal > M_PI )\n {\n angle_goal = -(M_PI - ( angle_goal - M_PI ) );\n }\n else if (angle_goal < -M_PI)\n {\n angle_goal = (M_PI + ( angle_goal + M_PI ) );\n }\n\n printf(\" Theta Goal: %f Theta Current: %f Error: %f \\n\",angle_goal,current_pose.theta, fabs(fabs(angle_goal) - fabs(current_pose.theta) ) );\n\n while(ros::ok() && ( fabs( fabs(angle_goal) - fabs(current_pose.theta) ) > .1 ) )\n {\n //geometry_msgs::Twist move;\n move.linear.x = 0.0; //speed value m/s\n\n if( angle > 0 )\n move.angular.z = 1;\n else\n move.angular.z = -1;\n\n movement_pub.publish(move);\n ros::spinOnce();\n rate.sleep();\n }\n printf(\" Theta Goal: %f Theta Current: %f Error: %f \\n\",angle_goal,current_pose.theta, fabs(fabs(angle_goal) - fabs(current_pose.theta) ) );\n\n \n move.angular.z = 0;\n movement_pub.publish(move);\n\n \n ros::spinOnce();\n rate.sleep();\n\n ROS_INFO(\" Move Linear:\");\n x = dist*cos(current_pose.theta);\n y = dist*sin(current_pose.theta);\n //printf(\"-----x %f y %f \\n\",x,y );\n x_goal = current_pose.x + x ;\n y_goal = current_pose.y + y ; \n\n\n double err1 = sqrt(pow(x_goal - current_pose.x,2 )+pow(y_goal - current_pose.y,2 )) ;\n double err2 = err1;\n double err2_aux =1000;\n\n while(ros::ok() && err2 > .01 && err2 <= err2_aux+.002 ) // ( fabs( fabs(x_goal) - fabs(current_pose.x) ) > .01 || fabs( fabs( y_goal) - fabs(current_pose.y)) > .01 ) ) \n {\n printf(\" XGoal: %f XCurrent: %f Err: %f \\n\",x_goal, current_pose.x,sqrt(pow(x_goal - current_pose.x,2 )+pow(y_goal - current_pose.y,2 )));\n\n printf(\" YGoal: %f YCurrent: %f Err: %f \\n\",y_goal, current_pose.y,sqrt(pow(x_goal - current_pose.x,2 )+pow(y_goal - current_pose.y,2 )));\n\n //geometry_msgs::Twist move;\n //velocity controls\n if( dist>0 )\n move.linear.x = 0.2; //speed value m/s\n else\n move.linear.x = -0.2; //speed value m/s\n move.angular.z = 0;\n movement_pub.publish(move);\n\n \n ros::spinOnce();\n rate.sleep();\n\n err2_aux = err2;\n err2= sqrt(pow(x_goal - current_pose.x,2 )+pow(y_goal - current_pose.y,2 ));\n }\n printf(\" XGoal: %f XCurrent: %f Err: %f \\n\",x_goal, current_pose.x,sqrt(pow(x_goal - current_pose.x,2 )+pow(y_goal - current_pose.y,2 )));\n printf(\" YGoal: %f YCurrent: %f Err: %f \\n\",y_goal, current_pose.y,sqrt(pow(x_goal - current_pose.x,2 )+pow(y_goal - current_pose.y,2 )));\n\n printf(\"%f > .01 && %f <= %f\\n\", err2 ,err2,err2_aux );\n printf(\"ERR1: %f ERR2: %f \\n\",err1, sqrt(pow(x_goal - current_pose.x,2 )+pow(y_goal - current_pose.y,2 )) );\n\n //geometry_msgs::Twist move;\n move.linear.x = 0;\n move.angular.z = 0;\n movement_pub.publish(move);\n \n res.done =1;\n ros::spinOnce();\n rate.sleep();\n \n}\n\n\nint main(int argc, char **argv)\n{\n once=0;\n ros::init(argc, argv, \"move_turtle_node\");\n ros::NodeHandle n;\n ros::Subscriber sub_odometry = n.subscribe(\"odom\", 1, odomCallback);\n //movement_pub = n.advertise<geometry_msgs::Twist>(\"/cmd_vel_mux/input/navi\",1); //for sensors the value after , should be higher to get a more accurate result (queued)\n movement_pub = n.advertise<geometry_msgs::Twist>(\"/cmd_vel\",1); //for sensors the value after , should be higher to get a more accurate result (queued)\n \n\n ros::ServiceServer service = n.advertiseService(\"simulator_move_RealRobot\", move_turtle);\n ROS_INFO(\"start move_turtle_node \");\n ros::spin();\n return 0;\n}\n" }, { "alpha_fraction": 0.4570677578449249, "alphanum_fraction": 0.46991822123527527, "avg_line_length": 25.534883499145508, "blob_id": "a8412c8c9191dd4c23fcca3ebc4412235b5c8abf", "content_id": "00bafeea9444977acb48411ded70aa516db64839", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3424, "license_type": "no_license", "max_line_length": 171, "num_lines": 129, "path": "/catkin_ws/src/simulator/src/state_machines/dfs.h", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "/***********************************************\n* *\n* dfs.h\t\t\t *\n* *\n* Diego Cordero *\n* *\n* Bio-Robotics Laboratory *\n* UNAM, 2019 *\n* *\n* *\n************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ros/package.h>\n\nint stack[500];\nint sp = 0;\nvoid push(int v){ stack[sp++] = v;}\n\nvoid pop(){sp--;}\n\nvoid print_stack(){\n\tprintf(\"\\nstack: \");\n for(int i=0; i < sp; i++)\n \tprintf(\" %d \",stack[i]);\n printf(\"\\n\");\n}\n\nvoid dfs_algorithm(int D ,int L)\n{\n\t sp=0;\n\tint menor,flagOnce;\n\tint contador=0;\n\tint node_actual = D;\n\tint flagPush;\n\n\twhile(node_actual != L)\n\t{\t\n\t\tprint_stack();\n\t\tflagPush = 1;\n\t\t//printf(\"aa %d \\n\",nodes[node_actual].num_conections );\n\t\tfor( int j = 0; j < nodes[node_actual].num_conections; j++)\n \t\t{\n \t\t\t//printf(\"** %c** \\n\",nodes[nodes[node_actual].conections[j].node].flag );\n \t\t\tif(nodes[nodes[node_actual].conections[j].node].flag == 'N')\n \t\t\t{\n \t\t\t\t//printf(\"Node actual %d \\n\",node_actual);\n \t\t\t\tnodes[nodes[node_actual].conections[j].node].flag = 'Y';\n \t\t\t\tpush(node_actual);\n \t\t\t\tnodes[node_actual].flag='Y';\n \t\t\t\tnode_actual = nodes[nodes[node_actual].conections[j].node].num_node;\n \t\t\t\t//printf(\"Node actual %d \\n\",node_actual);\n \t\t\t\tflagPush = 0;\n \t\t\t\tbreak;\t\n \t\t\t}\n \t\t}\n \t\t\n \t\tif( flagPush == 1 )\n \t\t{\t\n \t\t\tpop();\n \t\t\tnode_actual = sp - 1;\n\t\t}\n\t}\n\tpush(node_actual);\n}\n\n\n\n\nint dfs(float rx ,float ry ,float lx ,float ly, char *world_name,step *steps )\n{\n //char archivo[]=\"../data/obstacles/obstacles.top\";\n char archivo[150];\n int i;\n int start = 0;\n int goal = 0;\n //\"../data/obstacles/obstacles.top\";\n std::string paths = ros::package::getPath(\"simulator\");\n strcpy(archivo,paths.c_str());\n strcat(archivo,\"/src/data/\");\n strcat(archivo,world_name);\n strcat(archivo,\"/\");\n strcat(archivo,world_name);\n strcat(archivo,\".top\");\n\n\n for(int i=0; i<200; i++)\n {\n \t\tnodes[i].flag='N';\n \t\tnodes[i].num_conections = 0;\n \t\tnodes[i].parent = -1;\n \t\tnodes[i].acumulado = 0;\n }\n num_nodes=read_nodes(archivo);\n //printf(\"NUmero de nodos #: %d \\n\",num_nodes);\n for(i = 1; i < num_nodes; i++)\n {\n \t\tif ( sqrt(pow( nodes[i].x - rx ,2) + pow( nodes[i].y - ry ,2)) < sqrt( pow( nodes[start].x - rx ,2) + pow( nodes[start].y - ry ,2)) )\n \t\t{\t//\tprintf(\"r-n : %d Distancia %f Node x %f node y %f rx %f ry%f \\n\",i,sqrt(pow( nodes[i].x - rx ,2) + pow( nodes[i].y - ry ,2)),nodes[i].x,nodes[i].y,rx,ry );\n \t\t\tstart = i;\n \t\t}\n \t\tif (sqrt(pow( nodes[i].x - lx ,2) + pow( nodes[i].y - ly ,2)) < sqrt(pow( nodes[goal].x - lx ,2) + pow( nodes[goal].y - ly ,2) ) )\n \t\t\tgoal = i;\n }\n //for(int i=0; i<num_nodes; i++)\n //\tprintNode(i);\n \n //printf(\"%d %d \\n\",atoi(argv[1]),atoi(argv[2]) );\n\n dfs_algorithm(start,goal);\n\n //printf(\"Final Stack\\n\");\n //print_stack();\n\n\n for(int i=0; i < sp; i++)\n {\n \t//printf(\" %d \",stack[i]);\n \tsteps[i].node = nodes[stack[i]].num_node;\n\t \tsteps[i].x = nodes[stack[i]].x;\n\t \tsteps[i].y = nodes[stack[i]].y;\n }\n //printf(\"\\n\");\n\n\n\treturn 0;\n} \n" }, { "alpha_fraction": 0.707317054271698, "alphanum_fraction": 0.7103658318519592, "avg_line_length": 14.209301948547363, "blob_id": "aac3f86cc1f3cf09f22753b25040e7d8d20ca5c9", "content_id": "7d0bead4faf32fb7ae793664be7824c1bc6937c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 656, "license_type": "no_license", "max_line_length": 29, "num_lines": 43, "path": "/catkin_ws/src/simulator/src/utilities/simulator_structures.h", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "typedef struct parameters_\n{\n\tfloat robot_x;\n\tfloat robot_y;\n\tfloat robot_theta;\n\tfloat robot_radio;\n\tfloat robot_max_advance;\n\tfloat robot_turn_angle;\n\tint laser_num_sensors;\n\tfloat laser_origin;\n\tfloat laser_range;\n\tfloat laser_value;\n\tchar world_name[20];\n\tbool noise;\n\tbool run;\n\tfloat light_x;\n\tfloat light_y;\n\tint behavior;\n\tint steps;\n\tbool useRealRobot;\n\tbool useLidar;\n\tbool useSArray;\n} parameters;\n\ntypedef struct next_position_\n{\n\tfloat robot_x;\n\tfloat robot_y;\n\tfloat robot_theta;\n} next_position;\n\ntypedef struct movement_\n{\n\tfloat twist;\n\tfloat advance;\n} movement;\n\ntypedef struct step_\n{\n\tint node;\n\tfloat x;\n\tfloat y;\t\n} step;\n\n\n" }, { "alpha_fraction": 0.7489539980888367, "alphanum_fraction": 0.7531380653381348, "avg_line_length": 38.33333206176758, "blob_id": "ed22df8847b2d1ef41f125de89112a562706d829", "content_id": "28d025b552762a115e5ca08b6bd70d8b8778d084", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 239, "license_type": "no_license", "max_line_length": 54, "num_lines": 6, "path": "/catkin_ws/install.sh", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#!/bin/bash\nsudo apt-get install ros-melodic-turtlebot-*\nsudo apt-get install ros-melodic-teleop-twist-keyboard\nsudo apt-get install libcgal-qt5-dev libcgal-dev \nsudo apt-get install ros-melodic-joy\nfind . -name \"*.py\" | xargs chmod +x\n\n\n\n" }, { "alpha_fraction": 0.395225465297699, "alphanum_fraction": 0.40541672706604004, "avg_line_length": 36.113990783691406, "blob_id": "fae78a7afe58e05bbcbf59ff44391e92305228ab", "content_id": "fd761734a7796fdcfd7b451419e25c56729c282e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7163, "license_type": "no_license", "max_line_length": 108, "num_lines": 193, "path": "/catkin_ws/src/simulator/src/state_machines/sm_avoidance_destination.h", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "/********************************************************\n * *\n * *\n * state_machine_avoidance_destination.h \t*\n * *\n *\t\tJesus Savage\t\t\t\t*\n *\t\tDiego Cordero *\n * Edit by Miguel Sanchez\t\t *\n *\t\tFI-UNAM\t\t\t\t\t*\n *\t\t17-2-2019 *\n * *\n ********************************************************/\n\n\n\n#define THRESHOLD 36\n#define LIDAR_THRESHOLD 0.16// State Machine \nint sm_avoidance_destination( float *observations\n ,int size\n ,float intensity\n , int dest\n ,int obs \n ,movement *movements \n ,int *next_state \n ,float Mag_Advance \n ,float max_twist)\n{\n//Comment for simulation\nobs=quantize_laser(observations,size,LIDAR_THRESHOLD);\n\n \n\n int state = *next_state;\n int result=0;\n\n\n printf(\"Present State: %d \\n\", state);\n printf(\"intensity %f obstacles %d dest %d\\n\",intensity,obs,dest);\nfor (int i = 0; i < size ; i++ ) \n printf(\"laser observations[%d] %f\\n\",i,observations[i]);\n switch ( state ) {\n\n case 0:\n\n\t\tif (intensity > THRESHOLD){\n *movements=generate_output(STOP,Mag_Advance,max_twist);\n //printf(\"Present State: %d STOP\\n\", state);\n printf(\"\\n **************** Reached light source ******************************\\n\");\n *next_state = 0;\n\t\t\tresult = 1;\n }\n else{\n *movements=generate_output(FORWARD,Mag_Advance,max_twist);\n //printf(\"Present State: %d forward\\n\", state);\n *next_state = 1;\n }\n\n break;\n\n\n case 1:\n if (obs == 0){\n\t\t\t// there is not obstacle\n *movements=generate_output(FORWARD,Mag_Advance,max_twist);\n //printf(\"Present State: %d FORWARD\\n\", state);\n *next_state = 13;\n }\n else{\n *movements=generate_output(STOP,Mag_Advance,max_twist);\n //printf(\"Present State: %d STOP\\n\", state);\n\n if (obs == 1){\n // obtacle on the right\n *next_state = 4;\n }\n else if (obs == 2){\n // obtacle on the left\n *next_state = 2;\n }\n else if (obs == 3){\n\t\t\t\t// obstacle on the front\n *next_state = 6;\n }\n }\n\n break;\n\n case 2: // Backward, obstacle in the left\n *movements=generate_output(BACKWARD,Mag_Advance,max_twist);\n\t\t//printf(\"Present State: %d BACKWARD, obstacle LEFT\\n\", state);\n *next_state = 3;\n break;\n\n case 3: // right turn\n *movements=generate_output(RIGHT,Mag_Advance,max_twist);\n\t\t//printf(\"Present State: %d TURN RIGHT\\n\", state);\n *next_state = 0;\n break;\n\n case 4: // Backward, obstacle in the right\n *movements=generate_output(BACKWARD,Mag_Advance,max_twist);\n\t\t//printf(\"Present State: %d BACKWARD, obstacle RIGHT\\n\", state);\n *next_state = 5;\n break;\n\n case 5: // left turn\n *movements=generate_output(LEFT,Mag_Advance,max_twist);\n\t\t//printf(\"Present State: %d TURN LEFT\\n\", state);\n *next_state = 0;\n break;\n\n case 6: // Backward, obstacle in front\n *movements=generate_output(BACKWARD,Mag_Advance,max_twist);\n\t\t//printf(\"Present State: %d BACKWARD, obstacle FRONT\\n\", state);\n *next_state = 7;\n break;\n\n\tcase 7: /// Left turn\n *movements=generate_output(LEFT,Mag_Advance,max_twist);\n\t\t//printf(\"Present State: %d TURN 1 LEFT\\n\", state);\n *next_state = 8;\n break;\n\n case 8:// Left turn\n *movements=generate_output(LEFT,Mag_Advance,max_twist);\n\t\t//printf(\"Present State: %d TURN 2 LEFT\\n\", state);\n *next_state = 9;\n break;\n\n case 9: // Forward\n *movements=generate_output(FORWARD,Mag_Advance,max_twist);\n //printf(\"Present State: %d 1 FORWARD\\n\", state);\n *next_state = 10;\n break;\n\n case 10: // Forward\n *movements=generate_output(FORWARD,Mag_Advance,max_twist);\n //printf(\"Present State: %d 2 FORWARD\\n\", state);\n *next_state = 11;\n break;\n\n\tcase 11: // Right turn\n *movements=generate_output(RIGHT,Mag_Advance,max_twist);\n //printf(\"Present State: %d turn 1 RIGHT\\n\", state);\n *next_state = 12;\n break;\n\n case 12: // Right turn\n *movements=generate_output(RIGHT,Mag_Advance,max_twist);\n //printf(\"Present State: %d turn 2 RIGHT\\n\", state);\n *next_state = 0;\n break;\n\n case 13: // // check destination\n\t\tif (dest == 0){\n // go right\n *movements=generate_output(RIGHT,Mag_Advance,max_twist);\n //printf(\"Present State: %d RIGHT \\n\", state);\n *next_state = 3;\n }\n else if (dest == 1){\n // go left\n *movements=generate_output(LEFT,Mag_Advance,max_twist);\n //printf(\"Present State: %d LEFT\\n\", state);\n *next_state = 5;\n }\n else if (dest == 2){\n // go forward \n *movements=generate_output(FORWARD,Mag_Advance,max_twist);\n //printf(\"Present State: %d FORWARD\\n\", state);\n *next_state = 3;\n }\n else if (dest == 3){\n // go forward \n *movements=generate_output(FORWARD,Mag_Advance,max_twist);\n //printf(\"Present State: %d FORWARD\\n\", state);\n *next_state = 5;\n }\n break;\n\n\tdefault:\n\t\t//printf(\"State %d not defined used \", state);\n *movements=generate_output(STOP,Mag_Advance,max_twist);\n *next_state = 0;\n break;\n\n \n }\n\n printf(\"Next State: %d \\n\", *next_state);\n return result;\n\n}\n" }, { "alpha_fraction": 0.6370534300804138, "alphanum_fraction": 0.6595004796981812, "avg_line_length": 21.571428298950195, "blob_id": "b48754058a8e0eff41990ef560859103027806b5", "content_id": "4c186fd3084b56906d2583de8a253bd18d5f80cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3163, "license_type": "no_license", "max_line_length": 105, "num_lines": 140, "path": "/catkin_ws/src/simulator/src/visualization/objs_viz_node.cpp", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "// ROS\n#include <geometry_msgs/Point.h>\n#include <ros/package.h>\n#include \"simulator/Parameters.h\"\n#include \"simulator/simulator_parameters.h\"\n#include \"simulator/PosesArray.h\"\n#include \"simulator/poseCustom.h\"\n#include \"../utilities/simulator_structures.h\"\n#include <ros/ros.h>\n\n// For visualizing things in rviz\n#include <functional>\n\n//#include <rviz_visual_tools/rviz_visual_tools.h>\n#include <visualization_msgs/Marker.h>\n#include <visualization_msgs/MarkerArray.h>\n// C++\n#include <string>\n#include <vector>\n\n\nvisualization_msgs::Marker marker;\nvisualization_msgs::MarkerArray titulos;\ngeometry_msgs::Point point;\n\n\n\nvoid paramsCallback(const simulator::PosesArray::ConstPtr& objs)\n{\n titulos.markers.clear();\n marker.points.clear();\n visualization_msgs::Marker aux;\n for(int i = 0 ; i < objs->posesArray.size(); i++)\n {\n point.x = objs->posesArray[i].x ;\n point.y = objs->posesArray[i].y;\n point.z = .05;\n marker.points.push_back(point);\n\n \n\n\n \n \n visualization_msgs::Marker aux;\n aux.header.frame_id = \"map\";\n aux.header.stamp = ros::Time();\n aux.ns = \"my_namespace\";\n aux.id = i+100;\n aux.type = visualization_msgs::Marker::TEXT_VIEW_FACING;\n aux.action = visualization_msgs::Marker::ADD;\n aux.lifetime = ros::Duration(.1);\n aux.pose.position.x = objs->posesArray[i].x ;\n aux.pose.position.y = objs->posesArray[i].y;\n aux.pose.position.z = 0.10;\n aux.pose.orientation.x = 0.0;\n aux.pose.orientation.y = 0.0;\n aux.pose.orientation.z = 0.0;\n aux.pose.orientation.w = 1.0;\n aux.scale.x = .05;\n aux.scale.y = .05;\n aux.scale.z = .03;\n aux.color.a = 1.0; // Don't forget to set the alpha!\n aux.color.r = 0.0;\n aux.color.g = 0.0;\n aux.color.b = 0.0;\n aux.text= objs->posesArray[i].name;\n\n titulos.markers.push_back(aux);\n }\n\n\n}\n\n\nint main(int argc, char** argv)\n{\n ros::init(argc, argv, \"object_viz_node\");\n ros::NodeHandle n;\n ros::Subscriber params_sub = n.subscribe(\"objectsPose\", 0, paramsCallback);\n\n\n ros::Publisher vis_pub = n.advertise<visualization_msgs::Marker>( \"obj_marker\", 0 );\n ros::Publisher vis_pub_titles = n.advertise<visualization_msgs::MarkerArray>( \"obj_marker_titles\", 0 );\n\n\n\n\n\n\n marker.header.frame_id = \"map\";\n marker.header.stamp = ros::Time();\n marker.ns = \"my_namespace\";\n marker.id = 2;\n marker.type = visualization_msgs::Marker::CUBE_LIST;\n marker.action = visualization_msgs::Marker::ADD;\n marker.lifetime = ros::Duration(.1);\n marker.pose.position.x = 0;\n marker.pose.position.y = 0;\n marker.pose.position.z = 0;\n marker.pose.orientation.x = 0.0;\n marker.pose.orientation.y = 0.0;\n marker.pose.orientation.z = 0.0;\n marker.pose.orientation.w = 1.0;\n marker.scale.x = .05;\n marker.scale.y = .05;\n marker.scale.z = .05;\n marker.color.a = 1.0; // Don't forget to set the alpha!\n marker.color.r = 0.1;\n marker.color.g = 0.5;\n marker.color.b = 1.0;\n\n std_msgs::ColorRGBA color;\n\n color.r = 0;\n color.g = 0;\n color.b = 50;\n color.a = 1;\n\n\n\n\n ros::Rate r(10.0);\n\n while(n.ok())\n {\n\n \n vis_pub.publish( marker );\n vis_pub_titles.publish(titulos);\n\n ros::spinOnce(); \n r.sleep();\n\n }\n\n ROS_INFO_STREAM(\"Shutting down.\");\n\n return 0;\n}\n\n\n\n" }, { "alpha_fraction": 0.6727828979492188, "alphanum_fraction": 0.7339449524879456, "avg_line_length": 24.076923370361328, "blob_id": "92a28051cc95645df13445eee8b0f7ae8e4b4177", "content_id": "fd2a08ac79975b87a8773ade8193bc1d3d05bab5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 327, "license_type": "no_license", "max_line_length": 63, "num_lines": 13, "path": "/message.py", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "import time\nimport tkinter as tk\nfrom tkinter import filedialog\n\ntime.sleep(0.1)\nwindow = tk.Tk(className='Robot scan')\nwindow.geometry(\"200x100\")\nlabel = tk.Label(text = \"Please wait...\", font='Arial 17 bold')\nlabel.place(relx=0.5, rely=0.5)\nlabel.pack(pady=30)\n\nwindow.after(2600, lambda:window.destroy())\nwindow.mainloop()\n\n" }, { "alpha_fraction": 0.5025977492332458, "alphanum_fraction": 0.5108011960983276, "avg_line_length": 27.5625, "blob_id": "10bd599fa86d05eaa1fc7a3ae6a26c210efb1541", "content_id": "9a9b5d8d9a472211213f6ddb7e6d57cc95b38eb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3657, "license_type": "no_license", "max_line_length": 138, "num_lines": 128, "path": "/catkin_ws/src/simulator/src/state_machines/dijkstra.h", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ros/package.h>\n#include \"dijkstralib.h\"\n\n\n\nvoid dijkstra_algorithm(int D ,int L)\n{\n /*\n D = Nodo Inicial\n L = Nodo Final\n Y = Totalmente expandido\n N = Nuevo (Nodo sin padre ni acumulado)\n P = Nodo que no es ni Y ni N (Parcialmente expandido)\n\n Video explicativo https://www.youtube.com/watch?v=LLx0QVMZVkk\n */\n\n int menor,flagOnce;\n int contador = 0;\n int j;\n\n nodes[D].acumulado = 0;\n\n while( nodes[L].flag != 'Y')\n { \n for(j = 0 ; j < nodes[D].num_conections; j++)\n {\n if( nodes[ nodes[D].conections[j].node].flag == 'N')\n {\n nodes[nodes[D].conections[j].node].acumulado = nodes[D].acumulado + nodes[D].conections[j].cost;\n nodes[nodes[D].conections[j].node].parent = D;\n nodes[nodes[D].conections[j].node].flag = 'P';\n } \n else if( nodes[nodes[D].conections[j].node].flag == 'P' )\n {\n if( nodes[nodes[D].conections[j].node].acumulado > nodes[D].acumulado + nodes[D].conections[j].cost)\n {\n nodes[nodes[D].conections[j].node].acumulado = nodes[D].acumulado + nodes[D].conections[j].cost;\n nodes[nodes[D].conections[j].node].parent = D;\n }\n }\n }\n\n nodes[D].flag = 'Y';\n menor = 0;\n flagOnce = 1;\n for(int j = 0; j < num_nodes ; j++)\n {\n if(nodes[j].flag == 'P')\n {\n if(flagOnce)\n {\n menor = j;\n flagOnce = 0;\n }\n else if( nodes[menor].acumulado > nodes[j].acumulado )\n {\n menor = j;\n }\n } \n }\n D = menor;\n }\n}\n\nvoid printNode(int i) // use it for debug\n{\n printf(\"\\n\\n\");\n printf(\"# %d x %f y %f\\n\",nodes[i].num_node,nodes[i].x,nodes[i].y );\n printf(\"flag: %c parent: %d acumulado: %f \\n\",nodes[i].flag,nodes[i].parent,nodes[i].acumulado );\n printf(\"num_conections %d \\n\",nodes[i].num_conections);\n for(int j=0 ; j < nodes[i].num_conections; j++ )\n printf( \"%d %f \\n\",nodes[i].conections[j].node,nodes[i].conections[j].cost );\n}\n\nint dijkstra(float rx ,float ry ,float lx ,float ly, char *world_name,step *steps )\n{\n char archivo[150];\n int i;\n int start = 0;\n int goal = 0;\n int padre;\n std::string paths = ros::package::getPath(\"simulator\");\n strcpy(archivo,paths.c_str());\n strcat(archivo,\"/src/data/\");\n strcat(archivo,world_name);\n strcat(archivo,\"/\");\n strcat(archivo,world_name);\n strcat(archivo,\".top\");\n\n for(i = 0; i < MUM_NODES; i++)\n {\n nodes[i].flag='N';\n nodes[i].num_conections = 0;\n nodes[i].parent = -1;\n nodes[i].acumulado = 0;\n }\n \n num_nodes=read_nodes(archivo); // Se lee el arcivo .top\n\n\n for(i = 1; i < num_nodes; i++)\n {\n \t\tif( sqrt(pow( nodes[i].x - rx ,2) + pow( nodes[i].y - ry ,2)) < sqrt( pow( nodes[start].x - rx ,2) + pow( nodes[start].y - ry ,2)) )\t\n \t\t\tstart = i;\n \t\t\n \t\tif( sqrt(pow( nodes[i].x - lx ,2) + pow( nodes[i].y - ly ,2)) < sqrt(pow( nodes[goal].x - lx ,2) + pow( nodes[goal].y - ly ,2) ) )\n \t\t\tgoal = i;\n }\n\n dijkstra_algorithm (goal ,start); // Se pasan al reves para no tener que voltear la lista resultante.\n \n padre = start;\n i = 0;\n\n while( padre != -1)\n {\n \t steps[i].node = nodes[padre].num_node;\n \t steps[i].x = nodes[padre].x;\n \t steps[i].y = nodes[padre].y;\n i++;\n \t padre = nodes[padre].parent;\n }\n\treturn 0;\n} \n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 17.66666603088379, "blob_id": "23583abb4a22dde9d8f79113216fffb056649035", "content_id": "6f7ffb4ba3aa54d39816ed2f29db1ad7cedfda4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 55, "license_type": "no_license", "max_line_length": 42, "num_lines": 3, "path": "/catkin_ws/src/simulator/src/turtlebot/start_rviz_turtlebot.sh", "repo_name": "dieg4231/MobileRobotSimulator", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n roslaunch simulator rviz_turtlebot.launch" } ]
50
Antiochian/raycaster
https://github.com/Antiochian/raycaster
eb675144bc10d292c7c7c608ef02f6b6636c22ef
0f48b31db97a2d95b2e16234cf7a40e5660a1b48
0a60ca943df849c7f40290a2b3090b89b52a9a14
refs/heads/master
2020-08-27T12:43:59.365604
2020-01-14T20:18:13
2020-01-14T20:18:13
217,373,114
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49905064702033997, "alphanum_fraction": 0.5269233584403992, "avg_line_length": 32.50381851196289, "blob_id": "409aa95ee3b019a2d00f4d895af63a0a21dd0225", "content_id": "834ff679fc5ae5125c8cb231b9e468ae0a97be02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13167, "license_type": "no_license", "max_line_length": 119, "num_lines": 393, "path": "/raycaster.py", "repo_name": "Antiochian/raycaster", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 22 17:54:16 2019\nDOOM-like RAYTRACER\n@author: Antiochian\n-------\nCONTROLS:\nEsc to quit\nWSAD for movement\nuse the mouse to look around (or use Q and E to rotate view)\nPress leftclick or space to \"shoot\" and destroy walls\n\nYou can edit the map file in MSpaint, and white pixels will be treated as empty space\n-------\n-------\nSIGN CONVENTION:\n \n+---------> +x direction\n|\n|\n|\nv\n+y direction\n\ntheta is measured backwards kinda, so that a theta of +90deg points in the NEGATIVE y-direction\n\"\"\"\nimport pygame\nimport sys\nimport os\nfrom math import *\nimport numpy as np\nfrom matplotlib.image import imread\n\nblack = (0,0,0)\nwhite = (255,255,255)\nred = (255,0,0)\nblue = (0,0,255)\ngreen = (0,0,255)\ndebug = (255, 107, 223)\ngrey = (20,20,20)\nlightgrey = (191, 217, 198)\n\nfloorcolor = grey\nroofcolor = lightgrey\ndebugcolor = debug\nbackgroundcolor = black\n\ndef importgrid():\n grid_dict = {}\n grid = imread('map.jpg')\n grid = np.rint(grid)\n \n #detect alpha channel\n if grid.shape[2] == 4:\n for x in range( grid.shape[1]):\n for y in range(grid.shape[0]):\n if all( grid[y,x] == [255,255,255,255]):\n pass\n else:\n grid_dict[(x,y)] = grid[y,x]\n elif grid.shape[2] == 3:\n for y in range(grid.shape[0]):\n if all( grid[y,x] == [255,255,255]):\n pass\n else:\n grid_dict[(x,y)] = grid[y,x]\n return grid_dict,grid\n\ndef gridmaker(): \n #Import map file if possible\n if os.path.exists('map.jpg'):\n return importgrid()\n #make default map\n grid_dict = {}\n \n grid = np.array([[\"A\",\"A\",\"A\", \"A\",\"A\",\"A\", \"A\",\"A\",\"A\"]]) #\"spacr\" variable is just to keep matrix lined up.\n grid = np.append(grid,[[\"X\", 0 , 0 , 0 , 0 , 0 , 0 , 0, \"B\"]],axis = 0)\n grid = np.append(grid,[[\"X\", 0 , 0 , 0 , 0 , 0 , 0 , 0 ,\"B\"]],axis = 0)\n ########################--------------------------------------##########\n grid = np.append(grid,[[\"X\", 0 , 0 , 0 , 0 ,\"D\", 0 , 0, \"B\"]],axis = 0)\n grid = np.append(grid,[[\"X\", 0 , 0 , 0 , 0 ,\"D\", 0 , 0, \"B\"]],axis = 0)\n grid = np.append(grid,[[\"X\", 0 , 0 , 0 , 0 ,\"D\", 0 , 0, \"B\"]],axis = 0)\n ########################--------------------------------------##########\n grid = np.append(grid,[[\"X\", 0 , 0 , 0 , 0 , 0 , 0 , 0, \"B\"]],axis = 0)\n grid = np.append(grid,[[\"X\", 0 , 0 , 0 , 0 , 0 , 0 , 0, \"B\"]],axis = 0)\n grid = np.append(grid,[[\"Z\",\"Z\",\"Z\", \"Z\",\"Z\",\"Z\", \"Z\",\"Z\",\"Z\"]],axis = 0)\n #grid = np.flipud(grid)\n \n for x in range( grid.shape[1]):\n for y in range(grid.shape[0]):\n if grid[y,x] == \"A\":\n grid_dict[(x,y)] = white\n elif grid[y,x] == \"B\":\n grid_dict[(x,y)] = black\n elif grid[y,x] == \"X\":\n grid_dict[(x,y)] = red\n elif grid[y,x] == \"Z\":\n grid_dict[(x,y)] = blue\n elif grid[y,x] == \"D\":\n grid_dict[(x,y)] = debugcolor\n return grid_dict,grid\n\ndef checkwall(x,y,GRID=False):\n \"\"\"\n Inputs the xy coordinates (default) OR the GRID coordinates and returns True/False\n if there is/is not a wall present.\n \"\"\"\n if not GRID: #if GRID = false, convert to GRID coordinates\n x = x // gridsize\n y = y // gridsize\n if abs(x) > len(grid) or abs(y) > len(grid): #out of bounds catch\n return True\n if (x,y) in walldict.keys():\n return True\n else:\n return False\n\ndef lookup(angle): #returns true if looking up\n # NOTE: \"up\" means in positive y-direction, i.e. down on visual grid\n angle = angle % 360\n if 0 < angle < 180:\n return True\n else:\n return False\n\ndef lookright(angle):\n angle = angle % 360\n if (0 <= angle < 90) or ( 270 < angle <= 360):\n return True\n else:\n return False\n \ndef getintercepts( playerpos , angle ): \n (Px,Py) = playerpos\n angle = angle % 360\n \"\"\" input angle and position, returns Ax, Ay, Bx, By\n\"\"\"\n if lookup(angle) and lookright(angle):\n \"\"\"FIRST QUADRANT 0 <= angle < 90\n \"\"\"\n if angle == 0:\n angle += 1e-8 #this fuzz prevents divide-by-zero errors \n Ay = (Py // gridsize + 1 ) * gridsize #next horizontal line\n Ax = Px + (Ay - Py)/tan(radians(angle))\n \n dAy = gridsize\n dAx = dAy / tan(radians( angle))\n \n Bx = (Px // gridsize + 1 ) * gridsize\n By = Py + (Bx - Px)*tan(radians(angle)) \n \n dBx = gridsize\n dBy = dBx * tan(radians(angle)) \n elif lookup(angle) and (not lookright(angle)):\n \"\"\"OPTION B:\n ray is in 2nd quadrant: angle: 90 < angle < 180\n X | \"\"\"\n if angle == 180:\n angle -= 1e-8\n Ay = (Py // gridsize + 1 ) * gridsize #Ay > Py\n Ax = Px - (Ay - Py)/tan(radians(180 - angle)) #Ax < Px\n \n dAy = gridsize #positive\n dAx = - dAy / tan(radians(180 - angle)) #negative \n \n #VERTICAL INTERSECTS\n Bx = (Px // gridsize)*gridsize - 1 #prev vert line\n By = Py + abs((Bx - Px)*tan(radians(180 - angle))) #By > Py\n \n dBx = -gridsize #negative\n dBy = dBx * - tan(radians(180 - angle)) #positive ; minus sign is to keep Y increasing \n elif (not lookup(angle) ) and (not lookright(angle)):\n \"\"\" \n OPTION C:\n ray is in 3rd quadrant, angle: 180 < 270\n \"\"\"\n if angle == 180:\n angle += 1e8\n Ay = (Py // gridsize ) * gridsize - 1 #prev horizontal line\n Ax = Px + (Ay - Py)/tan(radians(angle - 180)) #note (Ay - Py) is negative\n \n dAy = -gridsize #negative\n dAx = dAy /tan(radians(angle - 180)) #negative \n \n #VERTICAL INTERSECTS\n Bx = (Px // gridsize)*gridsize - 1 #prev vert line\n By = Py + (Bx - Px)*tan(radians(angle - 180)) #minus sign is from tangent\n \n dBx = -gridsize #negative\n dBy = dBx*tan(radians(angle - 180)) #negative\n \n elif (not lookup(angle) ) and lookright(angle): \n \"\"\" \n OPTION D:\n ray is in 4th quadrant\n \"\"\" \n if angle == 360:\n angle -= 1e-8 #this fuzz prevents divide-by-zero errors \n Ay = (Py // gridsize) * gridsize - 1 #prev horizontal line\n Ax = Px + abs((Ay - Py)/tan(radians(360 - angle))) #this minus sign is from the tangent \n \n dAy = -gridsize\n dAx = dAy / -tan(radians(360 - angle)) #positive\n \n Bx = (Px // gridsize + 1 ) * gridsize #increasing\n By = Py - (Bx - Px)*tan(radians(360 - angle)) #decreasing\n \n dBx = gridsize\n dBy = dBx * -tan(radians(360 - angle))\n return Ax, Ay , dAx, dAy, Bx, By , dBx, dBy\n\ndef raycast(Px , Py , angle, projx):\n Ax, Ay , dAx, dAy, Bx, By , dBx, dBy = getintercepts( (Px,Py) , angle)\n nocollision = True\n while nocollision:\n distA = sqrt((Px-Ax)**2 + (Py-Ay)**2)\n distB = sqrt((Px-Bx)**2 + (Py-By)**2)\n if distA <= distB: #if A comes first\n if checkwall(Ax,Ay):\n return(Ax,Ay,distA)\n nocollision = False\n Ax += dAx\n Ay += dAy\n else:\n if checkwall(Bx,By):\n return(Bx,By,distB)\n nocollision = False\n Bx += dBx\n By += dBy\n \ndef drawwall(Wx,Wy,dist,projx):\n #takes raw coordinates as inputs\n Wx = Wx // gridsize\n Wy = Wy // gridsize\n \n if abs(Wx) > len(grid) or abs(Wy) > len(grid):\n newcolor = backgroundcolor #Out of bounds case\n height = 2\n else:\n m,K = 500,700\n shader = 1/(exp((dist - m) / K ) + 1) #falloff effect\n color = walldict[(Wx,Wy)]\n newcolor = (int(shader*color[0]),int(shader*color[1]),int(shader*color[2]))\n height = 60*projdistance / dist\n offset =( Ny - height )/2\n colRect = pygame.Rect(projx,offset, 1,height) #1pixel thick rectangle spanning whole screen\n pygame.draw.rect(PROJ, newcolor, colRect)\n return\n \n \ndef test(playerpos, angle):\n \"\"\"\n Test function used for debugging\n \"\"\"\n print(\"Test initiated. (Px,Py) = \",playerpos,\" ; angle = \",angle)\n angle = angle % 360\n (Px,Py) = playerpos\n Ax, Ay , dAx, dAy, Bx, By , dBx, dBy = getintercepts( (Px,Py) , angle) \n nocollision = True\n L = 0\n while nocollision:\n L += 1\n distA = sqrt((Px-Ax)**2 + (Py-Ay)**2)\n distB = sqrt((Px-Bx)**2 + (Py-By)**2)\n if distA <= distB: #if A comes first\n print(Ax//gridsize,Ay//gridsize)\n if checkwall(Ax,Ay):\n print(\"FINAL COLLISION.\")\n nocollision = False\n Ax += dAx\n Ay += dAy\n else:\n print(Bx//gridsize,By//gridsize)\n if checkwall(Bx,By):\n print(\"FINAL COLLISION.\")\n nocollision = False\n Bx += dBx\n By += dBy \n return\n\ndef applydrag(vel_x,vel_y,vel_z=None):\n speedsquared = vel_x**2 + vel_y**2 \n speed = sqrt(vel_x**2 + vel_y**2)\n if abs(vel_x) and abs(vel_y) > max_speed:\n return max_speed*np.sign(vel_x),max_speed*np.sign(vel_y),vel_z\n elif abs(vel_x) > max_speed:\n return max_speed*np.sign(vel_x),vel_y,vel_z\n elif abs(vel_y) > max_speed:\n return vel_x,max_speed*np.sign(vel_y),vel_z\n totaldrag = dragcoeff*speedsquared\n if speed == 0:\n return vel_x, vel_y, vel_z \n xdragaccel = -np.sign(vel_x)*abs(totaldrag * vel_x/speed) #split drag component-wise\n ydragaccel = -np.sign(vel_y)*abs(totaldrag * vel_y/ speed)\n vel_x += xdragaccel\n vel_y += ydragaccel\n if vel_z != None:\n zdragaccel = -9.81\n vel_z += zdragaccel\n return vel_x, vel_y,vel_z\n\ndef main():\n (Px,Py) = (193,193)\n viewangle = -15\n clock = pygame.time.Clock()\n vel_x = 0\n vel_y = 0\n vel_z = None\n while True: #MAIN GAME LOOP#\n clock.tick(FPS)\n window.blit(PROJ,(0,0))\n PROJ.fill(floorcolor) #fill screen with floor color\n pygame.draw.rect(PROJ, roofcolor, (0,int(Ny/2),Nx,int(Ny/2)) )\n pygame.display.update()\n projx = 0 #possible error here if screen index starts at 1 or 0\n \n for event in pygame.event.get(): #detect events\n if event.type == pygame.QUIT or pygame.key.get_pressed()[27]: #detect attempted exit\n pygame.quit()\n sys.exit()\n viewangle += looksensitivity*pygame.mouse.get_rel()[0]\n \n\n if pygame.key.get_pressed()[101]: #rotate with E\n viewangle += turnspeed\n if pygame.key.get_pressed()[113]: #rotate with Q\n viewangle -= turnspeed\n if pygame.key.get_pressed()[119]: # Go FORWARD\n vel_x += speed*cos(radians(viewangle))\n vel_y += speed*sin(radians(viewangle))\n if pygame.key.get_pressed()[115]: #Go BACKWARD\n vel_x -= speed*cos(radians(viewangle))\n vel_y -= speed*sin(radians(viewangle))\n if pygame.key.get_pressed()[100]: #Strafe RIGHT\n vel_x -= speed*sin(radians(viewangle))\n vel_y += speed*cos(radians(viewangle))\n if pygame.key.get_pressed()[97]: #Strafe LEFT\n vel_x += speed*sin(radians(viewangle))\n vel_y -= speed*cos(radians(viewangle))\n \n vel_x,vel_y,vel_z = applydrag(vel_x,vel_y,vel_z)\n #vel_x,vel_y = degradevelocity(vel_x,vel_y)\n nextPx = Px + vel_x\n nextPy = Py + vel_y\n if checkwall(nextPx,nextPy):\n vel_x = 0\n vel_y = 0\n else:\n Px = nextPx\n Py = nextPy\n \n if pygame.key.get_pressed()[32] or pygame.mouse.get_pressed()[0]: #SHOOT GUN\n PROJ.fill(white) #fill screen with floor color\n pygame.display.update()\n targetx,targety,disttarget = raycast(Px, Py ,viewangle, projx)\n tx = targetx // gridsize\n ty = targety // gridsize\n if (tx,ty) in walldict.keys():\n del walldict[(tx,ty)]\n \n angle = viewangle - FOV/2\n for projx in range(projwidth):\n Wx,Wy,distW = raycast(Px, Py ,angle, projx)\n drawwall(Wx,Wy, distW, projx)\n angle += columnangle \n\nclock = pygame.time.Clock()\nreboundcoeff = 0.05\nNx,Ny = 600,480\nFPS = 60\nspeed = 800/FPS\nplayermass = 70\nmax_speed = 2*speed\ndragcoeff = 0.01\nturnspeed = 8\nlooksensitivity = 180/Nx #this is calibrated so one screen = 1 half turn \ngridsize = 32\nFOV = 60 #degrees\nwalldict, grid = gridmaker() \n\n#derived parameters\nprojwidth,projheight = Nx,Ny\nprojdistance = (1/tan(radians(FOV/2))) * (projwidth/2) \ncolumnangle = FOV/projwidth #in degrees! # angle between rays/columns \n\n# set up surfaces\nwindow = pygame.display.set_mode( (Nx,Ny) )\npygame.display.set_caption(\"Raycaster v3.5 - Press Esc To Quit...\")\nPROJ = pygame.Surface( (Nx,Ny))\npygame.event.set_grab(True)\npygame.mouse.set_visible(False)\n\nmain()\n" }, { "alpha_fraction": 0.7313916087150574, "alphanum_fraction": 0.7394822239875793, "avg_line_length": 29.899999618530273, "blob_id": "ba613418c58e5a0b0ecbb3b37133d6dd8e9e2fda", "content_id": "92c52b517d674339d30a8bfd4a9cc2c356d6e746", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 618, "license_type": "no_license", "max_line_length": 152, "num_lines": 20, "path": "/README.md", "repo_name": "Antiochian/raycaster", "src_encoding": "UTF-8", "text": "# raycaster\n1990s-style 3D graphics engine supporting grid-based wall geometry and featuring mouselook FPS controls, collision detection and a primitive drag model.\n\nDraw an image in msPaint and the program will convert it to a map automatically! (white pixels are read as empty space)\n\nClick or press Space to \"shoot\" and destroy walls.\n\nTODO:\n- [ ] Add texture mapping\n- [x] Add collision detection\n- [ ] Add jumping, crouching, flying\n- [ ] Add viewbobbing\n\n-------------------\nSAMPLE:\nInput map:\n![input map](map_large.png)\n\n![Sample Scene](raycaster_demo_untextured.gif)\n![Shooting Gallery](shooting_gallery.gif)\n" } ]
2
input-output-hk/chain-wallet-libs
https://github.com/input-output-hk/chain-wallet-libs
1c868a65f244d597e1ca15ceccf8deccf1ab1790
a057240602474ee6c93d7ddc17258cab5910444e
ec96bbf13ddeca78b7289471e6e35c3289c35121
refs/heads/master
2023-07-25T04:01:04.178556
2022-07-06T09:51:35
2022-07-06T09:51:35
209,682,727
20
11
Apache-2.0
2019-09-20T01:51:31
2022-02-14T07:04:18
2023-01-20T23:12:36
Rust
[ { "alpha_fraction": 0.6769378781318665, "alphanum_fraction": 0.7019739747047424, "avg_line_length": 36.08928680419922, "blob_id": "722d80b31f3dbd2bdcbe0c831c0830fcab4ca548", "content_id": "8be6e4fe7b555e96625fa078ebde6754bcda0d21", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 2079, "license_type": "permissive", "max_line_length": 103, "num_lines": 56, "path": "/bindings/wallet-js/Cargo.toml", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "[package]\nauthors = [\"Enzo Cioppettini <[email protected]>\"]\ndescription = \"\"\"Wallet functionalities to interact with Jörmungandr\n\nThis package profiles all that is needed to have an healthy and secure\ninteraction with Jörmungandr blockchain technology.\n\"\"\"\nedition = \"2018\"\nlicense = \"MIT OR Apache-2.0\"\nname = \"wallet-js\"\nrepository = \"https://github.com/input-output-hk/chain-wallet-libs\"\nversion = \"0.7.0-pre4\"\n\n[lib]\ncrate-type = [\"cdylib\", \"rlib\"]\n\n[features]\ndefault = [\"console_error_panic_hook\"]\n\n[dependencies]\nchain-crypto = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-vote = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-impl-mockchain = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\ngetrandom = { version = \"0.2.2\", features = [\"js\"] }\nrand = \"0.8.3\"\nrand_chacha = \"0.3.0\"\nsymmetric-cipher = {path = \"../../symmetric-cipher\"}\nwallet-core = {path = \"../wallet-core\"}\nwasm-bindgen = \"0.2\"\njs-sys = \"0.3.40\"\nbech32 = \"0.7.2\"\n\n# The `console_error_panic_hook` crate provides better debugging of panics by\n# logging them with `console.error`. This is great for development, but requires\n# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for\n# code size when deploying.\nconsole_error_panic_hook = {version = \"0.1.1\", optional = true}\n\n# `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size\n# compared to the default allocator's ~10K. It is slower than the default\n# allocator, however.\n#\n# Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now.\nwee_alloc = {version = \"0.4.2\", optional = true}\n\n# clear_on_drop is a dependency of ed25519_dalek\n# The default can't be compiled to wasm, so it's necessary to enable either the 'nightly'\n# feature or this one.\nclear_on_drop = {version = \"0.2\", features = [\"no_cc\"]}\n\n[dev-dependencies]\nwasm-bindgen-test = \"0.3\"\n\n# See https://github.com/rustwasm/wasm-pack/issues/886\n[package.metadata.wasm-pack.profile.release]\nwasm-opt = [\"-O4\", \"--enable-mutable-globals\"]\n" }, { "alpha_fraction": 0.6431602239608765, "alphanum_fraction": 0.6748981475830078, "avg_line_length": 39.49484634399414, "blob_id": "07df4755338524331b7a94924af8bf9d9737e702", "content_id": "b855f24a23511d1bedb8adc8679241cc190eef83", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 11784, "license_type": "permissive", "max_line_length": 247, "num_lines": 291, "path": "/bindings/wallet-cordova/tests/src/main.js", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "import \"core-js/stable\";\nimport \"regenerator-runtime/runtime\";\n\nconst primitives = require('wallet-cordova-plugin.wallet');\n\nconst { hexStringToBytes, promisify, uint8ArrayEquals, uint32ArrayEquals } = require('./src/utils.js');\nconst keys = require('../../../test-vectors/free_keys/keys.json');\nconst genesis = require('../../../test-vectors/block0.json');\nconst BLOCK0_ID = genesis.id;\nconst ENCRYPTED_WALLET = keys.encrypted;\nconst PASSWORD = new Uint8Array(4);\nPASSWORD[0] = keys.password[0];\nPASSWORD[1] = keys.password[1];\nPASSWORD[2] = keys.password[2];\nPASSWORD[3] = keys.password[3];\nconst VOTE_ENCRYPTION_KEY = 'ristretto255_votepk1nc988wtjlrm5k0z43088p0rrvd5yhvc96k7zh99p6w74gupxggtqyx4792';\n\nconst DEFAULT_NONCES = [\n (2 ** 29) * 0,\n (2 ** 29) * 1,\n (2 ** 29) * 2,\n (2 ** 29) * 3,\n (2 ** 29) * 4,\n (2 ** 29) * 5,\n (2 ** 29) * 6,\n (2 ** 29) * 7,\n];\n\n// TODO: write settings getter for this\nconst BLOCK0_DATE = 1586637936;\nconst SLOT_DURATION = 10;\nconst SLOTS_PER_EPOCH = 100;\n\nlet promisifyP = f => promisify(primitives, f)\nconst importKeys = promisifyP(primitives.walletImportKeys);\nconst walletId = promisifyP(primitives.walletId);\nconst spendingCounters = promisifyP(primitives.walletSpendingCounters);\nconst totalFunds = promisifyP(primitives.walletTotalFunds);\nconst setState = promisifyP(primitives.walletSetState);\nconst deleteWallet = promisifyP(primitives.walletDelete);\nconst deleteSettings = promisifyP(primitives.settingsDelete);\nconst deleteProposal = promisifyP(primitives.proposalDelete);\nconst proposalNewPublic = promisifyP(primitives.proposalNewPublic);\nconst proposalNewPrivate = promisifyP(primitives.proposalNewPrivate);\nconst walletVote = promisifyP(primitives.walletVote);\nconst walletSetState = promisifyP(primitives.walletSetState);\nconst symmetricCipherDecrypt = promisifyP(primitives.symmetricCipherDecrypt);\nconst settingsGet = promisifyP(primitives.settingsGet);\nconst settingsNew = promisifyP(primitives.settingsNew);\nconst fragmentId = promisifyP(primitives.fragmentId);\nconst blockDateFromSystemTime = promisifyP(primitives.blockDateFromSystemTime);\nconst maxExpirationDate = promisifyP(primitives.maxExpirationDate);\n\nasync function walletFromFile() {\n const accountKey = hexStringToBytes(keys.account.private_key);\n return await importKeys(accountKey);\n}\n\nconst tests = [\n ['should recover wallet', async function () {\n const walletPtr = await walletFromFile();\n expect(walletPtr !== 0).toBe(true);\n const settingsPtr = await defaultSettings();\n\n expect(settingsPtr !== 0).toBe(true);\n const funds = await totalFunds(walletPtr);\n expect(parseInt(funds)).toBe(0);\n\n const accountId = await walletId(walletPtr);\n\n uint8ArrayEquals(new Uint8Array(accountId), hexStringToBytes(keys.account.account_id));\n\n await deleteSettings(settingsPtr);\n await deleteWallet(walletPtr);\n }],\n // there is nothing we can assert here, I think\n ['should be able to set state', async function () {\n const wallet = await walletFromFile();\n const value = 1000;\n await setState(wallet, value, DEFAULT_NONCES);\n }],\n ['can cast vote', async function () {\n const array = new Array(32);\n for (let index = 0; index < array.length; index++) {\n array[index] = index;\n }\n\n const votePlanId = new Uint8Array(array);\n const index = 0;\n const numChoices = 3;\n\n const proposalPtr = await proposalNewPublic(votePlanId, index, numChoices);\n const walletPtr = await walletFromFile();\n\n const settingsPtr = await defaultSettings();\n\n await walletSetState(walletPtr, 1000000, DEFAULT_NONCES);\n expect(uint32ArrayEquals(new Uint32Array(await spendingCounters(walletPtr)), new Uint32Array(DEFAULT_NONCES))).toBe(true);\n\n await walletVote(walletPtr, settingsPtr, proposalPtr, 0, await maxExpirationDate(settingsPtr, BLOCK0_DATE + 600), 0);\n\n const noncesAfterVote = new Uint32Array(await spendingCounters(walletPtr));\n\n const expectedNoncesAfter = DEFAULT_NONCES.slice();\n expectedNoncesAfter[0] = 1;\n\n expect(uint32ArrayEquals(new Uint32Array(noncesAfterVote), new Uint32Array(expectedNoncesAfter))).toBe(true);\n\n await deleteSettings(settingsPtr);\n await deleteWallet(walletPtr);\n await deleteProposal(proposalPtr);\n }],\n ['can cast private vote', async function () {\n const array = new Array(32);\n for (let index = 0; index < array.length; index++) {\n array[index] = index;\n }\n\n const votePlanId = new Uint8Array(array);\n const index = 0;\n const numChoices = 3;\n\n const proposalPtr = await proposalNewPrivate(votePlanId, index, numChoices, VOTE_ENCRYPTION_KEY);\n const walletPtr = await walletFromFile();\n const settingsPtr = await defaultSettings();\n await walletSetState(walletPtr, 1000000, DEFAULT_NONCES);\n await walletVote(walletPtr, settingsPtr, proposalPtr, 0, await maxExpirationDate(settingsPtr, BLOCK0_DATE + 600), 0);\n\n await deleteSettings(settingsPtr);\n await deleteWallet(walletPtr);\n await deleteProposal(proposalPtr);\n }],\n ['decrypts keys correctly', async function () {\n const decryptedKeys = await symmetricCipherDecrypt(PASSWORD, hexStringToBytes(ENCRYPTED_WALLET));\n const account = decryptedKeys.slice(0 * 64, 1 * 64);\n\n if (!uint8ArrayEquals(hexStringToBytes(keys.account.private_key), new Uint8Array(account))) {\n throw Error('wrong expected account');\n }\n }],\n ['decrypt QR', async function () {\n const encrypted = '01f4c73628793ad51150f3885c706474fb35f33d85c5e3d183773f8138f5d4294807ff71fd9de1fb1a31656520eb72ebefff19f563d51d4b70c1fed789ef73ca70e9870eff4516b2a2550978ede3062e3cf8dbb40408e6f977f7f7a3b92756902b37ca172dc8b2cb09456ee891';\n const expected = 'c86596c2d1208885db1fe3658406aa0f7cc7b8e13c362fe46a6db277fc5064583e487588c98a6c36e2e7445c0add36f83f171cb5ccfd815509d19cd38ecb0af3';\n const password = new Uint8Array(4);\n password[0] = 1;\n password[1] = 2;\n password[2] = 3;\n password[3] = 4;\n\n const decrypted = await symmetricCipherDecrypt(password, hexStringToBytes(encrypted));\n if (!uint8ArrayEquals(hexStringToBytes(expected), new Uint8Array(decrypted))) {\n throw Error('decryption failed');\n }\n }],\n ['new settings', async function () {\n const settingsExpected = {\n block0Hash: hexStringToBytes(BLOCK0_ID),\n discrimination: primitives.Discrimination.TEST,\n fees: {\n constant: \"1\",\n coefficient: \"2\",\n certificate: \"3\",\n certificatePoolRegistration: \"4\",\n certificateStakeDelegation: \"5\",\n certificateOwnerStakeDelegation: \"6\",\n certificateVotePlan: \"7\",\n certificateVoteCast: \"8\",\n }\n };\n\n const block0Date = \"110\";\n const slotDuration = \"10\";\n const era = { epochStart: \"0\", slotStart: \"0\", slotsPerEpoch: \"100\" };\n const transactionMaxExpiryEpochs = \"2\";\n\n const settingsPtr = await settingsNew(settingsExpected.block0Hash,\n settingsExpected.discrimination, settingsExpected.fees, block0Date,\n slotDuration, era, transactionMaxExpiryEpochs\n );\n\n expect(settingsPtr !== 0).toBe(true);\n\n const settings = await settingsGet(settingsPtr);\n\n expect(uint8ArrayEquals(settings.block0Hash, settingsExpected.block0Hash)).toBe(true);\n expect(settings.discrimination).toBe(settingsExpected.discrimination);\n\n expect(settings.fees.constant).toBe(settingsExpected.fees.constant);\n expect(settings.fees.coefficient).toBe(settingsExpected.fees.coefficient);\n expect(settings.fees.certificate).toBe(settingsExpected.fees.certificate);\n\n expect(settings.fees.certificatePoolRegistration).toBe(settingsExpected.fees.certificatePoolRegistration);\n expect(settings.fees.certificateStakeDelegation).toBe(settingsExpected.fees.certificateStakeDelegation);\n expect(settings.fees.certificateOwnerStakeDelegation).toBe(settingsExpected.fees.certificateOwnerStakeDelegation);\n\n expect(settings.fees.certificateVotePlan).toBe(settingsExpected.fees.certificateVotePlan);\n expect(settings.fees.certificateVoteCast).toBe(settingsExpected.fees.certificateVoteCast);\n\n await deleteSettings(settingsPtr);\n }],\n ['get vote fragment id', async function () {\n const array = new Array(32);\n for (let index = 0; index < array.length; index++) {\n array[index] = index;\n }\n\n const votePlanId = new Uint8Array(array);\n const index = 0;\n const numChoices = 3;\n\n const proposalPtr = await proposalNewPublic(votePlanId, index, numChoices);\n const walletPtr = await walletFromFile();\n\n const settingsPtr = await defaultSettings();\n\n await walletSetState(walletPtr, 1000000, DEFAULT_NONCES);\n\n const tx1 = await walletVote(walletPtr, settingsPtr, proposalPtr, 1, await maxExpirationDate(settingsPtr, BLOCK0_DATE + 600), 0);\n const tx2 = await walletVote(walletPtr, settingsPtr, proposalPtr, 2, await maxExpirationDate(settingsPtr, BLOCK0_DATE + 600), 1);\n\n await fragmentId(new Uint8Array(tx1));\n await fragmentId(new Uint8Array(tx2));\n\n await deleteSettings(settingsPtr);\n await deleteWallet(walletPtr);\n await deleteProposal(proposalPtr);\n }],\n ['systemtime to date', async function () {\n const settingsPtr = await defaultSettings();\n\n let first = await blockDateFromSystemTime(settingsPtr, BLOCK0_DATE);\n expect(first.epoch).toBe(\"0\");\n expect(first.slot).toBe(\"0\");\n\n let second = await blockDateFromSystemTime(settingsPtr, BLOCK0_DATE + SLOT_DURATION + 1);\n expect(second.epoch).toBe(\"0\");\n expect(second.slot).toBe(\"1\");\n\n let third = await blockDateFromSystemTime(settingsPtr, BLOCK0_DATE + SLOT_DURATION * SLOTS_PER_EPOCH);\n expect(third.epoch).toBe(\"1\");\n expect(third.slot).toBe(\"0\");\n }],\n]\n\nexports.defineAutoTests = function () {\n describe('primitive mappings', function () {\n it('clobber should exist', function () {\n expect(window.wallet).toBeDefined();\n });\n\n // For some reason, I can't get the Jasmine version that is used in the\n // testing framework to work with async functions directly, so instead I\n // define them as async functions (which return promises), and manually\n // wrap them with the asynchronous `done` function.\n tests.forEach(([name, f]) =>\n it(name, function (done) {\n f().then(done).catch(done.fail)\n }));\n });\n};\n\nexports.defineManualTests = require('./src/manual_tests.js');\n\nasync function defaultSettings() {\n const testSettings = {\n block0Hash: hexStringToBytes(BLOCK0_ID),\n discrimination: primitives.Discrimination.TEST,\n fees: {\n constant: \"1\",\n coefficient: \"2\",\n certificate: \"3\",\n certificatePoolRegistration: \"4\",\n certificateStakeDelegation: \"5\",\n certificateOwnerStakeDelegation: \"6\",\n certificateVotePlan: \"7\",\n certificateVoteCast: \"8\",\n }\n };\n\n const block0Date = JSON.stringify(BLOCK0_DATE);\n const slotDuration = JSON.stringify(SLOT_DURATION);\n const era = {epochStart: \"0\", slotStart: \"0\", slotsPerEpoch: JSON.stringify(SLOTS_PER_EPOCH)};\n const transactionMaxExpiryEpochs = \"2\";\n\n const settingsPtr = await settingsNew(testSettings.block0Hash,\n testSettings.discrimination, testSettings.fees, block0Date,\n slotDuration, era, transactionMaxExpiryEpochs\n );\n\n return settingsPtr;\n}\n" }, { "alpha_fraction": 0.6633032560348511, "alphanum_fraction": 0.6643653512001038, "avg_line_length": 26.691177368164062, "blob_id": "bb5d08538686d31244463dd8330ad2408628a97f", "content_id": "7e28e22ab191ebcc029d39f54e6327bd6a5e1185", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 1883, "license_type": "permissive", "max_line_length": 83, "num_lines": 68, "path": "/bindings/wallet-core/src/c/fragment.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use crate::{Error, Result};\nuse chain_core::{packer::Codec, property::DeserializeFromSlice};\nuse chain_impl_mockchain::fragment::Fragment;\nuse core::slice;\n\nuse super::{FragmentPtr, NulPtr, FRAGMENT_ID_LENGTH};\n\n/// # Safety\n///\n/// buffer must be non null and point to buffer_length bytes of valid memory.\n///\npub unsafe fn fragment_from_raw(\n buffer: *const u8,\n buffer_length: usize,\n fragment_out: *mut FragmentPtr,\n) -> Result {\n if buffer.is_null() {\n return Error::invalid_input(\"buffer\").with(NulPtr).into();\n }\n\n let fragment_out_ref = non_null_mut!(fragment_out);\n\n let bytes = slice::from_raw_parts(buffer, buffer_length);\n\n let fragment = match Fragment::deserialize_from_slice(&mut Codec::new(bytes)) {\n Ok(fragment) => fragment,\n Err(_e) => return Error::invalid_fragment().into(),\n };\n\n let fragment = Box::new(fragment);\n\n *fragment_out_ref = Box::into_raw(fragment);\n\n Result::success()\n}\n\n/// # Safety\n///\n/// fragment_ptr must be a pointer to memory allocated by this library, for\n/// example, with `fragment_from_raw`\n/// id_out must point to FRAGMENT_ID_LENGTH bytes of valid allocated writable\n/// memory\n/// This function checks for null pointers\n///\npub unsafe fn fragment_id(fragment_ptr: FragmentPtr, id_out: *mut u8) -> Result {\n let fragment = non_null!(fragment_ptr);\n\n let id = fragment.hash();\n\n let bytes = id.as_bytes();\n\n assert_eq!(bytes.len(), FRAGMENT_ID_LENGTH);\n\n std::ptr::copy(bytes.as_ptr(), id_out, bytes.len());\n\n Result::success()\n}\n\n/// # Safety\n///\n/// This function checks for null pointers, but take care that fragment_ptr was\n/// previously allocated by this library for example with fragment_from_raw\n///\npub unsafe fn fragment_delete(fragment_ptr: FragmentPtr) {\n if !fragment_ptr.is_null() {\n Box::from_raw(fragment_ptr as FragmentPtr);\n }\n}\n" }, { "alpha_fraction": 0.6285081505775452, "alphanum_fraction": 0.6499261260032654, "avg_line_length": 41.3125, "blob_id": "3da4dd67feb02a895eb99163768e047b8a233f6b", "content_id": "b348a962ad6a3351a5e48c9943386924fe74467a", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 1354, "license_type": "permissive", "max_line_length": 103, "num_lines": 32, "path": "/bindings/wallet-core/Cargo.toml", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "[package]\nauthors = [\"Nicolas Di Prima <[email protected]>\", \"Vincent Hanquez <[email protected]>\"]\nedition = \"2018\"\nlicense = \"MIT OR Apache-2.0\"\nname = \"wallet-core\"\nversion = \"0.7.0-pre4\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[lib]\ncrate-type = [\"lib\"]\n\n[dependencies]\nbip39 = {path = \"../../bip39\"}\nchain-addr = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-core = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-crypto = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-impl-mockchain = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-path-derivation = {path = \"../../chain-path-derivation\"}\nchain-ser = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-vote = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-time = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nhdkeygen = {path = \"../../hdkeygen\"}\nsymmetric-cipher = {path = \"../../symmetric-cipher\"}\nthiserror = {version = \"1.0.13\", default-features = false}\nwallet = {path = \"../../wallet\"}\nbech32 = \"0.7.2\"\n\nrand = { version = \"0.8.3\", features = [\"getrandom\"] }\n\n[dev-dependencies]\nrand_chacha = \"0.3.0\"\n" }, { "alpha_fraction": 0.48112526535987854, "alphanum_fraction": 0.5159894227981567, "avg_line_length": 32.67611312866211, "blob_id": "0529427e8ca875ece81a5bf396d3d08f2047ab24", "content_id": "03a8665ec884fe96ecbb41b66e1deeebdb7650f9", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 8318, "license_type": "permissive", "max_line_length": 137, "num_lines": 247, "path": "/bip39/src/entropy.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use crate::{Error, MnemonicIndex, Mnemonics, Result, Type, MAX_MNEMONIC_VALUE};\nuse std::ops::Deref;\n\n/// BIP39 entropy is used as root entropy for the HDWallet PRG\n/// to generate the HDWallet root keys.\n///\n/// See module documentation for mode details about how to use\n/// `Entropy`.\n#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, zeroize::ZeroizeOnDrop)]\npub enum Entropy {\n Entropy9([u8; 12]),\n Entropy12([u8; 16]),\n Entropy15([u8; 20]),\n Entropy18([u8; 24]),\n Entropy21([u8; 28]),\n Entropy24([u8; 32]),\n}\n\nimpl Entropy {\n /// Retrieve an `Entropy` from the given slice.\n ///\n /// # Error\n ///\n /// This function may fail if the given slice's length is not\n /// one of the supported entropy length. See [`Type`](./enum.Type.html)\n /// for the list of supported entropy sizes.\n ///\n pub fn from_slice(bytes: &[u8]) -> Result<Self> {\n let t = Type::from_entropy_size(bytes.len() * 8)?;\n Ok(Self::new(t, bytes))\n }\n\n /// generate entropy using the given random generator.\n ///\n /// # Example\n ///\n /// ```\n /// # extern crate rand;\n /// # use bip39::*;\n ///\n /// let entropy = Entropy::generate(Type::Type15Words, rand::random);\n /// ```\n ///\n pub fn generate<G>(t: Type, gen: G) -> Self\n where\n G: Fn() -> u8,\n {\n let bytes = [0u8; 32];\n let mut entropy = Self::new(t, &bytes[..]);\n for e in entropy.as_mut().iter_mut() {\n *e = gen();\n }\n entropy\n }\n\n fn new(t: Type, bytes: &[u8]) -> Self {\n let mut e = match t {\n Type::Type9Words => Entropy::Entropy9([0u8; 12]),\n Type::Type12Words => Entropy::Entropy12([0u8; 16]),\n Type::Type15Words => Entropy::Entropy15([0u8; 20]),\n Type::Type18Words => Entropy::Entropy18([0u8; 24]),\n Type::Type21Words => Entropy::Entropy21([0u8; 28]),\n Type::Type24Words => Entropy::Entropy24([0u8; 32]),\n };\n let len = e.as_ref().len();\n e.as_mut()[..len].copy_from_slice(&bytes[..len]);\n e\n }\n\n /// handy helper to retrieve the [`Type`](./enum.Type.html)\n /// from the `Entropy`.\n #[inline]\n pub fn get_type(&self) -> Type {\n match self {\n Entropy::Entropy9(_) => Type::Type9Words,\n Entropy::Entropy12(_) => Type::Type12Words,\n Entropy::Entropy15(_) => Type::Type15Words,\n Entropy::Entropy18(_) => Type::Type18Words,\n Entropy::Entropy21(_) => Type::Type21Words,\n Entropy::Entropy24(_) => Type::Type24Words,\n }\n }\n\n fn as_mut(&mut self) -> &mut [u8] {\n match self {\n Entropy::Entropy9(ref mut b) => b.as_mut(),\n Entropy::Entropy12(ref mut b) => b.as_mut(),\n Entropy::Entropy15(ref mut b) => b.as_mut(),\n Entropy::Entropy18(ref mut b) => b.as_mut(),\n Entropy::Entropy21(ref mut b) => b.as_mut(),\n Entropy::Entropy24(ref mut b) => b.as_mut(),\n }\n }\n\n fn hash(&self) -> [u8; 32] {\n use cryptoxide::digest::Digest;\n use cryptoxide::sha2::Sha256;\n let mut hasher = Sha256::new();\n let mut res = [0u8; 32];\n hasher.input(self.as_ref());\n hasher.result(&mut res);\n res\n }\n\n /// compute the checksum of the entropy, be aware that only\n /// part of the bytes may be useful for the checksum depending\n /// of the [`Type`](./enum.Type.html) of the `Entropy`.\n ///\n /// | entropy type | checksum size (in bits) |\n /// | ------------ | ----------------------- |\n /// | 9 words | 3 bits |\n /// | 12 words | 4 bits |\n /// | 15 words | 5 bits |\n /// | 18 words | 6 bits |\n /// | 21 words | 7 bits |\n /// | 24 words | 8 bits |\n ///\n /// # Example\n ///\n /// ```\n /// # extern crate rand;\n /// # use bip39::*;\n ///\n /// let entropy = Entropy::generate(Type::Type15Words, rand::random);\n ///\n /// let checksum = entropy.checksum() & 0b0001_1111;\n /// ```\n ///\n pub fn checksum(&self) -> u8 {\n let hash = self.hash()[0];\n match self.get_type() {\n Type::Type9Words => (hash >> 5) & 0b0000_0111,\n Type::Type12Words => (hash >> 4) & 0b0000_1111,\n Type::Type15Words => (hash >> 3) & 0b0001_1111,\n Type::Type18Words => (hash >> 2) & 0b0011_1111,\n Type::Type21Words => (hash >> 1) & 0b0111_1111,\n Type::Type24Words => hash,\n }\n }\n\n /// retrieve the `Entropy` from the given [`Mnemonics`](./struct.Mnemonics.html).\n ///\n /// # Example\n ///\n /// ```\n /// # use bip39::*;\n ///\n /// const MNEMONICS : &'static str = \"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about\";\n /// let mnemonics = Mnemonics::from_string(&dictionary::ENGLISH, MNEMONICS)\n /// .expect(\"validating the given mnemonics phrase\");\n ///\n /// let entropy = Entropy::from_mnemonics(&mnemonics)\n /// .expect(\"retrieving the entropy from the mnemonics\");\n /// ```\n ///\n /// # Error\n ///\n /// This function may fail if the Mnemonic has an invalid checksum. As part of the\n /// BIP39, the checksum must be embedded in the mnemonic phrase. This allow to check\n /// the mnemonics have been correctly entered by the user.\n ///\n pub fn from_mnemonics(mnemonics: &Mnemonics) -> Result<Self> {\n use super::bits::BitWriterBy11;\n let t = mnemonics.get_type();\n\n let mut to_validate = BitWriterBy11::new();\n for mnemonic in mnemonics.iter() {\n to_validate.write(mnemonic.0);\n }\n\n let mut r = to_validate.into_vec();\n\n let entropy_bytes = Vec::from(&r[..t.to_key_size() / 8]);\n let entropy = Self::new(t, &entropy_bytes[..]);\n if let Some(h) = r.pop() {\n let h2 = h >> (8 - t.checksum_size_bits());\n let cs = entropy.checksum();\n if cs != h2 {\n return Err(Error::InvalidChecksum(cs, h2));\n }\n };\n\n Ok(entropy)\n }\n\n /// convert the given `Entropy` into a mnemonic phrase.\n ///\n /// # Example\n ///\n /// ```\n /// # use bip39::*;\n ///\n /// let entropy = Entropy::Entropy12([0;16]);\n ///\n /// let mnemonics = entropy.to_mnemonics()\n /// .to_string(&dictionary::ENGLISH);\n /// ```\n ///\n pub fn to_mnemonics(&self) -> Mnemonics {\n use super::bits::BitReaderBy11;\n\n let t = self.get_type();\n let mut combined = Vec::from(self.as_ref());\n combined.extend(&self.hash()[..]);\n\n let mut reader = BitReaderBy11::new(&combined);\n\n let mut words: Vec<MnemonicIndex> = Vec::new();\n for _ in 0..t.mnemonic_count() {\n // here we are confident the entropy has already\n // enough bytes to read all the bits we need.\n let n = reader.read();\n // assert only in non optimized builds, Since we read 11bits\n // by 11 bits we should not allow values beyond 2047.\n debug_assert!( n <= MAX_MNEMONIC_VALUE\n , \"Something went wrong, the BitReaderBy11 did return an impossible value: {} (0b{:016b})\"\n , n, n\n );\n // here we can unwrap safely as 11bits can\n // only store up to the value 2047\n words.push(MnemonicIndex::new(n).unwrap());\n }\n // by design, it is safe to call unwrap here as\n // the mnemonic length has been validated by construction.\n Mnemonics::from_mnemonics(words).unwrap()\n }\n}\n\nimpl AsRef<[u8]> for Entropy {\n fn as_ref(&self) -> &[u8] {\n match self {\n Entropy::Entropy9(ref b) => b.as_ref(),\n Entropy::Entropy12(ref b) => b.as_ref(),\n Entropy::Entropy15(ref b) => b.as_ref(),\n Entropy::Entropy18(ref b) => b.as_ref(),\n Entropy::Entropy21(ref b) => b.as_ref(),\n Entropy::Entropy24(ref b) => b.as_ref(),\n }\n }\n}\n\nimpl Deref for Entropy {\n type Target = [u8];\n fn deref(&self) -> &Self::Target {\n self.as_ref()\n }\n}\n" }, { "alpha_fraction": 0.5391344428062439, "alphanum_fraction": 0.5432780981063843, "avg_line_length": 42.0098991394043, "blob_id": "f815a7d60dd0b6438f589069b086db8085a62964", "content_id": "e1ce1a47a4928404369334c2b694168a9467c5f8", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 4344, "license_type": "permissive", "max_line_length": 98, "num_lines": 101, "path": "/wallet/src/blockchain.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use chain_addr::Discrimination;\nuse chain_impl_mockchain::{\n block::Block,\n config::{Block0Date, ConfigParam},\n fee::{FeeAlgorithm as _, LinearFee},\n fragment::Fragment,\n header::HeaderId,\n ledger::{Block0Error, Error, Ledger},\n transaction::Input,\n};\nuse chain_time::TimeEra;\n\n#[derive(Clone)]\npub struct Settings {\n pub fees: LinearFee,\n pub discrimination: Discrimination,\n pub block0_initial_hash: HeaderId,\n pub block0_date: Block0Date,\n pub slot_duration: u8,\n pub time_era: TimeEra,\n pub transaction_max_expiry_epochs: u8,\n}\n\nimpl Settings {\n pub fn new(block: &Block) -> Result<Self, Error> {\n let header_id = block.header().id();\n let ledger = Ledger::new(header_id, block.contents().iter())?;\n\n let static_parameters = ledger.get_static_parameters().clone();\n let parameters = ledger.settings();\n\n // TODO: I think there is a bug in Ledger::new(), as it doesn't set the slot_duration in\n // the Settings.\n // This doesn't seem to matter for jormungandr anyway, because it gets the initial value\n // directly from the block0, and then just doesn't use the field in the settings anymore.\n // For now, just get the setting directly from the block0 here too, but should probably be\n // fixed in Ledger::new (or at least checked).\n let mut slot_duration = None;\n\n for fragment in block.contents().iter() {\n if let Fragment::Initial(initials) = fragment {\n for initial in initials.iter() {\n match initial {\n ConfigParam::Block0Date(_) => {}\n ConfigParam::Discrimination(_) => {}\n ConfigParam::ConsensusVersion(_) => {}\n ConfigParam::SlotsPerEpoch(_) => {}\n ConfigParam::SlotDuration(sd) => {\n slot_duration.replace(sd);\n }\n ConfigParam::EpochStabilityDepth(_) => {}\n ConfigParam::ConsensusGenesisPraosActiveSlotsCoeff(_) => {}\n ConfigParam::BlockContentMaxSize(_) => {}\n ConfigParam::AddBftLeader(_) => {}\n ConfigParam::RemoveBftLeader(_) => {}\n ConfigParam::LinearFee(_) => {}\n ConfigParam::ProposalExpiration(_) => {}\n ConfigParam::KesUpdateSpeed(_) => {}\n ConfigParam::TreasuryAdd(_) => {}\n ConfigParam::TreasuryParams(_) => {}\n ConfigParam::RewardPot(_) => {}\n ConfigParam::RewardParams(_) => {}\n ConfigParam::PerCertificateFees(_) => {}\n ConfigParam::FeesInTreasury(_) => {}\n ConfigParam::RewardLimitNone => {}\n ConfigParam::RewardLimitByAbsoluteStake(_) => {}\n ConfigParam::PoolRewardParticipationCapping(_) => {}\n ConfigParam::AddCommitteeId(_) => {}\n ConfigParam::RemoveCommitteeId(_) => {}\n ConfigParam::PerVoteCertificateFees(_) => {}\n ConfigParam::TransactionMaxExpiryEpochs(_) => {}\n }\n }\n }\n }\n\n Ok(Self {\n fees: parameters.linear_fees.clone(),\n discrimination: static_parameters.discrimination,\n block0_initial_hash: static_parameters.block0_initial_hash,\n block0_date: static_parameters.block0_start_time,\n slot_duration: *slot_duration\n .ok_or(Error::Block0(Block0Error::InitialMessageNoSlotDuration))?,\n time_era: ledger.era().clone(),\n transaction_max_expiry_epochs: ledger.settings().transaction_max_expiry_epochs,\n })\n }\n\n /// convenient function to check if a given input\n /// is covering at least its own input fees for a given transaction\n pub fn is_input_worth(&self, input: &Input) -> bool {\n let value = input.value();\n let minimal_value = self.fees.fees_for_inputs_outputs(1, 0);\n\n value > minimal_value\n }\n\n pub fn discrimination(&self) -> Discrimination {\n self.discrimination\n }\n}\n" }, { "alpha_fraction": 0.6617100238800049, "alphanum_fraction": 0.6755177974700928, "avg_line_length": 39.0638313293457, "blob_id": "d12bd2468dbcd3ab268af6fa52b91187c013889a", "content_id": "12b3757cd0225c6b69819f145b50da55f5438511", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 1883, "license_type": "permissive", "max_line_length": 80, "num_lines": 47, "path": "/bip39/src/error.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use std::result;\nuse thiserror::Error;\n\n/// Error regarding BIP39 operations\n#[derive(Debug, Error, PartialEq, Eq)]\npub enum Error {\n /// Received an unsupported number of mnemonic words. The parameter\n /// contains the unsupported number. Supported values are\n /// described as part of the [`Type`](./enum.Type.html).\n #[error(\"Unsupported number of mnemonic words: {0}\")]\n WrongNumberOfWords(usize),\n\n /// The entropy is of invalid size. The parameter contains the invalid size,\n /// the list of supported entropy size are described as part of the\n /// [`Type`](./enum.Type.html).\n #[error(\"Unsupported mnemonic entropy size: {0}\")]\n WrongKeySize(usize),\n\n /// The given mnemonic is out of bound, i.e. its index is above 2048 and\n /// is invalid within BIP39 specifications.\n #[error(\"The given mnemonic is out of bound, {0}\")]\n MnemonicOutOfBound(u16),\n\n /// Forward error regarding dictionary operations.\n #[error(\"Unknown mnemonic word\")]\n LanguageError(\n #[source]\n #[from]\n crate::dictionary::Error,\n ),\n\n /// the Seed is of invalid size. The parameter is the given seed size,\n /// the expected seed size is [`SEED_SIZE`](./constant.SEED_SIZE.html).\n #[error(\"Invalid Seed Size, expected 64 bytes, but received {0} bytes.\")]\n InvalidSeedSize(usize),\n\n /// checksum is invalid. The first parameter is the expected checksum,\n /// the second id the computed checksum. This error means that the given\n /// mnemonics are invalid to retrieve the original entropy. The user might\n /// have given an invalid mnemonic phrase.\n #[error(\"Invalid Entropy's Checksum, expected {0:08b} but found {1:08b}\")]\n InvalidChecksum(u8, u8),\n}\n\n/// convenient Alias to wrap up BIP39 operations that may return\n/// an [`Error`](./enum.Error.html).\npub type Result<T> = result::Result<T, Error>;\n" }, { "alpha_fraction": 0.5510461926460266, "alphanum_fraction": 0.564263105392456, "avg_line_length": 28.62979507446289, "blob_id": "2f17a79d3158ae2bc42df6cc7a3298da55514778", "content_id": "d64a67c47907b5859a00aebd76e2a6132e4320ca", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 33215, "license_type": "permissive", "max_line_length": 97, "num_lines": 1121, "path": "/chain-path-derivation/src/derivation.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use std::{\n convert::{TryFrom, TryInto},\n fmt::{self, Display},\n ops::Deref,\n str,\n};\nuse thiserror::Error;\n\n/// the soft derivation is upper bounded, this is the value\nconst SOFT_DERIVATION_UPPER_BOUND: u32 = 0x8000_0000;\n\n/// a derivation value that can be used to derive keys\n///\n/// There is 2 kind of derivations, the soft and the hard derivations.\n/// [`SoftDerivation`] are expected to allow derivation of the private\n/// keys and of the public keys. [`HardDerivation`] are expected to allow\n/// only the derivation of the private keys.\n///\n/// [`SoftDerivation`]: ./struct.SoftDerivation.html\n/// [`HardDerivation`]: ./struct.HardDerivation.html\n#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct Derivation(u32);\n\n/// wrapper to guarantee the given derivation is a soft derivation\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct SoftDerivation(Derivation);\n\n/// wrapper to guarantee the given derivation is a soft derivation\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct HardDerivation(Derivation);\n\n/// iterator to create derivation values\n///\n/// # Examples\n///\n/// ```\n/// # use chain_path_derivation::{Derivation, DerivationRange};\n/// let range = DerivationRange::new(..20);\n/// for (expected, derivation) in (0..20).zip(range) {\n/// assert_eq!(derivation, Derivation::new(expected));\n/// }\n/// ```\n#[derive(Debug)]\npub struct DerivationRange {\n range: std::ops::Range<Derivation>,\n}\n\n/// iterator to create derivation values\n///\n/// # Examples\n///\n/// ```\n/// # use chain_path_derivation::{Derivation, SoftDerivation, SoftDerivationRange};\n/// let range = SoftDerivationRange::new(..20);\n/// for (expected, derivation) in (0..20).zip(range) {\n/// assert_eq!(\n/// derivation,\n/// SoftDerivation::new_unchecked(Derivation::new(expected))\n/// );\n/// }\n/// ```\n#[derive(Debug, Clone)]\npub struct SoftDerivationRange {\n range: std::ops::Range<SoftDerivation>,\n}\n\n/// iterator to create derivation values\n///\n/// # Examples\n///\n/// ```\n/// # use chain_path_derivation::{Derivation, HardDerivation, HardDerivationRange};\n/// let range = HardDerivationRange::new(..0x8000_0020);\n/// for (expected, derivation) in (0x8000_0000..0x8000_0020).zip(range) {\n/// assert_eq!(\n/// derivation,\n/// HardDerivation::new_unchecked(Derivation::new(expected))\n/// );\n/// }\n/// ```\n#[derive(Debug, Clone)]\npub struct HardDerivationRange {\n range: std::ops::Range<HardDerivation>,\n}\n\n#[derive(Debug, Error)]\npub enum DerivationError {\n #[error(\"Not a valid derivation for a soft derivation ({0})\")]\n InvalidSoftDerivation(Derivation),\n #[error(\"Not a valid derivation for a hard derivation ({0})\")]\n InvalidHardDerivation(Derivation),\n}\n\nimpl Derivation {\n /// create a new derivation with the given index\n #[inline]\n pub const fn new(v: u32) -> Self {\n Self(v)\n }\n\n /// test if the given derivation is a soft derivation\n ///\n /// # Example\n ///\n /// ```\n /// # use chain_path_derivation::Derivation;\n /// let derivation = Derivation::new(42);\n /// assert!(derivation.is_soft_derivation());\n /// ```\n #[inline]\n pub fn is_soft_derivation(self) -> bool {\n self.0 < SOFT_DERIVATION_UPPER_BOUND\n }\n\n /// test if the given derivation is a hard derivation\n ///\n /// # Example\n ///\n /// ```\n /// # use chain_path_derivation::Derivation;\n /// let derivation = Derivation::new(0x8000_0010);\n /// assert!(derivation.is_hard_derivation());\n /// ```\n #[inline]\n pub fn is_hard_derivation(self) -> bool {\n !self.is_soft_derivation()\n }\n\n /// returns the max derivation index value\n ///\n /// ```\n /// # use chain_path_derivation::Derivation;\n /// let max = Derivation::max_value();\n /// assert_eq!(max, Derivation::new(4294967295));\n /// ```\n #[inline]\n pub const fn max_value() -> Self {\n Self::new(u32::max_value())\n }\n\n /// returns the min derivation index value\n ///\n /// ```\n /// # use chain_path_derivation::Derivation;\n /// let min = Derivation::min_value();\n /// assert_eq!(min, Derivation::new(0));\n /// ```\n #[inline]\n pub const fn min_value() -> Self {\n Self::new(u32::min_value())\n }\n\n /// calculate `derivation + rhs`\n ///\n /// Returns the tuple of the addition along with a boolean indicating whether\n /// an arithmetic overflow would occur. If an overflow would have occurred\n /// then the wrapped value is returned.\n ///\n /// # Examples\n ///\n /// Basic usage:\n ///\n /// ```\n /// # use chain_path_derivation::Derivation;\n /// assert_eq!(\n /// Derivation::new(5).overflowing_add(2),\n /// (Derivation::new(7), false)\n /// );\n /// assert_eq!(\n /// Derivation::max_value().overflowing_add(1),\n /// (Derivation::new(0), true)\n /// );\n /// ```\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n #[inline]\n pub const fn overflowing_add(self, rhs: u32) -> (Self, bool) {\n let (v, b) = self.0.overflowing_add(rhs);\n (Self(v), b)\n }\n\n /// saturating integer addition. Computes `self + rhs`, saturating\n /// at the numeric bounds instead of overflowing.\n ///\n /// # Examples\n ///\n /// Basic usage:\n ///\n /// ```\n /// # use chain_path_derivation::Derivation;\n /// assert_eq!(Derivation::new(100).saturating_add(1), Derivation::new(101));\n /// assert_eq!(Derivation::max_value().saturating_add(2048), Derivation::max_value());\n /// ```\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n #[inline]\n pub fn saturating_add(self, rhs: u32) -> Self {\n Self(self.0.saturating_add(rhs))\n }\n\n /// checked integer addition. Computes `self + rhs`, returning `None` if overflow\n /// would occurred.\n ///\n /// # Examples\n ///\n /// Basic usage:\n ///\n /// ```\n /// # use chain_path_derivation::Derivation;\n /// assert_eq!(Derivation::new(100).checked_add(1), Some(Derivation::new(101)));\n /// assert_eq!(Derivation::max_value().checked_add(2048), None);\n /// ```\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n #[inline]\n pub fn checked_add(self, rhs: u32) -> Option<Self> {\n self.0.checked_add(rhs).map(Self)\n }\n\n /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around the boundary\n /// of the type.\n ///\n /// # Examples\n ///\n /// Basic usage:\n ///\n /// ```\n /// # use chain_path_derivation::Derivation;\n /// assert_eq!(Derivation::new(100).wrapping_add(1), Derivation::new(101));\n /// assert_eq!(Derivation::max_value().wrapping_add(1), Derivation::new(0));\n /// ```\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n #[inline]\n pub const fn wrapping_add(self, rhs: u32) -> Self {\n Self(self.0.wrapping_add(rhs))\n }\n\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n #[inline]\n fn saturating_sub(self, rhs: u32) -> Self {\n Self(self.0.saturating_sub(rhs))\n }\n}\n\nimpl SoftDerivation {\n /// construct a soft derivation from the given derivation without\n /// checking the derivation is actually a soft derivation.\n ///\n /// this function does not perform any verification and if the value\n /// is not correct it will create a cascade of issues, be careful when\n /// utilizing this function.\n #[inline]\n pub const fn new_unchecked(derivation: Derivation) -> Self {\n Self(derivation)\n }\n\n /// build a soft derivation from the given `Derivation`. If the value\n /// is not a soft derivation it will return an error\n ///\n /// # Example\n ///\n /// ```\n /// # use chain_path_derivation::{Derivation, SoftDerivation, DerivationError};\n /// # fn func() -> Result<(), DerivationError> {\n /// let derivation = Derivation::new(42);\n /// let derivation = SoftDerivation::new(derivation)?;\n ///\n /// println!(\"derivation: {}\", derivation);\n /// # Ok(())\n /// # }\n /// #\n /// # func().unwrap();\n /// ```\n #[inline]\n pub fn new(derivation: Derivation) -> Result<Self, DerivationError> {\n if derivation.is_soft_derivation() {\n Ok(Self::new_unchecked(derivation))\n } else {\n Err(DerivationError::InvalidSoftDerivation(derivation))\n }\n }\n\n /// returns the max derivation index value\n ///\n /// ```\n /// # use chain_path_derivation::{Derivation, SoftDerivation};\n /// let max = SoftDerivation::max_value();\n /// assert_eq!(max, SoftDerivation::new_unchecked(Derivation::new(0x7FFF_FFFF)));\n /// ```\n #[inline]\n pub const fn max_value() -> Self {\n Self::new_unchecked(Derivation::new(SOFT_DERIVATION_UPPER_BOUND - 1))\n }\n\n /// returns the min derivation index value\n ///\n /// ```\n /// # use chain_path_derivation::{Derivation, SoftDerivation};\n /// let min = SoftDerivation::min_value();\n /// assert_eq!(min, SoftDerivation::new_unchecked(Derivation::new(0)));\n /// ```\n #[inline]\n pub const fn min_value() -> Self {\n Self::new_unchecked(Derivation::min_value())\n }\n\n /// calculate `self + rhs`\n ///\n /// Returns the tuple of the addition along with a boolean indicating whether\n /// an arithmetic overflow would occur. If an overflow would have occurred\n /// then the wrapped value is returned.\n ///\n /// # Examples\n ///\n /// Basic usage:\n ///\n /// ```\n /// # use chain_path_derivation::{Derivation, SoftDerivation};\n /// assert_eq!(\n /// SoftDerivation::new_unchecked(Derivation::new(5)).overflowing_add(2),\n /// (SoftDerivation::new_unchecked(Derivation::new(7)), false)\n /// );\n /// assert_eq!(\n /// SoftDerivation::max_value().overflowing_add(1),\n /// (SoftDerivation::new_unchecked(Derivation::new(0)), true)\n /// );\n /// ```\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n #[inline]\n pub fn overflowing_add(self, rhs: u32) -> (Self, bool) {\n let (v, b) = self.0.overflowing_add(rhs);\n\n if v.is_soft_derivation() {\n (Self::new_unchecked(v), b)\n } else {\n (\n Self::new_unchecked(Derivation::new(v.0 - SOFT_DERIVATION_UPPER_BOUND)),\n true,\n )\n }\n }\n\n /// saturating integer addition. Computes `self + rhs`, saturating\n /// at the numeric bounds instead of overflowing.\n ///\n /// # Examples\n ///\n /// Basic usage:\n ///\n /// ```\n /// # use chain_path_derivation::{Derivation, SoftDerivation};\n /// assert_eq!(\n /// SoftDerivation::new_unchecked(Derivation::new(100)).saturating_add(1),\n /// SoftDerivation::new_unchecked(Derivation::new(101))\n /// );\n /// assert_eq!(\n /// SoftDerivation::max_value().saturating_add(2048),\n /// SoftDerivation::max_value(),\n /// );\n /// ```\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n #[inline]\n pub fn saturating_add(self, rhs: u32) -> Self {\n let d = self.0.saturating_add(rhs);\n\n // allow `unwrap_or`, it's 32bits of integer or a function pointer\n #[allow(clippy::or_fun_call)]\n Self::new(d).unwrap_or(Self::max_value())\n }\n\n /// checked integer addition. Computes `self + rhs`, returning `None` if overflow\n /// would occurred.\n ///\n /// # Examples\n ///\n /// Basic usage:\n ///\n /// ```\n /// # use chain_path_derivation::{Derivation, SoftDerivation};\n /// assert_eq!(\n /// SoftDerivation::new_unchecked(Derivation::new(100)).checked_add(1),\n /// Some(SoftDerivation::new_unchecked(Derivation::new(101)))\n /// );\n /// assert_eq!(\n /// SoftDerivation::max_value().checked_add(2048),\n /// None,\n /// );\n /// ```\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n #[inline]\n pub fn checked_add(self, rhs: u32) -> Option<Self> {\n let d = self.0.checked_add(rhs)?;\n\n Self::new(d).ok()\n }\n\n /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around the boundary\n /// of the type.\n ///\n /// # Examples\n ///\n /// Basic usage:\n ///\n /// ```\n /// # use chain_path_derivation::{Derivation, SoftDerivation};\n /// assert_eq!(\n /// SoftDerivation::new_unchecked(Derivation::new(100)).wrapping_add(1),\n /// SoftDerivation::new_unchecked(Derivation::new(101))\n /// );\n /// assert_eq!(\n /// SoftDerivation::max_value().wrapping_add(1),\n /// SoftDerivation::new_unchecked(Derivation::new(0)),\n /// );\n /// ```\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n #[inline]\n pub fn wrapping_add(self, rhs: u32) -> Self {\n let (d, _) = self.overflowing_add(rhs);\n d\n }\n\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n #[inline]\n fn saturating_sub(self, rhs: u32) -> Self {\n let d = self.0.saturating_sub(rhs);\n\n // allow `unwrap_or`, it's 32bits of integer or a function pointer\n #[allow(clippy::or_fun_call)]\n Self::new(d).unwrap_or(Self::min_value())\n }\n}\n\nimpl HardDerivation {\n /// construct a hard derivation from the given derivation without\n /// checking the derivation is actually a hard derivation.\n ///\n /// this function does not perform any verification and if the value\n /// is not correct it will create a cascade of issues, be careful when\n /// utilizing this function.\n #[inline]\n pub const fn new_unchecked(derivation: Derivation) -> Self {\n Self(derivation)\n }\n\n /// build a hard derivation from the given `Derivation`. If the value\n /// is not a hard derivation it will return an error\n ///\n /// # Example\n ///\n /// ```\n /// # use chain_path_derivation::{Derivation, HardDerivation, DerivationError};\n /// # fn func() -> Result<(), DerivationError> {\n /// let derivation = Derivation::new(0x8000_0001);\n /// let derivation = HardDerivation::new(derivation)?;\n ///\n /// println!(\"derivation: {}\", derivation);\n /// # Ok(())\n /// # }\n /// #\n /// # func().unwrap();\n /// ```\n #[inline]\n pub fn new(derivation: Derivation) -> Result<Self, DerivationError> {\n if derivation.is_hard_derivation() {\n Ok(Self::new_unchecked(derivation))\n } else {\n Err(DerivationError::InvalidHardDerivation(derivation))\n }\n }\n\n /// returns the max derivation index value\n ///\n /// ```\n /// # use chain_path_derivation::{Derivation, HardDerivation};\n /// let max = HardDerivation::max_value();\n /// assert_eq!(max, HardDerivation::new_unchecked(Derivation::new(0xFFFF_FFFF)));\n /// ```\n #[inline]\n pub const fn max_value() -> Self {\n Self::new_unchecked(Derivation::max_value())\n }\n\n /// returns the min derivation index value\n ///\n /// ```\n /// # use chain_path_derivation::{Derivation, HardDerivation};\n /// let min = HardDerivation::min_value();\n /// assert_eq!(min, HardDerivation::new_unchecked(Derivation::new(0x8000_0000)));\n /// ```\n #[inline]\n pub const fn min_value() -> Self {\n Self::new_unchecked(Derivation::new(SOFT_DERIVATION_UPPER_BOUND))\n }\n\n /// calculate `self + rhs`\n ///\n /// Returns the tuple of the addition along with a boolean indicating whether\n /// an arithmetic overflow would occur. If an overflow would have occurred\n /// then the wrapped value is returned.\n ///\n /// # Examples\n ///\n /// Basic usage:\n ///\n /// ```\n /// # use chain_path_derivation::{Derivation, HardDerivation};\n /// assert_eq!(\n /// HardDerivation::new_unchecked(Derivation::new(0x8000_0005)).overflowing_add(2),\n /// (HardDerivation::new_unchecked(Derivation::new(0x8000_0007)), false)\n /// );\n /// assert_eq!(\n /// HardDerivation::max_value().overflowing_add(1),\n /// (HardDerivation::new_unchecked(Derivation::new(0x8000_0000)), true)\n /// );\n /// ```\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n #[inline]\n pub fn overflowing_add(self, rhs: u32) -> (Self, bool) {\n let (v, b) = self.0.overflowing_add(rhs);\n\n if v.is_hard_derivation() {\n (Self::new_unchecked(v), b)\n } else {\n (\n Self::new_unchecked(Derivation::new(v.0 + SOFT_DERIVATION_UPPER_BOUND)),\n true,\n )\n }\n }\n\n /// saturating integer addition. Computes `self + rhs`, saturating\n /// at the numeric bounds instead of overflowing.\n ///\n /// # Examples\n ///\n /// Basic usage:\n ///\n /// ```\n /// # use chain_path_derivation::{Derivation, HardDerivation};\n /// assert_eq!(\n /// HardDerivation::new_unchecked(Derivation::new(0x8000_0100)).saturating_add(1),\n /// HardDerivation::new_unchecked(Derivation::new(0x8000_0101))\n /// );\n /// assert_eq!(\n /// HardDerivation::max_value().saturating_add(2048),\n /// HardDerivation::max_value(),\n /// );\n /// ```\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n #[inline]\n pub fn saturating_add(self, rhs: u32) -> Self {\n let d = self.0.saturating_add(rhs);\n\n // allow `unwrap_or`, it's 32bits of integer or a function pointer\n #[allow(clippy::or_fun_call)]\n Self::new(d).unwrap_or(Self::max_value())\n }\n\n /// checked integer addition. Computes `self + rhs`, returning `None` if overflow\n /// would occurred.\n ///\n /// # Examples\n ///\n /// Basic usage:\n ///\n /// ```\n /// # use chain_path_derivation::{Derivation, HardDerivation};\n /// assert_eq!(\n /// HardDerivation::new_unchecked(Derivation::new(0x8000_0100)).checked_add(1),\n /// Some(HardDerivation::new_unchecked(Derivation::new(0x8000_0101)))\n /// );\n /// assert_eq!(\n /// HardDerivation::max_value().checked_add(2048),\n /// None,\n /// );\n /// ```\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n #[inline]\n pub fn checked_add(self, rhs: u32) -> Option<Self> {\n let d = self.0.checked_add(rhs)?;\n\n Self::new(d).ok()\n }\n\n /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around the boundary\n /// of the type.\n ///\n /// # Examples\n ///\n /// Basic usage:\n ///\n /// ```\n /// # use chain_path_derivation::{Derivation, HardDerivation};\n /// assert_eq!(\n /// HardDerivation::new_unchecked(Derivation::new(0x8000_0100)).wrapping_add(1),\n /// HardDerivation::new_unchecked(Derivation::new(0x8000_0101))\n /// );\n /// assert_eq!(\n /// HardDerivation::max_value().wrapping_add(1),\n /// HardDerivation::new_unchecked(Derivation::new(0x8000_0000)),\n /// );\n /// ```\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n #[inline]\n pub fn wrapping_add(self, rhs: u32) -> Self {\n let (d, _) = self.overflowing_add(rhs);\n d\n }\n\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n #[inline]\n fn saturating_sub(self, rhs: u32) -> Self {\n let d = self.0.saturating_sub(rhs);\n\n // allow `unwrap_or`, it's 32bits of integer or a function pointer\n #[allow(clippy::or_fun_call)]\n Self::new(d).unwrap_or(Self::min_value())\n }\n}\n\nimpl DerivationRange {\n /// create a derivation range from the given range\n pub fn new<R, T>(range: R) -> Self\n where\n R: std::ops::RangeBounds<T>,\n T: Into<Derivation> + Copy,\n {\n use std::ops::Bound;\n let start = match range.start_bound() {\n Bound::Unbounded => Derivation::min_value(),\n Bound::Included(b) => (*b).into(),\n Bound::Excluded(b) => (*b).into().saturating_add(1),\n };\n\n let end = match range.end_bound() {\n Bound::Unbounded => Derivation::max_value(),\n Bound::Included(b) => (*b).into().saturating_add(1),\n Bound::Excluded(b) => (*b).into(),\n };\n\n let range = std::ops::Range { start, end };\n\n Self { range }\n }\n}\n\nimpl SoftDerivationRange {\n /// create a SoftDerivation range from the given range\n ///\n /// # panics\n ///\n /// this function will panic if the bounds are not valid SoftDerivation\n /// values.\n pub fn new<R, T>(range: R) -> Self\n where\n R: std::ops::RangeBounds<T>,\n T: TryInto<SoftDerivation> + Copy,\n <T as std::convert::TryInto<SoftDerivation>>::Error: std::error::Error,\n {\n use std::ops::Bound;\n let start = match range.start_bound() {\n Bound::Unbounded => Ok(SoftDerivation::min_value()),\n Bound::Included(b) => (*b).try_into(),\n Bound::Excluded(b) => (*b).try_into().map(|v| v.saturating_add(1)),\n };\n\n let end = match range.end_bound() {\n Bound::Unbounded => Ok(SoftDerivation::max_value()),\n Bound::Included(b) => (*b).try_into().map(|v| v.saturating_add(1)),\n Bound::Excluded(b) => (*b).try_into(),\n };\n\n let start =\n start.unwrap_or_else(|e| panic!(\"min bound is not a valid SoftDerivation, {:?}\", e));\n let end =\n end.unwrap_or_else(|e| panic!(\"max bound is not a valid SoftDerivation, {:?}\", e));\n\n let range = std::ops::Range { start, end };\n\n Self { range }\n }\n}\n\nimpl HardDerivationRange {\n /// create a HardDerivation range from the given range\n ///\n /// # panics\n ///\n /// this function will panic if the bounds are not valid HardDerivation\n /// values.\n pub fn new<R, T>(range: R) -> Self\n where\n R: std::ops::RangeBounds<T>,\n T: TryInto<HardDerivation> + Copy,\n <T as std::convert::TryInto<HardDerivation>>::Error: std::error::Error,\n {\n use std::ops::Bound;\n let start = match range.start_bound() {\n Bound::Unbounded => Ok(HardDerivation::min_value()),\n Bound::Included(b) => (*b).try_into(),\n Bound::Excluded(b) => (*b).try_into().map(|v| v.saturating_add(1)),\n };\n\n let end = match range.end_bound() {\n Bound::Unbounded => Ok(HardDerivation::max_value()),\n Bound::Included(b) => (*b).try_into().map(|v| v.saturating_add(1)),\n Bound::Excluded(b) => (*b).try_into(),\n };\n\n let start =\n start.unwrap_or_else(|e| panic!(\"min bound is not a valid HardDerivation, {:?}\", e));\n let end =\n end.unwrap_or_else(|e| panic!(\"max bound is not a valid HardDerivation, {:?}\", e));\n\n let range = std::ops::Range { start, end };\n\n Self { range }\n }\n}\n\n/* Iterator **************************************************************** */\n\nimpl Iterator for DerivationRange {\n type Item = Derivation;\n\n fn next(&mut self) -> Option<Self::Item> {\n let start = self.range.start;\n if self.range.contains(&start) {\n self.range.start = start.saturating_add(1);\n Some(start)\n } else {\n None\n }\n }\n}\n\nimpl Iterator for SoftDerivationRange {\n type Item = SoftDerivation;\n\n fn next(&mut self) -> Option<Self::Item> {\n let start = self.range.start;\n if self.range.contains(&start) {\n self.range.start = start.saturating_add(1);\n Some(start)\n } else {\n None\n }\n }\n}\n\nimpl Iterator for HardDerivationRange {\n type Item = HardDerivation;\n\n fn next(&mut self) -> Option<Self::Item> {\n let start = self.range.start;\n if self.range.contains(&start) {\n self.range.start = start.saturating_add(1);\n Some(start)\n } else {\n None\n }\n }\n}\n\nimpl ExactSizeIterator for DerivationRange {\n fn len(&self) -> usize {\n let Derivation(start) = self.range.start;\n let Derivation(end) = self.range.end;\n\n (end - start) as usize\n }\n}\n\nimpl ExactSizeIterator for SoftDerivationRange {\n fn len(&self) -> usize {\n let Derivation(start) = self.range.start.0;\n let Derivation(end) = self.range.end.0;\n\n (end - start) as usize\n }\n}\n\nimpl ExactSizeIterator for HardDerivationRange {\n fn len(&self) -> usize {\n let Derivation(start) = self.range.start.0;\n let Derivation(end) = self.range.end.0;\n\n (end - start) as usize\n }\n}\n\nimpl DoubleEndedIterator for DerivationRange {\n fn next_back(&mut self) -> Option<Self::Item> {\n let next_back = self.range.end.saturating_sub(0);\n if self.range.contains(&next_back) {\n self.range.end = next_back;\n Some(next_back)\n } else {\n None\n }\n }\n}\n\nimpl DoubleEndedIterator for SoftDerivationRange {\n fn next_back(&mut self) -> Option<Self::Item> {\n let next_back = self.range.end.saturating_sub(0);\n if self.range.contains(&next_back) {\n self.range.end = next_back;\n Some(next_back)\n } else {\n None\n }\n }\n}\n\nimpl DoubleEndedIterator for HardDerivationRange {\n fn next_back(&mut self) -> Option<Self::Item> {\n let next_back = self.range.end.saturating_sub(0);\n if self.range.contains(&next_back) {\n self.range.end = next_back;\n Some(next_back)\n } else {\n None\n }\n }\n}\n\nimpl std::iter::FusedIterator for DerivationRange {}\nimpl std::iter::FusedIterator for SoftDerivationRange {}\nimpl std::iter::FusedIterator for HardDerivationRange {}\n\n/* Default ***************************************************************** */\n\nimpl Default for SoftDerivation {\n fn default() -> Self {\n Self::min_value()\n }\n}\n\nimpl Default for HardDerivation {\n fn default() -> Self {\n Self::min_value()\n }\n}\n\n/* Display ***************************************************************** */\n\nimpl Display for Derivation {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n if self.is_soft_derivation() {\n self.0.fmt(f)\n } else {\n write!(f, \"'{}\", self.0 - SOFT_DERIVATION_UPPER_BOUND)\n }\n }\n}\n\nimpl Display for SoftDerivation {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n self.0.fmt(f)\n }\n}\n\nimpl Display for HardDerivation {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n self.0.fmt(f)\n }\n}\n\n/* FromStr ***************************************************************** */\n\n#[derive(Error, Debug)]\npub enum ParseDerivationError {\n #[error(\"Not a valid derivation value\")]\n NaN(\n #[source]\n #[from]\n std::num::ParseIntError,\n ),\n\n #[error(\"Not a valid derivation\")]\n InvalidDerivation(\n #[source]\n #[from]\n DerivationError,\n ),\n}\n\nimpl str::FromStr for Derivation {\n type Err = ParseDerivationError;\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n if let Some(s) = s.strip_prefix('\\'') {\n s.parse::<u32>()\n .map(|v| v + SOFT_DERIVATION_UPPER_BOUND)\n .map(Derivation)\n .map_err(ParseDerivationError::NaN)\n } else {\n s.parse().map(Derivation).map_err(ParseDerivationError::NaN)\n }\n }\n}\n\nimpl str::FromStr for SoftDerivation {\n type Err = ParseDerivationError;\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n let derivation = s.parse()?;\n Ok(Self::new(derivation)?)\n }\n}\n\nimpl str::FromStr for HardDerivation {\n type Err = ParseDerivationError;\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n let derivation = s.parse()?;\n Ok(Self::new(derivation)?)\n }\n}\n\n/* Conversion ************************************************************** */\n\nimpl From<u32> for Derivation {\n fn from(v: u32) -> Derivation {\n Derivation(v)\n }\n}\n\nimpl From<Derivation> for u32 {\n fn from(d: Derivation) -> Self {\n d.0\n }\n}\n\nimpl From<SoftDerivation> for Derivation {\n fn from(d: SoftDerivation) -> Self {\n d.0\n }\n}\n\nimpl From<HardDerivation> for Derivation {\n fn from(d: HardDerivation) -> Self {\n d.0\n }\n}\n\nimpl TryFrom<Derivation> for SoftDerivation {\n type Error = DerivationError;\n\n fn try_from(value: Derivation) -> Result<Self, Self::Error> {\n Self::new(value)\n }\n}\n\nimpl TryFrom<Derivation> for HardDerivation {\n type Error = DerivationError;\n\n fn try_from(value: Derivation) -> Result<Self, Self::Error> {\n Self::new(value)\n }\n}\n\nimpl TryFrom<u32> for SoftDerivation {\n type Error = DerivationError;\n\n fn try_from(value: u32) -> Result<Self, Self::Error> {\n Self::new(Derivation::new(value))\n }\n}\n\nimpl TryFrom<u32> for HardDerivation {\n type Error = DerivationError;\n\n fn try_from(value: u32) -> Result<Self, Self::Error> {\n Self::new(Derivation::new(value))\n }\n}\n\n/* Deref ******************************************************************* */\n\nimpl Deref for Derivation {\n type Target = u32;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl Deref for SoftDerivation {\n type Target = u32;\n\n fn deref(&self) -> &Self::Target {\n self.0.deref()\n }\n}\n\nimpl Deref for HardDerivation {\n type Target = u32;\n\n fn deref(&self) -> &Self::Target {\n self.0.deref()\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use quickcheck::{Arbitrary, Gen};\n\n impl Arbitrary for Derivation {\n fn arbitrary<G: Gen>(g: &mut G) -> Self {\n Derivation(u32::arbitrary(g))\n }\n }\n\n impl Arbitrary for SoftDerivation {\n fn arbitrary<G: Gen>(g: &mut G) -> Self {\n let derivation = Derivation(u32::arbitrary(g) % SOFT_DERIVATION_UPPER_BOUND);\n Self::new(derivation).expect(\"Generated an invalid value for soft derivation\")\n }\n }\n\n impl Arbitrary for HardDerivation {\n fn arbitrary<G: Gen>(g: &mut G) -> Self {\n let derivation = Derivation(\n u32::arbitrary(g) % SOFT_DERIVATION_UPPER_BOUND + SOFT_DERIVATION_UPPER_BOUND,\n );\n Self::new(derivation).expect(\"Generated an invalid value for hard derivation\")\n }\n }\n\n #[test]\n fn derivation_iterator_1() {\n let range = DerivationRange::new(..8);\n let expected = vec![\n Derivation::new(0),\n Derivation::new(1),\n Derivation::new(2),\n Derivation::new(3),\n Derivation::new(4),\n Derivation::new(5),\n Derivation::new(6),\n Derivation::new(7),\n ];\n\n for (address, expected) in range.zip(expected) {\n assert_eq!(address, expected);\n }\n }\n\n #[test]\n fn derivation_iterator_2() {\n let range = DerivationRange::new(4..8);\n let expected = vec![\n Derivation::new(4),\n Derivation::new(5),\n Derivation::new(6),\n Derivation::new(7),\n ];\n\n for (address, expected) in range.zip(expected) {\n assert_eq!(address, expected);\n }\n }\n\n #[test]\n fn derivation_iterator_3() {\n let range = DerivationRange::new(4..=8);\n let expected = vec![\n Derivation::new(4),\n Derivation::new(5),\n Derivation::new(6),\n Derivation::new(7),\n Derivation::new(8),\n ];\n\n for (address, expected) in range.zip(expected) {\n assert_eq!(address, expected);\n }\n }\n\n #[test]\n fn derivation_iterator_4() {\n let range = DerivationRange::new::<_, u32>(..);\n\n assert_eq!(range.len(), u32::max_value() as usize);\n }\n\n #[test]\n fn to_string() {\n assert_eq!(Derivation(0).to_string(), \"0\");\n assert_eq!(Derivation(9289).to_string(), \"9289\");\n assert_eq!(Derivation(SOFT_DERIVATION_UPPER_BOUND).to_string(), \"'0\");\n assert_eq!(\n Derivation(SOFT_DERIVATION_UPPER_BOUND + 9289).to_string(),\n \"'9289\"\n );\n }\n\n #[quickcheck]\n fn fmt_parse_derivation(derivation: Derivation) -> bool {\n let s = derivation.to_string();\n let v = s.parse::<Derivation>().unwrap();\n\n v == derivation\n }\n\n #[quickcheck]\n fn fmt_parse_soft_derivation(derivation: SoftDerivation) -> bool {\n let s = derivation.to_string();\n let v = s.parse::<SoftDerivation>().unwrap();\n\n v == derivation\n }\n\n #[quickcheck]\n fn fmt_parse_hard_derivation(derivation: HardDerivation) -> bool {\n let s = derivation.to_string();\n let v = s.parse::<HardDerivation>().unwrap();\n\n v == derivation\n }\n}\n" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 30.5, "blob_id": "a4d0b86c754554a586b395fbcbe84ca25ad3a129", "content_id": "b9cc45ac901417a3f39628c48dcdc3f8bb1b20ab", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 63, "license_type": "permissive", "max_line_length": 44, "num_lines": 2, "path": "/bindings/wallet-uniffi/uniffi.toml", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "[bindings.kotlin]\npackage_name = \"com.iohk.jormungandr_wallet\"\n" }, { "alpha_fraction": 0.5390185117721558, "alphanum_fraction": 0.5563153624534607, "avg_line_length": 25.168420791625977, "blob_id": "702fd374ce4926ce4b01acd49b5cd2f9f4473ad0", "content_id": "2fa22361350ff39196346913f767fa897ab59fc0", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 4972, "license_type": "permissive", "max_line_length": 92, "num_lines": 190, "path": "/hdkeygen/src/account.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "//! account based wallet, does not really have any Hierarchical element in it\n//! thought it is part of the `keygen` entity so adding it in\n//!\n//! On the chain, an account can group stake while a rindex or a bip44 cannot\n//! as they represent individual coins, which have stake but they are not grouped\n//! and cannot be be controlled without having an account to group them\n\nuse chain_addr::{Address, Discrimination, Kind};\nuse chain_crypto::{AsymmetricKey, Ed25519, Ed25519Extended, PublicKey, SecretKey};\nuse cryptoxide::ed25519::{self, PRIVATE_KEY_LENGTH};\nuse std::{\n convert::TryInto,\n fmt::{self, Display},\n str::FromStr,\n};\n\npub type Seed = [u8; PRIVATE_KEY_LENGTH];\n\npub struct Account<K: AsymmetricKey> {\n secret: SecretKey<K>,\n counter: u32,\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct AccountId {\n id: [u8; AccountId::SIZE],\n}\n\nimpl Account<Ed25519> {\n pub fn from_seed(seed: Seed) -> Self {\n let secret = SecretKey::<Ed25519>::from_binary(&seed).unwrap();\n Account { secret, counter: 0 }\n }\n}\n\nimpl Account<Ed25519Extended> {\n pub fn from_secret_key(key: SecretKey<Ed25519Extended>) -> Self {\n Account {\n secret: key,\n counter: 0,\n }\n }\n}\n\nimpl<K: AsymmetricKey> Account<K> {\n pub fn account_id(&self) -> AccountId {\n AccountId { id: self.public() }\n }\n\n pub fn public(&self) -> [u8; AccountId::SIZE] {\n self.secret.to_public().as_ref().try_into().unwrap()\n }\n\n /// get the transaction counter\n ///\n /// this is the counter for the number of times a transaction has been successfully sent\n /// to the network with this account. It is used to sign transactions so it is important\n /// to keep it up to date as much as possible.\n pub fn counter(&self) -> u32 {\n self.counter\n }\n\n pub fn set_counter(&mut self, counter: u32) {\n self.counter = counter;\n }\n\n /// increase the counter with the given amount\n pub fn increase_counter(&mut self, atm: u32) {\n self.counter += atm\n }\n\n pub fn secret(&self) -> &SecretKey<K> {\n &self.secret\n }\n\n // pub fn seed(&self) -> &SEED {\n // &self.seed\n // }\n}\n\nimpl AccountId {\n /// the total size of an account ID\n pub const SIZE: usize = ed25519::PUBLIC_KEY_LENGTH;\n\n /// get the public address associated to this account identifier\n pub fn address(&self, discrimination: Discrimination) -> Address {\n let pk = if let Ok(pk) = PublicKey::from_binary(&self.id) {\n pk\n } else {\n unsafe { std::hint::unreachable_unchecked() }\n };\n let kind = Kind::Account(pk);\n\n Address(discrimination, kind)\n }\n}\n\n// impl Drop for Account {\n// fn drop(&mut self) {\n// cryptoxide::util::secure_memset(&mut self.seed, 0)\n// }\n// }\n\n/* Conversion ************************************************************** */\n\n// impl From<[u8; SEED_LENGTH]> for Account {\n// fn from(seed: [u8; SEED_LENGTH]) -> Self {\n// Self { seed, counter: 0 }\n// }\n// }\n\nimpl From<[u8; Self::SIZE]> for AccountId {\n fn from(id: [u8; Self::SIZE]) -> Self {\n Self { id }\n }\n}\n\nimpl From<AccountId> for PublicKey<Ed25519> {\n fn from(account: AccountId) -> PublicKey<Ed25519> {\n if let Ok(pk) = PublicKey::from_binary(&account.id) {\n pk\n } else {\n unsafe { std::hint::unreachable_unchecked() }\n }\n }\n}\n\nimpl AsRef<[u8]> for AccountId {\n fn as_ref(&self) -> &[u8] {\n self.id.as_ref()\n }\n}\n\n/* Display ***************************************************************** */\n\nimpl Display for AccountId {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n hex::encode(&self.id).fmt(f)\n }\n}\n\nimpl FromStr for AccountId {\n type Err = hex::FromHexError;\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n let mut id = [0; Self::SIZE];\n\n hex::decode_to_slice(s, &mut id)?;\n\n Ok(Self { id })\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use quickcheck::{Arbitrary, Gen};\n\n impl Clone for Account<Ed25519> {\n fn clone(&self) -> Self {\n Self {\n secret: self.secret.clone(),\n counter: self.counter,\n }\n }\n }\n\n impl Arbitrary for Account<Ed25519> {\n fn arbitrary<G: Gen>(g: &mut G) -> Self {\n let mut seed = [0; PRIVATE_KEY_LENGTH];\n g.fill_bytes(&mut seed);\n Self::from_seed(seed)\n }\n }\n\n impl Arbitrary for AccountId {\n fn arbitrary<G: Gen>(g: &mut G) -> Self {\n let mut id = [0; Self::SIZE];\n g.fill_bytes(&mut id);\n Self { id }\n }\n }\n\n #[quickcheck]\n fn account_id_to_string_parse(account_id: AccountId) -> bool {\n let s = account_id.to_string();\n let decoded = s.parse().unwrap();\n\n account_id == decoded\n }\n}\n" }, { "alpha_fraction": 0.4047139286994934, "alphanum_fraction": 0.4554794430732727, "avg_line_length": 27.86046600341797, "blob_id": "f8890f400947def2a9b405fbc6b08fbc58b845e6", "content_id": "9dd621715c69472110994f2f0a907da61c77be9b", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 4964, "license_type": "permissive", "max_line_length": 87, "num_lines": 172, "path": "/bip39/src/types.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use crate::{Error, Result};\nuse std::{fmt, result, str};\nuse thiserror::Error;\n\n#[derive(Error, Debug)]\npub enum ParseTypeError {\n #[error(\"Expecting a number\")]\n NaN(\n #[source]\n #[from]\n std::num::ParseIntError,\n ),\n #[error(\"Not a valid number of mnemonic, expected one of [9, 12, 15, 18, 21, 24]\")]\n InvalidNumber,\n}\n\n/// The support type of `Mnemonics`, i.e. the number of words supported in a\n/// mnemonic phrase.\n///\n/// This enum provide the following properties:\n///\n/// | number of words | entropy size (bits) | checksum size (bits) |\n/// | --------------- | ------------------- | --------------------- |\n/// | 9 | 96 | 3 |\n/// | 12 | 128 | 4 |\n/// | 15 | 160 | 5 |\n/// | 18 | 192 | 6 |\n/// | 21 | 224 | 7 |\n/// | 24 | 256 | 8 |\n///\n#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]\npub enum Type {\n Type9Words,\n Type12Words,\n Type15Words,\n Type18Words,\n Type21Words,\n Type24Words,\n}\nimpl Type {\n pub fn from_word_count(len: usize) -> Result<Self> {\n match len {\n 9 => Ok(Type::Type9Words),\n 12 => Ok(Type::Type12Words),\n 15 => Ok(Type::Type15Words),\n 18 => Ok(Type::Type18Words),\n 21 => Ok(Type::Type21Words),\n 24 => Ok(Type::Type24Words),\n _ => Err(Error::WrongNumberOfWords(len)),\n }\n }\n\n pub fn from_entropy_size(len: usize) -> Result<Self> {\n match len {\n 96 => Ok(Type::Type9Words),\n 128 => Ok(Type::Type12Words),\n 160 => Ok(Type::Type15Words),\n 192 => Ok(Type::Type18Words),\n 224 => Ok(Type::Type21Words),\n 256 => Ok(Type::Type24Words),\n _ => Err(Error::WrongKeySize(len)),\n }\n }\n\n pub fn to_key_size(self) -> usize {\n match self {\n Type::Type9Words => 96,\n Type::Type12Words => 128,\n Type::Type15Words => 160,\n Type::Type18Words => 192,\n Type::Type21Words => 224,\n Type::Type24Words => 256,\n }\n }\n\n pub fn checksum_size_bits(self) -> usize {\n match self {\n Type::Type9Words => 3,\n Type::Type12Words => 4,\n Type::Type15Words => 5,\n Type::Type18Words => 6,\n Type::Type21Words => 7,\n Type::Type24Words => 8,\n }\n }\n\n pub fn mnemonic_count(self) -> usize {\n match self {\n Type::Type9Words => 9,\n Type::Type12Words => 12,\n Type::Type15Words => 15,\n Type::Type18Words => 18,\n Type::Type21Words => 21,\n Type::Type24Words => 24,\n }\n }\n}\n\nimpl Default for Type {\n fn default() -> Type {\n Type::Type24Words\n }\n}\n\nimpl fmt::Display for Type {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n match self {\n Type::Type9Words => 9.fmt(f),\n Type::Type12Words => 12.fmt(f),\n Type::Type15Words => 15.fmt(f),\n Type::Type18Words => 18.fmt(f),\n Type::Type21Words => 21.fmt(f),\n Type::Type24Words => 24.fmt(f),\n }\n }\n}\n\nimpl str::FromStr for Type {\n type Err = ParseTypeError;\n fn from_str(s: &str) -> result::Result<Self, Self::Err> {\n let i = s.parse()?;\n match i {\n 9 => Ok(Type::Type9Words),\n 12 => Ok(Type::Type12Words),\n 15 => Ok(Type::Type15Words),\n 18 => Ok(Type::Type18Words),\n 21 => Ok(Type::Type21Words),\n 24 => Ok(Type::Type24Words),\n _ => Err(ParseTypeError::InvalidNumber),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use quickcheck::{Arbitrary, Gen};\n\n impl Arbitrary for Type {\n fn arbitrary<G: Gen>(g: &mut G) -> Self {\n use Type::*;\n const VALUES: &[Type] = &[\n Type9Words,\n Type12Words,\n Type15Words,\n Type18Words,\n Type21Words,\n Type24Words,\n ];\n let v = usize::arbitrary(g) % VALUES.len();\n VALUES[v]\n }\n }\n\n #[test]\n fn to_string() {\n assert_eq!(Type::Type9Words.to_string(), \"9\");\n assert_eq!(Type::Type12Words.to_string(), \"12\");\n assert_eq!(Type::Type15Words.to_string(), \"15\");\n assert_eq!(Type::Type18Words.to_string(), \"18\");\n assert_eq!(Type::Type21Words.to_string(), \"21\");\n assert_eq!(Type::Type24Words.to_string(), \"24\");\n }\n\n #[quickcheck]\n fn fmt_parse(t: Type) -> bool {\n let s = t.to_string();\n let v = s.parse::<Type>().unwrap();\n\n v == t\n }\n}\n" }, { "alpha_fraction": 0.5596266388893127, "alphanum_fraction": 0.5723541975021362, "avg_line_length": 30.542579650878906, "blob_id": "f4f42548fdcb68d651a0f0a2ceb506fffc6711bc", "content_id": "0c2ff1a8ca5fe75af0450ada6b37874600f583b3", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 12964, "license_type": "permissive", "max_line_length": 99, "num_lines": 411, "path": "/bindings/wallet-uniffi/src/lib.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use chain_crypto::bech32::Bech32;\nuse chain_crypto::Ed25519Extended;\nuse chain_crypto::SecretKey;\nuse chain_impl_mockchain::certificate::VotePlanId;\nuse chain_impl_mockchain::config;\nuse chain_impl_mockchain::fee;\nuse chain_impl_mockchain::fragment;\nuse chain_ser::{\n deser::{DeserializeFromSlice, Serialize},\n packer::Codec,\n};\nuse chain_vote::ElectionPublicKey;\nuse std::convert::{TryFrom, TryInto};\nuse std::num::NonZeroU64;\nuse std::sync::Arc;\nuse std::sync::Mutex;\nuse std::time::Duration;\nuse std::time::SystemTime;\nuse wallet_core::Error as CoreError;\nuse wallet_core::Options;\nuse wallet_core::Settings as InnerSettings;\nuse wallet_core::Wallet as InnerWallet;\n\nuniffi_macros::include_scaffolding!(\"lib\");\n\n#[derive(Debug, thiserror::Error)]\npub enum WalletError {\n #[error(\"malformed encryption key\")]\n InvalidEncryptionKey,\n #[error(\"malformed voteplan id\")]\n MalformedVotePlanId,\n #[error(\"malformed block0 hash\")]\n MalformedBlock0Hash,\n #[error(\"core error {0}\")]\n CoreError(#[from] CoreError),\n #[error(\"malformed secret key\")]\n MalformedSecretKey,\n #[error(\"time error {0}\")]\n TimeError(#[from] wallet::time::Error),\n #[error(\"cipher error\")]\n CipherError(#[from] symmetric_cipher::Error),\n #[error(\"invalid fragment\")]\n InvalidFragment,\n #[error(\"invalid spending counters\")]\n InvalidSpendingCounters,\n}\n\npub struct Wallet(Mutex<InnerWallet>);\n\npub struct Settings(Mutex<InnerSettings>);\n\npub struct Fragment(Mutex<fragment::Fragment>);\n\npub struct Proposal {\n pub vote_plan_id: Vec<u8>,\n pub index: u8,\n pub options: u8,\n pub payload_type: PayloadTypeConfig,\n}\n\npub struct SettingsRaw {\n pub fees: LinearFee,\n pub discrimination: Discrimination,\n pub block0_hash: Vec<u8>,\n pub block0_date: u64,\n pub slot_duration: u8,\n pub time_era: TimeEra,\n pub transaction_max_expiry_epochs: u8,\n}\n\npub struct LinearFee {\n pub constant: u64,\n pub coefficient: u64,\n pub certificate: u64,\n pub per_certificate_fees: PerCertificateFee,\n pub per_vote_certificate_fees: PerVoteCertificateFee,\n}\n\npub struct PerCertificateFee {\n pub certificate_pool_registration: u64,\n pub certificate_stake_delegation: u64,\n pub certificate_owner_stake_delegation: u64,\n}\n\npub struct PerVoteCertificateFee {\n pub certificate_vote_plan: u64,\n pub certificate_vote_cast: u64,\n}\n\npub enum Discrimination {\n Production,\n Test,\n}\n\npub struct TimeEra {\n pub epoch_start: u32,\n pub slot_start: u64,\n pub slots_per_epoch: u32,\n}\n\npub enum PayloadTypeConfig {\n Public,\n Private { encryption_key: String },\n}\n\npub struct BlockDate {\n epoch: u32,\n slot: u32,\n}\n\npub struct SecretKeyEd25519Extended(SecretKey<Ed25519Extended>);\n\n// kotlin codegen does not support wrapped types (rust newtypes) for now at least,\n// and writing custom type wrappers for this doesn't seem worth it.\npub type FragmentId = Vec<u8>;\npub type Value = u64;\npub type AccountId = Vec<u8>;\n\npub fn block_date_from_system_time(\n settings: Arc<Settings>,\n unix_epoch: u64,\n) -> Result<BlockDate, WalletError> {\n let settings_guard = settings.0.lock().unwrap();\n\n let time = SystemTime::UNIX_EPOCH + Duration::from_secs(unix_epoch);\n wallet::time::block_date_from_system_time(&settings_guard, time)\n .map(From::from)\n .map_err(From::from)\n}\n\npub fn max_expiration_date(\n settings: Arc<Settings>,\n current_time: u64,\n) -> Result<BlockDate, WalletError> {\n let settings = settings.0.lock().unwrap();\n wallet::time::max_expiration_date(\n &settings,\n SystemTime::UNIX_EPOCH + Duration::from_secs(current_time),\n )\n .map(From::from)\n .map_err(From::from)\n}\n\npub fn symmetric_cipher_decrypt(\n password: Vec<u8>,\n ciphertext: Vec<u8>,\n) -> Result<Vec<u8>, WalletError> {\n symmetric_cipher::decrypt(password, ciphertext)\n .map(|b| b.to_vec())\n .map_err(From::from)\n}\n\nimpl Wallet {\n pub fn new(account_key: Arc<SecretKeyEd25519Extended>) -> Result<Self, WalletError> {\n let inner = InnerWallet::recover_free_keys(account_key.0.clone().leak_secret().as_ref())\n .map_err(WalletError::CoreError)?;\n\n Ok(Self(Mutex::new(inner)))\n }\n\n pub fn set_state(&self, value: u64, counter: Vec<u32>) -> Result<(), WalletError> {\n let mut guard = self.0.lock().unwrap();\n\n guard\n .set_state(wallet_core::Value(value), counter)\n .map_err(|_| WalletError::InvalidSpendingCounters)?;\n\n Ok(())\n }\n\n pub fn account_id(&self) -> AccountId {\n self.0.lock().unwrap().id().as_ref().to_vec()\n }\n\n pub fn confirm_transaction(&self, id: FragmentId) {\n let h: [u8; 32] = id.try_into().unwrap();\n self.0.lock().unwrap().confirm_transaction(h.into())\n }\n\n pub fn vote(\n &self,\n settings: Arc<Settings>,\n proposal: Proposal,\n choice: u8,\n valid_until: BlockDate,\n lane: u8,\n ) -> Result<Vec<u8>, WalletError> {\n let settings = settings.0.lock().unwrap();\n let mut wallet = self.0.lock().unwrap();\n\n wallet\n .vote(\n settings.clone(),\n &proposal.try_into()?,\n wallet_core::Choice::new(choice),\n &valid_until.into(),\n lane,\n )\n .map(|bytes| bytes.into_vec())\n .map_err(WalletError::from)\n }\n\n pub fn spending_counters(&self) -> Vec<u32> {\n let wallet = self.0.lock().unwrap();\n\n wallet.spending_counter()\n }\n\n pub fn total_value(&self) -> Value {\n self.0.lock().unwrap().total_value().0\n }\n}\n\nimpl Settings {\n pub fn new(settings_init: SettingsRaw) -> Result<Self, WalletError> {\n let SettingsRaw {\n fees,\n discrimination,\n block0_hash,\n block0_date,\n slot_duration,\n time_era,\n transaction_max_expiry_epochs,\n } = settings_init;\n\n let discrimination = match discrimination {\n Discrimination::Production => chain_addr::Discrimination::Production,\n Discrimination::Test => chain_addr::Discrimination::Test,\n };\n\n let linear_fee = fee::LinearFee {\n constant: fees.constant,\n coefficient: fees.coefficient,\n certificate: fees.certificate,\n per_certificate_fees: fee::PerCertificateFee {\n certificate_pool_registration: NonZeroU64::new(\n fees.per_certificate_fees.certificate_pool_registration,\n ),\n certificate_stake_delegation: NonZeroU64::new(\n fees.per_certificate_fees.certificate_stake_delegation,\n ),\n certificate_owner_stake_delegation: NonZeroU64::new(\n fees.per_certificate_fees.certificate_owner_stake_delegation,\n ),\n },\n per_vote_certificate_fees: fee::PerVoteCertificateFee {\n certificate_vote_plan: NonZeroU64::new(\n fees.per_vote_certificate_fees.certificate_vote_plan,\n ),\n certificate_vote_cast: NonZeroU64::new(\n fees.per_vote_certificate_fees.certificate_vote_cast,\n ),\n },\n };\n\n let block0_hash: [u8; 32] = block0_hash\n .try_into()\n .map_err(|_| WalletError::MalformedBlock0Hash)?;\n\n Ok(Self(Mutex::new(InnerSettings {\n fees: linear_fee,\n discrimination,\n block0_initial_hash: block0_hash.into(),\n block0_date: config::Block0Date(block0_date),\n slot_duration,\n time_era: time_era.into(),\n transaction_max_expiry_epochs,\n })))\n }\n\n pub fn settings_raw(&self) -> SettingsRaw {\n let guard = self.0.lock().unwrap();\n\n SettingsRaw {\n fees: LinearFee {\n constant: guard.fees.constant,\n coefficient: guard.fees.coefficient,\n certificate: guard.fees.certificate,\n per_certificate_fees: PerCertificateFee {\n certificate_pool_registration: guard\n .fees\n .per_certificate_fees\n .certificate_pool_registration\n .map(NonZeroU64::get)\n .unwrap_or(0),\n certificate_stake_delegation: guard\n .fees\n .per_certificate_fees\n .certificate_stake_delegation\n .map(NonZeroU64::get)\n .unwrap_or(0),\n certificate_owner_stake_delegation: guard\n .fees\n .per_certificate_fees\n .certificate_owner_stake_delegation\n .map(NonZeroU64::get)\n .unwrap_or(0),\n },\n per_vote_certificate_fees: PerVoteCertificateFee {\n certificate_vote_plan: guard\n .fees\n .per_vote_certificate_fees\n .certificate_vote_plan\n .map(NonZeroU64::get)\n .unwrap_or(0),\n certificate_vote_cast: guard\n .fees\n .per_vote_certificate_fees\n .certificate_vote_cast\n .map(NonZeroU64::get)\n .unwrap_or(0),\n },\n },\n discrimination: match guard.discrimination {\n chain_addr::Discrimination::Production => Discrimination::Production,\n chain_addr::Discrimination::Test => Discrimination::Test,\n },\n block0_hash: guard.block0_initial_hash.as_bytes().to_vec(),\n block0_date: guard.block0_date.0,\n slot_duration: guard.slot_duration,\n time_era: TimeEra {\n // TODO: expose these things in chain_libs, they are not going to be anything else\n // than 0 for now, but just in case\n epoch_start: 0,\n slot_start: 0,\n slots_per_epoch: guard.time_era.slots_per_epoch(),\n },\n transaction_max_expiry_epochs: guard.transaction_max_expiry_epochs,\n }\n }\n}\n\nimpl SecretKeyEd25519Extended {\n pub fn new(bytes: Vec<u8>) -> Result<Self, WalletError> {\n SecretKey::<Ed25519Extended>::from_binary(bytes.as_ref())\n .map(Self)\n .map_err(|_| WalletError::MalformedSecretKey)\n }\n}\n\nimpl Fragment {\n pub fn new(bytes: Vec<u8>) -> Result<Self, WalletError> {\n let raw = fragment::Fragment::deserialize_from_slice(&mut Codec::new(bytes.as_ref()))\n .map_err(|_| WalletError::InvalidFragment)?;\n\n Ok(Self(Mutex::new(raw)))\n }\n\n pub fn id(&self) -> Vec<u8> {\n let fraw = self.0.lock().unwrap();\n\n fraw.hash().as_ref().to_vec()\n }\n\n pub fn serialize(&self) -> Vec<u8> {\n let guard = self.0.lock().unwrap();\n\n // I don't think this can actually fail, except for memory allocation of course, but that's\n // always the case.\n (*guard).serialize_as_vec().unwrap()\n }\n}\n\nimpl From<TimeEra> for chain_time::TimeEra {\n fn from(te: TimeEra) -> Self {\n chain_time::TimeEra::new(\n te.slot_start.into(),\n chain_time::Epoch(te.epoch_start),\n te.slots_per_epoch,\n )\n }\n}\n\nimpl TryFrom<Proposal> for wallet_core::Proposal {\n type Error = WalletError;\n\n fn try_from(p: Proposal) -> Result<Self, Self::Error> {\n Ok(wallet_core::Proposal::new(\n VotePlanId::try_from(p.vote_plan_id.as_ref())\n .map_err(|_| WalletError::MalformedVotePlanId)?,\n p.index,\n Options::new_length(p.options).unwrap(),\n match p.payload_type {\n PayloadTypeConfig::Public => wallet_core::PayloadTypeConfig::Public,\n PayloadTypeConfig::Private { encryption_key } => {\n let encryption_key = ElectionPublicKey::try_from_bech32_str(&encryption_key)\n .map_err(|_| WalletError::InvalidEncryptionKey)?;\n wallet_core::PayloadTypeConfig::Private(encryption_key)\n }\n },\n ))\n }\n}\n\nimpl From<BlockDate> for chain_impl_mockchain::block::BlockDate {\n fn from(d: BlockDate) -> Self {\n chain_impl_mockchain::block::BlockDate {\n epoch: d.epoch,\n slot_id: d.slot,\n }\n }\n}\n\nimpl From<chain_impl_mockchain::block::BlockDate> for BlockDate {\n fn from(block_date: chain_impl_mockchain::block::BlockDate) -> Self {\n BlockDate {\n epoch: block_date.epoch,\n slot: block_date.slot_id,\n }\n }\n}\n" }, { "alpha_fraction": 0.5946686863899231, "alphanum_fraction": 0.6332834959030151, "avg_line_length": 29.64122200012207, "blob_id": "b965e37503375cc15754f3198558179cd5f0191a", "content_id": "615116a6223d913ee83d77f57116cbbba54d7acd", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 4014, "license_type": "permissive", "max_line_length": 94, "num_lines": 131, "path": "/hdkeygen/src/bip44.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use crate::{Key, KeyRange};\nuse chain_addr::{Discrimination, Kind};\nuse chain_path_derivation::{\n bip44::{self, Bip44},\n Derivation, DerivationPath, HardDerivation, SoftDerivation, SoftDerivationRange,\n};\nuse ed25519_bip32::{XPrv, XPub};\n\nimpl Key<XPrv, Bip44<bip44::Root>> {\n pub fn purpose(&self, derivation: HardDerivation) -> Key<XPrv, Bip44<bip44::Purpose>> {\n self.derive_unchecked(derivation.into())\n }\n\n pub fn bip44(&self) -> Key<XPrv, Bip44<bip44::Purpose>> {\n self.purpose(bip44::PURPOSE_BIP44)\n }\n\n pub fn chimeric_bip44(&self) -> Key<XPrv, Bip44<bip44::Purpose>> {\n self.purpose(bip44::PURPOSE_CHIMERIC)\n }\n}\n\nimpl Key<XPrv, Bip44<bip44::Purpose>> {\n pub fn coin_type(&self, derivation: HardDerivation) -> Key<XPrv, Bip44<bip44::CoinType>> {\n self.derive_unchecked(derivation.into())\n }\n\n pub fn cardano(&self) -> Key<XPrv, Bip44<bip44::CoinType>> {\n const COIN_TYPE: HardDerivation =\n HardDerivation::new_unchecked(Derivation::new(0x8000_0717));\n self.coin_type(COIN_TYPE)\n }\n}\n\nimpl Key<XPrv, Bip44<bip44::CoinType>> {\n pub fn account(&self, derivation: HardDerivation) -> Key<XPrv, Bip44<bip44::Account>> {\n self.derive_unchecked(derivation.into())\n }\n}\n\nimpl<K> Key<K, Bip44<bip44::Account>> {\n const EXTERNAL: SoftDerivation = DerivationPath::<Bip44<bip44::Account>>::EXTERNAL;\n const INTERNAL: SoftDerivation = DerivationPath::<Bip44<bip44::Account>>::INTERNAL;\n const ACCOUNT: SoftDerivation = DerivationPath::<Bip44<bip44::Account>>::ACCOUNT;\n\n pub fn id(&self) -> HardDerivation {\n self.path().account()\n }\n}\n\nimpl Key<XPrv, Bip44<bip44::Account>> {\n pub fn change(&self, derivation: SoftDerivation) -> Key<XPrv, Bip44<bip44::Change>> {\n self.derive_unchecked(derivation.into())\n }\n\n pub fn external(&self) -> Key<XPrv, Bip44<bip44::Change>> {\n self.change(Self::EXTERNAL)\n }\n\n pub fn internal(&self) -> Key<XPrv, Bip44<bip44::Change>> {\n self.change(Self::INTERNAL)\n }\n\n pub fn account(&self) -> Key<XPrv, Bip44<bip44::Change>> {\n self.change(Self::ACCOUNT)\n }\n}\n\nimpl Key<XPub, Bip44<bip44::Account>> {\n pub fn change(&self, derivation: SoftDerivation) -> Key<XPub, Bip44<bip44::Change>> {\n self.derive_unchecked(derivation)\n }\n\n pub fn external(&self) -> Key<XPub, Bip44<bip44::Change>> {\n self.change(Self::EXTERNAL)\n }\n\n pub fn internal(&self) -> Key<XPub, Bip44<bip44::Change>> {\n self.change(Self::INTERNAL)\n }\n\n pub fn account(&self) -> Key<XPub, Bip44<bip44::Change>> {\n self.change(Self::ACCOUNT)\n }\n}\n\nimpl Key<XPrv, Bip44<bip44::Change>> {\n pub fn address(&self, derivation: SoftDerivation) -> Key<XPrv, Bip44<bip44::Address>> {\n self.derive_unchecked(derivation.into())\n }\n}\n\nimpl Key<XPub, Bip44<bip44::Change>> {\n pub fn address(&self, derivation: SoftDerivation) -> Key<XPub, Bip44<bip44::Address>> {\n self.derive_unchecked(derivation)\n }\n\n pub fn addresses(\n &self,\n range: SoftDerivationRange,\n ) -> KeyRange<XPub, SoftDerivationRange, Bip44<bip44::Change>, Bip44<bip44::Address>> {\n KeyRange::new(self, range)\n }\n}\n\nimpl Key<XPub, Bip44<bip44::Address>> {\n pub fn address_single(&self, discrimination: Discrimination) -> chain_addr::Address {\n let pk = self.pk();\n let kind = Kind::Single(pk);\n\n chain_addr::Address(discrimination, kind)\n }\n\n pub fn address_account(&self, discrimination: Discrimination) -> chain_addr::Address {\n let pk = self.pk();\n let kind = Kind::Account(pk);\n\n chain_addr::Address(discrimination, kind)\n }\n\n pub fn address_group(\n &self,\n discrimination: Discrimination,\n group: chain_crypto::PublicKey<chain_crypto::Ed25519>,\n ) -> chain_addr::Address {\n let pk = self.pk();\n let kind = Kind::Group(pk, group);\n\n chain_addr::Address(discrimination, kind)\n }\n}\n" }, { "alpha_fraction": 0.6617646813392639, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 21.66666603088379, "blob_id": "978a068b0f1445ae65767c061e4160c71892b7e0", "content_id": "91737a85fa9973f7a7b32405badbe951a1372c69", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 68, "license_type": "permissive", "max_line_length": 50, "num_lines": 3, "path": "/bindings/wallet-cordova/src/android/jna-compile.gradle", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "dependencies {\n implementation 'net.java.dev.jna:jna:5.9.0@aar'\n}\n" }, { "alpha_fraction": 0.5893293619155884, "alphanum_fraction": 0.6038532853126526, "avg_line_length": 33.6915168762207, "blob_id": "ab85a8d64991e939d740d4717540e68d65203baa", "content_id": "c8ee8bde09cca9f28f38cc251fb9efbd0f8adf32", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 13495, "license_type": "permissive", "max_line_length": 99, "num_lines": 389, "path": "/bindings/wallet-js/src/lib.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "//! JavaScript and TypeScript bindings for the Jormungandr wallet SDK.\n\nuse rand_chacha::rand_core::SeedableRng;\nuse rand_chacha::ChaCha20Rng;\nuse std::convert::TryInto;\nuse wasm_bindgen::prelude::*;\n\nmod utils;\n\npub use utils::set_panic_hook;\n\n// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global\n// allocator.\n#[cfg(feature = \"wee_alloc\")]\n#[global_allocator]\nstatic ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;\n\n/// A Wallet gives the user control over an account address\n/// controlled by a private key. It can also be used to convert other funds\n/// minted as UTxOs in the genesis block.\n#[wasm_bindgen]\npub struct Wallet(wallet_core::Wallet);\n\n/// Encapsulates blockchain settings needed for some operations.\n#[wasm_bindgen]\npub struct Settings(wallet_core::Settings);\n\n/// Information about a proposal in a vote plan deployed onto the blockchain.\n#[wasm_bindgen]\npub struct Proposal(wallet_core::Proposal);\n\n/// Identifier for a vote plan deployed onto the blockchain.\n#[wasm_bindgen]\npub struct VotePlanId([u8; wallet_core::VOTE_PLAN_ID_LENGTH]);\n\n#[wasm_bindgen]\npub struct Options(wallet_core::Options);\n\nimpl_secret_key!(\n Ed25519ExtendedPrivate,\n chain_crypto::Ed25519Extended,\n Ed25519Public\n);\nimpl_secret_key!(Ed25519Private, chain_crypto::Ed25519, Ed25519Public);\n\nimpl_public_key!(Ed25519Public, chain_crypto::Ed25519);\n\n/// Signature obtained with the Ed25519 algorithm.\n#[wasm_bindgen]\npub struct Ed25519Signature(chain_crypto::Signature<Box<[u8]>, chain_crypto::Ed25519>);\n\n/// Identifier of a block fragment, such as a vote transaction posted on the blockchain.\n#[wasm_bindgen]\npub struct FragmentId(wallet_core::FragmentId);\n\n/// A public key for the election protocol that is used to encrypt private ballots.\n#[wasm_bindgen]\npub struct ElectionPublicKey(chain_vote::ElectionPublicKey);\n\n/// this is used only for giving the Array a type in the typescript generated notation\n#[wasm_bindgen]\nextern \"C\" {\n #[wasm_bindgen(typescript_type = \"Array<FragmentId>\")]\n pub type FragmentIds;\n}\n\n#[wasm_bindgen]\npub struct BlockDate(chain_impl_mockchain::block::BlockDate);\n\n#[wasm_bindgen]\n#[derive(Clone)]\npub struct SpendingCounter(chain_impl_mockchain::account::SpendingCounter);\n\nimpl_collection!(SpendingCounters, SpendingCounter);\n\n#[wasm_bindgen]\nimpl Wallet {\n /// Imports private keys to create a wallet.\n ///\n /// The `account` parameter gives the Ed25519Extended private key\n /// of the account.\n ///\n /// The `keys` parameter should be a concatenation of Ed25519Extended\n /// private keys that will be used to retrieve the associated UTxOs.\n /// Pass an empty buffer when this functionality is not needed.\n pub fn import_keys(account: &[u8]) -> Result<Wallet, JsValue> {\n wallet_core::Wallet::recover_free_keys(account)\n .map_err(|e| JsValue::from(e.to_string()))\n .map(Wallet)\n }\n\n /// get the account ID bytes\n ///\n /// This ID is also the account public key, it can be used to retrieve the\n /// account state (the value, transaction counter etc...).\n pub fn id(&self) -> Vec<u8> {\n self.0.id().as_ref().to_vec()\n }\n\n /// Get the total value in the wallet.\n ///\n /// Make sure to call `retrieve_funds` prior to calling this function,\n /// otherwise the function will return `0`.\n pub fn total_value(&self) -> u64 {\n self.0.total_value().0\n }\n\n /// Update the wallet account state.\n ///\n /// The values to update the account state with can be retrieved from a\n /// node API endpoint. It sets the balance value on the account\n /// as well as the current spending counter.\n ///\n /// It is important to be sure to have an up to date wallet state\n /// before doing any transactions, otherwise future transactions may fail\n /// to be accepted by the blockchain nodes because of an invalid witness\n /// signature.\n pub fn set_state(&mut self, value: u64, counters: SpendingCounters) -> Result<(), JsValue> {\n self.0\n .set_state(\n wallet_core::Value(value),\n counters.0.into_iter().map(|c| c.0.into()).collect(),\n )\n .map_err(|e| JsValue::from(e.to_string()))\n }\n\n /// Cast a vote\n ///\n /// This function outputs a fragment containing a voting transaction.\n ///\n /// # Parameters\n ///\n /// * `settings` - ledger settings.\n /// * `proposal` - proposal information including the range of values\n /// allowed in `choice`.\n /// * `choice` - the option to vote for.\n /// * `valid_until` - the date until this transaction can be applied\n /// * `lane` - lane to use for the spending counter. Must be a number in the interval of [0, 7]\n ///\n /// # Errors\n ///\n /// The error is returned when `choice` does not fall withing the range of\n /// available choices specified in `proposal`.\n pub fn vote(\n &mut self,\n settings: &Settings,\n proposal: &Proposal,\n choice: u8,\n valid_until: &BlockDate,\n lane: u8,\n ) -> Result<Box<[u8]>, JsValue> {\n self.0\n .vote(\n settings.0.clone(),\n &proposal.0,\n wallet_core::Choice::new(choice),\n &valid_until.0,\n lane,\n )\n .map_err(|e| JsValue::from(e.to_string()))\n }\n\n /// Confirms that a transaction has been confirmed on the blockchain.\n ///\n /// This function will update the state of the wallet tracking pending\n /// transactions on fund conversion.\n pub fn confirm_transaction(&mut self, fragment: &FragmentId) {\n self.0.confirm_transaction(fragment.0);\n }\n}\n\n#[wasm_bindgen]\nimpl Proposal {\n /// Constructs a description of a public vote proposal from its constituent data.\n ///\n /// Parameters:\n /// * `vote_plan_id`: Identifier of the vote plan.\n /// * `index`: 0-based index of the proposal in the vote plan.\n /// * `options`: Descriptor of vote plan options, detailing the number of choices.\n pub fn new_public(vote_plan_id: VotePlanId, index: u8, options: Options) -> Self {\n Proposal(wallet_core::Proposal::new(\n vote_plan_id.0.into(),\n index,\n options.0,\n wallet_core::PayloadTypeConfig::Public,\n ))\n }\n\n /// Constructs a description of a private vote proposalfrom its constituent data.\n ///\n /// Parameters:\n /// * `vote_plan_id`: Identifier of the vote plan.\n /// * `index`: 0-based index of the proposal in the vote plan.\n /// * `options`: Descriptor of vote plan options, detailing the number of choices.\n /// * `election_key`: The public key for the vote plan used to encrypt ballots.\n pub fn new_private(\n vote_plan_id: VotePlanId,\n index: u8,\n options: Options,\n election_key: ElectionPublicKey,\n ) -> Self {\n Proposal(wallet_core::Proposal::new_private(\n vote_plan_id.0.into(),\n index,\n options.0,\n election_key.0,\n ))\n }\n}\n\n#[wasm_bindgen]\nimpl VotePlanId {\n /// Constructs a VotePlanId value from its byte array representation.\n pub fn from_bytes(bytes: &[u8]) -> Result<VotePlanId, JsValue> {\n let array: [u8; wallet_core::VOTE_PLAN_ID_LENGTH] = bytes\n .try_into()\n .map_err(|_| JsValue::from_str(\"Invalid vote plan id length\"))?;\n\n Ok(VotePlanId(array))\n }\n\n /// Deprecated; use `from_bytes`.\n pub fn new_from_bytes(bytes: &[u8]) -> Result<VotePlanId, JsValue> {\n Self::from_bytes(bytes)\n }\n}\n\n#[wasm_bindgen]\nimpl Options {\n pub fn new_length(length: u8) -> Result<Options, JsValue> {\n wallet_core::Options::new_length(length)\n .map_err(|e| JsValue::from(e.to_string()))\n .map(Options)\n }\n}\n\n#[wasm_bindgen]\nimpl Ed25519Signature {\n /// Constructs a signature object from its byte array representation.\n pub fn from_bytes(signature: &[u8]) -> Result<Ed25519Signature, JsValue> {\n chain_crypto::Signature::from_binary(signature)\n .map(Self)\n .map_err(|e| JsValue::from_str(&format!(\"Invalid signature {}\", e)))\n }\n\n /// Deprecated; use `from_bytes`.\n pub fn from_binary(signature: &[u8]) -> Result<Ed25519Signature, JsValue> {\n Self::from_bytes(signature)\n }\n\n /// Returns a byte array representation of the signature.\n pub fn to_bytes(&self) -> Box<[u8]> {\n self.0.as_ref().into()\n }\n}\n\n#[macro_export]\nmacro_rules! impl_public_key {\n ($name:ident, $wrapped_type:ty) => {\n #[wasm_bindgen]\n pub struct $name(chain_crypto::PublicKey<$wrapped_type>);\n\n #[wasm_bindgen]\n impl $name {\n /// Returns a byte array representation of the public key.\n // TODO: rename to `to_bytes` for harmonization with the rest of the API?\n pub fn bytes(&self) -> Box<[u8]> {\n self.0.as_ref().into()\n }\n\n /// Returns the key formatted as a string in Bech32 format.\n pub fn bech32(&self) -> String {\n use chain_crypto::bech32::Bech32 as _;\n self.0.to_bech32_str()\n }\n\n /// Uses the given signature to verify the given message.\n pub fn verify(&self, signature: &Ed25519Signature, msg: &[u8]) -> bool {\n let verification = signature.0.verify_slice(&self.0, msg);\n match verification {\n chain_crypto::Verification::Success => true,\n chain_crypto::Verification::Failed => false,\n }\n }\n }\n };\n}\n\n/// macro arguments:\n/// the exported name of the type\n/// the inner/mangled key type\n/// the name of the exported public key associated type\n#[macro_export]\nmacro_rules! impl_secret_key {\n ($name:ident, $wrapped_type:ty, $public:ident) => {\n #[wasm_bindgen]\n pub struct $name(chain_crypto::SecretKey<$wrapped_type>);\n\n #[wasm_bindgen]\n impl $name {\n /// Generates the key using OS-provided entropy.\n pub fn generate() -> $name {\n Self(chain_crypto::SecretKey::<$wrapped_type>::generate(\n rand::rngs::OsRng,\n ))\n }\n\n /// Generates the key from a seed value.\n /// For the same entropy value of 32 bytes, the same key will be generated.\n /// This seed will be fed to ChaChaRNG and allow pseudo random key generation.\n /// Do not use if you are not sure.\n pub fn from_seed(seed: &[u8]) -> Result<$name, JsValue> {\n let seed: [u8; 32] = seed\n .try_into()\n .map_err(|_| JsValue::from_str(\"Invalid seed, expected 32 bytes\"))?;\n\n let rng = ChaCha20Rng::from_seed(seed);\n\n Ok(Self(chain_crypto::SecretKey::<$wrapped_type>::generate(\n rng,\n )))\n }\n\n /// Returns the public key corresponding to this secret key.\n pub fn public(&self) -> $public {\n $public(self.0.to_public())\n }\n\n /// Returns the key represented by an array of bytes.\n /// Use with care: the secret key should not be revealed to external\n /// observers or exposed to untrusted code.\n // TODO: rename to leak_bytes() to emphasize the security caveats?\n pub fn bytes(&self) -> Box<[u8]> {\n self.0.clone().leak_secret().as_ref().into()\n }\n\n /// Signs the provided message with this secret key.\n pub fn sign(&self, msg: &[u8]) -> Ed25519Signature {\n Ed25519Signature::from_bytes(self.0.sign(&msg).as_ref()).unwrap()\n }\n }\n };\n}\n\n#[wasm_bindgen]\nimpl FragmentId {\n /// Constructs a fragment identifier from its byte array representation.\n pub fn from_bytes(bytes: &[u8]) -> Result<FragmentId, JsValue> {\n let array: [u8; std::mem::size_of::<wallet_core::FragmentId>()] = bytes\n .try_into()\n .map_err(|_| JsValue::from_str(\"Invalid fragment id\"))?;\n\n Ok(FragmentId(array.into()))\n }\n\n /// Deprecated; use `from_bytes`.\n pub fn new_from_bytes(bytes: &[u8]) -> Result<FragmentId, JsValue> {\n Self::from_bytes(bytes)\n }\n\n /// Returns a byte array representation of the fragment identifier.\n pub fn to_bytes(&self) -> Vec<u8> {\n self.0.as_bytes().to_vec()\n }\n}\n\n#[wasm_bindgen]\nimpl ElectionPublicKey {\n /// Constructs a key from its byte array representation.\n pub fn from_bytes(bytes: &[u8]) -> Result<ElectionPublicKey, JsValue> {\n chain_vote::ElectionPublicKey::from_bytes(bytes)\n .ok_or_else(|| JsValue::from_str(\"invalid binary format\"))\n .map(Self)\n }\n\n /// Decodes the key from a string in Bech32 format.\n pub fn from_bech32(bech32_str: &str) -> Result<ElectionPublicKey, JsValue> {\n use chain_crypto::bech32::Bech32;\n chain_vote::ElectionPublicKey::try_from_bech32_str(bech32_str)\n .map_err(|e| JsValue::from_str(&format!(\"invalid bech32 string {}\", e)))\n .map(Self)\n }\n}\n\n#[wasm_bindgen]\npub fn symmetric_decrypt(password: &[u8], data: &[u8]) -> Result<Box<[u8]>, JsValue> {\n symmetric_cipher::decrypt(password, data)\n .map_err(|e| JsValue::from_str(&format!(\"decryption failed {}\", e)))\n}\n" }, { "alpha_fraction": 0.57660311460495, "alphanum_fraction": 0.5791798830032349, "avg_line_length": 29.251670837402344, "blob_id": "f6ff4c4f7cb68d679c363d75562dbb8193cff981", "content_id": "d8a249898c0deda7516d96448596f0139be28ab8", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 13583, "license_type": "permissive", "max_line_length": 100, "num_lines": 449, "path": "/bindings/wallet-core/src/error.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use std::{\n error,\n fmt::{self, Display},\n result,\n};\n\n/// result returned by a call, this allows to check if an error\n/// occurred while executing the function.\n///\n/// if an error occurred it is then possible to collect more information\n/// about the kind of error as well as details from the underlying libraries\n/// that may be useful in case of bug reports or to figure out why the inputs\n/// were not valid and resulted in the function to return with error\n#[must_use = \"ignoring this may result in ignoring an error\"]\npub struct Result(result::Result<(), Error>);\n\n/// The error structure, contains details of what may have gone wrong\n///\n/// See the error's kind for the high level information of what went wrong,\n/// it is also possible to then extract details (if any) of the error.\n///\n#[derive(Debug)]\npub struct Error {\n kind: ErrorKind,\n details: Option<Box<dyn error::Error + Send + Sync + 'static>>,\n}\n\n/// a code representing the kind of error that occurred\n#[repr(u32)]\npub enum ErrorCode {\n /// the input was not valid, it may be because it was a null pointer\n /// where it was expected to be already allocated. See the details\n /// for more information.\n ///\n /// When this kind of error occurs it is likely a developer flow issue\n /// rather than a user input issue. See the error details for more\n /// details.\n InvalidInput = 1,\n\n /// an error occurred while recovering a wallet\n WalletRecovering = 2,\n\n /// the operation on the wallet conversion object fail, it may be\n /// an out of bound operation when attempting to access the `nth`\n /// transaction of the conversion.\n WalletConversion = 3,\n\n /// the provided voting choice is out of the allowed range\n WalletVoteOutOfRange = 4,\n\n /// the wallet failed to build a valid transaction, for example\n /// not enough funds available\n WalletTransactionBuilding = 5,\n\n /// error encrypting or decrypting transfer protocol payload\n SymmetricCipherError = 6,\n\n /// authentication failed\n SymmetricCipherInvalidPassword = 7,\n\n /// vote encryption key is invalid\n /// either because is not valid bech32, or because of the underlying bytes\n InvalidVoteEncryptionKey = 8,\n\n /// wallet out of funds\n NotEnoughFunds = 9,\n\n /// invalid fragment\n InvalidFragment = 10,\n\n /// invalid transaction validity date, it's either before the current blockchain or after the\n /// maximum possible interval\n InvalidTransactionValidityDate = 11,\n\n /// invalid spending counters provided to the set_state function\n InvalidSpendingCounters = 12,\n}\n\n#[derive(Debug)]\npub enum ErrorKind {\n /// kind of error where the input (named `argument_name`) is of\n /// invalid format or of unexpected value (null pointer).\n ///\n /// The `details` should provide more info on what caused the error.\n InvalidInput { argument_name: &'static str },\n\n /// an error occurred while recovering a wallet\n WalletRecovering,\n\n /// This is the kind of error that may happen when operating\n /// the transactions of the wallet conversion. For example,\n /// there may be an out of bound error\n WalletConversion,\n\n /// the provided voting choice is out of the allowed range\n WalletVoteOutOfRange,\n\n /// the wallet failed to build a valid transaction\n WalletTransactionBuilding,\n\n /// format error (malformed input, etc...)\n SymmetricCipherError,\n\n /// authentication failed\n SymmetricCipherInvalidPassword,\n\n /// vote encryption key is invalid\n /// either because is not valid bech32, or because of the underlying bytes\n InvalidVoteEncryptionKey,\n\n /// wallet out of funds\n NotEnoughFunds,\n\n /// invalid fragment\n InvalidFragment,\n\n /// invalid transaction validity date\n InvalidTransactionValidityDate,\n\n /// invalid spending counters provided to the set_state function\n InvalidSpendingCounters,\n}\n\nimpl ErrorKind {\n /// retrieve the error code associated to the error kind\n ///\n /// useful to extract the kind of error that occurred in a portable\n /// way, without to use string encoded version of the `ErrorKind`.\n pub fn code(&self) -> ErrorCode {\n match self {\n Self::InvalidInput { .. } => ErrorCode::InvalidInput,\n Self::WalletRecovering => ErrorCode::WalletRecovering,\n Self::WalletConversion => ErrorCode::WalletConversion,\n Self::WalletVoteOutOfRange => ErrorCode::WalletVoteOutOfRange,\n Self::WalletTransactionBuilding => ErrorCode::WalletTransactionBuilding,\n Self::SymmetricCipherError => ErrorCode::SymmetricCipherError,\n Self::SymmetricCipherInvalidPassword => ErrorCode::SymmetricCipherInvalidPassword,\n Self::InvalidVoteEncryptionKey => ErrorCode::InvalidVoteEncryptionKey,\n Self::NotEnoughFunds => ErrorCode::NotEnoughFunds,\n Self::InvalidFragment => ErrorCode::InvalidFragment,\n Self::InvalidTransactionValidityDate => ErrorCode::InvalidTransactionValidityDate,\n Self::InvalidSpendingCounters => ErrorCode::InvalidSpendingCounters,\n }\n }\n}\n\nimpl Error {\n /// access the error kind\n pub fn kind(&self) -> &ErrorKind {\n &self.kind\n }\n\n /// if there are details return the pointer to the error type that triggered\n /// the error.\n ///\n /// this is useful to display more details as to why an error occurred.\n pub fn details(&self) -> Option<&(dyn error::Error + Send + Sync + 'static)> {\n self.details.as_ref().map(|boxed| boxed.as_ref())\n }\n\n /// construct a Result which is an error with invalid inputs\n ///\n /// `argument_name` is expected to be a pointer to the parameter name.\n ///\n /// # example\n ///\n /// ```\n /// # use wallet_core::{Result, Error};\n /// # use thiserror::Error;\n /// # #[derive(Error, Debug)]\n /// # #[error(\"Unexpected null pointer\")]\n /// # struct NulPointer;\n /// fn example(pointer: *mut u8) -> Result {\n /// if pointer.is_null() {\n /// Error::invalid_input(\"pointer\")\n /// .with(NulPointer)\n /// .into()\n /// } else {\n /// Result::success()\n /// }\n /// }\n ///\n /// let result = example(std::ptr::null_mut());\n ///\n /// assert!(result.is_err());\n /// # assert!(!result.is_ok());\n /// ```\n pub fn invalid_input(argument_name: &'static str) -> Self {\n Self {\n kind: ErrorKind::InvalidInput { argument_name },\n details: None,\n }\n }\n\n pub fn wallet_recovering() -> Self {\n Self {\n kind: ErrorKind::WalletRecovering,\n details: None,\n }\n }\n\n pub fn wallet_conversion() -> Self {\n Self {\n kind: ErrorKind::WalletConversion,\n details: None,\n }\n }\n\n pub fn wallet_vote_range() -> Self {\n Self {\n kind: ErrorKind::WalletVoteOutOfRange,\n details: None,\n }\n }\n\n pub fn wallet_transaction() -> Self {\n Self {\n kind: ErrorKind::WalletTransactionBuilding,\n details: None,\n }\n }\n\n pub fn symmetric_cipher_error(err: symmetric_cipher::Error) -> Self {\n let kind = match err {\n symmetric_cipher::Error::AuthenticationFailed => {\n ErrorKind::SymmetricCipherInvalidPassword\n }\n _ => ErrorKind::SymmetricCipherError,\n };\n\n Self {\n kind,\n details: None,\n }\n }\n\n pub fn invalid_vote_encryption_key() -> Self {\n Self {\n kind: ErrorKind::InvalidVoteEncryptionKey,\n details: None,\n }\n }\n\n pub fn not_enough_funds() -> Self {\n Self {\n kind: ErrorKind::NotEnoughFunds,\n details: None,\n }\n }\n\n pub fn invalid_fragment() -> Self {\n Self {\n kind: ErrorKind::InvalidFragment,\n details: None,\n }\n }\n\n pub fn invalid_transaction_validity_date() -> Self {\n Self {\n kind: ErrorKind::InvalidTransactionValidityDate,\n details: None,\n }\n }\n\n pub fn invalid_spending_counters() -> Self {\n Self {\n kind: ErrorKind::InvalidSpendingCounters,\n details: None,\n }\n }\n\n /// set some details to the `Result` object if the `Result` is of\n /// error kind\n ///\n /// If the `Result` means success, then nothing is returned.\n ///\n /// # Example\n ///\n /// ```\n /// # use wallet_core::{Result, Error};\n /// # use thiserror::Error;\n /// # #[derive(Error, Debug)]\n /// # #[error(\"Unexpected null pointer\")]\n /// # struct NulPointer;\n /// fn example(pointer: *mut u8) -> Result {\n /// if pointer.is_null() {\n /// Error::invalid_input(\"pointer\").into()\n /// } else {\n /// Result::success()\n /// }\n /// }\n ///\n /// let mut input = 2;\n /// let input: *mut u8 = &mut 2;\n /// let result = example(input).with(NulPointer);\n ///\n /// # assert!(!result.is_err());\n /// assert!(result.is_ok());\n /// ```\n ///\n pub fn with<E>(self, details: E) -> Self\n where\n E: error::Error + Send + Sync + 'static,\n {\n Self {\n details: Some(Box::new(details)),\n ..self\n }\n }\n}\n\nimpl Result {\n /// returns `true` if the `Result` means success\n pub fn is_ok(&self) -> bool {\n self.0.is_ok()\n }\n\n /// returns `true` if the `Result` means error\n pub fn is_err(&self) -> bool {\n self.0.is_err()\n }\n\n /// if it is an error, this function will returns the the error object,\n /// otherwise it will return `None`\n pub fn error(&self) -> Option<&Error> {\n self.0.as_ref().err()\n }\n\n /// constructor to build a `Result` that means success\n ///\n /// # example\n ///\n /// ```\n /// # use wallet_core::Result;\n ///\n /// let result = Result::success();\n ///\n /// assert!(result.is_ok());\n /// # assert!(!result.is_err());\n /// ```\n pub fn success() -> Self {\n Self(Ok(()))\n }\n\n /// set some details to the `Result` object if the `Result` is of\n /// error kind\n ///\n /// If the `Result` means success, then nothing is returned.\n ///\n /// # Example\n ///\n /// ```\n /// # use wallet_core::{Result, Error};\n /// # use thiserror::Error;\n /// # #[derive(Error, Debug)]\n /// # #[error(\"Unexpected null pointer\")]\n /// # struct NulPointer;\n /// fn example(pointer: *mut u8) -> Result {\n /// if pointer.is_null() {\n /// Error::invalid_input(\"pointer\").into()\n /// } else {\n /// Result::success()\n /// }\n /// }\n ///\n /// let mut input = 2;\n /// let input: *mut u8 = &mut 2;\n /// let result = example(input).with(NulPointer);\n ///\n /// # assert!(!result.is_err());\n /// assert!(result.is_ok());\n /// ```\n ///\n pub fn with<E>(self, details: E) -> Self\n where\n E: error::Error + Send + Sync + 'static,\n {\n match self.0 {\n Ok(()) => Self::success(),\n Err(mut err) => {\n err.details = Some(Box::new(details));\n Self(Err(err))\n }\n }\n }\n\n pub fn into_c_api(self) -> *mut Error {\n match self.0 {\n Ok(()) => std::ptr::null_mut(),\n Err(err) => Box::into_raw(Box::new(err)),\n }\n }\n}\n\nimpl Display for ErrorKind {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Self::InvalidInput { argument_name } => {\n write!(f, \"The argument '{}' is invalid.\", argument_name)\n }\n Self::WalletRecovering => f.write_str(\"Error while recovering a wallet\"),\n Self::WalletConversion => {\n f.write_str(\"Error while performing operation on the wallet conversion object\")\n }\n Self::WalletVoteOutOfRange => {\n f.write_str(\"The provided choice is out of the vote variants range\")\n }\n Self::WalletTransactionBuilding => f.write_str(\n \"Failed to build a valid transaction, probably not enough funds available\",\n ),\n Self::SymmetricCipherError => f.write_str(\"malformed encryption or decryption payload\"),\n Self::SymmetricCipherInvalidPassword => f.write_str(\"invalid decryption password\"),\n Self::InvalidVoteEncryptionKey => f.write_str(\"invalid vote encryption key\"),\n Self::NotEnoughFunds => f.write_str(\"not enough funds to create transaction\"),\n Self::InvalidFragment => f.write_str(\"invalid fragment\"),\n Self::InvalidTransactionValidityDate => {\n f.write_str(\"invalid transaction validity date\")\n }\n Self::InvalidSpendingCounters => {\n f.write_str(\"invalid spending counters provided to the set account state function\")\n }\n }\n }\n}\n\nimpl Display for Error {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n self.kind.fmt(f)\n }\n}\n\nimpl error::Error for Error {\n fn source(&self) -> Option<&(dyn error::Error + 'static)> {\n self.details()\n .map(|trait_object| trait_object as &dyn error::Error)\n }\n}\n\nimpl From<Error> for Result {\n fn from(error: Error) -> Self {\n Self(Err(error))\n }\n}\n\nimpl From<result::Result<(), Error>> for Result {\n fn from(result: result::Result<(), Error>) -> Self {\n Self(result)\n }\n}\n" }, { "alpha_fraction": 0.6194690465927124, "alphanum_fraction": 0.6253687143325806, "avg_line_length": 17.83333396911621, "blob_id": "c73895251b8cc787f8b1076028fc4414effb4aa6", "content_id": "5657f044e0e2fea24b8fa2e89aab13ba9889d7d2", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 339, "license_type": "permissive", "max_line_length": 67, "num_lines": 18, "path": "/Cargo.toml", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "[workspace]\nmembers = [\n \"bip39\",\n \"chain-path-derivation\",\n \"hdkeygen\",\n \"wallet\",\n \"symmetric-cipher\",\n \"bindings/wallet-c\",\n \"bindings/wallet-js\",\n \"bindings/wallet-uniffi\",\n]\n\n[profile.release]\nlto = \"yes\"\nstrip = \"symbols\"\n\n[patch.crates-io]\ncryptoxide = { git = \"https://github.com/typed-io/cryptoxide.git\" }\n" }, { "alpha_fraction": 0.5451797842979431, "alphanum_fraction": 0.5593835115432739, "avg_line_length": 28.026315689086914, "blob_id": "6e7cc6672ce1ddefb4d4c09ba91cc91d09f29874", "content_id": "2a85324b7efc464a35e914a0d2f17c6cb2e0d8cd", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 3309, "license_type": "permissive", "max_line_length": 137, "num_lines": 114, "path": "/bip39/src/seed.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use crate::{Error, MnemonicString, Result};\nuse cryptoxide::hmac::Hmac;\nuse cryptoxide::pbkdf2::pbkdf2;\nuse cryptoxide::sha2::Sha512;\nuse std::ops::Deref;\n\n/// the expected size of a seed, in bytes.\npub const SEED_SIZE: usize = 64;\n\n/// A BIP39 `Seed` object, will be used to generate a given HDWallet\n/// root key.\n///\n/// See the module documentation for more details about how to use it\n/// within the `chain_wallet` library.\n#[derive(zeroize::ZeroizeOnDrop)]\npub struct Seed([u8; SEED_SIZE]);\n\nimpl Seed {\n /// create a Seed by taking ownership of the given array\n ///\n /// # Example\n ///\n /// ```\n /// use bip39::*;\n ///\n /// let bytes = [0u8;SEED_SIZE];\n /// let seed = Seed::from_bytes(bytes);\n ///\n /// assert!(seed.as_ref().len() == SEED_SIZE);\n /// ```\n pub fn from_bytes(buf: [u8; SEED_SIZE]) -> Self {\n Seed(buf)\n }\n\n /// create a Seed by copying the given slice into a new array\n ///\n /// # Example\n ///\n /// ```\n /// use bip39::*;\n ///\n /// let bytes = [0u8;SEED_SIZE];\n /// let wrong = [0u8;31];\n ///\n /// assert!(Seed::from_slice(&wrong[..]).is_err());\n /// assert!(Seed::from_slice(&bytes[..]).is_ok());\n /// ```\n ///\n /// # Error\n ///\n /// This constructor may fail if the given slice's length is not\n /// compatible to define a `Seed` (see [`SEED_SIZE`](./constant.SEED_SIZE.html)).\n ///\n pub fn from_slice(buf: &[u8]) -> Result<Self> {\n if buf.len() != SEED_SIZE {\n return Err(Error::InvalidSeedSize(buf.len()));\n }\n let mut v = [0u8; SEED_SIZE];\n v[..].clone_from_slice(buf);\n Ok(Seed::from_bytes(v))\n }\n\n /// get the seed from the given [`MnemonicString`] and the given password.\n ///\n /// [`MnemonicString`]: ./struct.MnemonicString.html\n ///\n /// Note that the `Seed` is not generated from the `Entropy` directly. It is a\n /// design choice of Bip39.\n ///\n /// # Safety\n ///\n /// The password is meant to allow plausible deniability. While it is possible\n /// not to use a password to protect the HDWallet it is better to add one.\n ///\n /// # Example\n ///\n /// ```\n /// # use bip39::*;\n ///\n /// const MNEMONICS : &'static str = \"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about\";\n /// let mnemonics = MnemonicString::new(&dictionary::ENGLISH, MNEMONICS.to_owned())\n /// .expect(\"valid Mnemonic phrase\");\n ///\n /// let seed = Seed::from_mnemonic_string(&mnemonics, b\"Bourbaki team rocks!\");\n /// ```\n ///\n pub fn from_mnemonic_string(mnemonics: &MnemonicString, password: &[u8]) -> Self {\n let mut salt = Vec::from(\"mnemonic\");\n salt.extend_from_slice(password);\n let mut mac = Hmac::new(Sha512::new(), mnemonics.as_bytes());\n let mut result = [0; SEED_SIZE];\n pbkdf2(&mut mac, &salt, 2048, &mut result);\n Self::from_bytes(result)\n }\n}\n\nimpl PartialEq for Seed {\n fn eq(&self, other: &Self) -> bool {\n self.0.as_ref() == other.0.as_ref()\n }\n}\n\nimpl AsRef<[u8]> for Seed {\n fn as_ref(&self) -> &[u8] {\n &self.0\n }\n}\n\nimpl Deref for Seed {\n type Target = [u8];\n fn deref(&self) -> &Self::Target {\n self.as_ref()\n }\n}\n" }, { "alpha_fraction": 0.6071428656578064, "alphanum_fraction": 0.6469155550003052, "avg_line_length": 38.74193572998047, "blob_id": "67d6428fa9910175d57cafc727b852c877eef495", "content_id": "e609182076506afd1bc8bb104fb015465e053e14", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 1232, "license_type": "permissive", "max_line_length": 105, "num_lines": 31, "path": "/wallet/Cargo.toml", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "[package]\nname = \"wallet\"\nversion = \"0.6.0-pre.1\"\nauthors = [\"Nicolas Di Prima <[email protected]>\", \"Vincent Hanquez <[email protected]>\"]\nedition = \"2018\"\nlicense = \"MIT OR Apache-2.0\"\n\n[dependencies]\ncryptoxide = \"0.4.2\"\ned25519-bip32 = \"0.4.0\"\ncbor_event = \"^2.1.3\"\nthiserror = { version = \"1.0.13\", default-features = false }\nbip39 = { path = \"../bip39\" }\nchain-path-derivation = { path = \"../chain-path-derivation\" }\nhdkeygen = { path = \"../hdkeygen\" }\nhex = \"0.4.2\"\nitertools = \"0.9\"\nhashlink = \"0.7.0\"\nzeroize = \"1.5.3\"\n\nchain-time = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-crypto = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-addr = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-impl-mockchain = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\ncardano-legacy-address = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nimhamt = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\n\n[dev-dependencies]\nquickcheck = \"0.9\"\nquickcheck_macros = \"0.9\"\nchain-ser = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\n" }, { "alpha_fraction": 0.5416245460510254, "alphanum_fraction": 0.5463430881500244, "avg_line_length": 30.676156997680664, "blob_id": "d80c53919a3e62dc8ffeff209d663347a8ac1b49", "content_id": "fd64682b2cdbc8a86f5c98016a30b50e0332122c", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 8901, "license_type": "permissive", "max_line_length": 100, "num_lines": 281, "path": "/wallet/src/account.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use super::transaction::AccountWitnessBuilder;\nuse crate::scheme::{on_tx_input_and_witnesses, on_tx_output};\nuse crate::states::States;\nuse chain_crypto::{Ed25519, Ed25519Extended, PublicKey, SecretKey};\nuse chain_impl_mockchain::accounting::account::SpendingCounterIncreasing;\nuse chain_impl_mockchain::{\n account::SpendingCounter,\n fragment::{Fragment, FragmentId},\n transaction::{Input, InputEnum},\n value::Value,\n};\npub use hdkeygen::account::AccountId;\nuse hdkeygen::account::{Account, Seed};\nuse thiserror::Error;\n\npub const MAX_LANES: usize = 8;\n\npub struct Wallet {\n account: EitherAccount,\n state: States<FragmentId, State>,\n}\n\n#[derive(Debug, Default)]\npub struct State {\n value: Value,\n counters: SpendingCounterIncreasing,\n}\n\npub struct WalletBuildTx<'a> {\n wallet: &'a mut Wallet,\n needed_input: Value,\n next_value: Value,\n current_counter: SpendingCounter,\n}\n\n#[derive(Debug, Error)]\npub enum Error {\n #[error(\"not enough funds, needed {needed:?}, available {current:?}\")]\n NotEnoughFunds { current: Value, needed: Value },\n #[error(\"invalid lane for spending counter\")]\n InvalidLane,\n #[error(\"malformed spending counters\")]\n MalformedSpendingCounters,\n #[error(\"spending counter does not match current state\")]\n NonMonotonicSpendingCounter,\n}\n\nenum EitherAccount {\n Seed(Account<Ed25519>),\n Extended(Account<Ed25519Extended>),\n}\n\nimpl Wallet {\n pub fn new_from_seed(seed: Seed) -> Wallet {\n Wallet {\n account: EitherAccount::Seed(Account::from_seed(seed)),\n state: States::new(FragmentId::zero_hash(), Default::default()),\n }\n }\n\n pub fn new_from_key(key: SecretKey<Ed25519Extended>) -> Wallet {\n Wallet {\n account: EitherAccount::Extended(Account::from_secret_key(key)),\n state: States::new(FragmentId::zero_hash(), Default::default()),\n }\n }\n\n pub fn account_id(&self) -> AccountId {\n match &self.account {\n EitherAccount::Extended(account) => account.account_id(),\n EitherAccount::Seed(account) => account.account_id(),\n }\n }\n\n /// set the state counter so we can sync with the blockchain and the\n /// local state\n ///\n /// TODO: some handling to provide information if needed:\n ///\n /// - [ ] check the counter is not regressing?\n /// - [ ] check that there is continuity?\n ///\n /// TODO: change to a constructor/initializator?, or just make it so it resets the state\n ///\n pub fn set_state(&mut self, value: Value, counters: Vec<SpendingCounter>) -> Result<(), Error> {\n let counters = SpendingCounterIncreasing::new_from_counters(counters)\n .ok_or(Error::MalformedSpendingCounters)?;\n\n self.state = States::new(FragmentId::zero_hash(), State { value, counters });\n\n Ok(())\n }\n\n pub fn spending_counter(&self) -> Vec<SpendingCounter> {\n self.state\n .last_state()\n .state()\n .counters\n .get_valid_counters()\n }\n\n pub fn value(&self) -> Value {\n self.state.last_state().state().value\n }\n\n /// confirm a pending transaction\n ///\n /// to only do once it is confirmed a transaction is on chain\n /// and is far enough in the blockchain history to be confirmed\n /// as immutable\n ///\n pub fn confirm(&mut self, fragment_id: &FragmentId) {\n self.state.confirm(fragment_id);\n }\n\n /// get all the pending transactions of the wallet\n ///\n /// If empty it means there's no pending transactions waiting confirmation\n ///\n pub fn pending_transactions(&self) -> impl Iterator<Item = &FragmentId> {\n self.state.unconfirmed_states().map(|(k, _)| k)\n }\n\n /// get the confirmed value of the wallet\n pub fn confirmed_value(&self) -> Value {\n self.state.confirmed_state().state().value\n }\n\n /// get the unconfirmed value of the wallet\n ///\n /// if `None`, it means there is no unconfirmed state of the wallet\n /// and the value can be known from `confirmed_value`.\n ///\n /// The returned value is the value we expect to see at some point on\n /// chain once all transactions are on chain confirmed.\n pub fn unconfirmed_value(&self) -> Option<Value> {\n let s = self.state.last_state();\n\n if s.is_confirmed() {\n None\n } else {\n Some(s.state().value)\n }\n }\n\n pub fn new_transaction(\n &mut self,\n needed_input: Value,\n lane: u8,\n ) -> Result<WalletBuildTx, Error> {\n let state = self.state.last_state().state();\n\n let current_counter = *state\n .counters\n .get_valid_counters()\n .get(lane as usize)\n .ok_or(Error::InvalidLane)?;\n\n let next_value =\n state\n .value\n .checked_sub(needed_input)\n .map_err(|_| Error::NotEnoughFunds {\n current: state.value,\n needed: needed_input,\n })?;\n\n Ok(WalletBuildTx {\n wallet: self,\n needed_input,\n current_counter,\n next_value,\n })\n }\n\n pub fn check_fragment(\n &mut self,\n fragment_id: &FragmentId,\n fragment: &Fragment,\n ) -> Result<bool, Error> {\n if self.state.contains(fragment_id) {\n return Ok(true);\n }\n\n let state = self.state.last_state().state();\n\n let mut new_value = state.value;\n\n let mut increment_counter = None;\n let mut at_least_one_output = false;\n\n match fragment {\n Fragment::Initial(_config_params) => {}\n Fragment::UpdateProposal(_update_proposal) => {}\n Fragment::UpdateVote(_signed_update) => {}\n Fragment::OldUtxoDeclaration(_utxos) => {}\n _ => {\n on_tx_input_and_witnesses(fragment, |(input, witness)| {\n if let InputEnum::AccountInput(id, input_value) = input.to_enum() {\n if self.account_id().as_ref() == id.as_ref() {\n new_value = new_value.checked_sub(input_value).expect(\"value overflow\");\n\n match witness {\n chain_impl_mockchain::transaction::Witness::Account(\n spending,\n _,\n ) => increment_counter = Some(spending),\n _ => unreachable!(\"wrong witness type in account input\"),\n }\n }\n }\n });\n on_tx_output(fragment, |(_, output)| {\n if output\n .address\n .public_key()\n .map(|pk| *pk == Into::<PublicKey<Ed25519>>::into(self.account_id()))\n .unwrap_or(false)\n {\n new_value = new_value.checked_add(output.value).unwrap();\n at_least_one_output = true;\n }\n })\n }\n };\n\n let counters = if let Some(counter) = increment_counter {\n let mut new = state.counters.clone();\n new.next_verify(counter)\n .map_err(|_| Error::NonMonotonicSpendingCounter)?;\n new\n } else {\n state.counters.clone()\n };\n\n let new_state = State {\n counters,\n value: new_value,\n };\n\n self.state.push(*fragment_id, new_state);\n\n Ok(at_least_one_output || increment_counter.is_some())\n }\n}\n\nimpl<'a> WalletBuildTx<'a> {\n pub fn input(&self) -> Input {\n Input::from_account_public_key(self.wallet.account_id().into(), self.needed_input)\n }\n\n pub fn witness_builder(&self) -> AccountWitnessBuilder {\n match &self.wallet.account {\n EitherAccount::Seed(account) => crate::transaction::AccountWitnessBuilder::Ed25519(\n account.secret().clone(),\n self.current_counter,\n ),\n EitherAccount::Extended(account) => {\n crate::transaction::AccountWitnessBuilder::Ed25519Extended(\n account.secret().clone(),\n self.current_counter,\n )\n }\n }\n }\n\n pub fn add_fragment_id(self, fragment_id: FragmentId) {\n let mut counters = self.wallet.state.last_state().state().counters.clone();\n\n // the counter comes from the current state, so this shouldn't panic\n counters.next_verify(self.current_counter).unwrap();\n\n self.wallet.state.push(\n fragment_id,\n State {\n value: self.next_value,\n counters,\n },\n );\n }\n}\n" }, { "alpha_fraction": 0.487458199262619, "alphanum_fraction": 0.4899665415287018, "avg_line_length": 21.148147583007812, "blob_id": "7c4459ff9b5033c1ad2c2f1497ec53558864fe41", "content_id": "0d0df57ebb015b85d82b8c6c363e780687c8b586", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1196, "license_type": "permissive", "max_line_length": 68, "num_lines": 54, "path": "/bindings/wallet-cordova/scripts/copy_jni_definitions.py", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom pathlib import Path\nimport subprocess\nimport sys\nimport shutil\nfrom directories import repository_directory, plugin_directory\n\n\ndef run():\n if (\n subprocess.run(\n [\n \"uniffi-bindgen\",\n \"generate\",\n \"-l\",\n \"kotlin\",\n \"src/lib.udl\",\n \"--config-path\",\n \"uniffi.toml\",\n \"-o\",\n \"codegen/kotlin\",\n ],\n cwd=repository_directory / \"bindings\" / \"wallet-uniffi\",\n ).returncode\n != 0\n ):\n print(\"couldn't build kotlin bindings\")\n sys.exit(1)\n\n src_files = (\n repository_directory\n / \"bindings\"\n / \"wallet-uniffi\"\n / \"codegen\"\n / \"kotlin\"\n / \"com\"\n / \"iohk\"\n / \"jormungandr_wallet\"\n ).glob(\"*kt\")\n\n dst = plugin_directory / Path(\"src/android/\")\n dst.mkdir(parents=True, exist_ok=True)\n\n print(\"Copy kotlin definitions from uniffi\")\n print(f\"destination: {dst}\")\n\n for file in src_files:\n print(f\"copy file: {file}\")\n shutil.copy(file, dst)\n\n\nif __name__ == \"__main__\":\n run()\n" }, { "alpha_fraction": 0.5963733792304993, "alphanum_fraction": 0.6467427611351013, "avg_line_length": 25.589284896850586, "blob_id": "e9afa8ba6888739c27c8fe5e186f1ebadba5cd6d", "content_id": "762d7bf2290395bac4522d86f5a8c4c959607bb4", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 1489, "license_type": "permissive", "max_line_length": 74, "num_lines": 56, "path": "/bindings/wallet-js/tests/web.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "//! Test suite for the Web and headless browsers.\n\n#![cfg(target_arch = \"wasm32\")]\n\nextern crate wasm_bindgen_test;\nuse wallet_js::*;\nuse wasm_bindgen_test::*;\n\nwasm_bindgen_test_configure!(run_in_browser);\n\nconst BLOCK0: &[u8] = include_bytes!(\"../../../test-vectors/block0\");\n\n#[wasm_bindgen_test]\nfn gen_key() {\n // just test that the random generator works\n let _key = Ed25519ExtendedPrivate::generate();\n}\n\n#[wasm_bindgen_test]\nfn gen_key_from_seed() {\n let seed1 = [1u8; 32];\n let key1 = Ed25519ExtendedPrivate::from_seed(seed1.as_ref()).unwrap();\n let key2 = Ed25519ExtendedPrivate::from_seed(seed1.as_ref()).unwrap();\n\n assert_eq!(key1.bytes(), key2.bytes());\n\n let seed2 = [2u8; 32];\n let key3 = Ed25519ExtendedPrivate::from_seed(seed2.as_ref()).unwrap();\n\n assert_ne!(key3.bytes(), key1.bytes());\n}\n\n#[wasm_bindgen_test]\nfn gen_key_from_invalid_seed_fails() {\n const INVALID_SEED_SIZE: usize = 32 + 1;\n let bad_seed = [2u8; INVALID_SEED_SIZE];\n assert!(Ed25519ExtendedPrivate::from_seed(bad_seed.as_ref()).is_err())\n}\n\n#[wasm_bindgen_test]\nfn sign_verify_extended() {\n let key = Ed25519ExtendedPrivate::generate();\n let msg = [1, 2, 3, 4u8];\n let signature = key.sign(&msg);\n\n assert!(key.public().verify(&signature, &msg));\n}\n\n#[wasm_bindgen_test]\nfn sign_verify() {\n let key = Ed25519Private::generate();\n let msg = [1, 2, 3, 4u8];\n let signature = key.sign(&msg);\n\n assert!(key.public().verify(&signature, &msg));\n}\n" }, { "alpha_fraction": 0.7665369510650635, "alphanum_fraction": 0.7665369510650635, "avg_line_length": 27.55555534362793, "blob_id": "e359faabbb098851709fa6b97941187b1653116c", "content_id": "7868a03ae458b3d0ad9af34a4071d9c27112ddd6", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 257, "license_type": "permissive", "max_line_length": 93, "num_lines": 9, "path": "/wallet/src/transaction/mod.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "mod builder;\nmod strategy;\nmod witness_builder;\n\npub use self::{\n builder::{AddInputStatus, TransactionBuilder},\n strategy::{InputStrategy, OutputStrategy, Strategy, StrategyBuilder, DEFAULT_STRATEGIES},\n witness_builder::AccountWitnessBuilder,\n};\n" }, { "alpha_fraction": 0.6472222208976746, "alphanum_fraction": 0.6583333611488342, "avg_line_length": 26.69230842590332, "blob_id": "530577a8859c801be50b1331778eb1f713f7928e", "content_id": "f2c7dc340aab8a215902bc6301abb629ba467db4", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 720, "license_type": "permissive", "max_line_length": 85, "num_lines": 26, "path": "/hdkeygen/src/rindex/mod.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "//! random indexes wallet - 2 Level of randomly chosen hard derivation indexes Wallet\n\nmod hdpayload;\n\nuse crate::Key;\nuse chain_path_derivation::{\n rindex::{self, Rindex},\n DerivationPath,\n};\nuse ed25519_bip32::XPrv;\npub use hdpayload::{decode_derivation_path, HdKey};\n\nimpl Key<XPrv, Rindex<rindex::Root>> {\n pub fn key(\n &self,\n derivation_path: &DerivationPath<Rindex<rindex::Address>>,\n ) -> Key<XPrv, Rindex<rindex::Address>> {\n self.derive_path_unchecked(derivation_path)\n }\n\n /// get an address recovering object, this object can be used to check the\n /// ownership of addresses\n pub fn hd_key(&self) -> HdKey {\n HdKey::new(self.public().public_key())\n }\n}\n" }, { "alpha_fraction": 0.5764331221580505, "alphanum_fraction": 0.6401273608207703, "avg_line_length": 21.5, "blob_id": "1737f77351a3404f54fb848d844f6b7bb891533e", "content_id": "493ec13526fcbee3f52631d25f11eeee5a843f7d", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 314, "license_type": "permissive", "max_line_length": 60, "num_lines": 14, "path": "/chain-path-derivation/Cargo.toml", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "[package]\nname = \"chain-path-derivation\"\nversion = \"0.1.0\"\nauthors = [\"Nicolas Di Prima <[email protected]>\", \"Vincent Hanquez <[email protected]>\"]\nedition = \"2018\"\nlicense = \"MIT OR Apache-2.0\"\n\n[dependencies]\nthiserror = { version = \"1.0.13\", default-features = false }\n\n[dev-dependencies]\nquickcheck = \"0.9\"\nquickcheck_macros = \"0.9\"\npaste = \"0.1.8\"" }, { "alpha_fraction": 0.6660133004188538, "alphanum_fraction": 0.6881614923477173, "avg_line_length": 37.07462692260742, "blob_id": "bb88d9f84b6e0b6d68d6b7e5bce6d080684e726d", "content_id": "2bbe0db01ff0b9e7234f6f51f0956218af8628c0", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 5102, "license_type": "permissive", "max_line_length": 106, "num_lines": 134, "path": "/bip39/src/dictionary.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "//! Language support for BIP39 implementations.\n//!\n//! We provide default dictionaries for the some common languages.\n//! This interface is exposed to allow users to implement custom\n//! dictionaries.\n//!\n//! Because this module is part of the `chain_wallet` crate and that we\n//! need to keep the dependencies as small as possible we do not support\n//! UTF8 NFKD by default. Users must be sure to compose (or decompose)\n//! our output (or input) UTF8 strings.\n//!\n\nuse thiserror::Error;\n\nuse crate::MnemonicIndex;\n\n/// Errors associated to a given language/dictionary\n#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Error)]\npub enum Error {\n /// this means the given word is not in the Dictionary of the Language.\n #[error(\"Mnemonic word not found in dictionary \\\"{0}\\\"\")]\n MnemonicWordNotFoundInDictionary(String),\n}\n\n/// trait to represent the the properties that needs to be associated to\n/// a given language and its dictionary of known mnemonic words.\n///\npub trait Language {\n fn name(&self) -> &'static str;\n fn separator(&self) -> &'static str;\n fn lookup_mnemonic(&self, word: &str) -> Result<MnemonicIndex, Error>;\n fn lookup_word(&self, mnemonic: MnemonicIndex) -> Result<String, Error>;\n}\n\n/// Default Dictionary basic support for the different main languages.\n/// This dictionary expect the inputs to have been normalized (UTF-8 NFKD).\n///\n/// If you wish to implement support for non pre-normalized form you can\n/// create reuse this dictionary in a custom struct and implement support\n/// for [`Language`](./trait.Language.html) accordingly (_hint_: use\n/// [`unicode-normalization`](https://crates.io/crates/unicode-normalization)).\n///\npub struct DefaultDictionary {\n pub words: [&'static str; 2048],\n pub name: &'static str,\n}\n\nimpl Language for DefaultDictionary {\n fn name(&self) -> &'static str {\n self.name\n }\n fn separator(&self) -> &'static str {\n \" \"\n }\n fn lookup_mnemonic(&self, word: &str) -> Result<MnemonicIndex, Error> {\n match self.words.iter().position(|x| x == &word) {\n None => Err(Error::MnemonicWordNotFoundInDictionary(word.to_string())),\n Some(v) => {\n Ok(\n // it is safe to call unwrap as we guarantee that the\n // returned index `v` won't be out of bound for a\n // `MnemonicIndex` (DefaultDictionary.words is an array of 2048 elements)\n MnemonicIndex::new(v as u16).unwrap(),\n )\n }\n }\n }\n fn lookup_word(&self, mnemonic: MnemonicIndex) -> Result<String, Error> {\n Ok(unsafe { self.words.get_unchecked(mnemonic.0 as usize) }).map(|s| String::from(*s))\n }\n}\n\n/// default English dictionary as provided by the\n/// [BIP39 standard](https://github.com/bitcoin/bips/blob/master/bip-0039/bip-0039-wordlists.md#wordlists)\n///\npub const ENGLISH: DefaultDictionary = DefaultDictionary {\n words: include!(\"bip39_english.txt\"),\n name: \"english\",\n};\n\n/// default French dictionary as provided by the\n/// [BIP39 standard](https://github.com/bitcoin/bips/blob/master/bip-0039/bip-0039-wordlists.md#french)\n///\npub const FRENCH: DefaultDictionary = DefaultDictionary {\n words: include!(\"bip39_french.txt\"),\n name: \"french\",\n};\n\n/// default Japanese dictionary as provided by the\n/// [BIP39 standard](https://github.com/bitcoin/bips/blob/master/bip-0039/bip-0039-wordlists.md#japanese)\n///\npub const JAPANESE: DefaultDictionary = DefaultDictionary {\n words: include!(\"bip39_japanese.txt\"),\n name: \"japanese\",\n};\n\n/// default Korean dictionary as provided by the\n/// [BIP39 standard](https://github.com/bitcoin/bips/blob/master/bip-0039/bip-0039-wordlists.md#japanese)\n///\npub const KOREAN: DefaultDictionary = DefaultDictionary {\n words: include!(\"bip39_korean.txt\"),\n name: \"korean\",\n};\n\n/// default chinese simplified dictionary as provided by the\n/// [BIP39 standard](https://github.com/bitcoin/bips/blob/master/bip-0039/bip-0039-wordlists.md#chinese)\n///\npub const CHINESE_SIMPLIFIED: DefaultDictionary = DefaultDictionary {\n words: include!(\"bip39_chinese_simplified.txt\"),\n name: \"chinese-simplified\",\n};\n/// default chinese traditional dictionary as provided by the\n/// [BIP39 standard](https://github.com/bitcoin/bips/blob/master/bip-0039/bip-0039-wordlists.md#chinese)\n///\npub const CHINESE_TRADITIONAL: DefaultDictionary = DefaultDictionary {\n words: include!(\"bip39_chinese_traditional.txt\"),\n name: \"chinese-traditional\",\n};\n\n/// default italian dictionary as provided by the\n/// [BIP39 standard](https://github.com/bitcoin/bips/blob/master/bip-0039/bip-0039-wordlists.md#italian)\n///\npub const ITALIAN: DefaultDictionary = DefaultDictionary {\n words: include!(\"bip39_italian.txt\"),\n name: \"italian\",\n};\n\n/// default spanish dictionary as provided by the\n/// [BIP39 standard](https://github.com/bitcoin/bips/blob/master/bip-0039/bip-0039-wordlists.md#spanish)\n///\npub const SPANISH: DefaultDictionary = DefaultDictionary {\n words: include!(\"bip39_spanish.txt\"),\n name: \"spanish\",\n};\n" }, { "alpha_fraction": 0.5992434620857239, "alphanum_fraction": 0.6016324758529663, "avg_line_length": 30.99363136291504, "blob_id": "6ecd8c5d1e83317029078aaeb65bc6a69720091c", "content_id": "7407f60713a6b644a3afdb4cf9a6702d10c4f266", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 5023, "license_type": "permissive", "max_line_length": 97, "num_lines": 157, "path": "/bindings/wallet-core/src/wallet.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use crate::{Error, Proposal};\nuse chain_core::property::Serialize as _;\nuse chain_crypto::SecretKey;\nuse chain_impl_mockchain::{\n account::SpendingCounter,\n block::BlockDate,\n fragment::{Fragment, FragmentId},\n value::Value,\n vote::Choice,\n};\nuse wallet::{AccountId, Settings};\n\n/// the wallet\n///\n/// * use the `recover` function to recover the wallet from the mnemonics/password;\n/// * use the `retrieve_funds` to retrieve initial funds (if necessary) from the block0;\n/// then you can use `total_value` to see how much was recovered from the initial block0;\n///\npub struct Wallet {\n account: wallet::Wallet,\n}\n\nimpl Wallet {\n /// Returns address of the account with the given chain discrimination.\n pub fn account(&self, discrimination: chain_addr::Discrimination) -> chain_addr::Address {\n self.account.account_id().address(discrimination)\n }\n\n pub fn id(&self) -> AccountId {\n self.account.account_id()\n }\n\n /// Retrieve a wallet from a list of free keys used as utxo's\n ///\n /// You can also use this function to recover a wallet even after you have\n /// transferred all the funds to the new format (see the [Self::convert] function).\n ///\n /// Parameters\n ///\n /// * `account_key`: the private key used for voting\n /// * `keys`: unused\n ///\n /// # Errors\n ///\n /// The function may fail if:\n ///\n /// TODO\n ///\n pub fn recover_free_keys(account_key: &[u8]) -> Result<Self, Error> {\n let account = wallet::Wallet::new_from_key(SecretKey::from_binary(account_key).unwrap());\n\n Ok(Wallet { account })\n }\n\n /// use this function to confirm a transaction has been properly received\n ///\n /// This function will automatically update the state of the wallet\n pub fn confirm_transaction(&mut self, id: FragmentId) {\n self.account.confirm(&id);\n }\n\n /// get the current spending counter\n ///\n pub fn spending_counter(&self) -> Vec<u32> {\n self.account\n .spending_counter()\n .into_iter()\n .map(SpendingCounter::into)\n .collect()\n }\n\n /// get the total value in the wallet\n ///\n /// make sure to call `retrieve_funds` prior to calling this function\n /// otherwise you will always have `0`\n ///\n /// Once a conversion has been performed, this value can be use to display\n /// how much the wallet started with or retrieved from the chain.\n ///\n pub fn total_value(&self) -> Value {\n self.account.value()\n }\n\n /// Update the wallet's account state.\n ///\n /// The values to update the account state with can be retrieved from a\n /// Jormungandr API endpoint. It sets the balance value on the account\n /// as well as the current spending counter.\n ///\n /// It is important to be sure to have an up to date wallet state\n /// before doing any transactions, otherwise future transactions may fail\n /// to be accepted by the blockchain nodes because of an invalid witness\n /// signature.\n pub fn set_state(&mut self, value: Value, counters: Vec<u32>) -> Result<(), Error> {\n self.account\n .set_state(\n value,\n counters.into_iter().map(SpendingCounter::from).collect(),\n )\n .map_err(|_| Error::invalid_spending_counters())\n }\n\n /// Cast a vote\n ///\n /// This function outputs a fragment containing a voting transaction.\n ///\n /// # Parameters\n ///\n /// * `settings` - ledger settings.\n /// * `proposal` - proposal information including the range of values\n /// allowed in `choice`.\n /// * `choice` - the option to vote for.\n ///\n /// # Errors\n ///\n /// The error is returned when `choice` does not fall withing the range of\n /// available choices specified in `proposal`.\n pub fn vote(\n &mut self,\n settings: Settings,\n proposal: &Proposal,\n choice: Choice,\n valid_until: &BlockDate,\n lane: u8,\n ) -> Result<Box<[u8]>, Error> {\n let payload = if let Some(payload) = proposal.vote(choice) {\n payload\n } else {\n return Err(Error::wallet_vote_range());\n };\n\n let mut builder = wallet::TransactionBuilder::new(&settings, payload, *valid_until);\n\n let value = builder.estimate_fee_with(1, 0);\n\n let account_tx_builder = self\n .account\n .new_transaction(value, lane)\n .map_err(|_| Error::not_enough_funds())?;\n\n let input = account_tx_builder.input();\n let witness_builder = account_tx_builder.witness_builder();\n\n builder.add_input(input, witness_builder);\n\n let tx = builder\n .finalize_tx(())\n .map_err(|e| Error::wallet_transaction().with(e))?;\n\n let fragment = Fragment::VoteCast(tx);\n let id = fragment.hash();\n\n account_tx_builder.add_fragment_id(id);\n\n Ok(fragment.serialize_as_vec().unwrap().into_boxed_slice())\n }\n}\n" }, { "alpha_fraction": 0.63111412525177, "alphanum_fraction": 0.7033514380455017, "avg_line_length": 20.861385345458984, "blob_id": "25aa0734ec6845bc6d4053e97bc822898c1d1c71", "content_id": "beadcaec42bc514740ced4add6018d17868eefeb", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4416, "license_type": "permissive", "max_line_length": 90, "num_lines": 202, "path": "/CHANGELOG.md", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "# Changelog\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n## Unreleased\n\n- *breaking change*: wallet_spending_counter replaced by wallet_spending_counters\n- *breaking change*: wallet_set_state now takes an array of spending counters \n- *breaking change*: wallet_vote now takes a lane as an argument\n- *breaking change*: wallet_import_keys now takes a single argument with the\n account key.\n\n## [0.8.0-alpha1]\n\n- Remove the keygen crate due to lack of need for it.\n- Remove wallet-jni and use wallet-uniffi instead.\n\n## [0.7.0-pre4] 2021-09-02\n\n- Bech32 HRP for encryption key now is set by chain-libs\n\n## [0.7.0-pre3] 2021-08-27\n\n- Fix compilation issue in iOS for cordova\n\n## [0.7.0-pre2] 2021-08-26\n\n### Changed\n\n- Improved documentation\n- Recover from mnemonics can now take a password\n\n#### Wallet-js\n\n- *deprecated*: VotePlanId::new_from_bytes\n- *deprecated*: Ed25519Signature::from_binary\n- *deprecated*: FragmentId::new_from_bytes\n\n### Added\n\n#### Wallet-js\n\n- VotePlanId::from_bytes\n- Ed25519Signature::from_bytes\n- FragmentId::from_bytes\n\n## [0.7.0-pre1] 2021-08-25\n\n### Changed\n\n- *breaking change*: `wallet_vote_cast` and `wallet_convert` now require the TTL argument.\n- *breaking change*: `settings_new` takes new arguments needed for managing time.\n\n### Added\n\n- max_expiration_date\n- block_date_from_system_time\n\n## [0.6.0-pre2] 2021-05-14\n\n### Added\n\n#### cordova - c - java\n\n- spending_counter\n- settings_new\n- settings_get\n- fragment_from_raw\n- fragment_id\n- fragment_delete\n\n### Changed\n\npending_transactions now returns transactions in order relative to the same\nwallet type instead of arbitrary order. First starting with deadalus/yoroi/free\nutxo keys (those are all exclusive) in order of creating, and then the account\ntransactions, also in order of creation (and signing).\n\n## [0.6.0-pre1]\n\n### Changed\n\n#### cordova - c - java - wallet-js \n\n- *breaking change*: Take a bech32 string in proposal_new_private instead of raw bytes\n\n## [0.5.0] - 2021-01-05\n\n## [0.5.0-pre9] - 2020-12-17\n\n- Add explicit link to libdl.so in release process\n\n## [0.5.0-pre8] - 2020-12-04\n\n#### wallet-js\n\n- Remove `symmetric_encrypt` (moved to *keygen*)\n- Remove `symmetric_decrypt` (moved to *keygen*)\n- Remove `bech32_decode_to_bytes` (moved to *keygen*)\n\n#### keygen\n\nAdd specific package used for daedalus catalyst\n\n*Features*\n\n- Generate Ed25519Extended private/public keys.\n- Encrypt keys with pin.\n- Decode bech32 strings.\n\n## [0.5.0-pre7] - 2020-11-16\n\n#### wallet-js\n\n- Expose function to decode bech32 to byte array\n\n## [0.5.0-pre6] - 2020-11-06\n\n### Changed\n\n#### wallet-js\n\n- Put the package into scope as @iohk-jormungandr/wallet-js\n- Change the output file prefix to generate files named `wallet.js` etc.\n\n## [0.5.0-pre5] - 2020-10-30\n\n### Added\n\n#### wallet-js\n\n- Add Ed25519Extended generation from seed\n- Key signing and verification.\n- Add the other kinds of private keys: \n - Ed25519\n\n#### Cordova-android | Java | C | Electron/Browser\n- vote_proposal_new_public\n- vote_proposal_new_private\n\n#### Cordova-electron/browser\n- add confirm/get pending transactions\n- add import keys (free keys)\n- pin decryption (symmetric cipher decrypt)\n\n### Deprecated\n\n- proposal_new: In favour of the specific functions for each case. This\nfunction takes an enum, which currently only can be used to cast public\nvotes (the internal function still uses rust enums, this is only for non-rust\napis).\n\n## [0.5.0-pre4] - 2020-10-13\n\n### Added\n\n#### wallet-js\n\n- Key pair generation support.\n- Symmetric encryption and decryption support.\n\n## [0.5.0-pre3] - 2020-09-04\n\n### Fixed\n\n- Decryption function now returns an error if the authentication fails.\n\n### Added\n\n#### wallet-cordova\n\n- iOS support for the import key and decryption functions.\n\n## [0.5.0-pre2] - 2020-08-18\n\n### Fixed\n- Wrong secret key type was used when recovering from mnemonics.\n\n## [0.5.0-pre1] - 2020-08-18\n### Added\n\n- New utxo store.\n- Allow recovering from single free utxo keys.\n- Custom symmetric encryption/decryption module.\n\n## [0.4.0] - 2020-07-08\n\n## [0.4.0-pre3] - 2020-06-22\n\n## [0.4.0-pre2] - 2020-06-04\n\n## [0.4.0-pre1] - 2020-06-03\n\n## [0.3.1] - 2020-22-05\n\n## [0.3.0] - 2020-05-01\n\n## [0.2.0] - 2020-04-15\n\n## [0.1.0] - 2020-04-10\n" }, { "alpha_fraction": 0.6790369749069214, "alphanum_fraction": 0.6838520169258118, "avg_line_length": 40.1352653503418, "blob_id": "6446b397aaa30140e7361b2b9078846a62733c99", "content_id": "c4e6f4fdd9726e77688c0c00fcb80ceb0e1d1262", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 17030, "license_type": "permissive", "max_line_length": 156, "num_lines": 414, "path": "/bindings/wallet-cordova/www/wallet.js", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "var exec = require('cordova/exec');\nvar argscheck = require('cordova/argscheck');\nvar base64 = require('cordova/base64');\n\nconst NATIVE_CLASS_NAME = 'WalletPlugin';\n\nconst WALLET_IMPORT_KEYS_TAG = 'WALLET_IMPORT_KEYS';\nconst WALLET_TOTAL_FUNDS_ACTION_TAG = 'WALLET_TOTAL_FUNDS';\nconst WALLET_SPENDING_COUNTER_ACTION_TAG = 'WALLET_SPENDING_COUNTER';\nconst WALLET_ID_TAG = 'WALLET_ID';\nconst WALLET_SET_STATE_ACTION_TAG = 'WALLET_SET_STATE';\nconst WALLET_VOTE_ACTION_TAG = 'WALLET_VOTE';\nconst WALLET_CONFIRM_TRANSACTION = 'WALLET_CONFIRM_TRANSACTION';\nconst PROPOSAL_NEW_PUBLIC_ACTION_TAG = 'PROPOSAL_NEW_PUBLIC';\nconst PROPOSAL_NEW_PRIVATE_ACTION_TAG = 'PROPOSAL_NEW_PRIVATE';\nconst WALLET_DELETE_ACTION_TAG = 'WALLET_DELETE';\nconst SETTINGS_DELETE_ACTION_TAG = 'SETTINGS_DELETE';\nconst PROPOSAL_DELETE_ACTION_TAG = 'PROPOSAL_DELETE';\nconst WALLET_PENDING_TRANSACTIONS = 'WALLET_PENDING_TRANSACTIONS';\nconst SYMMETRIC_CIPHER_DECRYPT = 'SYMMETRIC_CIPHER_DECRYPT';\nconst SETTINGS_NEW = 'SETTINGS_NEW';\nconst SETTINGS_GET = 'SETTINGS_GET';\nconst FRAGMENT_ID = 'FRAGMENT_ID';\nconst BLOCK_DATE_FROM_SYSTEM_TIME = 'BLOCK_DATE_FROM_SYSTEM_TIME';\nconst MAX_EXPIRATION_DATE = 'MAX_EXPIRATION_DATE';\n\nconst VOTE_PLAN_ID_LENGTH = 32;\nconst FRAGMENT_ID_LENGTH = 32;\nconst ED25519_EXTENDED_LENGTH = 64;\n\n/**\n * THOUGHTS/TODO\n * add a more idiomatic abstraction on top of these primitive functions and expose that, something more similar to what wasm-bindgen does\n * I'm still not sure what javascript features can we use here (ES6, can we bring dependencies?, promises?)\n*/\n\n/**\n * wallet module.\n * @exports wallet-cordova-plugin.wallet\n */\nvar plugin = {\n /**\n * @callback pointerCallback\n * @param {string} ptr - callback that returns a pointer to a native object\n */\n\n /**\n * @callback errorCallback\n * @param {string} error - error description\n */\n\n /**\n * @callback SettingsCallback\n * @param {Settings} settings\n */\n\n /**\n * @callback BlockDateCallback\n * @param {BlockDate} date\n */\n\n /**\n * @typedef Settings\n * @type {object}\n * @property {Uint8Array} block0Hash\n * @property {Discrimination} discrimination\n * @property {Fees} fees\n */\n\n /**\n * @typedef Fees\n * @type {object}\n * @property {string} constant\n * @property {string} coefficient\n * @property {string} certificate\n * @property {string} certificatePoolRegistration\n * @property {string} certificateStakeDelegation\n * @property {string} certificateOwnerStakeDelegation\n * @property {string} certificateVotePlan\n * @property {string} certificateVoteCast\n */\n\n /**\n * @typedef TimeEra\n * @type {object}\n * @property {string} epochStart\n * @property {string} slotStart\n * @property {string} slotsPerEpoch\n */\n\n /**\n * @typedef BlockDate\n * @type {object}\n * @property {string} epoch\n * @property {string} slot\n */\n\n /**\n * @readonly\n * @enum {number}\n */\n Discrimination: {\n PRODUCTION: 0,\n TEST: 1\n },\n\n /**\n * @param {Uint8Array} accountKey a 64bytes array representing an Ed25519Extended private key\n * @param {pointerCallback} successCallback on success returns a pointer to a Wallet object\n * @param {errorCallback} errorCallback if the input arrays are malformed\n */\n walletImportKeys: function (accountKey, successCallback, errorCallback) {\n argscheck.checkArgs('*ff', 'walletImportKeys', arguments);\n checkUint8Array({ name: 'accountKey', testee: accountKey, optLength: ED25519_EXTENDED_LENGTH });\n\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, WALLET_IMPORT_KEYS_TAG, [accountKey.buffer]);\n },\n\n /**\n * @param {string} ptr a pointer to a wallet obtained with walletRestore\n * @param {function} successCallback returns a number\n * @param {errorCallback} errorCallback description (TODO)\n */\n walletTotalFunds: function (ptr, successCallback, errorCallback) {\n argscheck.checkArgs('sff', 'walletTotalFunds', arguments);\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, WALLET_TOTAL_FUNDS_ACTION_TAG, [ptr]);\n },\n\n /**\n * @param {string} ptr a pointer to a wallet\n * @param {function} successCallback returns an array of spending counters\n * @param {errorCallback} errorCallback this function should not fail\n */\n walletSpendingCounters: function (ptr, successCallback, errorCallback) {\n argscheck.checkArgs('sff', 'walletTotalFunds', arguments);\n\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, WALLET_SPENDING_COUNTER_ACTION_TAG, [ptr]);\n },\n\n /**\n * get the wallet id\n\n * This ID is the identifier to use against the blockchain/explorer to retrieve\n * the state of the wallet (counter, total value etc...)\n *\n * # Safety\n *\n * This function dereference raw pointers (wallet). Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors\n *\n * @param {string} ptr a pointer to a Wallet object obtained with WalletRestore\n * @param {function} successCallback the return value is an ArrayBuffer, which has the binary representation of the account id.\n * @param {function} errorCallback this function may fail if the wallet pointer is null\n */\n walletId: function (ptr, successCallback, errorCallback) {\n argscheck.checkArgs('sff', 'walletId', arguments);\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, WALLET_ID_TAG, [ptr]);\n },\n\n /**\n *\n * update the wallet account state\n *\n * this is the value retrieved from any jormungandr endpoint that allows to query\n * for the account state. It gives the value associated to the account as well as\n * the counter.\n *\n * It is important to be sure to have an updated wallet state before doing any\n * transactions otherwise future transactions may fail to be accepted by any\n * nodes of the blockchain because of invalid signature state.\n *\n * # Errors\n *\n * this function may fail if the wallet pointer is null;\n * @param {string} ptr a pointer to a Wallet object obtained with WalletRestore\n * @param {number} value\n * @param {number[]} an array of numbers between 0 and 2^32\n * @param {function} successCallback\n * @param {function} errorCallback\n *\n */\n walletSetState: function (ptr, value, nonces, successCallback, errorCallback) {\n argscheck.checkArgs('snaff', 'walletSetState', arguments);\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, WALLET_SET_STATE_ACTION_TAG, [ptr, value, nonces]);\n },\n\n /**\n *\n * Get a signed transaction with a vote of `choice` to the given proposal, ready to be sent to the network.\n *\n * # Errors\n *\n * this function may fail if if any of the pointers are is null;\n * @param {string} walletPtr a pointer to a Wallet object obtained with walletRestore\n * @param {string} settingsPtr a pointer to a Settings object obtained with walletRetrieveFunds\n * @param {string} proposalPtr a pointer to a Proposal object obtained with proposalNew\n * @param {number} choice a number between 0 and Proposal's numChoices - 1\n * @param {BlockDate} validUntil maximum date in which this fragment can be applied to the ledger\n * @param {number} lane to use for the spending counter (or nonce). Must be a number in the interval of [0, 7]\n * @param {function} successCallback on success the callback returns a byte array representing a transaction\n * @param {function} errorCallback can fail if the choice doesn't validate with the given proposal\n *\n */\n walletVote: function (walletPtr, settingsPtr, proposalPtr, choice, validUntil, lane, successCallback, errorCallback) {\n argscheck.checkArgs('sssn*nff', 'walletVote', arguments);\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, WALLET_VOTE_ACTION_TAG, [walletPtr, settingsPtr, proposalPtr, choice, validUntil, lane]);\n },\n\n /**\n * @param {string} walletPtr a pointer to a wallet obtained with walletRestore\n * @param {pointerCallback} successCallback\n * @param {errorCallback} errorCallback\n */\n walletPendingTransactions: function (walletPtr, successCallback, errorCallback) {\n argscheck.checkArgs('sff', 'walletPendingTransactions', arguments);\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, WALLET_PENDING_TRANSACTIONS, [walletPtr]);\n },\n\n /**\n * @param {string} walletPtr a pointer to a wallet obtained with walletRestore\n * @param {Uint8Array} transactionId the transaction id in bytes\n * @param {pointerCallback} successCallback\n * @param {errorCallback} errorCallback\n */\n walletConfirmTransaction: function (walletPtr, transactionId, successCallback, errorCallback) {\n argscheck.checkArgs('s*ff', 'walletConfirmTransaction', arguments);\n checkUint8Array({ name: 'transactionId', testee: transactionId, optLength: FRAGMENT_ID_LENGTH });\n\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, WALLET_CONFIRM_TRANSACTION, [walletPtr, transactionId.buffer]);\n },\n\n /**\n * Get a proposal object, used to validate the vote on `walletVote`\n *\n * @param {Uint8Array} votePlanId a byte array of 32 elements that identifies the voteplan\n * @param {number} index the index of the proposal in the voteplan\n * @param {number} numChoices the number of choices of the proposal, used to validate the choice\n * @param {function} successCallback returns an object with ignored, and value properties\n * @param {errorCallback} errorCallback\n */\n proposalNewPublic: function (votePlanId, index, numChoices, successCallback, errorCallback) {\n argscheck.checkArgs('*nnff', 'proposalNewPublic', arguments);\n checkUint8Array({ name: 'votePlanId', testee: votePlanId, optLength: VOTE_PLAN_ID_LENGTH });\n\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, PROPOSAL_NEW_PUBLIC_ACTION_TAG, [votePlanId.buffer, index, numChoices]);\n },\n\n /**\n * Get a proposal object, used to validate the vote on `walletVote`\n *\n * @param {Uint8Array} votePlanId a byte array of 32 elements that identifies the voteplan\n * @param {number} index the index of the proposal in the voteplan\n * @param {number} numChoices the number of choices of the proposal, used to validate the choice\n * @param {string} encryptionVoteKey bech32 string representing the\n * single key used to encrypt a vote, generated from the public keys\n * from all committee members\n * @param {function} successCallback returns an object with ignored, and value properties\n * @param {errorCallback} errorCallback\n */\n proposalNewPrivate: function (votePlanId, index, numChoices, encryptionVoteKey, successCallback, errorCallback) {\n argscheck.checkArgs('*nnsff', 'proposalNewPrivate', arguments);\n checkUint8Array({ name: 'votePlanId', testee: votePlanId, optLength: VOTE_PLAN_ID_LENGTH });\n\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, PROPOSAL_NEW_PRIVATE_ACTION_TAG, [votePlanId.buffer, index, numChoices, encryptionVoteKey]);\n },\n\n /**\n * @param {Uint8Array} password the encryption password as bytes\n * @param {Uint8Array} ciphertext the encrypted bytes\n * @param {pointerCallback} successCallback on success returns a pointer to a Wallet object\n * @param {errorCallback} errorCallback this function can fail if the mnemonics are invalid\n */\n symmetricCipherDecrypt: function (password, ciphertext, successCallback, errorCallback) {\n argscheck.checkArgs('**ff', 'symmetricCipherDecrypt', arguments);\n checkUint8Array({ name: 'password', testee: password });\n checkUint8Array({ name: 'ciphertext', testee: ciphertext });\n\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, SYMMETRIC_CIPHER_DECRYPT, [password.buffer, ciphertext.buffer]);\n },\n\n /**\n * @param {Uint8Array} block0Hash\n * @param {Discrimination} discrimination\n * @param {Fees} fees\n * @param {string} block0Date\n * @param {string} slotDuration\n * @param {TimeEra} era\n * @param {string} transactionMaxExpiryEpochs\n * @param {pointerCallback} successCallback\n * @param {errorCallback} errorCallback\n */\n settingsNew: function (\n block0Hash,\n discrimination,\n fees,\n block0Date,\n slotDuration,\n era,\n transactionMaxExpiryEpochs,\n successCallback,\n errorCallback\n ) {\n argscheck.checkArgs('*n*ss*sff', 'settingsNew', arguments);\n checkUint8Array({ name: 'block0Hash', testee: block0Hash });\n\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, SETTINGS_NEW, [\n block0Hash.buffer,\n discrimination,\n fees,\n block0Date,\n slotDuration,\n era,\n transactionMaxExpiryEpochs\n ]);\n },\n\n /**\n * @param {string} settingsPtr\n * @param {SettingsCallback} settingsCallback\n * @param {errorCallback} errorCallback\n */\n settingsGet: function (settingsPtr, settingsCallback, errorCallback) {\n argscheck.checkArgs('sff', 'settingsGet', arguments);\n\n const decodeBase64 = function (arg) {\n arg.block0Hash = new Uint8Array(base64.toArrayBuffer(arg.block0Hash));\n settingsCallback(arg);\n };\n\n exec(decodeBase64, errorCallback, NATIVE_CLASS_NAME, SETTINGS_GET, [settingsPtr]);\n },\n\n /**\n * @param {Uint8Array} transaction\n * @param {TransactionIdCallback} successCallback\n * @param {errorCallback} errorCallback\n */\n fragmentId: function (transaction, successCallback, errorCallback) {\n argscheck.checkArgs('*ff', 'transactionId', arguments);\n checkUint8Array({ name: 'transaction', testee: transaction });\n\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, FRAGMENT_ID, [transaction.buffer]);\n },\n\n /**\n * @param {string} settingsPtr\n * @param {number} date\n * @param {BlockDateCallback} successCallback\n * @param {errorCallback} errorCallback\n */\n blockDateFromSystemTime: function (settingsPtr, date, successCallback, errorCallback) {\n argscheck.checkArgs('snff', 'blockDateFromSystemTime', arguments);\n\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, BLOCK_DATE_FROM_SYSTEM_TIME, [settingsPtr, date]);\n },\n\n /**\n * @param {string} settingsPtr\n * @param {number} currentTime\n * @param {BlockDateCallback} successCallback\n * @param {errorCallback} errorCallback\n */\n maxExpirationDate: function (settingsPtr, currentTime, successCallback, errorCallback) {\n argscheck.checkArgs('snff', 'maxExpirationDate', arguments);\n\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, MAX_EXPIRATION_DATE, [settingsPtr, currentTime]);\n },\n\n /**\n * @param {string} ptr a pointer to a Wallet obtained with walletRestore\n * @param {function} successCallback indicates success. Does not return anything.\n * @param {errorCallback} errorCallback\n */\n walletDelete: function (ptr, successCallback, errorCallback) {\n argscheck.checkArgs('sff', 'walletDelete', arguments);\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, WALLET_DELETE_ACTION_TAG, [ptr]);\n },\n\n /**\n * @param {string} ptr a pointer to a Settings object obtained with walletRetrieveFunds\n * @param {function} successCallback indicates success. Does not return anything.\n * @param {errorCallback} errorCallback\n */\n settingsDelete: function (ptr, successCallback, errorCallback) {\n argscheck.checkArgs('sff', 'settingsDelete', arguments);\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, SETTINGS_DELETE_ACTION_TAG, [ptr]);\n },\n\n /**\n * @param {string} ptr a pointer to a Proposal object obtained with proposalNew\n * @param {function} successCallback indicates success. Does not return anything.\n * @param {errorCallback} errorCallback\n */\n proposalDelete: function (ptr, successCallback, errorCallback) {\n argscheck.checkArgs('sff', 'proposalDelete', arguments);\n exec(successCallback, errorCallback, NATIVE_CLASS_NAME, PROPOSAL_DELETE_ACTION_TAG, [ptr]);\n }\n};\n\nfunction checkUint8Array (arg) {\n var typeName = require('cordova/utils').typeName;\n var validType = arg.testee && typeName(arg.testee) === 'Uint8Array';\n if (!validType) {\n throw TypeError('expected ' + arg.name + ' to be of type Uint8Array');\n }\n\n var validLength = arg.optLength ? arg.testee.length === arg.optLength : true;\n if (!validLength) {\n throw TypeError('expected ' + arg.name + ' to have length ' + arg.optLength + ' found: ' + arg.testee.length);\n }\n}\n\nmodule.exports = plugin;\n" }, { "alpha_fraction": 0.6051779985427856, "alphanum_fraction": 0.6278316974639893, "avg_line_length": 35.35293960571289, "blob_id": "2b7b1c9e4221a9cb4bab113281ca954c47acefc6", "content_id": "0b8ac9d8ff047ee433cfea1e9a373f5c3830fccc", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 618, "license_type": "permissive", "max_line_length": 103, "num_lines": 17, "path": "/bindings/wallet-c/Cargo.toml", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "[package]\nname = \"jormungandrwallet\"\nversion = \"0.7.0-pre4\"\nauthors = [\"Nicolas Di Prima <[email protected]>\", \"Vincent Hanquez <[email protected]>\"]\nedition = \"2018\"\nlicense = \"MIT OR Apache-2.0\"\n\n[lib]\ncrate-type = [\"staticlib\", \"cdylib\"]\n\n[dependencies]\nbip39 = { path = \"../../bip39\" }\nwallet = { path = \"../../wallet\" }\nchain-ser = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-addr = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-impl-mockchain = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nwallet-core = { path = \"../wallet-core\"}\n" }, { "alpha_fraction": 0.637499988079071, "alphanum_fraction": 0.637499988079071, "avg_line_length": 25.66666603088379, "blob_id": "eacfac642ff40296fe794a6a0e214713e9ac0359", "content_id": "3866cf57b708b438345bf8f52c22911de682791a", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 80, "license_type": "permissive", "max_line_length": 65, "num_lines": 3, "path": "/bindings/wallet-uniffi/build.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "fn main() {\n uniffi_build::generate_scaffolding(\"./src/lib.udl\").unwrap();\n}\n" }, { "alpha_fraction": 0.6550324559211731, "alphanum_fraction": 0.6590909361839294, "avg_line_length": 29.25, "blob_id": "2d61b17f5226f4911b0a5598311a52825e91db54", "content_id": "f3f581cb487d25bc44e6f407cd238cfad096c1b6", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 13552, "license_type": "permissive", "max_line_length": 99, "num_lines": 448, "path": "/bindings/wallet-core/src/c/mod.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "//! This module expose handy C compatible functions to reuse in the different\n//! C style bindings that we have (wallet-c, wallet-jni...)\n#[macro_use]\nmod macros;\npub mod fragment;\npub mod settings;\npub mod time;\npub mod vote;\n\nuse crate::{Error, Proposal, Result, Wallet};\nuse chain_impl_mockchain::{fragment::Fragment, value::Value, vote::Choice};\nuse std::convert::TryInto;\n\nuse thiserror::Error;\npub use wallet::Settings;\n\nuse self::time::BlockDate;\n\npub type WalletPtr = *mut Wallet;\npub type SettingsPtr = *mut Settings;\npub type ProposalPtr = *mut Proposal;\npub type ErrorPtr = *mut Error;\npub type FragmentPtr = *mut Fragment;\n\n#[derive(Debug, Error)]\n#[error(\"null pointer\")]\nstruct NulPtr;\n\n#[derive(Debug, Error)]\n#[error(\"access out of bound\")]\nstruct OutOfBound;\n\npub const FRAGMENT_ID_LENGTH: usize = 32;\npub const NONCES_SIZE: usize = 8 * 4;\n\n/// recover a wallet from an account and a list of utxo keys\n///\n/// You can also use this function to recover a wallet even after you have\n/// transferred all the funds to the new format (see the _convert_ function)\n///\n/// The recovered wallet will be returned in `wallet_out`.\n///\n/// # parameters\n///\n/// * account_key: the Ed25519 extended key used wallet's account address private key\n/// in the form of a 64 bytes array. \n/// * utxo_keys: an array of Ed25519 keys in the form of 64 bytes, used as utxo\n/// keys for the wallet\n/// * utxo_keys_len: the number of keys in the utxo_keys array (not the number of bytes)\n/// * wallet_out: the recovered wallet\n///\n/// # Safety\n///\n/// This function dereference raw pointers (password and wallet_out). Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n///\n/// # errors\n///\n/// The function may fail if:\n///\n/// * the `wallet_out` is null pointer\n///\npub unsafe fn wallet_import_keys(account_key: *const u8, wallet_out: *mut WalletPtr) -> Result {\n let wallet_out = non_null_mut!(wallet_out);\n let account_key: &u8 = non_null!(account_key);\n\n let account_key: &[u8] = std::slice::from_raw_parts(account_key as *const u8, 64);\n\n let result = Wallet::recover_free_keys(account_key);\n\n match result {\n Ok(wallet) => {\n *wallet_out = Box::into_raw(Box::new(wallet));\n Result::success()\n }\n Err(err) => err.into(),\n }\n}\n\n/// get the wallet id\n///\n/// This ID is the identifier to use against the blockchain/explorer to retrieve\n/// the state of the wallet (counter, total value etc...)\n///\n/// # Parameters\n///\n/// * wallet: the recovered wallet (see recover function);\n/// * id_out: a ready allocated pointer to an array of 32bytes. If this array is not\n/// 32bytes this may result in a buffer overflow.\n///\n/// # Safety\n///\n/// This function dereference raw pointers (wallet and id_out). Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n///\n/// the `id_out` needs to be ready allocated 32bytes memory. If not this will result\n/// in an undefined behavior, in the best scenario it will be a buffer overflow.\n///\n/// # Errors\n///\n/// * this function may fail if the wallet pointer is null;\n///\npub unsafe fn wallet_id(wallet: WalletPtr, id_out: *mut u8) -> Result {\n let wallet: &Wallet = if let Some(wallet) = wallet.as_ref() {\n wallet\n } else {\n return Error::invalid_input(\"wallet\").with(NulPtr).into();\n };\n if id_out.is_null() {\n return Error::invalid_input(\"id_out\").with(NulPtr).into();\n }\n\n let id = wallet.id();\n\n let id_out = std::slice::from_raw_parts_mut(id_out, wallet::AccountId::SIZE);\n\n id_out.copy_from_slice(id.as_ref());\n\n Result::success()\n}\n\n/// Confirm the previously generated transaction identified by fragment_id\n///\n/// # Safety\n///\n/// This function dereference raw pointers (wallet, fragment_id). Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors. It's also asummed that fragment_id is\n/// a pointer to FRAGMENT_ID_LENGTH bytes of contiguous data.\n///\npub unsafe fn wallet_confirm_transaction(wallet: WalletPtr, fragment_id: *const u8) -> Result {\n let wallet = non_null_mut!(wallet);\n let fragment_id: &u8 = non_null!(fragment_id);\n\n let fragment_id_bytes: [u8; FRAGMENT_ID_LENGTH] =\n std::slice::from_raw_parts(fragment_id as *const u8, FRAGMENT_ID_LENGTH)\n .try_into()\n .unwrap();\n\n wallet.confirm_transaction(fragment_id_bytes.into());\n\n Result::success()\n}\n\n/// get the current spending counter for the (only) account in this wallet\n///\n/// the memory can be deallocated with `spending_counters_delete`.\n///\n/// # Errors\n///\n/// * this function may fail if the wallet pointer is null;\n///\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n///\npub unsafe fn wallet_spending_counters(\n wallet: WalletPtr,\n spending_counters_ptr_out: *mut SpendingCounters,\n) -> Result {\n let wallet = non_null!(wallet);\n let spending_counters_out = non_null_mut!(spending_counters_ptr_out);\n\n let counters = wallet.spending_counter().into_boxed_slice();\n let len = counters.len();\n\n let raw_ptr = Box::into_raw(counters);\n\n (*spending_counters_out).data = raw_ptr as *mut u32;\n (*spending_counters_out).len = len;\n\n Result::success()\n}\n\n/// get the total value in the wallet\n///\n/// make sure to call `retrieve_funds` prior to calling this function\n/// otherwise you will always have `0`\n///\n/// After calling this function the results is returned in the `total_out`.\n///\n/// # Errors\n///\n/// * this function may fail if the wallet pointer is null;\n///\n/// If the `total_out` pointer is null, this function does nothing\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n///\npub unsafe fn wallet_total_value(wallet: WalletPtr, total_out: *mut u64) -> Result {\n let wallet = if let Some(wallet) = wallet.as_ref() {\n wallet\n } else {\n return Error::invalid_input(\"wallet\").with(NulPtr).into();\n };\n\n if let Some(total_out) = total_out.as_mut() {\n let total = wallet.total_value();\n\n *total_out = *total.as_ref();\n }\n\n Result::success()\n}\n\n#[repr(C)]\npub struct SpendingCounters {\n pub data: *mut u32,\n pub len: usize,\n}\n\n/// update the wallet account state\n///\n/// this is the value retrieved from any jormungandr endpoint that allows to query\n/// for the account state. It gives the value associated to the account as well as\n/// the counter.\n///\n/// It is important to be sure to have an updated wallet state before doing any\n/// transactions otherwise future transactions may fail to be accepted by any\n/// nodes of the blockchain because of invalid signature state.\n///\n/// # Errors\n///\n/// * this function may fail if the wallet pointer is null;\n///\n/// # Safety\n///\n/// The wallet argument must be a pointer previously returned by this library. The data field in\n/// nonces must be not null and point to an array of `len` size.\npub unsafe fn wallet_set_state(wallet: WalletPtr, value: u64, nonces: SpendingCounters) -> Result {\n let wallet = if let Some(wallet) = wallet.as_mut() {\n wallet\n } else {\n return Error::invalid_input(\"wallet\").with(NulPtr).into();\n };\n\n let value = Value(value);\n\n let nonces = std::slice::from_raw_parts_mut(nonces.data, nonces.len).to_vec();\n\n match wallet.set_state(value, nonces) {\n Ok(_) => Result::success(),\n Err(e) => e.into(),\n }\n}\n\n#[repr(C)]\npub struct TransactionOut {\n pub data: *const u8,\n pub len: usize,\n}\n\n/// build the vote cast transaction\n///\n/// # Errors\n///\n/// This function may fail upon receiving a null pointer or a `choice` value\n/// that does not fall within the range specified in `proposal`.\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though the function checks if\n/// the pointers are null. Mind not to put random values in or you may see\n/// unexpected behaviors.\npub unsafe fn wallet_vote_cast(\n wallet: WalletPtr,\n settings: SettingsPtr,\n proposal: ProposalPtr,\n choice: u8,\n valid_until: BlockDate,\n lane: u8,\n transaction_out: *mut TransactionOut,\n) -> Result {\n let wallet = if let Some(wallet) = wallet.as_mut() {\n wallet\n } else {\n return Error::invalid_input(\"wallet\").with(NulPtr).into();\n };\n\n let settings = if let Some(settings) = settings.as_ref() {\n settings.clone()\n } else {\n return Error::invalid_input(\"settings\").with(NulPtr).into();\n };\n\n let proposal = if let Some(proposal) = proposal.as_ref() {\n proposal\n } else {\n return Error::invalid_input(\"proposal\").with(NulPtr).into();\n };\n\n if transaction_out.is_null() {\n return Error::invalid_input(\"transaction_out\").with(NulPtr).into();\n }\n\n let choice = Choice::new(choice);\n\n let transaction = match wallet.vote(settings, proposal, choice, &valid_until.into(), lane) {\n Ok(transaction) => Box::leak(transaction),\n Err(err) => return err.into(),\n };\n\n (*transaction_out).data = transaction.as_ptr();\n (*transaction_out).len = transaction.len();\n\n Result::success()\n}\n\n/// decrypt payload of the wallet transfer protocol\n///\n/// Parameters\n///\n/// password: byte buffer with the encryption password\n/// password_length: length of the password buffer\n/// ciphertext: byte buffer with the encryption password\n/// ciphertext_length: length of the password buffer\n/// plaintext_out: used to return a pointer to a byte buffer with the decrypted text\n/// plaintext_out_length: used to return the length of decrypted text\n///\n/// The returned buffer is in the heap, so make sure to call the delete_buffer function\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though the function checks if\n/// the pointers are null. Mind not to put random values in or you may see\n/// unexpected behaviors.\npub unsafe fn symmetric_cipher_decrypt(\n password: *const u8,\n password_length: usize,\n ciphertext: *const u8,\n ciphertext_length: usize,\n plaintext_out: *mut *const u8,\n plaintext_out_length: *mut usize,\n) -> Result {\n let password = non_null!(password);\n let ciphertext = non_null!(ciphertext);\n\n let password = std::slice::from_raw_parts(password, password_length);\n let ciphertext = std::slice::from_raw_parts(ciphertext, ciphertext_length);\n\n match symmetric_cipher::decrypt(password, ciphertext) {\n Ok(plaintext) => {\n let len = plaintext.len();\n let ptr = Box::into_raw(plaintext);\n\n let out_len = non_null_mut!(plaintext_out_length);\n let out = non_null_mut!(plaintext_out);\n\n *out_len = len;\n *out = ptr as *const u8;\n\n Result::success()\n }\n Err(err) => Error::symmetric_cipher_error(err).into(),\n }\n}\n\n/// delete the pointer and free the allocated memory\n///\n/// # Safety\n///\n/// The point must have been previously returned by this library\npub unsafe fn wallet_delete_error(error: ErrorPtr) {\n if !error.is_null() {\n let boxed = Box::from_raw(error);\n\n std::mem::drop(boxed);\n }\n}\n\n/// delete the pointer and free the allocated memory\n///\n/// # Safety\n///\n/// The point must have been previously returned by this library\npub unsafe fn wallet_delete_settings(settings: SettingsPtr) {\n if !settings.is_null() {\n let boxed = Box::from_raw(settings);\n\n std::mem::drop(boxed);\n }\n}\n\n/// delete the pointer, zero all the keys and free the allocated memory\n///\n/// # Safety\n///\n/// The pointer must have been previously returned by this library\npub unsafe fn wallet_delete_wallet(wallet: WalletPtr) {\n if !wallet.is_null() {\n let boxed = Box::from_raw(wallet);\n\n std::mem::drop(boxed);\n }\n}\n\n/// delete the pointer\n///\n/// # Safety\n///\n/// The pointer must have been previously returned by this library\npub unsafe fn wallet_delete_proposal(proposal: ProposalPtr) {\n if !proposal.is_null() {\n let boxed = Box::from_raw(proposal);\n\n std::mem::drop(boxed);\n }\n}\n\n/// Release the memory holding the spending counters\n///\n/// # Safety\n///\n/// This function is safe as long as the structure returned by this library is not modified.\n/// This function should only be called with a structure returned by this library.\npub unsafe fn spending_counters_delete(spending_counters: SpendingCounters) {\n let SpendingCounters { data, len } = spending_counters;\n if !data.is_null() {\n let data = std::slice::from_raw_parts_mut(data, len);\n let data = Box::from_raw(data as *mut [u32]);\n std::mem::drop(data);\n }\n}\n\n/// Delete a binary buffer that was returned by this library alongside with its\n/// length.\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\npub unsafe fn delete_buffer(ptr: *mut u8, length: usize) {\n if !ptr.is_null() {\n let data = std::slice::from_raw_parts_mut(ptr, length);\n let data = Box::from_raw(data as *mut [u8]);\n std::mem::drop(data);\n }\n}\n" }, { "alpha_fraction": 0.573221743106842, "alphanum_fraction": 0.5857740640640259, "avg_line_length": 18.91666603088379, "blob_id": "03d47372527436ed516aa87e4ffb19f740dc6eab", "content_id": "5c3fbb15436675455b567e72d6ce5f7b17328fcf", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 717, "license_type": "permissive", "max_line_length": 56, "num_lines": 36, "path": "/wallet/src/password.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use std::ops::{Deref, DerefMut};\n\n#[derive(Debug, Default, Clone, zeroize::ZeroizeOnDrop)]\npub struct ScrubbedBytes(Vec<u8>);\n\npub type Password = ScrubbedBytes;\n\nimpl From<Vec<u8>> for ScrubbedBytes {\n fn from(v: Vec<u8>) -> Self {\n Self(v)\n }\n}\n\nimpl From<String> for ScrubbedBytes {\n fn from(v: String) -> Self {\n Self(v.into_bytes())\n }\n}\n\nimpl AsRef<[u8]> for ScrubbedBytes {\n fn as_ref(&self) -> &[u8] {\n self.0.as_ref()\n }\n}\n\nimpl Deref for ScrubbedBytes {\n type Target = [u8];\n fn deref(&self) -> &Self::Target {\n self.0.deref()\n }\n}\nimpl DerefMut for ScrubbedBytes {\n fn deref_mut(&mut self) -> &mut Self::Target {\n self.0.deref_mut()\n }\n}\n" }, { "alpha_fraction": 0.6128807663917542, "alphanum_fraction": 0.6238468289375305, "avg_line_length": 31.642045974731445, "blob_id": "05aacf0cf74f60a5d55a95d6417f632f6b2b9145", "content_id": "fcabd5b1bef22a84af3a9adce5e779c90cfeb6c3", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 5745, "license_type": "permissive", "max_line_length": 101, "num_lines": 176, "path": "/bip39/src/lib.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "//! BIP39 mnemonics\n//!\n//! Can be used to generate the root key of a given HDWallet,\n//! an address or simply convert bits to mnemonic for human friendly\n//! value.\n//!\n//! For more details about the protocol, see\n//! [Bitcoin Improvement Proposal 39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki)\n//!\n//! # Example\n//!\n//! ## To create a new HDWallet\n//!\n//! ```\n//! # extern crate rand;\n//! #\n//! # use bip39::*;\n//!\n//! // first, you need to generate the original entropy\n//! let entropy = Entropy::generate(Type::Type18Words, rand::random);\n//!\n//! // human readable mnemonics (in English) to retrieve the original entropy\n//! // and eventually recover a HDWallet.\n//! let mnemonic_phrase = entropy.to_mnemonics().to_string(&dictionary::ENGLISH);\n//!\n//! // The seed of the HDWallet is generated from the mnemonic string\n//! // in the associated language.\n//! let seed = Seed::from_mnemonic_string(&mnemonic_phrase, b\"some password\");\n//! ```\n//!\n//! ## To recover a HDWallet\n//!\n//! ```\n//! # use bip39::*;\n//!\n//! let mnemonics = \"mimic left ask vacant toast follow bitter join diamond gate attend obey\";\n//!\n//! // to retrieve the seed, you only need the mnemonic string,\n//! // here we construct the `MnemonicString` by verifying the\n//! // mnemonics are valid against the given dictionary (English here).\n//! let mnemonic_phrase = MnemonicString::new(&dictionary::ENGLISH, mnemonics.to_owned())\n//! .expect(\"the given mnemonics are valid English words\");\n//!\n//! // The seed of the HDWallet is generated from the mnemonic string\n//! // in the associated language.\n//! let seed = Seed::from_mnemonic_string(&mnemonic_phrase, b\"some password\");\n//! ```\n//!\n\n#[cfg(test)]\nextern crate quickcheck;\n#[cfg(test)]\n#[macro_use(quickcheck)]\nextern crate quickcheck_macros;\n\nmod bits;\nmod entropy;\nmod error;\nmod mnemonic;\nmod seed;\nmod types;\n\npub mod dictionary;\n\npub use self::{\n entropy::Entropy,\n error::{Error, Result},\n mnemonic::{MnemonicIndex, MnemonicString, Mnemonics, MAX_MNEMONIC_VALUE},\n seed::{Seed, SEED_SIZE},\n types::Type,\n};\n\n#[cfg(test)]\nmod test {\n use super::*;\n use rand::random;\n\n use unicode_normalization::UnicodeNormalization;\n\n use crate::{dictionary::Language, Entropy, Seed};\n\n #[test]\n fn english_dic() {\n let dic = &dictionary::ENGLISH;\n\n assert_eq!(dic.lookup_mnemonic(\"abandon\"), Ok(MnemonicIndex(0)));\n assert_eq!(dic.lookup_mnemonic(\"crack\"), Ok(MnemonicIndex(398)));\n assert_eq!(dic.lookup_mnemonic(\"shell\"), Ok(MnemonicIndex(1579)));\n assert_eq!(dic.lookup_mnemonic(\"zoo\"), Ok(MnemonicIndex(2047)));\n\n assert_eq!(dic.lookup_word(MnemonicIndex(0)), Ok(\"abandon\".to_string()));\n assert_eq!(dic.lookup_word(MnemonicIndex(398)), Ok(\"crack\".to_string()));\n assert_eq!(\n dic.lookup_word(MnemonicIndex(1579)),\n Ok(\"shell\".to_string())\n );\n assert_eq!(dic.lookup_word(MnemonicIndex(2047)), Ok(\"zoo\".to_string()));\n }\n\n #[test]\n fn mnemonic_zero() {\n let entropy = Entropy::Entropy12([0; 16]);\n let mnemonics = entropy.to_mnemonics();\n let entropy2 = Entropy::from_mnemonics(&mnemonics).unwrap();\n assert_eq!(entropy.as_ref(), entropy2.as_ref());\n }\n\n #[test]\n fn mnemonic_7f() {\n let entropy = Entropy::Entropy12([0x7f; 16]);\n let mnemonics = entropy.to_mnemonics();\n let entropy2 = Entropy::from_mnemonics(&mnemonics).unwrap();\n assert_eq!(entropy.as_ref(), entropy2.as_ref());\n }\n\n #[test]\n fn from_mnemonic_to_mnemonic() {\n let entropy = Entropy::generate(Type::Type12Words, random);\n let mnemonics = entropy.to_mnemonics();\n let entropy2 = Entropy::from_mnemonics(&mnemonics).unwrap();\n assert_eq!(entropy.as_ref(), entropy2.as_ref());\n }\n\n #[derive(Debug)]\n struct TestVector {\n entropy: &'static str,\n mnemonics: &'static str,\n seed: &'static str,\n passphrase: &'static str,\n }\n\n fn mk_test<D: dictionary::Language>(test: &TestVector, dic: &D) {\n // decompose the UTF8 inputs before processing:\n let mnemonics: String = test.mnemonics.nfkd().collect();\n let passphrase: String = test.passphrase.nfkd().collect();\n\n let mnemonics_ref = Mnemonics::from_string(dic, &mnemonics).expect(\"valid mnemonics\");\n let mnemonics_str = MnemonicString::new(dic, mnemonics).expect(\"valid mnemonics string\");\n let entropy_ref = Entropy::from_slice(&hex::decode(test.entropy).unwrap())\n .expect(\"decode entropy from hex\");\n let seed_ref =\n Seed::from_slice(&hex::decode(test.seed).unwrap()).expect(\"decode seed from hex\");\n\n assert!(mnemonics_ref.get_type() == entropy_ref.get_type());\n\n assert!(entropy_ref.to_mnemonics() == mnemonics_ref);\n assert!(\n entropy_ref\n == Entropy::from_mnemonics(&mnemonics_ref)\n .expect(\"retrieve entropy from mnemonics\")\n );\n\n assert_eq!(\n seed_ref.as_ref(),\n Seed::from_mnemonic_string(&mnemonics_str, passphrase.as_bytes()).as_ref()\n );\n }\n\n fn mk_tests<D: dictionary::Language>(tests: &[TestVector], dic: &D) {\n for test in tests {\n mk_test(test, dic);\n }\n }\n\n #[test]\n fn test_vectors_english() {\n mk_tests(TEST_VECTORS_ENGLISH, &dictionary::ENGLISH)\n }\n #[test]\n fn test_vectors_japanese() {\n mk_tests(TEST_VECTORS_JAPANESE, &dictionary::JAPANESE)\n }\n\n const TEST_VECTORS_ENGLISH: &[TestVector] = &include!(\"test_vectors/bip39_english.txt\");\n const TEST_VECTORS_JAPANESE: &[TestVector] = &include!(\"test_vectors/bip39_japanese.txt\");\n}\n" }, { "alpha_fraction": 0.5821689963340759, "alphanum_fraction": 0.5974717140197754, "avg_line_length": 24.474576950073242, "blob_id": "1ec42a48b75d0c770f7a9513150855c4ec45faea", "content_id": "ea3a1ad87bed6c17272cfbf8ae7970e870bb242c", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1503, "license_type": "permissive", "max_line_length": 77, "num_lines": 59, "path": "/bindings/wallet-cordova/scripts/build_jni.py", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom pathlib import Path\nimport subprocess\nimport sys\nimport shutil\nfrom copy_jni_definitions import run as copy_definitions\nfrom directories import rust_build_directory, plugin_directory\n\nlibname = \"libuniffi_jormungandr_wallet.so\"\nandroid_libs_directory = Path(\"src/android/libs\")\n\ntargets = {\n \"aarch64-linux-android\": \"arm64-v8a\",\n \"armv7-linux-androideabi\": \"armeabi-v7a\",\n \"i686-linux-android\": \"x86\",\n \"x86_64-linux-android\": \"x86_64\",\n}\n\n\ndef copy_libs(release=True):\n for rust_target, android_target in targets.items():\n dst = plugin_directory / android_libs_directory / android_target\n dst.mkdir(parents=True, exist_ok=True)\n\n debug_or_release = \"release\" if release else \"debug\"\n\n src = rust_build_directory / rust_target / debug_or_release / libname\n shutil.copy(src, dst)\n\n\ndef run(release=True):\n for rust_target, android_target in targets.items():\n arguments = [\n \"cross\",\n \"rustc\",\n \"--target\",\n rust_target,\n \"-p\",\n \"wallet-uniffi\",\n \"--features\",\n \"builtin-bindgen\",\n ]\n\n if release:\n arguments = arguments + [\"--release\", \"--\", \"-C\", \"lto\"]\n\n out = subprocess.run(arguments)\n\n if out.returncode != 0:\n print(\"couldn't build for target: \", rust_target)\n sys.exit(1)\n\n copy_libs(release)\n copy_definitions()\n\n\nif __name__ == \"__main__\":\n run()\n" }, { "alpha_fraction": 0.5354494452476501, "alphanum_fraction": 0.5360426902770996, "avg_line_length": 35.64130401611328, "blob_id": "c781055256d01eae90592386ee88af5e4c25e784", "content_id": "ecb05e78bfb12d2bdeabb39352a71e907f3f47de", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3371, "license_type": "permissive", "max_line_length": 97, "num_lines": 92, "path": "/bindings/wallet-cordova/tests/src/manual_tests.js", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "const primitives = require('wallet-cordova-plugin.wallet');\n\nconst { hex, hexStringToBytes } = require('./utils.js');\n\n// TODO: untangle this nesting hell. I still don't know if I can use promises/async here\nfunction restoreManualInputWallet(mnemonics, hexBlock, callBack) {\n window.wallet.walletRestore(mnemonics, wallet => {\n window.wallet.walletRetrieveFunds(wallet, hexStringToBytes(hexBlock), settings => {\n window.wallet.walletTotalFunds(wallet, retrievedFunds => {\n window.wallet.settingsDelete(settings, () => {\n window.wallet.walletDelete(wallet, () => {\n callBack(undefined, retrievedFunds);\n }, err => { callBack(new Error(`couldn't delete wallet ${err}`)); });\n }, err => { callBack(new Error(`couldn't delete settings ${err}`)); });\n }, err => { callBack(new Error(`couldn't get total funds ${err}`)); });\n }, err => {\n callBack(new Error(`could not retrieve funds ${err}`));\n });\n }, err => {\n callBack(new Error(`could not create wallet ${err}`));\n });\n}\n\nfunction getAccountId(mnemonics, callBack) {\n primitives.walletRestore(mnemonics, wallet => {\n primitives.walletId(wallet, function (id) {\n callBack(undefined, hex(id));\n }, function (err) {\n callBack(new Error(`could not get account id ${err}`));\n });\n }, err => {\n callBack(new Error(`could not create wallet ${err}`));\n });\n}\n\nmodule.exports = function (contentEl, createActionButton) {\n var logMessage = function (message, color) {\n var log = document.getElementById('info');\n var logLine = document.createElement('div');\n if (color) {\n logLine.style.color = color;\n }\n logLine.innerHTML = message;\n log.appendChild(logLine);\n };\n\n var clearLog = function () {\n var log = document.getElementById('info');\n log.innerHTML = '';\n };\n\n const form =\n '<div> <label> mnemonics </label> <textarea id=\"mnemonics\" rows=\"1\"></textarea> </div>' +\n '<div> <label> block(hex) </label> <textarea id=\"block\" rows=\"1\"></textarea> </div>' +\n '<div id=\"get_funds\"> </div>' +\n '<div id=\"account\"> </div>';\n\n contentEl.innerHTML = '<div id=\"info\"></div>' + form;\n\n createActionButton(\n 'get funds',\n function () {\n clearLog();\n const mnemonics = document.getElementById('mnemonics').value;\n const block = document.getElementById('block').value;\n restoreManualInputWallet(mnemonics, block, (error, value) => {\n if (error) {\n logMessage(`Error: ${error}`, null);\n } else {\n logMessage(`Funds: ${value}`, null);\n }\n });\n },\n 'get_funds'\n );\n\n createActionButton(\n 'get account id',\n function () {\n clearLog();\n const mnemonics = document.getElementById('mnemonics').value;\n getAccountId(mnemonics, (error, value) => {\n if (error) {\n logMessage(`Error: ${error}`, null);\n } else {\n logMessage(`account id: ${value}`, null);\n }\n });\n },\n 'account'\n );\n};\n" }, { "alpha_fraction": 0.6942551136016846, "alphanum_fraction": 0.6962025165557861, "avg_line_length": 33.233333587646484, "blob_id": "f000afcdfee70dd4237c321b893bf736e7b21216", "content_id": "db9f59b3ba4df8a77961dffdfe0ab4d9640899d7", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 2054, "license_type": "permissive", "max_line_length": 99, "num_lines": 60, "path": "/bindings/wallet-c/src/time.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use wallet_core::c::time::{block_date_from_system_time, max_epiration_date, BlockDate};\n\nuse crate::{ErrorPtr, Settings};\n\n/// This function dereference raw pointers. Even though the function checks if\n/// the pointers are null. Mind not to put random values in or you may see\n/// unexpected behaviors.\n///\n/// # Arguments\n///\n/// *settings*: the blockchain settings previously allocated with this library. \n/// *date*: desired date of expiration for a fragment. It must be expressed in seconds since the\n/// unix epoch.\n/// *block_date_out*: pointer to an allocated BlockDate structure, the memory should be writable.\n///\n/// # Safety\n///\n/// pointers should be allocated by this library and be valid.\n/// null pointers are checked and will result in an error.\n///\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_block_date_from_system_time(\n settings: *const Settings,\n date: u64,\n block_date_out: *mut BlockDate,\n) -> ErrorPtr {\n let r = block_date_from_system_time(settings.cast::<wallet::Settings>(), date, block_date_out);\n\n r.into_c_api() as ErrorPtr\n}\n\n/// This function dereference raw pointers. Even though the function checks if\n/// the pointers are null. Mind not to put random values in or you may see\n/// unexpected behaviors.\n///\n/// # Arguments\n///\n/// *settings*: the blockchain settings previously allocated with this library. \n/// *current_time*: Current real time. It must be expressed in seconds since the unix epoch.\n/// *block_date_out*: pointer to an allocated BlockDate structure, the memory should be writable.\n///\n/// # Safety\n///\n/// pointers should be allocated by this library and be valid.\n/// null pointers are checked and will result in an error.\n///\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_max_expiration_date(\n settings: *const Settings,\n current_time: u64,\n block_date_out: *mut BlockDate,\n) -> ErrorPtr {\n let r = max_epiration_date(\n settings.cast::<wallet::Settings>(),\n current_time,\n block_date_out,\n );\n\n r.into_c_api() as ErrorPtr\n}\n" }, { "alpha_fraction": 0.5924925208091736, "alphanum_fraction": 0.597895622253418, "avg_line_length": 29.84649085998535, "blob_id": "b00a6ad7d5b745d6fd2b5eb7083188167ddb677c", "content_id": "8a3e77e716ef2892b1d8ddec453a385d193a5b3c", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 7033, "license_type": "permissive", "max_line_length": 137, "num_lines": 228, "path": "/bip39/src/mnemonic.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use zeroize::ZeroizeOnDrop;\n\nuse crate::{dictionary, Error, Result, Type};\nuse std::{fmt, ops::Deref, str};\n\n/// the maximum authorized value for a mnemonic. i.e. 2047\npub const MAX_MNEMONIC_VALUE: u16 = 2047;\n\n/// Safe representation of a valid mnemonic index (see\n/// [`MAX_MNEMONIC_VALUE`](./constant.MAX_MNEMONIC_VALUE.html)).\n///\n/// See [`dictionary module documentation`](./dictionary/index.html) for\n/// more details about how to use this.\n///\n#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]\npub struct MnemonicIndex(pub u16);\n\n/// Language agnostic mnemonic phrase representation.\n///\n/// This is an handy intermediate representation of a given mnemonic\n/// phrase. One can use this intermediate representation to translate\n/// mnemonic from one [`Language`](./dictionary/trait.Language.html)\n/// to another. **However** keep in mind that the [`Seed`](./struct.Seed.html)\n/// is linked to the mnemonic string in a specific language, in a specific\n/// dictionary. The [`Entropy`](./struct.Entropy.html) will be the same\n/// but the resulted [`Seed`](./struct.Seed.html) will differ and all\n/// the derived key of a HDWallet using the [`Seed`](./struct.Seed.html)\n/// as a source to generate the root key.\n///\n#[derive(Debug, PartialEq, Eq, Clone)]\npub struct Mnemonics(Vec<MnemonicIndex>);\n\n/// Validated mnemonic words. This guarantee a given mnemonic phrase\n/// has been safely validated against a dictionary.\n///\n/// See the module documentation for more details about how to use it\n/// within the `chain_wallet` library.\n#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, ZeroizeOnDrop)]\npub struct MnemonicString(String);\n\nimpl MnemonicString {\n /// create a `MnemonicString` from the given `String`. This function\n /// will validate the mnemonic phrase against the given [`Language`]\n ///\n /// [`Language`]: ./dictionary/trait.Language.html\n ///\n /// # Example\n ///\n /// ```\n /// # use bip39::*;\n ///\n /// const MNEMONICS : &'static str = \"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about\";\n /// let mnemonics = MnemonicString::new(&dictionary::ENGLISH, MNEMONICS.to_owned())\n /// .expect(\"valid Mnemonic phrase\");\n /// ```\n ///\n /// # Error\n ///\n /// This function may fail if one or all words are not recognized\n /// in the given [`Language`].\n ///\n pub fn new<D>(dic: &D, s: String) -> Result<Self>\n where\n D: dictionary::Language,\n {\n let _ = Mnemonics::from_string(dic, &s)?;\n\n Ok(MnemonicString(s))\n }\n}\n\nimpl MnemonicIndex {\n /// smart constructor, validate the given value fits the mnemonic index\n /// boundaries (see [`MAX_MNEMONIC_VALUE`](./constant.MAX_MNEMONIC_VALUE.html)).\n ///\n /// # Example\n ///\n /// ```\n /// # use bip39::*;\n /// #\n /// let index = MnemonicIndex::new(1029);\n /// assert!(index.is_ok());\n /// // this line will fail\n /// let index = MnemonicIndex::new(4029);\n /// assert_eq!(index, Err(Error::MnemonicOutOfBound(4029)));\n /// ```\n ///\n /// # Error\n ///\n /// returns an [`Error::MnemonicOutOfBound`](enum.Error.html#variant.MnemonicOutOfBound)\n /// if the given value does not fit the valid values.\n ///\n pub fn new(m: u16) -> Result<Self> {\n if m <= MAX_MNEMONIC_VALUE {\n Ok(MnemonicIndex(m))\n } else {\n Err(Error::MnemonicOutOfBound(m))\n }\n }\n\n /// lookup in the given dictionary to retrieve the mnemonic word.\n ///\n /// # panic\n ///\n /// this function may panic if the\n /// [`Language::lookup_word`](./dictionary/trait.Language.html#method.lookup_word)\n /// returns an error. Which should not happen.\n ///\n pub fn to_word<D>(self, dic: &D) -> String\n where\n D: dictionary::Language,\n {\n dic.lookup_word(self).unwrap()\n }\n\n /// retrieve the Mnemonic index from the given word in the\n /// given dictionary.\n ///\n /// # Error\n ///\n /// May fail with a [`LanguageError`](enum.Error.html#variant.LanguageError)\n /// if the given [`Language`](./dictionary/trait.Language.html) returns the\n /// given word is not within its dictionary.\n ///\n pub fn from_word<D>(dic: &D, word: &str) -> Result<Self>\n where\n D: dictionary::Language,\n {\n let v = dic.lookup_mnemonic(word)?;\n Ok(v)\n }\n}\n\nimpl Mnemonics {\n /// get the [`Type`](./enum.Type.html) of this given `Mnemonics`.\n ///\n /// # panic\n ///\n /// the only case this function may panic is if the `Mnemonics` has\n /// been badly constructed (i.e. not from one of the given smart\n /// constructor).\n ///\n pub fn get_type(&self) -> Type {\n Type::from_word_count(self.0.len()).unwrap()\n }\n\n /// get the mnemonic string representation in the given\n /// [`Language`](./dictionary/trait.Language.html).\n ///\n pub fn to_string<D>(&self, dic: &D) -> MnemonicString\n where\n D: dictionary::Language,\n {\n let mut vec = String::new();\n let mut first = true;\n for m in self.0.iter() {\n if first {\n first = false;\n } else {\n vec.push_str(dic.separator());\n }\n vec.push_str(&m.to_word(dic))\n }\n MnemonicString(vec)\n }\n\n /// Construct the `Mnemonics` from its string representation in the given\n /// [`Language`](./dictionary/trait.Language.html).\n ///\n /// # Error\n ///\n /// May fail with a [`LanguageError`](enum.Error.html#variant.LanguageError)\n /// if the given [`Language`](./dictionary/trait.Language.html) returns the\n /// given word is not within its dictionary.\n ///\n pub fn from_string<D>(dic: &D, mnemonics: &str) -> Result<Self>\n where\n D: dictionary::Language,\n {\n let mut vec = vec![];\n for word in mnemonics.split(dic.separator()) {\n vec.push(MnemonicIndex::from_word(dic, word)?);\n }\n Mnemonics::from_mnemonics(vec)\n }\n\n /// Construct the `Mnemonics` from the given array of `MnemonicIndex`.\n ///\n /// # Error\n ///\n /// May fail if this is an invalid number of `MnemonicIndex`.\n ///\n pub fn from_mnemonics(mnemonics: Vec<MnemonicIndex>) -> Result<Self> {\n let _ = Type::from_word_count(mnemonics.len())?;\n Ok(Mnemonics(mnemonics))\n }\n\n pub(crate) fn iter(&self) -> impl Iterator<Item = &MnemonicIndex> {\n self.0.iter()\n }\n}\n\nimpl AsRef<[MnemonicIndex]> for Mnemonics {\n fn as_ref(&self) -> &[MnemonicIndex] {\n &self.0[..]\n }\n}\n\nimpl Deref for MnemonicString {\n type Target = str;\n fn deref(&self) -> &Self::Target {\n self.0.deref()\n }\n}\n\nimpl fmt::Display for MnemonicString {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n\nimpl Drop for Mnemonics {\n fn drop(&mut self) {\n for byte in self.0.iter_mut() {\n *byte = MnemonicIndex(0);\n }\n }\n}\n" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 29, "blob_id": "77a908d9b69c441d893481ca1eb777a87558dc5b", "content_id": "a63eb244ecb12b6db76bbf4e139f370234388a84", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 90, "license_type": "permissive", "max_line_length": 77, "num_lines": 3, "path": "/bindings/wallet-c/regen_header.sh", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "#! /bin/sh\n\ncbindgen --config cbindgen.toml --crate jormungandrwallet --output wallet.h .\n" }, { "alpha_fraction": 0.5852712988853455, "alphanum_fraction": 0.6408268809318542, "avg_line_length": 31.25, "blob_id": "0d08cddd20d696b081c4726124cebfd13d3a5d8a", "content_id": "2db9311194cb6badcc3f7edde4ce8530ae02f61b", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 774, "license_type": "permissive", "max_line_length": 105, "num_lines": 24, "path": "/hdkeygen/Cargo.toml", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "[package]\nname = \"hdkeygen\"\nversion = \"0.2.0\"\nauthors = [\"Nicolas Di Prima <[email protected]>\", \"Vincent Hanquez <[email protected]>\"]\nedition = \"2018\"\nlicense = \"MIT OR Apache-2.0\"\n\n[dependencies]\ncryptoxide = \"0.4.2\"\ned25519-bip32 = \"0.4.0\"\nbip39 = { path = \"../bip39\" }\ncbor_event = \"^2.1.3\"\nthiserror = { version = \"1.0.13\", default-features = false }\nchain-path-derivation = { path = \"../chain-path-derivation\" }\nhex = \"0.4.2\"\nzeroize = \"1.5.3\"\n\nchain-crypto = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-addr = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\ncardano-legacy-address = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\n\n[dev-dependencies]\nquickcheck = \"0.9\"\nquickcheck_macros = \"0.9\"\n" }, { "alpha_fraction": 0.7093595862388611, "alphanum_fraction": 0.7192118167877197, "avg_line_length": 15.916666984558105, "blob_id": "a770a23cd3411162e74142d742ef0f62e47b17d4", "content_id": "ae30e7023a1d2ead42d59898e99307fa6cca6c10", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 203, "license_type": "permissive", "max_line_length": 35, "num_lines": 12, "path": "/hdkeygen/src/lib.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "#[cfg(test)]\nextern crate quickcheck;\n#[cfg(test)]\n#[macro_use(quickcheck)]\nextern crate quickcheck_macros;\n\npub mod account;\npub mod bip44;\nmod key;\npub mod rindex;\n\npub use self::key::{Key, KeyRange};\n" }, { "alpha_fraction": 0.6168308854103088, "alphanum_fraction": 0.6202929615974426, "avg_line_length": 37.62963104248047, "blob_id": "6fd3c385d7b72036a7a856e11fc97ceb2c12b171", "content_id": "2f159c7a7c496ef37eaaf1ce8f281b6c044f2f44", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 18775, "license_type": "permissive", "max_line_length": 99, "num_lines": 486, "path": "/bindings/wallet-cordova/src/android/WalletPlugin.kt", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "package com.iohk.jormungandr_wallet;\n\nimport android.util.Base64\nimport android.util.Log\nimport org.apache.cordova.*\nimport org.json.JSONArray\nimport org.json.JSONException\nimport org.json.JSONObject\nimport java.text.Normalizer\nimport java.text.Normalizer.Form\nimport java.util.concurrent.atomic.AtomicInteger\n\nclass WalletPlugin\n/**\n * Constructor.\n */\n : CordovaPlugin() {\n @ExperimentalUnsignedTypes\n private val wallets: MutableMap<Int, Wallet> = mutableMapOf()\n private var nextWalletId = AtomicInteger()\n\n @ExperimentalUnsignedTypes\n private val settingsPool: MutableMap<Int, Settings> = mutableMapOf()\n private var nextSettingsId = AtomicInteger()\n\n @ExperimentalUnsignedTypes\n private val pendingTransactionsPool: MutableMap<Int, List<List<UByte>>> = mutableMapOf()\n private var nextPendingTransactionsId = AtomicInteger()\n\n @ExperimentalUnsignedTypes\n private val proposalPool: MutableMap<Int, Proposal> = mutableMapOf()\n private var nextProposalId = AtomicInteger()\n\n /**\n * Sets the context of the Command. This can then be used to do things like get\n * file paths associated with the Activity.\n *\n * @param cordova The context of the main Activity.\n * @param webView The CordovaWebView Cordova is running in.\n */\n override fun initialize(cordova: CordovaInterface?, webView: CordovaWebView?) {\n super.initialize(cordova, webView)\n Log.d(TAG, \"Initializing wallet plugin\")\n }\n\n /**\n * Executes the request and returns PluginResult.\n *\n * @param action The action to execute.\n * @param args JSONArry of arguments for the plugin.\n * @param callbackContext The callback id used when calling back into\n * JavaScript.\n * @return True if the action was valid, false if not.\n */\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n override fun execute(\n action: String,\n args: CordovaArgs,\n callbackContext: CallbackContext\n ): Boolean {\n Log.d(TAG, \"action: $action\")\n when (action) {\n \"WALLET_IMPORT_KEYS\" -> walletImportKeys(args, callbackContext)\n \"SYMMETRIC_CIPHER_DECRYPT\" -> symmetricCipherDecrypt(args, callbackContext)\n \"SETTINGS_NEW\" -> settingsNew(args, callbackContext)\n \"SETTINGS_GET\" -> settingsGet(args, callbackContext)\n \"WALLET_VOTE\" -> walletVote(args, callbackContext)\n \"WALLET_TOTAL_FUNDS\" -> walletTotalFunds(args, callbackContext)\n \"WALLET_SPENDING_COUNTER\" -> walletSpendingCounters(args, callbackContext)\n \"WALLET_ID\" -> walletId(args, callbackContext)\n \"WALLET_SET_STATE\" -> walletSetState(args, callbackContext)\n \"PENDING_TRANSACTIONS_SIZE\" -> pendingTransactionsSize(args, callbackContext)\n \"PENDING_TRANSACTIONS_GET\" -> pendingTransactionsGet(args, callbackContext)\n \"BLOCK_DATE_FROM_SYSTEM_TIME\" -> blockDateFromSystemTime(args, callbackContext)\n \"MAX_EXPIRATION_DATE\" -> maxExpirationDate(args, callbackContext)\n \"PROPOSAL_NEW_PUBLIC\" -> proposalNewPublic(args, callbackContext)\n \"PROPOSAL_NEW_PRIVATE\" -> proposalNewPrivate(args, callbackContext)\n \"FRAGMENT_ID\" -> fragmentId(args, callbackContext)\n \"WALLET_DELETE\" -> walletDelete(args, callbackContext)\n \"SETTINGS_DELETE\" -> settingsDelete(args, callbackContext)\n \"PROPOSAL_DELETE\" -> proposalDelete(args, callbackContext)\n \"PENDING_TRANSACTIONS_DELETE\" -> pendingTransactionsDelete(args, callbackContext)\n else -> {\n Log.w(TAG, \"not found: $action\")\n return false\n }\n }\n return true\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun walletImportKeys(args: CordovaArgs, callbackContext: CallbackContext) {\n val accountKey = args.getArrayBuffer(0).toUByteArray().toList()\n\n try {\n val walletId = nextWalletId.incrementAndGet()\n wallets[walletId] = Wallet(SecretKeyEd25519Extended(accountKey))\n callbackContext.success(walletId.toString())\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun symmetricCipherDecrypt(args: CordovaArgs, callbackContext: CallbackContext) {\n val password = args.getArrayBuffer(0).toUByteArray()\n val ciphertext = args.getArrayBuffer(1).toUByteArray()\n\n try {\n val decrypted =\n symmetricCipherDecrypt(password.toList(), ciphertext.toList()).toUByteArray()\n .toByteArray()\n callbackContext.success(decrypted)\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun settingsNew(args: CordovaArgs, callbackContext: CallbackContext) {\n val block0Hash = args.getArrayBuffer(0).toUByteArray().toList()\n val discriminationInput = args.getInt(1)\n val fees = args[2] as JSONObject\n val block0Date = args.getString(3).toULong()\n val slotDuration = args.getString(4).toUByte()\n val era = args[5] as JSONObject\n val transactionMaxExpiryEpochs = args.getString(6).toUByte()\n try {\n val constant = fees.getString(\"constant\").toULong()\n val coefficient = fees.getString(\"coefficient\").toULong()\n val certificate = fees.getString(\"certificate\").toULong()\n val certificatePoolRegistration =\n fees.getString(\"certificatePoolRegistration\").toULong()\n val certificateStakeDelegation = fees.getString(\"certificateStakeDelegation\").toULong()\n val certificateOwnerStakeDelegation =\n fees.getString(\"certificateOwnerStakeDelegation\").toULong()\n val certificateVotePlan = fees.getString(\"certificateVotePlan\").toULong()\n val certificateVoteCast = fees.getString(\"certificateVoteCast\").toULong()\n val linearFees: LinearFee = LinearFee(\n constant, coefficient, certificate,\n PerCertificateFee(\n certificatePoolRegistration.toULong(), certificateStakeDelegation.toULong(),\n certificateOwnerStakeDelegation.toULong()\n ),\n PerVoteCertificateFee(\n certificateVotePlan.toULong(),\n certificateVoteCast.toULong()\n )\n )\n val discrimination: Discrimination =\n if (discriminationInput == 0) Discrimination.PRODUCTION else Discrimination.TEST\n val timeEra = TimeEra(\n era.getString(\"epochStart\").toUInt(),\n era.getString(\"slotStart\").toULong(),\n era.getString(\"slotsPerEpoch\").toUInt()\n )\n val settingsInit = SettingsRaw(\n linearFees, discrimination, block0Hash, block0Date, slotDuration,\n timeEra, transactionMaxExpiryEpochs\n )\n\n val settingsId = nextSettingsId.incrementAndGet()\n settingsPool[settingsId] = Settings(settingsInit)\n\n callbackContext.success(settingsId.toString())\n } catch (e: java.lang.Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun settingsGet(args: CordovaArgs, callbackContext: CallbackContext) {\n val settingsId = args.getInt(0)\n try {\n val settings = settingsPool[settingsId]\n\n val settingsRaw = settings?.settingsRaw()\n\n val fees = settingsRaw?.fees\n val discrimination: Discrimination? = settingsRaw?.discrimination\n val block0Hash = settingsRaw?.block0Hash?.toUByteArray()\n val feesJson = JSONObject().put(\"constant\", fees?.constant.toString())\n .put(\"coefficient\", fees?.coefficient.toString())\n .put(\"certificate\", fees?.certificate.toString())\n .put(\n \"certificatePoolRegistration\",\n fees?.perCertificateFees?.certificatePoolRegistration.toString()\n )\n .put(\n \"certificateStakeDelegation\",\n fees?.perCertificateFees?.certificateStakeDelegation.toString()\n )\n .put(\n \"certificateOwnerStakeDelegation\",\n fees?.perCertificateFees?.certificateOwnerStakeDelegation.toString()\n )\n .put(\n \"certificateVotePlan\",\n fees?.perVoteCertificateFees?.certificateVotePlan.toString()\n )\n .put(\n \"certificateVoteCast\",\n fees?.perVoteCertificateFees?.certificateVoteCast.toString()\n )\n val result: JSONObject = JSONObject().put(\"fees\", feesJson)\n .put(\n \"discrimination\",\n if (discrimination === Discrimination.PRODUCTION) 0 else 1\n )\n .put(\n \"block0Hash\", Base64.encodeToString(\n block0Hash?.asByteArray(),\n Base64.NO_WRAP\n )\n )\n\n callbackContext.success(result)\n } catch (e: java.lang.Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun walletVote(args: CordovaArgs, callbackContext: CallbackContext) {\n val walletId = args.getInt(0)\n val settingsId = args.getInt(1)\n val proposalId = args.getInt(2)\n val choice = args.getString(3).toUByte()\n val expirationDate = args[4] as JSONObject\n val epoch = expirationDate.getString(\"epoch\").toUInt()\n val slot = expirationDate.getString(\"slot\").toUInt()\n val lane = args.getString(5).toUByte()\n\n val wallet = wallets[walletId]\n val settings = settingsPool[settingsId]\n val proposal = proposalPool[proposalId]\n\n val validUntil = BlockDate(epoch, slot)\n\n try {\n val tx = wallet?.vote(settings!!, proposal!!, choice, validUntil, lane)\n\n callbackContext.success(tx?.toUByteArray()?.toByteArray())\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun walletTotalFunds(args: CordovaArgs, callbackContext: CallbackContext) {\n val walletId = args.getInt(0)\n val wallet = wallets[walletId]\n try {\n callbackContext.success(wallet?.totalValue().toString())\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun walletSpendingCounters(args: CordovaArgs, callbackContext: CallbackContext) {\n val walletId = args.getInt(0)\n val wallet = wallets[walletId]\n try {\n val array = JSONArray()\n for (nonce in wallet?.spendingCounters()!!) {\n array.put(nonce)\n }\n callbackContext.success(array)\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun walletId(args: CordovaArgs, callbackContext: CallbackContext) {\n val walletId = args.getInt(0)\n val wallet = wallets[walletId]\n\n try {\n val id = wallet?.accountId()?.toUByteArray()?.toByteArray()\n callbackContext.success(id)\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun walletSetState(args: CordovaArgs, callbackContext: CallbackContext) {\n val walletId = args.getInt(0)\n val value = args.getString(1).toULong()\n val rawCounters = args.getJSONArray(2)\n\n val counters = mutableListOf<UInt>()\n for (i in 0 until rawCounters.length()) {\n counters.add(rawCounters.getString(i).toUInt())\n }\n\n try {\n wallets[walletId]?.setState(value, counters)\n callbackContext.success()\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun pendingTransactionsSize(args: CordovaArgs, callbackContext: CallbackContext) {\n val pendingTransactionsId = args.getInt(0)\n val pendingTransactions = pendingTransactionsPool[pendingTransactionsId]\n try {\n val size = pendingTransactions?.size\n callbackContext.success(size.toString())\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun pendingTransactionsGet(args: CordovaArgs, callbackContext: CallbackContext) {\n val pendingTransactionsId = args.getInt(0)\n val index = args.getInt(1)\n try {\n val transaction = pendingTransactionsPool[pendingTransactionsId]?.get(index)\n\n callbackContext.success(transaction?.toUByteArray()?.toByteArray())\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun blockDateFromSystemTime(args: CordovaArgs, callbackContext: CallbackContext) {\n val settingsId = args.getInt(0)\n val unixEpoch = args.getString(1).toULong()\n val settings = settingsPool[settingsId]\n try {\n val blockDate = blockDateFromSystemTime(settings!!, unixEpoch)\n val json =\n JSONObject().put(\"epoch\", blockDate.epoch.toString()).put(\n \"slot\",\n blockDate.slot.toString()\n )\n callbackContext.success(json)\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun maxExpirationDate(args: CordovaArgs, callbackContext: CallbackContext) {\n val settingsId = args.getInt(0)\n val unixEpoch = args.getString(1).toULong()\n val settings = settingsPool[settingsId]\n try {\n val blockDate = maxExpirationDate(settings!!, unixEpoch)\n val json =\n JSONObject().put(\"epoch\", blockDate.epoch.toString()).put(\n \"slot\",\n blockDate.slot.toString()\n )\n callbackContext.success(json)\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun proposalNewPublic(args: CordovaArgs, callbackContext: CallbackContext) {\n val votePlanId = args.getArrayBuffer(0).toUByteArray().toList()\n val index = args.getString(1).toUByte()\n val numChoices = args.getString(2).toUByte()\n try {\n val proposal = Proposal(votePlanId, index, numChoices, PayloadTypeConfig.Public)\n\n val proposalId = nextProposalId.incrementAndGet()\n proposalPool[proposalId] = proposal\n callbackContext.success(proposalId.toString())\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun proposalNewPrivate(args: CordovaArgs, callbackContext: CallbackContext) {\n val votePlanId = args.getArrayBuffer(0).toUByteArray().toList()\n val index = args.getString(1).toUByte()\n val numChoices = args.getString(2).toUByte()\n val encryptingVoteKey = args.getString(3)\n try {\n val proposal = Proposal(\n votePlanId, index, numChoices, PayloadTypeConfig.Private(\n encryptingVoteKey\n )\n )\n\n val proposalId = nextProposalId.incrementAndGet()\n proposalPool[proposalId] = proposal\n callbackContext.success(proposalId.toString())\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun fragmentId(args: CordovaArgs, callbackContext: CallbackContext) {\n val transaction = args.getArrayBuffer(0).toUByteArray().toList()\n try {\n val fragment = Fragment(transaction)\n val id = fragment.id()\n fragment.destroy()\n callbackContext.success(id.toUByteArray().toByteArray())\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun walletDelete(args: CordovaArgs, callbackContext: CallbackContext) {\n val walletId: Int = args.getInt(0)\n try {\n wallets[walletId]?.destroy()\n callbackContext.success()\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun settingsDelete(args: CordovaArgs, callbackContext: CallbackContext) {\n val settingsId: Int = args.getInt(0)\n try {\n settingsPool[settingsId]?.destroy()\n callbackContext.success()\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun proposalDelete(args: CordovaArgs, callbackContext: CallbackContext) {\n val proposalId: Int = args.getInt(0)\n try {\n proposalPool.remove(proposalId)\n callbackContext.success()\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n @ExperimentalUnsignedTypes\n @Throws(JSONException::class)\n private fun pendingTransactionsDelete(args: CordovaArgs, callbackContext: CallbackContext) {\n val pid: Int = args.getInt(0)\n try {\n pendingTransactionsPool.remove(pid)\n callbackContext.success()\n } catch (e: Exception) {\n callbackContext.error(e.message)\n }\n }\n\n companion object {\n const val TAG = \"WALLET\"\n }\n}\n\n" }, { "alpha_fraction": 0.5126469731330872, "alphanum_fraction": 0.5151407122612, "avg_line_length": 27.93814468383789, "blob_id": "2716567e6680bc31af23d1d7172579a687785440", "content_id": "87c4a02e6e146f985e84c9b16beefcff88101676", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 2807, "license_type": "permissive", "max_line_length": 86, "num_lines": 97, "path": "/bindings/wallet-core/src/vote.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use chain_impl_mockchain::{\n certificate::{VoteCast, VotePlanId},\n vote::{self, Choice, Options, Payload},\n};\nuse chain_vote::{ElectionPublicKey, Vote};\n\npub const VOTE_PLAN_ID_LENGTH: usize = 32;\n\npub struct Proposal {\n vote_plan_id: VotePlanId,\n index: u8,\n options: Options,\n payload_type: PayloadTypeConfig,\n}\n\npub enum PayloadTypeConfig {\n Public,\n Private(ElectionPublicKey),\n}\n\nimpl Proposal {\n pub fn new(\n vote_plan_id: VotePlanId,\n index: u8,\n options: Options,\n payload_type: PayloadTypeConfig,\n ) -> Self {\n Self {\n vote_plan_id,\n index,\n options,\n payload_type,\n }\n }\n\n pub fn new_public(vote_plan_id: VotePlanId, index: u8, options: Options) -> Self {\n Self::new(vote_plan_id, index, options, PayloadTypeConfig::Public)\n }\n\n pub fn new_private(\n vote_plan_id: VotePlanId,\n index: u8,\n options: Options,\n key: ElectionPublicKey,\n ) -> Self {\n Self::new(\n vote_plan_id,\n index,\n options,\n PayloadTypeConfig::Private(key),\n )\n }\n\n pub fn vote(&self, choice: Choice) -> Option<VoteCast> {\n if !self.options.validate(choice) {\n return None;\n }\n\n let payload = match self.payload_type {\n PayloadTypeConfig::Public => Payload::Public { choice },\n PayloadTypeConfig::Private(ref key) => {\n let mut rng = rand::rngs::OsRng;\n\n // there is actually no way to build an Options object that\n // doesn't start from 0, but the fact that internally is a range\n // allows it, so I take the length of the interval just in case\n // for the size of the unit vector. There is no difference\n // anyway if the start is zero\n let length = self\n .options\n .choice_range()\n .end\n .checked_sub(self.options.choice_range().start)?;\n\n // the Choice was validated already, so this can't overflow\n let choice = choice.as_byte() - self.options.choice_range().start;\n\n let vote = Vote::new(length.into(), choice.into());\n let (encrypted_vote, proof) = vote::encrypt_vote(\n &mut rng,\n &chain_vote::Crs::from_hash(self.vote_plan_id.as_ref()),\n key,\n vote,\n );\n\n Payload::Private {\n encrypted_vote,\n proof,\n }\n }\n };\n\n let cast = VoteCast::new(self.vote_plan_id.clone(), self.index, payload);\n\n Some(cast)\n }\n}\n" }, { "alpha_fraction": 0.5926103591918945, "alphanum_fraction": 0.5964491367340088, "avg_line_length": 26.0649356842041, "blob_id": "33bc0d47a6b74e33e6be1c2a7d297b029dcc1519", "content_id": "3b178651b0f2ccb38170e6a2a95ae8695ac68478", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 2084, "license_type": "permissive", "max_line_length": 95, "num_lines": 77, "path": "/bindings/wallet-core/src/c/time.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use crate::{Error, Result};\nuse std::time::{Duration, SystemTime};\nuse wallet::Settings;\n\n#[repr(C)]\npub struct BlockDate {\n pub epoch: u32,\n pub slot: u32,\n}\n\nimpl From<chain_impl_mockchain::block::BlockDate> for BlockDate {\n fn from(date: chain_impl_mockchain::block::BlockDate) -> Self {\n BlockDate {\n epoch: date.epoch,\n slot: date.slot_id,\n }\n }\n}\n\nimpl From<BlockDate> for chain_impl_mockchain::block::BlockDate {\n fn from(date: BlockDate) -> Self {\n chain_impl_mockchain::block::BlockDate {\n epoch: date.epoch,\n slot_id: date.slot,\n }\n }\n}\n\n///\n/// # Safety\n///\n/// settings should be a pointer to a valid settings object allocated by this library with, for\n/// example, settings_build.\npub unsafe fn block_date_from_system_time(\n settings: *const Settings,\n date: u64,\n block_date_out: *mut BlockDate,\n) -> Result {\n let settings = non_null!(settings);\n match wallet::time::block_date_from_system_time(\n settings,\n SystemTime::UNIX_EPOCH + Duration::from_secs(date),\n ) {\n Ok(block_date) => {\n (*block_date_out).epoch = block_date.epoch;\n (*block_date_out).slot = block_date.slot_id;\n\n Result::success()\n }\n Err(_) => Error::invalid_transaction_validity_date().into(),\n }\n}\n\n///\n/// # Safety\n///\n/// settings should be a pointer to a valid settings object allocated by this library with, for\n/// example, settings_build.\npub unsafe fn max_epiration_date(\n settings: *const Settings,\n current_time: u64,\n block_date_out: *mut BlockDate,\n) -> Result {\n let settings = non_null!(settings);\n match wallet::time::max_expiration_date(\n settings,\n SystemTime::UNIX_EPOCH + Duration::from_secs(current_time),\n ) {\n Ok(block_date) => {\n (*block_date_out).epoch = block_date.epoch;\n (*block_date_out).slot = block_date.slot_id;\n\n Result::success()\n }\n Err(_) => Error::invalid_transaction_validity_date().into(),\n }\n}\n" }, { "alpha_fraction": 0.6183580756187439, "alphanum_fraction": 0.6273336410522461, "avg_line_length": 32.158729553222656, "blob_id": "99db726d833ef5ad7edbd30e6a08729f22755542", "content_id": "e489837e0b9fd43a8968b704352b2c6102f3eb46", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 8356, "license_type": "permissive", "max_line_length": 109, "num_lines": 252, "path": "/bindings/wallet-core/src/c/settings.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use super::NulPtr;\nuse crate::{Error, Result};\nuse chain_impl_mockchain::{config, fee, header::HeaderId};\nuse std::{convert::TryInto, num::NonZeroU64};\nuse wallet::Settings;\n\n/// Linear fee using the basic affine formula\n/// `COEFFICIENT * bytes(COUNT(tx.inputs) + COUNT(tx.outputs)) + CONSTANT + CERTIFICATE*COUNT(certificates)`.\n#[repr(C)]\n#[derive(Default)]\npub struct LinearFee {\n pub constant: u64,\n pub coefficient: u64,\n pub certificate: u64,\n pub per_certificate_fees: PerCertificateFee,\n pub per_vote_certificate_fees: PerVoteCertificateFee,\n}\n\n#[repr(C)]\n#[derive(Default)]\npub struct PerCertificateFee {\n pub certificate_pool_registration: u64,\n pub certificate_stake_delegation: u64,\n pub certificate_owner_stake_delegation: u64,\n}\n\n#[repr(C)]\n#[derive(Default)]\npub struct PerVoteCertificateFee {\n pub certificate_vote_plan: u64,\n pub certificate_vote_cast: u64,\n}\n\n#[repr(C)]\npub enum Discrimination {\n Production = 0, // just for consistency, it's not like it matters\n Test,\n}\n\npub type Epoch = u32;\npub type Slot = u64;\n\n#[repr(C)]\npub struct TimeEra {\n pub epoch_start: Epoch,\n pub slot_start: Slot,\n pub slots_per_epoch: u32,\n}\n\nimpl From<TimeEra> for chain_time::TimeEra {\n fn from(te: TimeEra) -> Self {\n chain_time::TimeEra::new(\n te.slot_start.into(),\n chain_time::Epoch(te.epoch_start),\n te.slots_per_epoch,\n )\n }\n}\n\n#[repr(C)]\npub struct SettingsInit {\n pub fees: LinearFee,\n pub discrimination: Discrimination,\n /// block_0_initial_hash is assumed to point to 32 bytes of readable memory\n pub block0_initial_hash: *const u8,\n /// Unix timestamp of the genesis block.\n /// Provides an anchor to compute block dates from calendar date/time.\n pub block0_date: u64,\n pub slot_duration: u8,\n pub time_era: TimeEra,\n pub transaction_max_expiry_epochs: u8,\n}\n\n/// # Safety\n///\n/// settings_out must point to valid writable memory\npub unsafe fn settings_new(settings: SettingsInit, settings_out: *mut *mut Settings) -> Result {\n let SettingsInit {\n fees,\n discrimination,\n block0_initial_hash,\n block0_date,\n slot_duration,\n time_era,\n transaction_max_expiry_epochs,\n } = settings;\n\n let settings_out = non_null_mut!(settings_out);\n\n let discrimination = match discrimination {\n Discrimination::Production => chain_addr::Discrimination::Production,\n Discrimination::Test => chain_addr::Discrimination::Test,\n };\n\n let block0_initial_hash =\n HeaderId::from_bytes(non_null_array!(block0_initial_hash, 32).try_into().unwrap());\n\n let linear_fee = fee::LinearFee {\n constant: fees.constant,\n coefficient: fees.coefficient,\n certificate: fees.certificate,\n per_certificate_fees: fee::PerCertificateFee {\n certificate_pool_registration: NonZeroU64::new(\n fees.per_certificate_fees.certificate_pool_registration,\n ),\n certificate_stake_delegation: NonZeroU64::new(\n fees.per_certificate_fees.certificate_stake_delegation,\n ),\n certificate_owner_stake_delegation: NonZeroU64::new(\n fees.per_certificate_fees.certificate_owner_stake_delegation,\n ),\n },\n per_vote_certificate_fees: fee::PerVoteCertificateFee {\n certificate_vote_plan: NonZeroU64::new(\n fees.per_vote_certificate_fees.certificate_vote_plan,\n ),\n certificate_vote_cast: NonZeroU64::new(\n fees.per_vote_certificate_fees.certificate_vote_cast,\n ),\n },\n };\n\n let ptr = Box::into_raw(Box::new(Settings {\n fees: linear_fee,\n discrimination,\n block0_initial_hash,\n block0_date: config::Block0Date(block0_date),\n slot_duration,\n time_era: time_era.into(),\n transaction_max_expiry_epochs,\n }));\n\n *settings_out = ptr;\n\n Result::success()\n}\n\n/// # Safety\n///\n/// This function also assumes that settings is a valid pointer previously\n/// obtained with this library, a null check is performed, but is important that\n/// the data it points to is valid\n///\n/// linear_fee_out must point to valid writable memory, a null check is\n/// performed\npub unsafe fn settings_fees(settings: *const Settings, linear_fee_out: *mut LinearFee) -> Result {\n let settings = non_null!(settings);\n // In theory, getting a &mut from linear_fee_output and setting the fields\n // one by one should be fine, becuase is repr(C), we are not reading, and\n // the fields are just numbers (no Drop nor anything).\n // In practice, it may be UB and I don't think it's worth the hassle, so we\n // just create a new one fully initialized and use ptr::write\n\n let fees = settings.fees.clone();\n\n let fees = LinearFee {\n constant: fees.constant,\n coefficient: fees.coefficient,\n certificate: fees.certificate,\n per_certificate_fees: PerCertificateFee {\n certificate_pool_registration: fees\n .per_certificate_fees\n .certificate_pool_registration\n .map(Into::into)\n .unwrap_or(0),\n certificate_stake_delegation: fees\n .per_certificate_fees\n .certificate_stake_delegation\n .map(Into::into)\n .unwrap_or(0),\n certificate_owner_stake_delegation: fees\n .per_certificate_fees\n .certificate_owner_stake_delegation\n .map(Into::into)\n .unwrap_or(0),\n },\n per_vote_certificate_fees: PerVoteCertificateFee {\n certificate_vote_plan: fees\n .per_vote_certificate_fees\n .certificate_vote_plan\n .map(Into::into)\n .unwrap_or(0),\n certificate_vote_cast: fees\n .per_vote_certificate_fees\n .certificate_vote_cast\n .map(Into::into)\n .unwrap_or(0),\n },\n };\n\n if linear_fee_out.is_null() {\n Error::invalid_input(\"linear_fee_out\").with(NulPtr).into()\n } else {\n // we are actually not checking alignment anywhere, and I think it is\n // unlikely to get unaligned data for a struct that's essentially a u64\n // array, but just in case\n // we could just put a comment, though\n std::ptr::write_unaligned(linear_fee_out, fees);\n Result::success()\n }\n}\n\n/// # Safety\n///\n/// This function also assumes that settings is a valid pointer previously\n/// obtained with this library, a null check is performed, but is important that\n/// the data it points to is valid\n///\n/// discrimination_out must point to valid writable memory, a null check is\n/// performed\npub unsafe fn settings_discrimination(\n settings: *const Settings,\n discrimination_out: *mut Discrimination,\n) -> Result {\n let settings = non_null!(settings);\n\n let discrimination = match settings.discrimination {\n chain_addr::Discrimination::Production => Discrimination::Production,\n chain_addr::Discrimination::Test => Discrimination::Test,\n };\n\n if discrimination_out.is_null() {\n Error::invalid_input(\"discrimination_out\")\n .with(NulPtr)\n .into()\n } else {\n // again, an enum with 2 values will probably be 1 byte, or 4 maybe...\n // maybe in this case we can assume it is aligned\n std::ptr::write_unaligned(discrimination_out, discrimination);\n Result::success()\n }\n}\n\n/// # Safety\n///\n/// This function assumes block0_hash points to 32 bytes of valid memory\n/// This function also assumes that settings is a valid pointer previously\n/// obtained with this library, a null check is performed, but is important that\n/// the data it points to is valid\n#[no_mangle]\npub unsafe fn settings_block0_hash(settings: *const Settings, block0_hash: *mut u8) -> Result {\n let settings = non_null!(settings);\n\n if block0_hash.is_null() {\n Error::invalid_input(\"block0_hash\").with(NulPtr).into()\n } else {\n let bytes = settings.block0_initial_hash.as_bytes();\n\n std::ptr::copy(bytes.as_ptr(), block0_hash, bytes.len());\n Result::success()\n }\n}\n" }, { "alpha_fraction": 0.5490446090698242, "alphanum_fraction": 0.5598726272583008, "avg_line_length": 22.08823585510254, "blob_id": "2c9a9c7c2cff85a29faeab7018b09664a859ec6a", "content_id": "35aeb9ba22b879854159c756aceced334ec5ef61", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1570, "license_type": "permissive", "max_line_length": 81, "num_lines": 68, "path": "/bindings/wallet-cordova/scripts/build_ios.py", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom pathlib import Path\nimport subprocess\nimport sys\nimport shutil\nfrom directories import (\n repository_directory,\n script_directory,\n rust_build_directory,\n plugin_directory,\n)\n\nlibname = \"libjormungandrwallet.a\"\n\nlibrary_header_src = repository_directory / Path(\"bindings/wallet-c/wallet.h\")\nlibrary_header_dst = plugin_directory / Path(\"src/ios/LibWallet.h\")\n\ntargets = {\n \"x86_64-apple-ios\": \"x86_64\",\n \"aarch64-apple-ios\": \"arm64\",\n}\n\n\ndef run(release=True):\n lipo_args = [\n \"lipo\",\n \"-create\",\n \"-output\",\n str(plugin_directory / \"src/ios/\" / libname),\n ]\n\n for rust_target, apple_target in targets.items():\n arguments = [\n \"cargo\",\n \"rustc\",\n \"--target\",\n rust_target,\n \"-p\",\n \"jormungandrwallet\",\n ]\n\n if release:\n arguments = arguments + [\"--release\", \"--\", \"-C\", \"lto\"]\n\n out = subprocess.run(arguments)\n if out.returncode != 0:\n print(\"couldn't build for target: \", rust_target)\n sys.exit(1)\n\n debug_or_release = \"release\" if release else \"debug\"\n\n lipo_args += [\n \"-arch\",\n apple_target,\n str(rust_build_directory / rust_target / debug_or_release / libname),\n ]\n\n out = subprocess.run(lipo_args)\n if out.returncode != 0:\n print(\"couldn't build universal lib\")\n sys.exit(1)\n\n shutil.copy(library_header_src, library_header_dst)\n\n\nif __name__ == \"__main__\":\n run()\n" }, { "alpha_fraction": 0.561847984790802, "alphanum_fraction": 0.5704172849655151, "avg_line_length": 26.670103073120117, "blob_id": "72e2ee23c6cf913224c13f0a5db3fee6a47b0416", "content_id": "6c54ef869d34a194cc56cf0e3edf71f3400458fc", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 2684, "license_type": "permissive", "max_line_length": 99, "num_lines": 97, "path": "/wallet/tests/account.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "mod utils;\n\nuse self::utils::State;\nuse chain_crypto::SecretKey;\nuse chain_impl_mockchain::{\n account::SpendingCounter,\n certificate::VoteCast,\n fragment::Fragment,\n value::Value,\n vote::{Choice, Payload},\n};\nuse wallet::MAX_LANES;\n\nconst BLOCK0: &[u8] = include_bytes!(\"../../test-vectors/block0\");\nconst ACCOUNT_KEY: &str = include_str!(\"../../test-vectors/free_keys/key1.prv\");\n\n#[test]\nfn update_state_overrides_old() {\n let mut account = wallet::Wallet::new_from_key(\n SecretKey::from_binary(\n hex::decode(String::from(ACCOUNT_KEY).trim())\n .unwrap()\n .as_ref(),\n )\n .unwrap(),\n );\n\n assert_eq!(account.confirmed_value(), Value::zero());\n\n account\n .set_state(\n Value(110),\n (0..MAX_LANES)\n .map(|lane| SpendingCounter::new(lane, 1))\n .collect(),\n )\n .unwrap();\n\n assert_eq!(account.confirmed_value(), Value(110));\n}\n\n#[test]\nfn cast_vote() {\n let mut account = wallet::Wallet::new_from_key(\n SecretKey::from_binary(\n hex::decode(String::from(ACCOUNT_KEY).trim())\n .unwrap()\n .as_ref(),\n )\n .unwrap(),\n );\n\n let mut state = State::new(BLOCK0);\n let settings = state.settings().expect(\"valid initial settings\");\n\n for fragment in state.initial_contents() {\n account.check_fragment(&fragment.hash(), fragment).unwrap();\n account.confirm(&fragment.hash());\n }\n\n let vote_plan_id = &state.active_vote_plans()[0];\n\n let choice = Choice::new(1);\n\n let current_time =\n std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(settings.block0_date.0);\n\n for i in 0..16 {\n let payload = Payload::Public { choice };\n let cast = VoteCast::new(vote_plan_id.clone(), i, payload);\n\n let mut builder = wallet::TransactionBuilder::new(\n &settings,\n cast.clone(),\n wallet::time::max_expiration_date(&settings, current_time).unwrap(),\n );\n\n let value = builder.estimate_fee_with(1, 0);\n\n let account_tx_builder = account.new_transaction(value, i % 8).unwrap();\n let input = account_tx_builder.input();\n let witness_builder = account_tx_builder.witness_builder();\n\n builder.add_input(input, witness_builder);\n\n let tx = builder.finalize_tx(()).unwrap();\n\n let fragment = Fragment::VoteCast(tx);\n let id = fragment.hash();\n\n account_tx_builder.add_fragment_id(id);\n\n state\n .apply_fragments(&[fragment])\n .expect(\"couldn't apply votecast fragment\");\n }\n}\n" }, { "alpha_fraction": 0.5295416712760925, "alphanum_fraction": 0.5295416712760925, "avg_line_length": 32.2293586730957, "blob_id": "43135d900765fa554c3ac47d2c77000d601b3985", "content_id": "ea5836e83a15b36e2cf9471a643a33fe9543f1bf", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 3622, "license_type": "permissive", "max_line_length": 78, "num_lines": 109, "path": "/wallet/src/scheme/mod.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use chain_impl_mockchain::{\n fragment::Fragment,\n transaction::{Input, Output, Witness},\n};\n\npub(crate) fn on_tx_output<FO>(fragment: &Fragment, on_output: FO)\nwhere\n FO: FnMut((usize, Output<chain_addr::Address>)),\n{\n match fragment {\n Fragment::Initial(_config_params) => {}\n Fragment::UpdateProposal(_update_proposal) => {}\n Fragment::UpdateVote(_signed_update) => {}\n Fragment::OldUtxoDeclaration(_utxos) => {}\n Fragment::Evm(_) => {}\n Fragment::Transaction(tx) => for_each_output(tx, on_output),\n Fragment::OwnerStakeDelegation(tx) => for_each_output(tx, on_output),\n Fragment::StakeDelegation(tx) => for_each_output(tx, on_output),\n Fragment::PoolRegistration(tx) => for_each_output(tx, on_output),\n Fragment::PoolRetirement(tx) => for_each_output(tx, on_output),\n Fragment::PoolUpdate(tx) => for_each_output(tx, on_output),\n Fragment::VotePlan(tx) => for_each_output(tx, on_output),\n Fragment::VoteCast(tx) => for_each_output(tx, on_output),\n Fragment::VoteTally(tx) => for_each_output(tx, on_output),\n Fragment::MintToken(tx) => for_each_output(tx, on_output),\n Fragment::EvmMapping(tx) => for_each_output(tx, on_output),\n }\n}\n\nfn for_each_output<F, Extra>(\n tx: &chain_impl_mockchain::transaction::Transaction<Extra>,\n on_output: F,\n) where\n F: FnMut((usize, Output<chain_addr::Address>)),\n{\n tx.as_slice()\n .outputs()\n .iter()\n .enumerate()\n .for_each(on_output)\n}\n\npub(crate) fn on_tx_input_and_witnesses<FI>(fragment: &Fragment, on_input: FI)\nwhere\n FI: FnMut((Input, Witness)),\n{\n match fragment {\n Fragment::Initial(_config_params) => {}\n Fragment::UpdateProposal(_update_proposal) => {}\n Fragment::UpdateVote(_signed_update) => {}\n Fragment::OldUtxoDeclaration(_utxos) => {}\n Fragment::Evm(_) => {}\n Fragment::Transaction(tx) => tx\n .as_slice()\n .inputs_and_witnesses()\n .iter()\n .for_each(on_input),\n Fragment::OwnerStakeDelegation(tx) => tx\n .as_slice()\n .inputs_and_witnesses()\n .iter()\n .for_each(on_input),\n Fragment::StakeDelegation(tx) => tx\n .as_slice()\n .inputs_and_witnesses()\n .iter()\n .for_each(on_input),\n Fragment::PoolRegistration(tx) => tx\n .as_slice()\n .inputs_and_witnesses()\n .iter()\n .for_each(on_input),\n Fragment::PoolRetirement(tx) => tx\n .as_slice()\n .inputs_and_witnesses()\n .iter()\n .for_each(on_input),\n Fragment::PoolUpdate(tx) => tx\n .as_slice()\n .inputs_and_witnesses()\n .iter()\n .for_each(on_input),\n Fragment::VotePlan(tx) => tx\n .as_slice()\n .inputs_and_witnesses()\n .iter()\n .for_each(on_input),\n Fragment::VoteCast(tx) => tx\n .as_slice()\n .inputs_and_witnesses()\n .iter()\n .for_each(on_input),\n Fragment::VoteTally(tx) => tx\n .as_slice()\n .inputs_and_witnesses()\n .iter()\n .for_each(on_input),\n Fragment::MintToken(tx) => tx\n .as_slice()\n .inputs_and_witnesses()\n .iter()\n .for_each(on_input),\n Fragment::EvmMapping(tx) => tx\n .as_slice()\n .inputs_and_witnesses()\n .iter()\n .for_each(on_input),\n }\n}\n" }, { "alpha_fraction": 0.5948401093482971, "alphanum_fraction": 0.6192656755447388, "avg_line_length": 32.85271453857422, "blob_id": "79ec5f0309f9603aa0738de7af5563e30e1cf606", "content_id": "55aa501b5cf131c7d8e0e8812b9b3af0b6d26728", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 13101, "license_type": "permissive", "max_line_length": 108, "num_lines": 387, "path": "/chain-path-derivation/src/bip44.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "//! # Bip44 derivation scheme\n//!\n//! based on the [BIP-0044] scheme.\n//!\n//! While nearly only the full bip44 address is indeed interesting, it is\n//! valuable to keep the different intermediate steps as they can be reused\n//! to define specific API objects.\n//!\n//! For example, for example a wallet with support to multiple coin types\n//! will be interested to keep the `m/'44` path. For every account it is\n//! interesting to keep the `m/'44/'<coin_type>/'<account>`.\n//!\n//! We have the 5 levels of Derivations: `m / purpose' / coin_type' / account' / change / address_index`\n//!\n//! # Examples\n//!\n//! basic usage:\n//!\n//! ```\n//! # use chain_path_derivation::{Derivation, HardDerivation};\n//! # const BITCOIN: HardDerivation = HardDerivation::new_unchecked(Derivation::new(0x8000_0000));\n//! # const ACCOUNT_01: HardDerivation = HardDerivation::new_unchecked(Derivation::new(0x8000_0000));\n//! #\n//! use chain_path_derivation::bip44;\n//!\n//! let account = bip44::new().bip44().coin_type(BITCOIN).account(ACCOUNT_01);\n//! assert_eq!(account.to_string(), \"m/'44/'0/'0\")\n//! ```\n//!\n//! then it is possible to generate addresses from there:\n//!\n//! ```\n//! # use chain_path_derivation::{Derivation, HardDerivation, SoftDerivation};\n//! # const BITCOIN: HardDerivation = HardDerivation::new_unchecked(Derivation::new(0x8000_0000));\n//! # const ACCOUNT_01: HardDerivation = HardDerivation::new_unchecked(Derivation::new(0x8000_0000));\n//! #\n//! # use chain_path_derivation::bip44;\n//! #\n//! # let account = bip44::new().bip44().coin_type(BITCOIN).account(ACCOUNT_01);\n//! let change = account.external();\n//! let first_address = change.address(SoftDerivation::min_value().wrapping_add(0));\n//! let second_address = change.address(SoftDerivation::min_value().wrapping_add(1));\n//! assert_eq!(first_address.to_string(), \"m/'44/'0/'0/0/0\");\n//! assert_eq!(second_address.to_string(), \"m/'44/'0/'0/0/1\");\n//! ```\n\nuse crate::{\n AnyScheme, Derivation, DerivationPath, DerivationPathRange, HardDerivation,\n ParseDerivationPathError, SoftDerivation, SoftDerivationRange,\n};\nuse std::str::{self, FromStr};\n\n/// scheme for the Bip44 chain path derivation\n///\n#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct Bip44<P>(std::marker::PhantomData<P>);\n\n#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct Root;\n#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct Purpose;\n#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct CoinType;\n#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct Account;\n#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct Change;\n#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct Address;\n\nconst INDEX_PURPOSE: usize = 0;\nconst INDEX_COIN_TYPE: usize = 1;\nconst INDEX_ACCOUNT: usize = 2;\nconst INDEX_CHANGE: usize = 3;\nconst INDEX_ADDRESS: usize = 4;\n\n/// the BIP44 purpose ('44). This is the first item of the derivation path\npub const PURPOSE_BIP44: HardDerivation =\n HardDerivation::new_unchecked(Derivation::new(0x8000_002C));\n\n/// the Chimeric BIP44 purpose ('1852). This is the first item of the derivation path\n///\npub const PURPOSE_CHIMERIC: HardDerivation =\n HardDerivation::new_unchecked(Derivation::new(0x8000_073C));\n\n/// create a Bip44 chain path derivation\n///\n/// This derivation level is not really interesting, though it is interesting\n/// to consider the following levels which can then be constructed via\n/// each individual type.\n///\n/// See [module documentation] for more details\n///\n/// [module documentation]: ./index.html\n#[inline]\npub fn new() -> DerivationPath<Bip44<Root>> {\n DerivationPath::new_empty()\n}\n\nimpl DerivationPath<Bip44<Root>> {\n pub fn bip44(&self) -> DerivationPath<Bip44<Purpose>> {\n let mut p = self.clone();\n p.push(PURPOSE_BIP44.into());\n p.coerce_unchecked()\n }\n\n /// use the same \"model\" of 5 derivation level but instead of starting with the\n /// bip44 Hard Derivation uses the `'1852` (`'0x073C`) derivation path.\n ///\n /// see https://input-output-hk.github.io/adrestia/docs/key-concepts/hierarchical-deterministic-wallets/\n ///\n pub fn chimeric(&self) -> DerivationPath<Bip44<Purpose>> {\n let mut p = self.clone();\n p.push(PURPOSE_CHIMERIC.into());\n p.coerce_unchecked()\n }\n}\n\nimpl DerivationPath<Bip44<Purpose>> {\n /// add the next derivation level for the Bip44 chain path derivation.\n ///\n /// See [module documentation] for more details\n ///\n /// [module documentation]: ./index.html\n pub fn coin_type(&self, coin_type: HardDerivation) -> DerivationPath<Bip44<CoinType>> {\n let mut ct = self.clone();\n ct.push(coin_type.into());\n ct.coerce_unchecked()\n }\n\n #[inline]\n pub fn purpose(&self) -> HardDerivation {\n HardDerivation::new_unchecked(self.get_unchecked(INDEX_PURPOSE))\n }\n}\n\nimpl DerivationPath<Bip44<CoinType>> {\n /// See [module documentation] for more details\n ///\n /// [module documentation]: ./index.html\n pub fn account(&self, account: HardDerivation) -> DerivationPath<Bip44<Account>> {\n let mut a = self.clone();\n a.push(account.into());\n a.coerce_unchecked()\n }\n\n #[inline]\n pub fn purpose(&self) -> HardDerivation {\n HardDerivation::new_unchecked(self.get_unchecked(INDEX_PURPOSE))\n }\n\n #[inline]\n pub fn coin_type(&self) -> HardDerivation {\n HardDerivation::new_unchecked(self.get_unchecked(INDEX_COIN_TYPE))\n }\n}\n\nimpl DerivationPath<Bip44<Account>> {\n pub const EXTERNAL: SoftDerivation = SoftDerivation::new_unchecked(Derivation::new(0));\n pub const INTERNAL: SoftDerivation = SoftDerivation::new_unchecked(Derivation::new(1));\n pub const ACCOUNT: SoftDerivation = SoftDerivation::new_unchecked(Derivation::new(2));\n\n /// See [module documentation] for more details\n ///\n /// [module documentation]: ./index.html\n fn change(&self, change: SoftDerivation) -> DerivationPath<Bip44<Change>> {\n let mut c = self.clone();\n c.push(change.into());\n c.coerce_unchecked()\n }\n\n /// See [module documentation] for more details\n ///\n /// [module documentation]: ./index.html\n pub fn external(&self) -> DerivationPath<Bip44<Change>> {\n self.change(Self::EXTERNAL)\n }\n\n /// See [module documentation] for more details\n ///\n /// [module documentation]: ./index.html\n pub fn internal(&self) -> DerivationPath<Bip44<Change>> {\n self.change(Self::INTERNAL)\n }\n\n /// See [module documentation] for more details\n ///\n /// [module documentation]: ./index.html\n pub fn reward_account(&self) -> DerivationPath<Bip44<Change>> {\n debug_assert_eq!(self.purpose(), PURPOSE_CHIMERIC,);\n self.change(Self::ACCOUNT)\n }\n\n #[inline]\n pub fn purpose(&self) -> HardDerivation {\n HardDerivation::new_unchecked(self.get_unchecked(INDEX_PURPOSE))\n }\n\n #[inline]\n pub fn coin_type(&self) -> HardDerivation {\n HardDerivation::new_unchecked(self.get_unchecked(INDEX_COIN_TYPE))\n }\n\n #[inline]\n pub fn account(&self) -> HardDerivation {\n HardDerivation::new_unchecked(self.get_unchecked(INDEX_ACCOUNT))\n }\n}\n\nimpl DerivationPath<Bip44<Change>> {\n /// See [module documentation] for more details\n ///\n /// [module documentation]: ./index.html\n pub fn address(&self, address: SoftDerivation) -> DerivationPath<Bip44<Address>> {\n let mut a = self.clone();\n a.push(address.into());\n a.coerce_unchecked()\n }\n\n /// build a range of addresses\n ///\n /// # panics\n ///\n /// This function will panic is the range is out of bounds for a valid\n /// address (`SoftDerivation`).\n ///\n /// # Examples\n ///\n /// Generate the first 20 chain path derivation addresses, from 0 to 19 (inclusive):\n ///\n /// ```\n /// # use chain_path_derivation::{Derivation, HardDerivation, SoftDerivation};\n /// # const BITCOIN: HardDerivation = HardDerivation::new_unchecked(Derivation::new(0x8000_0000));\n /// # const ACCOUNT_01: HardDerivation = HardDerivation::new_unchecked(Derivation::new(0x8000_0000));\n /// #\n /// # use chain_path_derivation::bip44;\n /// #\n /// let account = bip44::new().bip44().coin_type(BITCOIN).account(ACCOUNT_01);\n /// let change = account.external();\n /// let end = SoftDerivation::min_value().saturating_add(20);\n ///\n /// let addresses = change.addresses((..end)).collect::<Vec<_>>();\n ///\n /// assert_eq!(addresses[0].to_string(), \"m/'44/'0/'0/0/0\");\n /// assert_eq!(addresses[1].to_string(), \"m/'44/'0/'0/0/1\");\n /// // ..\n /// assert_eq!(addresses[19].to_string(), \"m/'44/'0/'0/0/19\");\n /// ```\n pub fn addresses<R, T>(\n &self,\n range: R,\n ) -> DerivationPathRange<DerivationPath<Bip44<Address>>, SoftDerivationRange, SoftDerivation>\n where\n R: std::ops::RangeBounds<T>,\n T: std::convert::TryInto<SoftDerivation> + Copy,\n <T as std::convert::TryInto<SoftDerivation>>::Error: std::error::Error,\n {\n let range = SoftDerivationRange::new(range);\n\n self.clone().coerce_unchecked().sub_range(range)\n }\n\n #[inline]\n pub fn purpose(&self) -> HardDerivation {\n HardDerivation::new_unchecked(self.get_unchecked(INDEX_PURPOSE))\n }\n\n #[inline]\n pub fn coin_type(&self) -> HardDerivation {\n HardDerivation::new_unchecked(self.get_unchecked(INDEX_COIN_TYPE))\n }\n\n #[inline]\n pub fn account(&self) -> HardDerivation {\n HardDerivation::new_unchecked(self.get_unchecked(INDEX_ACCOUNT))\n }\n\n #[inline]\n pub fn change(&self) -> SoftDerivation {\n SoftDerivation::new_unchecked(self.get_unchecked(INDEX_CHANGE))\n }\n}\n\nimpl DerivationPath<Bip44<Address>> {\n #[inline]\n pub fn purpose(&self) -> HardDerivation {\n HardDerivation::new_unchecked(self.get_unchecked(INDEX_PURPOSE))\n }\n\n #[inline]\n pub fn coin_type(&self) -> HardDerivation {\n HardDerivation::new_unchecked(self.get_unchecked(INDEX_COIN_TYPE))\n }\n\n #[inline]\n pub fn account(&self) -> HardDerivation {\n HardDerivation::new_unchecked(self.get_unchecked(INDEX_ACCOUNT))\n }\n\n #[inline]\n pub fn change(&self) -> SoftDerivation {\n SoftDerivation::new_unchecked(self.get_unchecked(INDEX_CHANGE))\n }\n\n #[inline]\n pub fn address(&self) -> SoftDerivation {\n SoftDerivation::new_unchecked(self.get_unchecked(INDEX_ADDRESS))\n }\n}\n\n/* FromStr ***************************************************************** */\n\nmacro_rules! mk_from_str_dp_bip44 {\n ($t:ty, $len:expr) => {\n impl FromStr for DerivationPath<$t> {\n type Err = ParseDerivationPathError;\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n let dp = s.parse::<DerivationPath<AnyScheme>>()?;\n\n if dp.len() == $len {\n Ok(dp.coerce_unchecked())\n } else {\n Err(ParseDerivationPathError::InvalidNumberOfDerivations {\n actual: dp.len(),\n expected: $len,\n })\n }\n }\n }\n };\n}\n\nmk_from_str_dp_bip44!(Bip44<Root>, 0);\nmk_from_str_dp_bip44!(Bip44<Purpose>, 1);\nmk_from_str_dp_bip44!(Bip44<CoinType>, 2);\nmk_from_str_dp_bip44!(Bip44<Account>, 3);\nmk_from_str_dp_bip44!(Bip44<Change>, 4);\nmk_from_str_dp_bip44!(Bip44<Address>, 5);\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use quickcheck::{Arbitrary, Gen};\n\n macro_rules! mk_arbitrary_dp_bip44 {\n ($t:ty, $len:expr) => {\n impl Arbitrary for DerivationPath<$t> {\n fn arbitrary<G: Gen>(g: &mut G) -> Self {\n let dp = std::iter::repeat_with(|| Derivation::arbitrary(g))\n .take($len)\n .collect::<DerivationPath<AnyScheme>>();\n dp.coerce_unchecked()\n }\n }\n };\n }\n\n mk_arbitrary_dp_bip44!(Bip44<Root>, 0);\n mk_arbitrary_dp_bip44!(Bip44<Purpose>, 1);\n mk_arbitrary_dp_bip44!(Bip44<CoinType>, 2);\n mk_arbitrary_dp_bip44!(Bip44<Account>, 3);\n mk_arbitrary_dp_bip44!(Bip44<Change>, 4);\n mk_arbitrary_dp_bip44!(Bip44<Address>, 5);\n\n macro_rules! mk_quickcheck_dp_bip44 {\n ($t:ty) => {\n paste::item! {\n #[quickcheck]\n #[allow(non_snake_case)]\n fn [< fmt_parse $t>](derivation_path: DerivationPath<Bip44<$t>>) -> bool {\n let s = derivation_path.to_string();\n let v = s.parse::<DerivationPath<Bip44<$t>>>().unwrap();\n\n v == derivation_path\n }\n }\n };\n }\n\n mk_quickcheck_dp_bip44!(Root);\n mk_quickcheck_dp_bip44!(Purpose);\n mk_quickcheck_dp_bip44!(CoinType);\n mk_quickcheck_dp_bip44!(Account);\n mk_quickcheck_dp_bip44!(Change);\n mk_quickcheck_dp_bip44!(Address);\n}\n" }, { "alpha_fraction": 0.7201917171478271, "alphanum_fraction": 0.7663271427154541, "avg_line_length": 42.894737243652344, "blob_id": "e283f06b3f770bd9886f4cc01edf730f836f6268", "content_id": "dafe9761f4a513fb1ffabd147f722aef4e4e9509", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1669, "license_type": "permissive", "max_line_length": 128, "num_lines": 38, "path": "/doc/EME.md", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "### Enhanced Mnemonic Encoding (EME) -- Draft\n\nWe add an extra mnemonic word to the encoding, this allows us to have an extra\n11 bits for the scheme metadata. The EME scheme:\n\n* Improves the detection and versioning compared to the standard BIP39\n* EME mnemonics is not accepted by a compliant BIP39 implementation by always having 1 extra word\n* EME mnemonics maps trivially to a BIP39 mnemonics by stripping the first word.\n\nThe first 2 bits are defined for the type, which given different type imply\ndifferent parsing of the following bits\n\n* 2 bits : where the value represent:\n * 0: wallet key seed\n * 1: reserved for paper wallet\n * 2: reserved for extension. UX should report unknown type\n * 3: reversed for extension. UX should report unknown type\n\nThe following apply to wallet key seed:\n\n* 2 bits : master key derivation version.\n * Version 0: use the scheme defined below\n* 3 bits : mnemonic size (invalid=0b000,12=0b001, 15=0b010, 18=0b011, 21=0b100, 24=0b101, and by extension: 27=0b110, 30=0b111) \n* 4 bits : checksum of the first 2 words (22bits) 0b1111. How is it computed ? \n\nThe mnemonic size allows after the words to determine the number of words are\nexpected for this instance. This can be used for the UI either during the\nprocess of filling the mnemonic or at the end to do simple validation.\n\nThe 2 words checksum allows for early detection of the validity of the EME.\nIn the UX, on the 3rd word entered, early checksuming can allow detection, with\nsome margin of error, whether or not the EME encoding is valid. This allow for\nextra feedback during the UX, and help detect classic bip39 scheme from EME\nscheme.\n\n```\nTODO test vectors\n```\n\n" }, { "alpha_fraction": 0.7454545497894287, "alphanum_fraction": 0.7454545497894287, "avg_line_length": 35.66666793823242, "blob_id": "60fad78cffffb066b627fb6fc6a1d7a673219bf2", "content_id": "c24b326aa848319a6b0c1f0c70c64e362211f623", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 110, "license_type": "permissive", "max_line_length": 90, "num_lines": 3, "path": "/bindings/wallet-uniffi/gen_bindings.sh", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env sh\n\n uniffi-bindgen generate -l kotlin src/lib.udl --config-path uniffi.toml -o codegen/kotlin\n" }, { "alpha_fraction": 0.7337770462036133, "alphanum_fraction": 0.7437604069709778, "avg_line_length": 24.04166603088379, "blob_id": "5308494b0c9cb12f4f02c6d2ae8017b04749b1f7", "content_id": "470c2cad690d9df95858f8e18cb0cdc0ad4b8f38", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 601, "license_type": "permissive", "max_line_length": 96, "num_lines": 24, "path": "/chain-path-derivation/src/lib.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "//! BIP44 addressing\n//!\n//! provides all the logic to create safe sequential addresses\n//! using BIP44 specification.\n//!\n\n#[cfg(test)]\nextern crate quickcheck;\n#[cfg(test)]\n#[macro_use(quickcheck)]\nextern crate quickcheck_macros;\n\npub mod bip44;\nmod derivation;\nmod derivation_path;\npub mod rindex;\n\npub use self::{\n derivation::{\n Derivation, DerivationError, DerivationRange, HardDerivation, HardDerivationRange,\n ParseDerivationError, SoftDerivation, SoftDerivationRange,\n },\n derivation_path::{AnyScheme, DerivationPath, DerivationPathRange, ParseDerivationPathError},\n};\n" }, { "alpha_fraction": 0.5993788838386536, "alphanum_fraction": 0.6055900454521179, "avg_line_length": 19.125, "blob_id": "ac48c031f4e6646a1c0fb9ac4bf9d0351be5771c", "content_id": "a596b3d0e02c694f0982beb68ef808a4735b8137", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 322, "license_type": "permissive", "max_line_length": 46, "num_lines": 16, "path": "/bindings/wallet-core/src/conversion.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use chain_impl_mockchain::transaction::Input;\n\npub struct Conversion {\n pub(crate) ignored: Vec<Input>,\n pub(crate) transactions: Vec<Vec<u8>>,\n}\n\nimpl Conversion {\n pub fn ignored(&self) -> &[Input] {\n &self.ignored\n }\n\n pub fn transactions(&self) -> &[Vec<u8>] {\n &self.transactions\n }\n}\n" }, { "alpha_fraction": 0.6554712653160095, "alphanum_fraction": 0.6603466868400574, "avg_line_length": 22.679487228393555, "blob_id": "3ff292a78aebe05ed69e90e210d25e0f610d6696", "content_id": "66b33e5e10542ac608c02a7fe3af9ae03eaa2302", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 1847, "license_type": "permissive", "max_line_length": 102, "num_lines": 78, "path": "/bindings/wallet-c/cbindgen.toml", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "# This is a template cbindgen.toml file with all of the default values.\n# Some values are commented out because their absence is the real default.\n#\n# See https://github.com/eqrion/cbindgen/blob/master/docs.md#cbindgentoml\n# for detailed documentation of every option here.\n\nlanguage = \"C\"\n\n############## Options for Wrapping the Contents of the Header #################\n\nheader = \"\"\"/**\n * Wallet for Jörmungandr blockchain\n *\n * Provide support for recovering funds from both Yoroi and Daedalus wallets.\n *\n * Copyright 2020, Input Output HK Ltd\n * Licensed with: MIT OR Apache-2.0\n */\"\"\"\ninclude_guard = \"IOHK_CHAIN_WALLET_LIBC_\"\nautogen_warning = \"/* Warning, this file is autogenerated by cbindgen. Don't modify this manually. */\"\ninclude_version = true\n\n############################ Code Style Options ################################\n\nbraces = \"NextLine\"\nline_length = 80\ntab_width = 2\ndocumentation_style = \"doxy\"\n\n############################# Codegen Options ##################################\n\nstyle = \"both\"\n\n[export]\nitem_types = []\nrenaming_overrides_prefixing = false\n\n[fn]\nrename_args = \"None\"\nargs = \"auto\"\nsort_by = \"Name\"\n\n[struct]\nrename_fields = \"None\"\n\n[enum]\nrename_variants = \"None\"\nadd_sentinel = false\nprefix_with_name = true\nderive_helper_methods = false\nderive_const_casts = false\nderive_mut_casts = false\nderive_tagged_enum_destructor = false\nderive_tagged_enum_copy_constructor = false\nenum_class = true\nprivate_default_tagged_enum_constructor = false\n\n[const]\nallow_static_const = true\nallow_constexpr = false\n\n[macro_expansion]\nbitflags = false\n\n############## Options for How Your Rust library Should Be Parsed ##############\n\n[parse]\nparse_deps = true\ninclude = [\"wallet-core\"]\nexclude = []\nclean = false\nextra_bindings = []\n\n[parse.expand]\ncrates = []\nall_features = false\ndefault_features = true\nfeatures = []" }, { "alpha_fraction": 0.4166666567325592, "alphanum_fraction": 0.4166666567325592, "avg_line_length": 23, "blob_id": "b07c2e5e4d1f3102671f35f53edf909c10bc4a83", "content_id": "a71ef8601e42f09bfdd297ac5d7f43eb922aada7", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 840, "license_type": "permissive", "max_line_length": 58, "num_lines": 35, "path": "/bindings/wallet-core/src/c/macros.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "macro_rules! non_null {\n ( $obj:expr ) => {\n if let Some(obj) = $obj.as_ref() {\n obj\n } else {\n return Error::invalid_input(stringify!($expr))\n .with(crate::c::NulPtr)\n .into();\n }\n };\n}\n\nmacro_rules! non_null_mut {\n ( $obj:expr ) => {\n if let Some(obj) = $obj.as_mut() {\n obj\n } else {\n return Error::invalid_input(stringify!($expr))\n .with(crate::c::NulPtr)\n .into();\n }\n };\n}\n\nmacro_rules! non_null_array {\n ( $obj:expr, $len:expr) => {\n if $obj.is_null() {\n return Error::invalid_input(stringify!($expr))\n .with(crate::c::NulPtr)\n .into();\n } else {\n std::slice::from_raw_parts($obj, $len)\n }\n };\n}\n" }, { "alpha_fraction": 0.5661401748657227, "alphanum_fraction": 0.5715696215629578, "avg_line_length": 26.37837791442871, "blob_id": "d80ff092ff51920b5d78afb20f8f59f4b3d8cf29", "content_id": "7c04e23f1ed68758dcb1d55281d58d471484ebad", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 2026, "license_type": "permissive", "max_line_length": 90, "num_lines": 74, "path": "/wallet/tests/utils/mod.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use chain_impl_mockchain::{\n accounting::account::SpendingCounterIncreasing,\n block::Block,\n certificate::VotePlanId,\n fragment::Fragment,\n ledger::{Error as LedgerError, Ledger},\n value::Value,\n};\nuse chain_ser::{deser::DeserializeFromSlice, packer::Codec};\nuse wallet::Settings;\n\npub struct State {\n block0: Block,\n pub ledger: Ledger,\n}\n\nimpl State {\n pub fn new<B>(block0_bytes: B) -> Self\n where\n B: AsRef<[u8]>,\n {\n let block0 = Block::deserialize_from_slice(&mut Codec::new(block0_bytes.as_ref()))\n .expect(\"valid block0\");\n let hh = block0.header().id();\n let ledger = Ledger::new(hh, block0.fragments()).unwrap();\n\n Self { block0, ledger }\n }\n\n #[allow(dead_code)]\n pub fn initial_contents(&self) -> impl Iterator<Item = &'_ Fragment> {\n self.block0.contents().iter()\n }\n\n pub fn settings(&self) -> Result<Settings, LedgerError> {\n Settings::new(&self.block0)\n }\n\n #[allow(dead_code)]\n pub fn active_vote_plans(&self) -> Vec<VotePlanId> {\n self.ledger\n .active_vote_plans()\n .into_iter()\n .map(|plan| plan.id)\n .collect()\n }\n\n pub fn apply_fragments<'a, F>(&'a mut self, fragments: F) -> Result<(), LedgerError>\n where\n F: IntoIterator<Item = &'a Fragment>,\n {\n let block_date = self.ledger.date();\n let mut new_ledger = self.ledger.clone();\n for fragment in fragments {\n new_ledger = self.ledger.apply_fragment(fragment, block_date)?;\n }\n\n self.ledger = new_ledger;\n\n Ok(())\n }\n\n #[allow(dead_code)]\n pub fn get_account_state(\n &self,\n account_id: wallet::AccountId,\n ) -> Option<(SpendingCounterIncreasing, Value)> {\n self.ledger\n .accounts()\n .get_state(&chain_crypto::PublicKey::from(account_id).into())\n .ok()\n .map(|account_state| (account_state.spending.clone(), account_state.value))\n }\n}\n" }, { "alpha_fraction": 0.5195924639701843, "alphanum_fraction": 0.5250783562660217, "avg_line_length": 19.918033599853516, "blob_id": "22dc008a77abe7543bc8170ac0d24d840784db24", "content_id": "c1b353a46b6012fff560720a411e02a22913fbb5", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1276, "license_type": "permissive", "max_line_length": 74, "num_lines": 61, "path": "/test-vectors/rebuild_genesis_data.py", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport binascii\nimport subprocess\nimport json\nimport os\nfrom pathlib import Path\n\nscript_directory = Path(__file__).parent\n\nos.chdir(script_directory)\n\n\ndef regen_block_bin():\n # make sure the block0 file is up-to-date\n # although this depends on the installed version of jcli\n subprocess.check_call(\n [\n \"jcli\",\n \"genesis\",\n \"encode\",\n \"--input\",\n \"genesis.yaml\",\n \"--output\",\n \"block0\",\n ],\n )\n\n\ndef update_json_file():\n # the json file has the genesis id and the block as hex, this makes it\n # easier to read it from the cordova js tests\n blockHex = None\n\n with open(\"block0\", \"rb\") as file:\n binaryData = file.read()\n\n blockHex = binascii.hexlify(binaryData)\n\n blockId = subprocess.check_output(\n [\"jcli\", \"genesis\", \"hash\", \"--input\", \"block0\"],\n ).strip()\n\n with open(\"block0.json\", \"w\") as file:\n file.write(\n json.dumps(\n {\n \"id\": blockId.decode(\"utf-8\"),\n \"hex\": blockHex.decode(\"utf-8\"),\n }\n )\n )\n\n\ndef run():\n regen_block_bin()\n update_json_file()\n\n\nif __name__ == \"__main__\":\n run()\n" }, { "alpha_fraction": 0.62232905626297, "alphanum_fraction": 0.6308760643005371, "avg_line_length": 27.363636016845703, "blob_id": "e025be355756c9beb4a2f153fa6d3af550884682", "content_id": "b2337a2d8e51be4e994011e0387c673afcd7248c", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 1872, "license_type": "permissive", "max_line_length": 96, "num_lines": 66, "path": "/wallet/src/time.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use crate::Settings;\nuse chain_impl_mockchain::block::BlockDate;\nuse chain_time::{SlotDuration, TimeFrame, Timeline};\nuse std::time::{Duration, SystemTime};\n\n#[derive(Debug, thiserror::Error)]\npub enum Error {\n #[error(\"date is outside valid ttl range\")]\n FinalDateOutOfRange,\n #[error(\"blockchain has not started\")]\n BeforeBlock0Date,\n}\n\npub fn block_date_from_system_time(\n settings: &Settings,\n date: SystemTime,\n) -> Result<BlockDate, Error> {\n let start_time = SystemTime::UNIX_EPOCH + Duration::from_secs(settings.block0_date.0);\n let timeline = Timeline::new(start_time);\n let tf = TimeFrame::new(\n timeline,\n SlotDuration::from_secs(settings.slot_duration as u32),\n );\n\n let final_slot_offset = tf.slot_at(&date).unwrap();\n\n let date = settings\n .time_era\n .from_slot_to_era(final_slot_offset)\n .unwrap();\n\n Ok(BlockDate {\n epoch: date.epoch.0,\n slot_id: date.slot.0,\n })\n}\n\npub fn max_expiration_date(\n settings: &Settings,\n current_time: SystemTime,\n) -> Result<BlockDate, Error> {\n let start_time = SystemTime::UNIX_EPOCH + Duration::from_secs(settings.block0_date.0);\n let timeline = Timeline::new(start_time);\n let tf = TimeFrame::new(\n timeline,\n SlotDuration::from_secs(settings.slot_duration as u32),\n );\n\n let current_slot_offset = tf.slot_at(&current_time).ok_or(Error::BeforeBlock0Date)?;\n\n let current_date = settings\n .time_era\n .from_slot_to_era(current_slot_offset)\n .unwrap();\n\n let last_valid_epoch = current_date.epoch.0 + settings.transaction_max_expiry_epochs as u32;\n\n Ok(BlockDate {\n epoch: last_valid_epoch,\n slot_id: settings\n .time_era\n .slots_per_epoch()\n .checked_sub(1)\n .expect(\"slots per epoch can't be zero\"),\n })\n}\n" }, { "alpha_fraction": 0.6444026231765747, "alphanum_fraction": 0.664158046245575, "avg_line_length": 36.96428680419922, "blob_id": "10520fd2459a031b7f9818dfcfd48a38c752e534", "content_id": "78b0d340136a3a6f816da96d9fd9105651848af5", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 1063, "license_type": "permissive", "max_line_length": 103, "num_lines": 28, "path": "/bindings/wallet-uniffi/Cargo.toml", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "[package]\nname = \"wallet-uniffi\"\nversion = \"0.1.0\"\nedition = \"2018\"\n\n[lib]\ncrate-type = [ \"cdylib\" ]\nname = \"uniffi_jormungandr_wallet\"\n\n[dependencies]\nuniffi = \"0.16.0\"\nuniffi_macros = \"0.16.0\"\nwallet-core = { path = \"../wallet-core\" }\nwallet = {path = \"../../wallet\"}\nsymmetric-cipher = {path = \"../../symmetric-cipher\"}\nchain-vote = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-addr = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-impl-mockchain = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-crypto = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-time = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nchain-ser = { git = \"https://github.com/input-output-hk/chain-libs.git\", branch = \"master\" }\nthiserror = {version = \"1.0\", default-features = false}\n\n[build-dependencies]\nuniffi_build = \"0.16.0\"\n\n[features]\nbuiltin-bindgen = [\"uniffi_build/builtin-bindgen\"]\n" }, { "alpha_fraction": 0.7016885280609131, "alphanum_fraction": 0.7350844144821167, "avg_line_length": 36.88625717163086, "blob_id": "61bd04d14cade06cd421ad9901e34dc4c2c0f822", "content_id": "7fc813e26b1c3125a271f8fcc17b453a23774728", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7995, "license_type": "permissive", "max_line_length": 151, "num_lines": 211, "path": "/doc/CRYPTO.md", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "---\ntitle: Wallet Cryptography and Encoding\nsubtitle: 'Status: In Progress'\nauthor: Vincent Hanquez, Nicolas Di Prima\ndocumentclass: scrartcl\ntoc: t\nnumbersections: true\n---\n\n# Wallet Cryptography and Encoding\n\n## Mnemonics encoding\n\nWe define a way for easily enter and write down arbitrary binary seed using a\nsimple dictionary of known words (available in many different languages).\n\nThe motivation here is to have sentence of words easy to read and write sentences,\nwhich map uniquely back and forth to a sized binary data. It apply to any\nbinary, but usually is useful for binary data that need to be saved\nor transfer, and need to be less sensible to human errors.\n\n### Bip39\n\nWe used BIP39 dictionaries, and the BIP39 mnemonic encoding to represent\nbinaries of size multiple of 32 bits.\n\nValid BIP39 Encoding defined (where CS is Checksum Size):\n\n| Num Mnemonic | Entropy & CS | Entropy Size | CS |\n| ------------ | ------------ | ------------------- | ------ |\n| 9 words | 99 bits | 96 bits (12 bytes) | 3 bits |\n| 12 words | 132 bits | 128 bits (16 bytes) | 4 bits |\n| 15 words | 165 bits | 160 bits (20 bytes) | 5 bits |\n| 18 words | 198 bits | 192 bits (24 bytes) | 6 bits |\n| 21 words | 231 bits | 224 bits (28 bytes) | 7 bits |\n| 24 words | 264 bits | 254 bits (32 bytes) | 8 bits |\n\nWords of the dictionary are different enough that it should\nbe hard to swap by mistake one word by another close by,\nThere's also a lightweight checksuming mechanism which\nprevent to some extend swapping some words of the dictionary\nby another with reasonable probability.\n\n## Origin Key generation\n\nThe origin key is the material that is used to generate everything else in a\ngiven wallet. It should be composed of high quality randomness (also known as\nentropy).\n\nA valid seed is a binary value of 128 to 256 bits, in 32 bits increment (16 to\n32 bytes in 4 bytes increment). Any other seed size is invalid and should be\nrejected.\n\nThe size of the seed is only affecting the initial master key generation, after\nthat it doesn't have any effect (apart from the underlying security\nimplication).\n\nGeneration:\n\n1. Generate 16, 20, 24, 28, 32 bytes (128 bits to 256 bits in 32 bits increment) as seed, from high quality random.\n2. UX:\n * Encode the bytes to mnemonics either in BIP39 and EME, or both.\n * Display to the user for safe keeping (recovery, etc).\n\nRecovery:\n\n1. UX: Use the BIP39 dictionary for allowed words & autocompletion\n2. UX: Detect whether it's a BIP39 (12,15,18,21,24 words) or EME encoding (13, 16, 19, 22, 25 words)\n3. UX: Decode the words to binary\n\n```\nTODO test vector origin key to EME and BIP39\n```\n\n## Master key generation (to cryptographic key)\n\nInputs:\n\n* Origin Key: A valid Origin Key as described above\n* Password: any byte array of any size.\n\nOutput:\n\n* A valid extended private key (XPrv)\n\nA XPrv is 96 bytes, and composed of:\n\n* 64 bytes: an extended ED25519 secret key composed of:\n * 32 bytes: ed25519 curve scalar, which should have some specific bits clear and some set (see tweakBits)\n * 32 bytes: ed25519 binary blob used as IV for signing\n* 32 bytes: chain code for the ed25519-bip32 scheme\n\nGenerally we're narrowing the choice of primitives to Key Derivation Function\n(KDF) to provide the binary extension from seed (12 to 24 bytes) to a larger\nbinary value (here 96 bytes).\n\n(Example of existing KDF: pbkdf2, bcrypt, scrypt, argon2)\n\nThis system is a multi factor cryptographic retrieval, which is similar to\nmulti factor authentication (or more specifically 2FA) but applied to\ncryptographic key retrieval:\n\n* The seed: something we have: either newly generated or from a recovery\n* The password: something we know: user chosen password\n\nGiven the lack of any structure requirement of the output bits, along with\nproviding a strong multi factor cryptographic material retrieval, this also\nprovide plausible deniability; It's not possible to identify whether the\npassword is correct (and correctly entered), short of looking for specific\nusage recorded elsewhere (e.g. looks for own utxos on a wallet). This present\nsome challenge at the user level, as losing the password or not entering\ncorrectly, lead to a brand new wallet. It is also valid to either leave the\npassword empty or hardcode it to a specific string, although that could create\nwallet interoperability issues.\n\nAlong with those requirement, it should be (reasonably) slow to compute, to\nprevent simple case of brute forcing in case of leak of the seed.\n\nGiven the password, we need to use a password based key derivation function.\nWithout any other external constraint, we would choose argon2, but given that\nwe need to be conservative for support reason and the ability to be embedded in\nsmall hardware, we will choose pbkdf2 which enjoy wide support and large number\nof implementations. Furthermore, it is also the primitive of choice for BIP39\nmaster key generation.\n\nNote that this choice doesn't protect against brute forcing from ASIC and GPU\nimplementations, however because of plausible deniability, even though the\nfunction can be computed really fast on specialized hardware, it's still hard\nto test whether or not the master key is the right one and thus terminate the\nsearch. This final search step involves many derivations (BIP44), and many\naddress generation searches in an existing blockchain.\n\nThe algorithm for master key generation:\n\n masterKeyGeneration(seed, password) {\n data := PBKDF2(kdf=HMAC-SHA512, iter=4096,\n salt=seed,\n\t\t password=password,\n\t\t outputLen=96);\n masterKey := tweakBits(data);\n }\n\n tweakBits(data) {\n // on the ed25519 scalar leftmost 32 bytes:\n // * clear the lowest 3 bits\n // * clear the highest bit\n // * clear the 3rd highest bit\n // * set the highest 2nd bit\n data[0] &= ~0b111;\n data[31] &= 0b00011111;\n data[31] |= 0b01000000;\n }\n\n\n```\nTODO add test vectors of seed+password to output\n```\n\n## Wallet Hierarchical Deterministic (HD) Key Derivation\n\nDerivation is the process to transform a XPrv into another XPrv having a one way process:\n\n Parent XPrv ---> Child XPrv\n Child XPrv -/-> Parent Xprv\n\nWe supplement this derivation with a hierarchy and 32 bits indices, and effectively turn\nderivation into the ability to derive an \"infinite\"\" number of keys, organised in a tree fashion,\nwith at the root of this binary, one unique XPrv, which by call the `master key`.\n\n### Scheme\n\nWe use the scheme defined here, based on [Hierarchical Deterministic Keys over a Non-linear keyspace](https://cardanolaunch.com/assets/Ed25519_BIP.pdf)\n\n## BIP44\n\nwe use:\n\n* `H(X)` to indicate a hardened index X of `0 <= X <= 2^31-1` which encode a value of `2^31 + X`\n* `S(X)` to indicate a softened index X of `0 <= X <= 2^31-1` which encode a value of `X`\n\nWe define the following derivation path, where we repeadtly derive 5 levels\nfrom the root key to obtain a leaf:\n\n root / H(44) / H(COIN_TYPE) / H(ACCOUNT) / S(CHANGE) / S(INDEX)\n\n### Account\n\nThis level splits the key space into independent user identities, so the wallet\nnever mixes the coins across different accounts.\n\nAccounts are numbered from index 0 in sequentially increasing manner.\n\nSoftware should prevent a creation of an account if a previous account does not\nhave a transaction history (meaning none of its addresses have been used\nbefore).\n\n### Change\n\nCHANGE is 0 (used for external chain) or 1 (used for change address).\n\nExternal chain is used for addresses that are meant to be visible outside of\nthe wallet (e.g. for receiving payments). Internal chain is used for addresses\nwhich are not meant to be visible outside of the wallet and is used for return\ntransaction change.\n\n### Extension to Accounting style\n\nBIP44 is defined related to utxo, but we add another change constant of 2\nto generate reusable accounts for a given bip44 account.\n\n root/H(44) / H(COIN_TYPE) / H(ACCOUNT) / S(2) / S(ACCOUNT-INDEX)\n\n" }, { "alpha_fraction": 0.6738544702529907, "alphanum_fraction": 0.6738544702529907, "avg_line_length": 20.823530197143555, "blob_id": "7fc7e61212e8a17b1c6dfcb7d20c9abbd467e321", "content_id": "91f6961aa90c1cba6d5dc192c7630cd162d3eb71", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 371, "license_type": "permissive", "max_line_length": 55, "num_lines": 17, "path": "/bindings/wallet-core/src/lib.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "pub mod c;\nmod error;\nmod vote;\nmod wallet;\n\npub use self::{\n error::{Error, ErrorCode, ErrorKind, Result},\n vote::Proposal,\n wallet::Wallet,\n};\npub use ::wallet::Settings;\npub use chain_impl_mockchain::{\n fragment::{Fragment, FragmentId},\n value::Value,\n vote::{Choice, Options, PayloadType},\n};\npub use vote::{PayloadTypeConfig, VOTE_PLAN_ID_LENGTH};\n" }, { "alpha_fraction": 0.450155645608902, "alphanum_fraction": 0.531442403793335, "avg_line_length": 31.193763732910156, "blob_id": "c7b6ffdc6bd864ed438fe4ea804576809d95df55", "content_id": "08fd0e25200431c2ee26bece189ee9dd395ba292", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 14455, "license_type": "permissive", "max_line_length": 99, "num_lines": 449, "path": "/hdkeygen/src/rindex/hdpayload.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "//! HD Payload\n//!\n//! The HD Payload is an Address attribute stored along the address\n//! in encrypted form.\n//!\n//! This use chacha20poly1305 to auth-encrypt a BIP39 derivation\n//! path, which is then stored in the address. The owner of the\n//! symmetric key used to encrypt, can then decrypt the address\n//! payload and find the derivation path associated with it.\n//!\nuse chain_path_derivation::{AnyScheme, Derivation, DerivationPath};\nuse cryptoxide::{chacha20poly1305::ChaCha20Poly1305, hmac::Hmac, pbkdf2::pbkdf2, sha2::Sha512};\nuse ed25519_bip32::XPub;\nuse thiserror::Error;\n\nconst NONCE: &[u8] = b\"serokellfore\";\nconst SALT: &[u8] = b\"address-hashing\";\nconst TAG_LEN: usize = 16;\npub const HDKEY_SIZE: usize = 32;\n/// This is the max size we accept to try to decrypt a HDPayload.\n/// This is due to avoid trying to decrypt content that are way beyond\n/// reasonable size.\npub const MAX_PAYLOAD_SIZE: usize = 48;\n\n#[derive(Debug, Error)]\npub enum Error {\n #[error(\"Cannot decrypt the Legacy Address Payload\")]\n CannotDecrypt,\n #[error(\"Invalid Payload, expecting at least 16 bytes\")]\n NotEnoughEncryptedData,\n /// this relates to the issue that addresses with the payload data\n /// can have an infinite length (as long as it fits in the max block size\n /// and max transaction size).\n #[error(\"the Legacy Address Payload is too large ({0} bytes), limited to {1} bytes max.\")]\n PayloadIsTooLarge(usize, usize),\n}\n\nconst CBOR_INDEFINITE_ARRAY: u8 = 0x9F;\nconst CBOR_BREAK: u8 = 0xFF;\n\n#[cfg(test)]\nconst CBOR_MAX_INLINE_ENCODING: u32 = 23;\n#[cfg(test)]\nconst CBOR_PAYLOAD_LENGTH_U8: u8 = 24;\n#[cfg(test)]\nconst CBOR_PAYLOAD_LENGTH_U16: u8 = 25;\n#[cfg(test)]\nconst CBOR_PAYLOAD_LENGTH_U32: u8 = 26;\n\n#[cfg(test)]\nfn encode_derivation(buf: &mut Vec<u8>, derivation: Derivation) {\n let value: u32 = *derivation;\n\n if value <= CBOR_MAX_INLINE_ENCODING {\n buf.push(value as u8);\n } else if value < 0x1_00 {\n buf.push(CBOR_PAYLOAD_LENGTH_U8);\n buf.push(value as u8);\n } else if value < 0x1_00_00 {\n buf.push(CBOR_PAYLOAD_LENGTH_U16);\n buf.push(((value & 0xFF_00) >> 8) as u8);\n buf.push((value & 0x00_FF) as u8);\n } else {\n buf.push(CBOR_PAYLOAD_LENGTH_U32);\n buf.push(((value & 0xFF_00_00_00) >> 24) as u8);\n buf.push(((value & 0x00_FF_00_00) >> 16) as u8);\n buf.push(((value & 0x00_00_FF_00) >> 8) as u8);\n buf.push((value & 0x00_00_00_FF) as u8);\n }\n}\n\nfn cursor_read(reader: &mut &[u8]) -> Option<u8> {\n use std::io::Read as _;\n let mut b = [0];\n let sz = reader.read(&mut b).ok()?;\n if sz == 1 {\n Some(b[0])\n } else {\n None\n }\n}\n\nfn decode_derivation(reader: &mut &[u8]) -> Option<Derivation> {\n let b: u8 = cursor_read(reader)?;\n let v = match b {\n 0x00..=0x17 => b as u32,\n 0x18 => cursor_read(reader)? as u32,\n 0x19 => {\n let b1 = cursor_read(reader)? as u32;\n let b2 = cursor_read(reader)? as u32;\n b1 << 8 | b2\n }\n 0x1a => {\n let b1 = cursor_read(reader)? as u32;\n let b2 = cursor_read(reader)? as u32;\n let b3 = cursor_read(reader)? as u32;\n let b4 = cursor_read(reader)? as u32;\n b1 << 24 | b2 << 16 | b3 << 8 | b4\n }\n _ => return None,\n };\n\n Some(Derivation::from(v))\n}\n\n#[cfg(test)]\nfn encode_derivation_path<S>(derivation_path: &DerivationPath<S>) -> Vec<u8> {\n let mut buf = Vec::with_capacity(32);\n\n buf.push(CBOR_INDEFINITE_ARRAY);\n for derivation in derivation_path.iter().copied() {\n encode_derivation(&mut buf, derivation);\n }\n buf.push(CBOR_BREAK);\n\n buf\n}\n\npub fn decode_derivation_path(buf: &[u8]) -> Option<DerivationPath<AnyScheme>> {\n let mut cursor = buf; // std::io::Cursor::new(buf);\n let mut dp = DerivationPath::new();\n\n if cursor_read(&mut cursor)? != CBOR_INDEFINITE_ARRAY {\n return None;\n }\n\n loop {\n let derivation = decode_derivation(&mut cursor)?;\n dp = dp.append_unchecked(derivation);\n\n if cursor.len() <= 1 {\n if cursor_read(&mut cursor)? != CBOR_BREAK {\n return None;\n } else {\n break;\n }\n }\n }\n\n Some(dp)\n}\n\n/// The key to encrypt and decrypt HD payload\n#[derive(Clone, zeroize::ZeroizeOnDrop)]\npub struct HdKey([u8; HDKEY_SIZE]);\nimpl HdKey {\n /// Create a new `HDKey` from an extended public key\n pub fn new(root_pub: &XPub) -> Self {\n let mut mac = Hmac::new(Sha512::new(), root_pub.as_ref());\n let mut result = [0; HDKEY_SIZE];\n let iters = 500;\n pbkdf2(&mut mac, SALT, iters, &mut result);\n HdKey(result)\n }\n\n #[cfg(test)]\n pub fn encrypt(&self, input: &[u8]) -> Vec<u8> {\n let mut ctx = ChaCha20Poly1305::new(&self.0, NONCE, &[]);\n\n let len = input.len();\n\n let mut out: Vec<u8> = vec![0; len];\n let mut tag = [0; TAG_LEN];\n\n ctx.encrypt(input, &mut out[0..len], &mut tag);\n out.extend_from_slice(&tag[..]);\n out\n }\n\n pub fn decrypt(&self, input: &[u8]) -> Result<Vec<u8>, Error> {\n if input.len() <= TAG_LEN {\n return Err(Error::NotEnoughEncryptedData);\n };\n let len = input.len() - TAG_LEN;\n if len >= MAX_PAYLOAD_SIZE {\n return Err(Error::PayloadIsTooLarge(len, MAX_PAYLOAD_SIZE));\n }\n\n let mut ctx = ChaCha20Poly1305::new(&self.0, NONCE, &[]);\n\n let mut out: Vec<u8> = vec![0; len];\n\n if ctx.decrypt(&input[..len], &mut out[..], &input[len..]) {\n Ok(out)\n } else {\n Err(Error::CannotDecrypt)\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use bip39::SEED_SIZE;\n use ed25519_bip32::XPrv;\n\n fn generate_from_daedalus_seed(bytes: &[u8]) -> XPrv {\n use cryptoxide::mac::Mac;\n\n let mut mac = Hmac::new(Sha512::new(), bytes);\n\n let mut iter = 1;\n\n loop {\n let s = format!(\"Root Seed Chain {}\", iter);\n mac.reset();\n mac.input(s.as_bytes());\n let mut block = [0u8; 64];\n mac.raw_result(&mut block);\n\n let mut sk = [0; 32];\n sk.clone_from_slice(&block.as_ref()[0..32]);\n let mut cc = [0; 32];\n cc.clone_from_slice(&block.as_ref()[32..64]);\n let xprv = XPrv::from_nonextended_force(&sk, &cc);\n\n // check if we find a good candidate\n if xprv.as_ref()[31] & 0x20 == 0 {\n return xprv;\n }\n\n iter += 1;\n }\n }\n\n #[test]\n fn encrypt() {\n let bytes = vec![42u8; MAX_PAYLOAD_SIZE - 1];\n let sk = generate_from_daedalus_seed(&[0; SEED_SIZE]);\n let pk = sk.public();\n\n let key = HdKey::new(&pk);\n let payload = key.encrypt(&bytes);\n assert_eq!(bytes, key.decrypt(&payload).unwrap())\n }\n\n #[test]\n fn decrypt_too_small() {\n const TOO_SMALL_PAYLOAD: usize = TAG_LEN - 1;\n let bytes = vec![42u8; TOO_SMALL_PAYLOAD];\n let sk = generate_from_daedalus_seed(&[0; SEED_SIZE]);\n let pk = sk.public();\n\n let key = HdKey::new(&pk);\n match key.decrypt(&bytes).unwrap_err() {\n Error::NotEnoughEncryptedData => {}\n err => unreachable!(\"expecting Error::NotEnoughEncryptedData but got {:#?}\", err),\n }\n }\n #[test]\n fn decrypt_too_large() {\n const TOO_LARGE_PAYLOAD: usize = 2 * MAX_PAYLOAD_SIZE;\n let bytes = vec![42u8; TOO_LARGE_PAYLOAD];\n let sk = generate_from_daedalus_seed(&[0; SEED_SIZE]);\n let pk = sk.public();\n\n let key = HdKey::new(&pk);\n match key.decrypt(&bytes).unwrap_err() {\n Error::PayloadIsTooLarge(len, _too_large) => {\n assert_eq!(len, TOO_LARGE_PAYLOAD - TAG_LEN)\n }\n err => unreachable!(\n \"expecting Error::PayloadIsTooLarge({}) but got {:#?}\",\n TOO_LARGE_PAYLOAD - TAG_LEN,\n err\n ),\n }\n }\n\n #[test]\n fn path_cbor_encoding() {\n let path = derivation_path(&[0.into(), 1.into(), 2.into()]);\n let cbor = encode_derivation_path(&path);\n dbg!(&cbor);\n let expected = decode_derivation_path(&cbor);\n assert_eq!(Some(path), expected);\n }\n\n #[test]\n fn hdpayload() {\n let path = derivation_path(&[0.into(), 1.into(), 2.into()]);\n let path = encode_derivation_path(&path);\n let sk = generate_from_daedalus_seed(&[0; SEED_SIZE]);\n let pk = sk.public();\n\n let key = HdKey::new(&pk);\n let payload = key.encrypt(&path);\n assert_eq!(path, key.decrypt(&payload).unwrap())\n }\n\n #[test]\n fn unit1() {\n let key = HdKey([0u8; 32]);\n let dat = [0x9f, 0x00, 0x01, 0x0ff];\n let expected = [\n 0xda, 0xac, 0x4a, 0x55, 0xfc, 0xa7, 0x48, 0xf3, 0x2f, 0xfa, 0xf4, 0x9e, 0x2b, 0x41,\n 0xab, 0x86, 0xf3, 0x54, 0xdb, 0x96,\n ];\n let got = key.encrypt(&dat[..]);\n assert_eq!(&expected[..], &got[..])\n }\n\n #[test]\n fn unit2() {\n let path = derivation_path(&[0.into(), 1.into()]);\n let expected = [0x9f, 0x00, 0x01, 0x0ff];\n let cbor = encode_derivation_path(&path);\n assert_eq!(&expected[..], &cbor[..])\n }\n\n struct GoldenTest {\n xprv_key: [u8; ed25519_bip32::XPRV_SIZE],\n hdkey: [u8; HDKEY_SIZE],\n payload: &'static [u8],\n addressing: [Derivation; 2],\n }\n\n const GOLDEN_TESTS: &[GoldenTest] = &[\n GoldenTest {\n xprv_key: [\n 32, 15, 90, 64, 107, 113, 208, 132, 181, 199, 158, 192, 82, 246, 119, 189, 80, 23,\n 31, 95, 219, 198, 94, 39, 18, 166, 174, 186, 139, 177, 243, 82, 202, 175, 171, 241,\n 217, 208, 101, 229, 20, 60, 84, 114, 214, 1, 73, 40, 25, 142, 239, 22, 239, 146,\n 66, 82, 121, 206, 22, 120, 24, 45, 126, 66, 208, 108, 114, 200, 223, 219, 60, 98,\n 75, 118, 2, 56, 104, 230, 68, 215, 229, 31, 241, 136, 165, 71, 176, 231, 189, 125,\n 179, 211, 163, 66, 186, 210,\n ],\n hdkey: [\n 96, 3, 72, 241, 97, 26, 53, 38, 110, 107, 149, 105, 139, 250, 203, 125, 73, 152,\n 12, 195, 158, 54, 84, 69, 99, 239, 234, 122, 177, 179, 59, 200,\n ],\n payload: &[\n 0x33, 0x1c, 0xd6, 0xc3, 0x02, 0x5d, 0x59, 0xa1, 0x6a, 0x5f, 0x82, 0x9e, 0xd7, 0xf2,\n 0x4c, 0xf8, 0x74, 0xf3, 0xab, 0x50,\n ],\n addressing: [Derivation::new(0), Derivation::new(0)],\n },\n GoldenTest {\n xprv_key: [\n 32, 15, 90, 64, 107, 113, 208, 132, 181, 199, 158, 192, 82, 246, 119, 189, 80, 23,\n 31, 95, 219, 198, 94, 39, 18, 166, 174, 186, 139, 177, 243, 82, 202, 175, 171, 241,\n 217, 208, 101, 229, 20, 60, 84, 114, 214, 1, 73, 40, 25, 142, 239, 22, 239, 146,\n 66, 82, 121, 206, 22, 120, 24, 45, 126, 66, 208, 108, 114, 200, 223, 219, 60, 98,\n 75, 118, 2, 56, 104, 230, 68, 215, 229, 31, 241, 136, 165, 71, 176, 231, 189, 125,\n 179, 211, 163, 66, 186, 210,\n ],\n hdkey: [\n 96, 3, 72, 241, 97, 26, 53, 38, 110, 107, 149, 105, 139, 250, 203, 125, 73, 152,\n 12, 195, 158, 54, 84, 69, 99, 239, 234, 122, 177, 179, 59, 200,\n ],\n payload: &[\n 0x33, 0x06, 0x56, 0x3c, 0x02, 0xd0, 0x2f, 0x38, 0x1e, 0x78, 0xdf, 0x84, 0x04, 0xc3,\n 0x50, 0x56, 0x76, 0xd5, 0x5e, 0x45, 0x71, 0x93, 0xe7, 0x4a, 0x34, 0xb6, 0x90, 0xec,\n ],\n addressing: [Derivation::new(0x8000_0000), Derivation::new(0x8000_0000)],\n },\n ];\n\n fn derivation_path(d: &[Derivation]) -> DerivationPath<AnyScheme> {\n let mut dp = DerivationPath::new();\n\n for d in d {\n dp = dp.append_unchecked(*d);\n }\n\n dp\n }\n\n fn run_golden_test(golden_test: &GoldenTest) {\n let xprv = XPrv::from_bytes_verified(golden_test.xprv_key).unwrap();\n let hdkey = HdKey(golden_test.hdkey);\n let payload = Vec::from(golden_test.payload);\n let path = derivation_path(&golden_test.addressing[..]);\n let path = encode_derivation_path(&path);\n\n let our_hdkey = HdKey::new(&xprv.public());\n assert_eq!(hdkey.0, our_hdkey.0);\n\n let our_payload = hdkey.encrypt(&path);\n assert_eq!(payload, our_payload);\n\n let our_path = hdkey.decrypt(&payload).unwrap();\n assert_eq!(path, our_path);\n }\n\n #[test]\n fn golden_tests() {\n for golden_test in GOLDEN_TESTS {\n run_golden_test(golden_test)\n }\n }\n}\n\n#[cfg(test)]\n#[cfg(feature = \"with-bench\")]\nmod bench {\n use hdpayload::{self, *};\n use hdwallet;\n use test;\n\n #[bench]\n fn decrypt_fail(b: &mut test::Bencher) {\n let path = Path::new(vec![0, 1]);\n let seed = hdwallet::Seed::from_bytes([0; hdwallet::SEED_SIZE]);\n let sk = hdwallet::XPrv::generate_from_seed(&seed);\n let pk = sk.public();\n\n let key = HDKey::new(&pk);\n let payload = key.encrypt_path(&path);\n\n let seed = hdwallet::Seed::from_bytes([1; hdwallet::SEED_SIZE]);\n let sk = hdwallet::XPrv::generate_from_seed(&seed);\n let pk = sk.public();\n let key = HDKey::new(&pk);\n b.iter(|| {\n let _ = key.decrypt(&payload);\n })\n }\n\n #[bench]\n fn decrypt_ok(b: &mut test::Bencher) {\n let path = Path::new(vec![0, 1]);\n let seed = hdwallet::Seed::from_bytes([0; hdwallet::SEED_SIZE]);\n let sk = hdwallet::XPrv::generate_from_seed(&seed);\n let pk = sk.public();\n\n let key = HDKey::new(&pk);\n let payload = key.encrypt_path(&path);\n\n b.iter(|| {\n let _ = key.decrypt(&payload);\n })\n }\n\n #[bench]\n fn decrypt_with_cbor(b: &mut test::Bencher) {\n let path = Path::new(vec![0, 1]);\n let seed = hdwallet::Seed::from_bytes([0; hdwallet::SEED_SIZE]);\n let sk = hdwallet::XPrv::generate_from_seed(&seed);\n let pk = sk.public();\n\n let key = HDKey::new(&pk);\n let payload = key.encrypt_path(&path);\n\n b.iter(|| {\n let _ = key.decrypt_path(&payload);\n })\n }\n}\n" }, { "alpha_fraction": 0.7933579087257385, "alphanum_fraction": 0.7933579087257385, "avg_line_length": 37.71428680419922, "blob_id": "9f96729b1191e43471be5f5c21cc302fc43a8496", "content_id": "ccc311ec5788014cf7c32780e5bef121a18e9f80", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 271, "license_type": "permissive", "max_line_length": 60, "num_lines": 7, "path": "/bindings/wallet-cordova/scripts/directories.py", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "from pathlib import Path\n\nscript_directory = Path(__file__).parent\nplugin_directory = script_directory.parent\ntests_directory = plugin_directory / \"tests\"\nrepository_directory = script_directory.parent.parent.parent\nrust_build_directory = repository_directory / \"target\"\n" }, { "alpha_fraction": 0.44524475932121277, "alphanum_fraction": 0.5384820699691772, "avg_line_length": 28.28515625, "blob_id": "dcd9a40085a69211eab237cd7ff08871e12da1d5", "content_id": "559a8d37b3f0b8b52b5b20c884c40c00a8e8ee3c", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 7497, "license_type": "permissive", "max_line_length": 99, "num_lines": 256, "path": "/symmetric-cipher/src/lib.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use cryptoxide::chacha20poly1305::ChaCha20Poly1305;\nuse cryptoxide::hmac::Hmac;\nuse cryptoxide::pbkdf2::pbkdf2;\nuse cryptoxide::sha2::Sha512;\nuse std::convert::TryInto;\nuse thiserror::Error;\nuse zeroize::Zeroizing;\n\n#[derive(Error, Debug)]\npub enum Error {\n #[error(\"invalid payload protocol\")]\n InvalidProtocol,\n #[error(\"expected data to be a multiple of 64 bytes\")]\n InvalidDataLength,\n #[error(\"encrypted data should not be null\")]\n EmptyPayload,\n #[error(\"missing data\")]\n MalformedInput,\n #[error(transparent)]\n IoError(#[from] std::io::Error),\n #[error(\"wrong password\")]\n AuthenticationFailed,\n}\n\nstruct View<T: AsRef<[u8]>>(pub T);\n\nconst ITERS: u32 = 12983;\nconst PROTOCOL_SIZE: usize = 1;\nconst SALT_SIZE: usize = 16;\nconst NONCE_SIZE: usize = 12;\nconst TAG_SIZE: usize = 16;\n\npub fn encrypt<G: rand::Rng + rand::CryptoRng>(\n password: impl AsRef<[u8]>,\n data: impl AsRef<[u8]>,\n mut random: G,\n) -> Result<Box<[u8]>, Error> {\n if data.as_ref().is_empty() {\n return Err(Error::EmptyPayload);\n }\n\n if data.as_ref().len() % 64 != 0 {\n return Err(Error::InvalidDataLength);\n }\n\n let aad = [];\n\n let salt = {\n let mut salt = [0u8; SALT_SIZE];\n random.fill(&mut salt);\n salt\n };\n\n let nonce = {\n let mut nonce = [0u8; NONCE_SIZE];\n random.fill(&mut nonce);\n nonce\n };\n\n let symmetric_key = derive_symmetric_key(password, salt);\n\n let mut chacha20 = ChaCha20Poly1305::new(&*symmetric_key, &nonce, &aad);\n\n let (ciphertext, tag) = {\n let mut ciphertext = vec![0u8; data.as_ref().len()];\n let mut tag = [0u8; 16];\n chacha20.encrypt(data.as_ref(), &mut ciphertext, &mut tag);\n\n (ciphertext.into_boxed_slice(), tag)\n };\n\n let mut buffer =\n vec![0u8; PROTOCOL_SIZE + SALT_SIZE + NONCE_SIZE + ciphertext.len() + TAG_SIZE];\n\n let parts: [&[u8]; 5] = [&[1u8], &salt, &nonce, &ciphertext, &tag];\n\n let mut low = 0;\n\n for part in parts.iter() {\n buffer[low..low + part.len()].copy_from_slice(part);\n low += part.len();\n }\n\n Ok(buffer.into_boxed_slice())\n}\n\npub fn decrypt<T: AsRef<[u8]>>(password: impl AsRef<[u8]>, data: T) -> Result<Box<[u8]>, Error> {\n let data = View::new(data)?;\n\n let aad = [];\n\n if data.protocol() != 0x1 {\n return Err(Error::InvalidProtocol);\n }\n\n let key = derive_symmetric_key(password, data.salt().try_into().unwrap());\n\n let mut chacha20 = ChaCha20Poly1305::new(&*key, data.nonce(), &aad);\n\n let mut plaintext = vec![0u8; data.encrypted_data().len()];\n\n if chacha20.decrypt(data.encrypted_data(), &mut plaintext, data.tag()) {\n Ok(plaintext.into_boxed_slice())\n } else {\n Err(Error::AuthenticationFailed)\n }\n}\n\nimpl<T: AsRef<[u8]>> View<T> {\n fn new(inner: T) -> Result<View<T>, Error> {\n if inner.as_ref().len() <= PROTOCOL_SIZE + SALT_SIZE + NONCE_SIZE + TAG_SIZE {\n Err(Error::MalformedInput)\n } else {\n let data = Self(inner);\n\n if data.encrypted_data().is_empty() {\n Err(Error::EmptyPayload)\n } else if data.encrypted_data().len() % 64 != 0 {\n Err(Error::InvalidDataLength)\n } else {\n Ok(data)\n }\n }\n }\n\n fn protocol(&self) -> u8 {\n self.0.as_ref()[0]\n }\n\n fn salt(&self) -> &[u8] {\n &self.0.as_ref()[PROTOCOL_SIZE..PROTOCOL_SIZE + SALT_SIZE]\n }\n\n fn nonce(&self) -> &[u8] {\n &self.0.as_ref()[PROTOCOL_SIZE + SALT_SIZE..PROTOCOL_SIZE + SALT_SIZE + NONCE_SIZE]\n }\n\n fn encrypted_data(&self) -> &[u8] {\n let data_len = self\n .0\n .as_ref()\n .len()\n .checked_sub(PROTOCOL_SIZE + SALT_SIZE + NONCE_SIZE + TAG_SIZE)\n .unwrap();\n\n let starting_pos = PROTOCOL_SIZE + SALT_SIZE + NONCE_SIZE;\n &self.0.as_ref()[starting_pos..starting_pos + data_len]\n }\n\n fn tag(&self) -> &[u8] {\n let start = self.0.as_ref().len().checked_sub(TAG_SIZE).unwrap();\n &self.0.as_ref()[start..]\n }\n}\n\nfn derive_symmetric_key(password: impl AsRef<[u8]>, salt: [u8; SALT_SIZE]) -> Zeroizing<[u8; 32]> {\n let mut symmetric_key = [0u8; 32];\n\n let mut mac = Hmac::new(Sha512::new(), password.as_ref());\n pbkdf2(&mut mac, &salt[..], ITERS, &mut symmetric_key);\n\n Zeroizing::new(symmetric_key)\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use rand::SeedableRng;\n\n fn get_random_gen() -> rand_chacha::ChaChaRng {\n rand_chacha::ChaChaRng::seed_from_u64(33)\n }\n\n #[test]\n fn encrypt_decrypt() {\n let mut bytes: Vec<u8> = vec![];\n bytes.extend([1u8; 64].iter());\n bytes.extend([2u8; 64].iter());\n bytes.extend([3u8; 64].iter());\n\n let password = [1u8, 2, 3, 4];\n\n let slice = encrypt(&password, &bytes[..], get_random_gen()).unwrap();\n\n assert_eq!(&decrypt(&password, slice).unwrap()[..], &bytes[..]);\n }\n\n #[test]\n fn encrypt_non_64_bytes() {\n let bytes = [0u8; 65];\n let password = [1u8, 2, 3, 4];\n\n assert!(encrypt(&password, &bytes[..], get_random_gen()).is_err())\n }\n\n #[test]\n fn encrypt_decrypt_empty_payload() {\n let bytes = [];\n let password = [1u8, 2, 3, 4];\n\n assert!(encrypt(&password, &bytes[..], get_random_gen()).is_err())\n }\n\n #[test]\n fn test_vectors_account_two_utxo() {\n let account = [\n 200u8, 101, 150, 194, 209, 32, 136, 133, 219, 31, 227, 101, 132, 6, 170, 15, 124, 199,\n 184, 225, 60, 54, 47, 228, 106, 109, 178, 119, 252, 80, 100, 88, 62, 72, 117, 136, 201,\n 138, 108, 54, 226, 231, 68, 92, 10, 221, 54, 248, 63, 23, 28, 181, 204, 253, 129, 85,\n 9, 209, 156, 211, 142, 203, 10, 243,\n ];\n\n let key1 = [\n 48, 21, 89, 204, 178, 212, 204, 126, 158, 84, 166, 245, 90, 128, 150, 11, 182, 145,\n 183, 177, 64, 149, 73, 239, 134, 149, 169, 46, 164, 26, 111, 79, 64, 82, 49, 168, 6,\n 194, 231, 185, 208, 219, 48, 225, 94, 224, 204, 31, 38, 28, 27, 159, 150, 21, 99, 107,\n 72, 189, 137, 254, 123, 230, 234, 31,\n ];\n\n let key2 = [\n 168, 182, 189, 240, 128, 199, 79, 188, 49, 51, 126, 222, 75, 102, 146, 194, 235, 237,\n 126, 52, 175, 109, 152, 183, 187, 205, 71, 140, 240, 123, 13, 94, 217, 63, 126, 157,\n 74, 163, 175, 222, 50, 26, 225, 171, 182, 27, 131, 68, 194, 67, 201, 208, 180, 7, 203,\n 248, 145, 125, 182, 223, 44, 101, 61, 234,\n ];\n\n let password = [1u8, 2, 3, 4];\n\n let mut bytes = [0u8; 64 * 3];\n\n bytes[0..64].copy_from_slice(&account);\n bytes[64..2 * 64].copy_from_slice(&key1);\n bytes[2 * 64..3 * 64].copy_from_slice(&key2);\n\n let slice = encrypt(&password, &bytes[..], get_random_gen()).unwrap();\n assert_eq!(&decrypt(&password, slice).unwrap()[..], &bytes[..]);\n }\n\n #[test]\n fn wrong_password() {\n let mut bytes: Vec<u8> = vec![];\n bytes.extend([1u8; 64].iter());\n bytes.extend([2u8; 64].iter());\n bytes.extend([3u8; 64].iter());\n\n let password = [1u8, 2, 3, 4];\n\n let slice = encrypt(&password, &bytes[..], get_random_gen()).unwrap();\n\n let password = [5u8, 6, 7, 8];\n assert!(matches!(\n decrypt(&password, slice),\n Err(Error::AuthenticationFailed)\n ));\n }\n}\n" }, { "alpha_fraction": 0.5977272987365723, "alphanum_fraction": 0.6545454263687134, "avg_line_length": 24.882352828979492, "blob_id": "3b26e1d452015b144d58a4b5c22069751ae6a7e4", "content_id": "93b2b04671e30d937d31df0ee5305d4801e20a8a", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 440, "license_type": "permissive", "max_line_length": 96, "num_lines": 17, "path": "/symmetric-cipher/Cargo.toml", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "[package]\nauthors = [\"Nicolas Di Prima <[email protected]>\", \"Vincent Hanquez <[email protected]>\", \"Enzo Cioppettini <[email protected]\"]\nedition = \"2018\"\nlicense = \"MIT OR Apache-2.0\"\nname = \"symmetric-cipher\"\nversion = \"0.5.0\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\ncryptoxide = \"0.4.2\"\nrand = \"0.8.3\"\nthiserror = {version = \"1.0.13\", default-features = false}\nzeroize = \"1.5.3\"\n\n[dev-dependencies]\nrand_chacha = \"0.3.0\"\n" }, { "alpha_fraction": 0.2954416275024414, "alphanum_fraction": 0.3983176052570343, "avg_line_length": 31.105838775634766, "blob_id": "66fa410a8239eb7f372687dfdf8ac91f23122027", "content_id": "f596c7ba2e6e3210444c6e2a2520746d3e3f4033", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 8797, "license_type": "permissive", "max_line_length": 60, "num_lines": 274, "path": "/bip39/src/bits.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "#[derive(Debug, PartialEq, Eq, Copy, Clone)]\nenum State {\n S0,\n S1,\n S2,\n S3,\n S4,\n S5,\n S6,\n S7,\n}\n\npub struct BitWriterBy11 {\n buffer: Vec<u8>,\n state: State,\n}\n\nimpl BitWriterBy11 {\n pub fn new() -> Self {\n BitWriterBy11 {\n buffer: Vec::new(),\n state: State::S0,\n }\n }\n\n pub fn into_vec(self) -> Vec<u8> {\n self.buffer\n }\n\n pub fn write(&mut self, e: u16) {\n match self.state {\n State::S0 => {\n let x = e >> 3 & 0b1111_1111;\n let y = e << 5 & 0b1110_0000;\n self.buffer.push(x as u8);\n self.buffer.push(y as u8);\n self.state = State::S1;\n }\n State::S1 => {\n let x = e >> 6 & 0b0001_1111;\n let y = e << 2 & 0b1111_1100;\n if let Some(last) = self.buffer.last_mut() {\n *last |= x as u8;\n } else {\n unreachable!()\n }\n self.buffer.push(y as u8);\n self.state = State::S2;\n }\n State::S2 => {\n let x = e >> 9 & 0b0000_0011;\n let y = e >> 1 & 0b1111_1111;\n let z = e << 7 & 0b1000_0000;\n if let Some(last) = self.buffer.last_mut() {\n *last |= x as u8;\n } else {\n unreachable!()\n }\n self.buffer.push(y as u8);\n self.buffer.push(z as u8);\n self.state = State::S3;\n }\n State::S3 => {\n let x = e >> 4 & 0b0111_1111;\n let y = e << 4 & 0b1111_0000;\n if let Some(last) = self.buffer.last_mut() {\n *last |= x as u8;\n } else {\n unreachable!()\n }\n self.buffer.push(y as u8);\n self.state = State::S4;\n }\n State::S4 => {\n let x = e >> 7 & 0b0000_1111;\n let y = e << 1 & 0b1111_1110;\n if let Some(last) = self.buffer.last_mut() {\n *last |= x as u8;\n } else {\n unreachable!()\n }\n self.buffer.push(y as u8);\n self.state = State::S5;\n }\n State::S5 => {\n let x = e >> 10 & 0b0000_0001;\n let y = e >> 2 & 0b1111_1111;\n let z = e << 6 & 0b1100_0000;\n if let Some(last) = self.buffer.last_mut() {\n *last |= x as u8;\n } else {\n unreachable!()\n }\n self.buffer.push(y as u8);\n self.buffer.push(z as u8);\n self.state = State::S6;\n }\n State::S6 => {\n let x = e >> 5 & 0b0011_1111;\n let y = e << 3 & 0b1111_1000;\n if let Some(last) = self.buffer.last_mut() {\n *last |= x as u8;\n } else {\n unreachable!()\n }\n self.buffer.push(y as u8);\n self.state = State::S7;\n }\n State::S7 => {\n let x = e >> 8 & 0b0000_0111;\n let y = e & 0b1111_1111;\n if let Some(last) = self.buffer.last_mut() {\n *last |= x as u8;\n } else {\n unreachable!()\n }\n self.buffer.push(y as u8);\n self.state = State::S0;\n }\n }\n }\n}\n\npub struct BitReaderBy11<'a> {\n buffer: &'a [u8],\n state: State,\n}\n\nimpl<'a> BitReaderBy11<'a> {\n pub fn new(bytes: &'a [u8]) -> Self {\n BitReaderBy11 {\n buffer: bytes,\n state: State::S0,\n }\n }\n\n pub fn read(&mut self) -> u16 {\n match self.state {\n State::S0 => {\n assert!(self.buffer.len() > 1);\n let x = self.buffer[0] as u16 & 0b1111_1111;\n let y = self.buffer[1] as u16 & 0b1110_0000;\n self.state = State::S1;\n self.buffer = &self.buffer[1..];\n (x << 3) | (y >> 5)\n }\n State::S1 => {\n assert!(self.buffer.len() > 1);\n let x = self.buffer[0] as u16 & 0b0001_1111;\n let y = self.buffer[1] as u16 & 0b1111_1100;\n self.state = State::S2;\n self.buffer = &self.buffer[1..];\n (x << 6) | (y >> 2)\n }\n State::S2 => {\n assert!(self.buffer.len() > 2);\n let x = self.buffer[0] as u16 & 0b0000_0011;\n let y = self.buffer[1] as u16 & 0b1111_1111;\n let z = self.buffer[2] as u16 & 0b1000_0000;\n self.state = State::S3;\n self.buffer = &self.buffer[2..];\n (x << 9) | (y << 1) | (z >> 7)\n }\n State::S3 => {\n assert!(self.buffer.len() > 1);\n let x = self.buffer[0] as u16 & 0b0111_1111;\n let y = self.buffer[1] as u16 & 0b1111_0000;\n self.state = State::S4;\n self.buffer = &self.buffer[1..];\n (x << 4) | (y >> 4)\n }\n State::S4 => {\n assert!(self.buffer.len() > 1);\n let x = self.buffer[0] as u16 & 0b0000_1111;\n let y = self.buffer[1] as u16 & 0b1111_1110;\n self.state = State::S5;\n self.buffer = &self.buffer[1..];\n (x << 7) | (y >> 1)\n }\n State::S5 => {\n assert!(self.buffer.len() > 2);\n let x = self.buffer[0] as u16 & 0b0000_0001;\n let y = self.buffer[1] as u16 & 0b1111_1111;\n let z = self.buffer[2] as u16 & 0b1100_0000;\n self.state = State::S6;\n self.buffer = &self.buffer[2..];\n (x << 10) | (y << 2) | (z >> 6)\n }\n State::S6 => {\n assert!(self.buffer.len() > 1);\n let x = self.buffer[0] as u16 & 0b0011_1111;\n let y = self.buffer[1] as u16 & 0b1111_1000;\n self.state = State::S7;\n self.buffer = &self.buffer[1..];\n (x << 5) | (y >> 3)\n }\n State::S7 => {\n assert!(self.buffer.len() > 1);\n let x = self.buffer[0] as u16 & 0b0000_0111;\n let y = self.buffer[1] as u16 & 0b1111_1111;\n self.state = State::S0;\n self.buffer = &self.buffer[2..];\n (x << 8) | y\n }\n }\n }\n}\n\n#[cfg(test)]\nmod test {\n use super::*;\n\n #[test]\n fn bit_read_by_11() {\n const BYTES: &[u8] = &[\n 0b0000_0000,\n 0b0010_0000,\n 0b0000_0100,\n 0b0000_0000,\n 0b1000_0000,\n 0b0001_0000,\n 0b0000_0010,\n 0b0000_0000,\n 0b0100_0000,\n 0b0000_1000,\n 0b0000_0001,\n 0b1000_0000,\n 0b0011_0000,\n 0b0000_0110,\n 0b0000_0000,\n 0b1100_0000,\n 0b0001_1000,\n 0b0000_0011,\n 0b0000_0000,\n 0b0110_0000,\n 0b0000_1100,\n 0b0000_0001,\n ];\n let mut reader = BitReaderBy11::new(BYTES);\n\n let byte = reader.read();\n assert_eq!(byte, 0b000_0000_0001);\n let byte = reader.read();\n assert_eq!(byte, 0b000_0000_0001);\n let byte = reader.read();\n assert_eq!(byte, 0b000_0000_0001);\n let byte = reader.read();\n assert_eq!(byte, 0b000_0000_0001);\n let byte = reader.read();\n assert_eq!(byte, 0b000_0000_0001);\n let byte = reader.read();\n assert_eq!(byte, 0b000_0000_0001);\n let byte = reader.read();\n assert_eq!(byte, 0b000_0000_0001);\n let byte = reader.read();\n assert_eq!(byte, 0b000_0000_0001);\n let byte = reader.read();\n assert_eq!(byte, 0b100_0000_0001);\n let byte = reader.read();\n assert_eq!(byte, 0b100_0000_0001);\n let byte = reader.read();\n assert_eq!(byte, 0b100_0000_0001);\n let byte = reader.read();\n assert_eq!(byte, 0b100_0000_0001);\n let byte = reader.read();\n assert_eq!(byte, 0b100_0000_0001);\n let byte = reader.read();\n assert_eq!(byte, 0b100_0000_0001);\n let byte = reader.read();\n assert_eq!(byte, 0b100_0000_0001);\n let byte = reader.read();\n assert_eq!(byte, 0b100_0000_0001);\n }\n}\n" }, { "alpha_fraction": 0.6081982851028442, "alphanum_fraction": 0.6134413480758667, "avg_line_length": 30.548871994018555, "blob_id": "02081c7fca01176e9a82c1389648e4030130535b", "content_id": "85f7375cf3587a74b50375ea64524af61f5c89ef", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 4196, "license_type": "permissive", "max_line_length": 87, "num_lines": 133, "path": "/bindings/wallet-core/src/c/vote.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use super::ProposalPtr;\nuse crate::{vote::PayloadTypeConfig, Error, Proposal, Result as AbiResult};\nuse chain_crypto::bech32::Bech32;\nuse chain_impl_mockchain::{certificate::VotePlanId, vote::Options as VoteOptions};\nuse chain_vote::ElectionPublicKey;\nuse std::convert::{TryFrom, TryInto};\nuse std::ffi::CStr;\npub use wallet::Settings;\n\n// using generics in this module is questionable, but it's used just for code\n// re-use, the idea is to have two functions, and then it's exposed that way in\n// wallet-c/wallet-jni (with manual name mangling).\n// for the C interface, a tagged union could be used as input too, but I think\n// using the same approach for all the interfaces it's better.\n// something else that could work is a new opaque type.\npub struct ProposalPublic;\npub struct ProposalPrivate<'a>(pub &'a CStr);\n\nimpl TryInto<PayloadTypeConfig> for ProposalPublic {\n type Error = Error;\n\n fn try_into(self) -> Result<PayloadTypeConfig, Error> {\n Ok(PayloadTypeConfig::Public)\n }\n}\n\nimpl<'a> TryInto<PayloadTypeConfig> for ProposalPrivate<'a> {\n type Error = Error;\n\n fn try_into(self) -> Result<PayloadTypeConfig, Error> {\n const INPUT_NAME: &str = \"election_public_key\";\n\n self.0\n .to_str()\n .map_err(|_| Error::invalid_input(INPUT_NAME))\n .and_then(|s| {\n ElectionPublicKey::try_from_bech32_str(s)\n .map_err(|_| Error::invalid_vote_encryption_key())\n })\n .map(PayloadTypeConfig::Private)\n }\n}\n\n/// build the proposal object\n///\n/// # Errors\n///\n/// This function may fail if:\n///\n/// * a null pointer was provided as an argument.\n/// * `num_choices` is out of the allowed range.\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though the function checks if\n/// the pointers are null. Mind not to put random values in or you may see\n/// unexpected behaviors.\npub unsafe fn proposal_new<P>(\n vote_plan_id: *const u8,\n index: u8,\n num_choices: u8,\n payload_type: P,\n proposal_out: *mut ProposalPtr,\n) -> AbiResult\nwhere\n P: TryInto<PayloadTypeConfig>,\n P::Error: Into<AbiResult>,\n{\n let options = match VoteOptions::new_length(num_choices) {\n Ok(options) => options,\n Err(err) => return Error::invalid_input(\"num_choices\").with(err).into(),\n };\n\n let vote_plan_id = non_null_array!(vote_plan_id, crate::vote::VOTE_PLAN_ID_LENGTH);\n let vote_plan_id = match VotePlanId::try_from(vote_plan_id) {\n Ok(id) => id,\n Err(err) => return Error::invalid_input(\"vote_plan_id\").with(err).into(),\n };\n\n let payload_type = match payload_type.try_into() {\n Ok(payload_type) => payload_type,\n Err(err) => return err.into(),\n };\n\n let proposal = Proposal::new(vote_plan_id, index, options, payload_type);\n *non_null_mut!(proposal_out) = Box::into_raw(Box::new(proposal));\n\n AbiResult::success()\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn cast_private_vote() {\n use chain_vote::{\n committee::{MemberCommunicationKey, MemberState},\n tally::Crs,\n };\n let vote_plan_id = [0u8; crate::vote::VOTE_PLAN_ID_LENGTH];\n\n let shared_string =\n b\"Example of a shared string. This should be VotePlan.to_id()\".to_owned();\n let h = Crs::from_hash(&shared_string);\n\n let mut rng = rand::thread_rng();\n\n let mc1 = MemberCommunicationKey::new(&mut rng);\n let mc = [mc1.to_public()];\n\n let threshold = 1;\n\n let m1 = MemberState::new(&mut rng, threshold, &h, &mc, 0);\n\n let pk = ElectionPublicKey::from_participants(&[m1.public_key()]);\n\n let election_public_key = pk.to_bech32_str();\n let election_public_key = std::ffi::CString::new(election_public_key).unwrap();\n\n let mut proposal: ProposalPtr = std::ptr::null_mut();\n unsafe {\n let result = proposal_new(\n vote_plan_id.as_ptr(),\n 0,\n 2,\n ProposalPrivate(&election_public_key),\n (&mut proposal) as *mut ProposalPtr,\n );\n assert!(result.is_ok());\n }\n }\n}\n" }, { "alpha_fraction": 0.7002529501914978, "alphanum_fraction": 0.7053119540214539, "avg_line_length": 33.37681198120117, "blob_id": "af75b9e53bcefee94c89150df3c75fa4254c6cf5", "content_id": "6fa29d61ee761e12d9f483e4f5e4308ae2452c7f", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 2372, "license_type": "permissive", "max_line_length": 100, "num_lines": 69, "path": "/bindings/wallet-c/src/settings.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use super::{ErrorPtr, SettingsPtr};\nuse wallet_core::c::settings::{\n settings_block0_hash, settings_discrimination, settings_fees, settings_new, Discrimination,\n LinearFee, SettingsInit,\n};\n\n/// # Safety\n///\n/// settings_out must point to valid writable memory\n/// block_0_hash is assumed to point to 32 bytes of readable memory\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_settings_new(\n settings_init: SettingsInit,\n settings_out: *mut SettingsPtr,\n) -> ErrorPtr {\n settings_new(\n settings_init,\n settings_out as *mut *mut wallet_core::Settings,\n )\n .into_c_api() as ErrorPtr\n}\n\n/// # Safety\n///\n/// This function also assumes that settings is a valid pointer previously\n/// obtained with this library, a null check is performed, but is important that\n/// the data it points to is valid\n///\n/// linear_fee_out must point to valid writable memory, a null check is\n/// performed\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_settings_fees(\n settings: SettingsPtr,\n linear_fee_out: *mut LinearFee,\n) -> ErrorPtr {\n settings_fees(settings as *const wallet_core::Settings, linear_fee_out).into_c_api() as ErrorPtr\n}\n\n/// # Safety\n///\n/// This function also assumes that settings is a valid pointer previously\n/// obtained with this library, a null check is performed, but is important that\n/// the data it points to is valid\n///\n/// discrimination_out must point to valid writable memory, a null check is\n/// performed\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_settings_discrimination(\n settings: SettingsPtr,\n discrimination_out: *mut Discrimination,\n) -> ErrorPtr {\n settings_discrimination(settings as *const wallet_core::Settings, discrimination_out)\n .into_c_api() as ErrorPtr\n}\n\n/// # Safety\n///\n/// This function assumes block0_hash points to 32 bytes of valid memory\n/// This function also assumes that settings is a valid pointer previously\n/// obtained with this library, a null check is performed, but is important that\n/// the data it points to is valid\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_settings_block0_hash(\n settings: SettingsPtr,\n block0_hash: *mut u8,\n) -> ErrorPtr {\n settings_block0_hash(settings as *const wallet_core::Settings, block0_hash).into_c_api()\n as ErrorPtr\n}\n" }, { "alpha_fraction": 0.5803393125534058, "alphanum_fraction": 0.5963073968887329, "avg_line_length": 24.0625, "blob_id": "79418057ac8674bab020a7568dc3792fbc40dae4", "content_id": "60c8f478ba50fc37c14d8a4fe26e25b37b248e0d", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2004, "license_type": "permissive", "max_line_length": 97, "num_lines": 80, "path": "/bindings/wallet-cordova/tests/src/utils.js", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "// copypasted ArrayBuffer to Hex string function\nconst byteToHex = [];\n\nfor (let n = 0; n <= 0xff; ++n) {\n const hexOctet = ('0' + n.toString(16)).slice(-2);\n byteToHex.push(hexOctet);\n}\n\nfunction hex(arrayBuffer) {\n const buff = new Uint8Array(arrayBuffer);\n const hexOctets = [];\n\n for (let i = 0; i < buff.length; ++i) { hexOctets.push(byteToHex[buff[i]]); }\n\n return hexOctets.join('');\n}\n\nfunction hexStringToBytes(string) {\n const bytes = [];\n for (let c = 0; c < string.length; c += 2) { bytes.push(parseInt(string.substr(c, 2), 16)); }\n return Uint8Array.from(bytes);\n}\n\n/**\n * helper to convert the cordova-callback-style to promises, to make tests simpler\n * @param {function} f\n * @returns {function}\n */\nfunction promisify(thisArg, f) {\n const newFunction = function () {\n const args = Array.prototype.slice.call(arguments);\n return new Promise(function (resolve, reject) {\n const success = function () {\n resolve(arguments[0]);\n };\n\n const error = function () {\n reject(arguments[0]);\n };\n\n args.push(success);\n args.push(error);\n\n f.apply(thisArg, args);\n });\n };\n return newFunction;\n}\n\nfunction uint8ArrayEquals(a, b) {\n if (!(a instanceof Uint8Array) || !(b instanceof Uint8Array)) {\n throw Error('invalid arguments, expected a Uint8Array');\n }\n\n return arrayEquals(a, b);\n}\n\nfunction uint32ArrayEquals(a, b) {\n if (!(a instanceof Uint32Array) || !(b instanceof Uint32Array)) {\n throw Error('invalid arguments, expected a Uint32Array');\n }\n\n return arrayEquals(a, b);\n}\n\nfunction arrayEquals(a, b) {\n const length = a.length === b.length;\n\n let elements = true;\n\n for (let i = 0; i < a.length; i++) {\n elements = elements && a[i] === b[i];\n }\n\n return length && elements;\n}\n\nmodule.exports = {\n hex, hexStringToBytes, promisify, uint8ArrayEquals, uint32ArrayEquals\n}" }, { "alpha_fraction": 0.6063302159309387, "alphanum_fraction": 0.6082121729850769, "avg_line_length": 27.935644149780273, "blob_id": "6fcd6312ec13ea75dec6c66b404a8aae5c52b0b1", "content_id": "0bf7101a73715a2729003b9214338678e0c24eb3", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5845, "license_type": "permissive", "max_line_length": 88, "num_lines": 202, "path": "/bindings/wallet-cordova/scripts/test.py", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport subprocess\n\nfrom pathlib import Path\nimport subprocess\nimport sys\nimport shutil\nimport argparse\nimport os\nimport re\n\nfrom build_jni import run as build_jni\nfrom build_jni import copy_libs as copy_jni_libs\nfrom copy_jni_definitions import run as copy_jni_definitions\nfrom build_ios import run as build_ios\nfrom directories import repository_directory, plugin_directory, tests_directory\n\nsys.path.append(str(repository_directory / \"test-vectors\"))\nfrom rebuild_genesis_data import run as rebuild_genesis_data\n\n\ndef sed(original: str, replacement: str, file: Path):\n # TODO: this may have some problems, but I'm also not sure if I want to use\n # `sed`, mostly for Windows compatibility\n with open(file, \"r\") as config:\n lines = config.readlines()\n\n with open(file, \"w\") as config:\n for line in lines:\n config.write(re.sub(original, replacement, line))\n\n\ndef create_hello_world(build_dir: Path):\n os.makedirs(build_dir, exist_ok=True)\n\n subprocess.check_call(\n [\"cordova\", \"create\", \"hello\", \"com.example.hello\", \"HelloWorld\"],\n cwd=build_dir,\n )\n\n\ndef enable_kotlin(app_dir: Path):\n file = app_dir / \"config.xml\"\n\n with open(file, \"r\") as config:\n lines = config.readlines()\n\n with open(file, \"w\") as config:\n for line in lines[:-1]:\n config.write(line)\n\n config.write(' <preference name=\"GradlePluginKotlinEnabled\" value=\"true\" />')\n config.write(\n ' <preference name=\"GradlePluginKotlinCodeStyle\" value=\"official\" />'\n )\n config.write(\n ' <preference name=\"GradlePluginKotlinVersion\" value=\"1.3.50\" />'\n )\n\n config.write(lines[-1])\n\n\ndef install_test_framework(app_dir: Path):\n subprocess.check_call(\n [\"cordova\", \"plugin\", \"add\", \"cordova-plugin-test-framework\"], cwd=app_dir\n )\n\n sed(\n '<content src=\"index.html\" />',\n '<content src=\"cdvtests/index.html\" />',\n app_dir / \"config.xml\",\n )\n\n\ndef install_platforms(app_dir: Path, android=True, ios=True):\n if android:\n subprocess.check_call(\n [\"cordova\", \"platform\", \"add\", \"[email protected]\"], cwd=app_dir\n )\n subprocess.check_call([\"cordova\", \"requirements\", \"android\"], cwd=app_dir)\n\n if ios:\n subprocess.check_call([\"cordova\", \"platform\", \"add\", \"ios\"], cwd=app_dir)\n subprocess.check_call([\"cordova\", \"requirements\", \"ios\"], cwd=app_dir)\n\n\ndef install_main_plugin(\n app_dir: Path, reinstall=True, android=False, ios=False, cargo_build=True\n):\n if reinstall:\n subprocess.call(\n [\"cordova\", \"plugin\", \"rm\", \"wallet-cordova-plugin\"], cwd=app_dir\n )\n\n if android:\n if cargo_build:\n build_jni(release=False)\n else:\n copy_jni_libs(release=False)\n copy_jni_definitions()\n\n if ios:\n build_ios(release=False)\n\n subprocess.check_call(\n [\"cordova\", \"plugin\", \"add\", str(plugin_directory)], cwd=app_dir\n )\n\n\ndef install_test_plugin(app_dir: Path, reinstall=True, regen_vectors=True):\n subprocess.check_call([\"npm\", \"install\"], cwd=tests_directory)\n\n if regen_vectors:\n # make sure the genesis is up-to-date\n rebuild_genesis_data()\n\n subprocess.check_call([\"npm\", \"run\", \"build\"], cwd=tests_directory)\n\n if reinstall:\n subprocess.call(\n [\"cordova\", \"plugin\", \"rm\", \"wallet-cordova-plugin-tests\"], cwd=app_dir\n )\n\n subprocess.check_call(\n [\"cordova\", \"plugin\", \"add\", str(tests_directory)], cwd=app_dir\n )\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Create test harness\")\n\n platform_choices = [\"android\", \"ios\"]\n\n parser.add_argument(\n \"--platform\", required=True, nargs=\"+\", choices=platform_choices\n )\n parser.add_argument(\"command\", choices=[\"full\", \"reload-plugin\", \"reload-tests\"])\n parser.add_argument(\"-d\", \"--directory\", type=Path, required=True)\n parser.add_argument(\"-r\", \"--run\", choices=platform_choices)\n\n parser.add_argument(\"--cargo-build\", dest=\"cargo_build\", action=\"store_true\")\n parser.add_argument(\"--no-cargo-build\", dest=\"cargo_build\", action=\"store_false\")\n\n parser.add_argument(\n \"--regen-test-vectors\", dest=\"regen_test_vectors\", action=\"store_true\"\n )\n parser.add_argument(\n \"--no-regen-test-vectors\", dest=\"regen_test_vectors\", action=\"store_false\"\n )\n\n parser.set_defaults(feature=True)\n\n args = parser.parse_args()\n\n android = \"android\" in args.platform\n ios = \"ios\" in args.platform\n\n build_dir = args.directory\n\n app_dir = build_dir / \"hello\"\n\n if args.command == \"full\":\n create_hello_world(build_dir)\n enable_kotlin(app_dir)\n install_platforms(app_dir, android=android, ios=ios)\n install_test_framework(app_dir)\n install_main_plugin(\n app_dir,\n reinstall=False,\n android=android,\n ios=ios,\n cargo_build=args.cargo_build,\n )\n install_test_plugin(\n app_dir, reinstall=False, regen_vectors=args.regen_test_vectors\n )\n\n if args.command == \"reload-plugin\":\n install_main_plugin(app_dir, reinstall=True, android=android, ios=ios)\n\n if args.command == \"reload-tests\":\n install_test_plugin(\n app_dir, reinstall=True, regen_vectors=args.regen_test_vectors\n )\n\n if ios:\n subprocess.check_call(\n [\n \"cordova\",\n \"build\",\n \"ios\",\n \"--debug\",\n ],\n cwd=app_dir,\n )\n\n if android:\n subprocess.check_call([\"cordova\", \"build\", \"android\"], cwd=app_dir)\n\n if args.run:\n subprocess.check_call([\"cordova\", \"run\", args.run], cwd=app_dir)\n" }, { "alpha_fraction": 0.7642560601234436, "alphanum_fraction": 0.7677518129348755, "avg_line_length": 37.47058868408203, "blob_id": "16e1bf98c9574fc5496ff160a2eb4b9391743b1b", "content_id": "58b5a477d38fbedfa25fcb66dd01cbf0124a5acc", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4577, "license_type": "permissive", "max_line_length": 188, "num_lines": 119, "path": "/bindings/wallet-cordova/README.md", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "# Getting started \n\nThe javascript documentation for this module can be generated with jsdoc by\nrunning:\n\n```bash\nnpm install\nnpm run doc\n```\n\nThe generated files can be found at the `doc` directory, and can be read by\nopening `index.html` with a web browser.\n\nAt the moment the best source for examples are the javascript\n[tests](tests/src/main.js).\n\n# Development\n\n## Getting started\n\nThe [official cordova\ndocumentation](https://cordova.apache.org/docs/en/11.x/guide/hybrid/plugins/index.html)\nis the best place to start.\n\n## Requirements\n\n### General\n\nAs a baseline, Node.js and the cordova cli are required. Since the process of\nrunning the tests involves creating an application. The documentation at\n[installing-the-cordova-cli](https://cordova.apache.org/docs/en/11.x/guide/cli/index.html#installing-the-cordova-cli)\ncan be used as a guide. Check out also the [Android\ndocumentation](https://cordova.apache.org/docs/en/11.x/guide/platforms/android/index.html)\nand the [iOS\ndocumentation](https://cordova.apache.org/docs/en/11.x/guide/platforms/ios/plugin.html)\nfor requirements specific to the platform you are going to be developing for.\n\nAdditionally, python3 is required to run the helper scripts.\n\n\n`jcli` is required to generate the genesis file that it is used in\nthe test-vectors, installation instructions can be found in the [jormungandr's\nrepository](https://github.com/input-output-hk/jormungandr). It's recommended\nthat the `jcli` version is built with the same version of `chain-libs` that is\nused to build the plugin (which can be found in the Cargo.lock file), although\nit's not strictly necessary as long as the genesis binary encoding is\ncompatible.\n\n### Android\n\n- [cross](https://github.com/cross-rs/cross) is currently used for building the\nnative libraries for Android.\n- [uniffi-bindgen](https://github.com/mozilla/uniffi-rs). The version must be the same one that is used in the `wallet-uniffi` crate. This can be found [here](../wallet-uniffi/Cargo.toml).\n\n\n### iOS\n\nThe ios rust platforms:\n\n- `rustup target add x86_64-apple-ios`\n- `rustup target add aarch64-apple-ios`\n\n[cbindgen](https://github.com/eqrion/cbindgen) is necessary for regenerating the\nC header, which is then used from the [Objetive C code](src/ios/WalletPlugin.m) in this package. Since the\nlatest version is in source control, this is only needed if the core API\nchanges. The [regen_header.sh](../bindings/wallet-c/regen_header.sh) script can\nbe used to do this.\n\n## Overview\n\nThe core of the plugin is written in rust, and ffi is used to bridge that to\neither Objective-C or Kotlin, depending on the platform.\n\nThe [wallet.js](www/wallet.js) file has the top level Javascript api for the\nplugin users, which is mostly a one-to-one mapping to the API of the\nwallet-core rust crate.\n\nThe iOS part of the plugin is backed by the [wallet-c](../wallet-c/wallet.h)\npackage, while the Android support is provided via the\n[wallet-uniffi](../wallet-uniffi/src/lib.udl) package. Both are also thin\nwrappers over **wallet-core**.\n\n## Build\n\n[build_jni.py](scripts/build_jni.py) in the `scripts` directory will compile the\nAndroid native libraries, generate the Kotlin bindings, and copy those to this\npackage in the `src/android` directory.\n\n[build_ios.py](scripts/build_ios.py) in the `scripts` directory will compile the\niOS native libraries, and copy those along the C header to this package. \n\n`npm pack` can be used to make a distributable version of the plugin as an npm\npackage.\n\n## Running the tests\n\nThe *tests* directory contains a Cordova plugin with [js\ntests](tests/src/main.js), we use\n[cordova-plugin-test-framework](https://github.com/apache/cordova-plugin-test-framework)\nas a test harness. \n\nThe [test.py](scripts/test.py) script can be used to build\nthe plugin and setup the test harness. For example, the following command will\n\n- create a cordova application at the `~/cdvtest/hello` directory. The cdvtest directory must not exist, as the script will not overwrite it.\n- install the cordova-plugin-test-framework.\n- build the native libraries for the android platform, and copy those to\n src/android/libs.\n- build the wallet-uniffi kotlin bindings for the native library.\n- install the plugin at this directory.\n- install the plugin in the tests directory.\n- run the test application if there is an emulator or device available.\n\n```bash\npython3 test.py --platform android -d ~/cdvtest --cargo-build --run android full\n```\n\nThe `reload-plugin` and `reload-tests` commands can be used if only one of\nthose was modified, to avoid having to redo the whole process." }, { "alpha_fraction": 0.684421181678772, "alphanum_fraction": 0.6872498393058777, "avg_line_length": 30.81154441833496, "blob_id": "b51cec389cb184236001831e2a4fd5048bfa56da", "content_id": "6633c946e35c4819c3b84c26c47a90f16f10f846", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 18737, "license_type": "permissive", "max_line_length": 98, "num_lines": 589, "path": "/bindings/wallet-c/src/lib.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "pub mod settings;\npub mod time;\nuse std::{\n ffi::{CStr, CString},\n os::raw::c_char,\n};\npub use wallet::Settings as SettingsRust;\nuse wallet_core::c::{\n fragment::{fragment_delete, fragment_from_raw, fragment_id},\n spending_counters_delete, symmetric_cipher_decrypt,\n time::BlockDate,\n vote, wallet_delete_error, wallet_delete_proposal, wallet_delete_settings,\n wallet_delete_wallet, wallet_id, wallet_import_keys, wallet_set_state,\n wallet_spending_counters, wallet_total_value, wallet_vote_cast, SpendingCounters,\n TransactionOut,\n};\nuse wallet_core::{\n Error as ErrorRust, Fragment as FragmentRust, Proposal as ProposalRust, Wallet as WalletRust,\n};\n\n#[repr(C)]\npub struct Wallet {}\n#[repr(C)]\npub struct Settings {}\n#[repr(C)]\npub struct Proposal {}\n#[repr(C)]\npub struct Fragment;\n#[repr(C)]\npub struct Error {}\n\n#[repr(C)]\npub struct EncryptingVoteKey {}\n\npub type WalletPtr = *mut Wallet;\npub type SettingsPtr = *mut Settings;\npub type ProposalPtr = *mut Proposal;\npub type FragmentPtr = *mut Fragment;\npub type ErrorPtr = *mut Error;\npub type EncryptingVoteKeyPtr = *mut EncryptingVoteKey;\n\n/// recover a wallet from an account and a list of utxo keys\n///\n/// You can also use this function to recover a wallet even after you have\n/// transferred all the funds to the new format (see the _convert_ function)\n///\n/// The recovered wallet will be returned in `wallet_out`.\n///\n/// # parameters\n///\n/// * account_key: the Ed25519 extended key used wallet's account address private key\n/// in the form of a 64 bytes array.\n/// * utxo_keys: an array of Ed25519 extended keys in the form of 64 bytes, used as utxo\n/// keys for the wallet\n/// * utxo_keys_len: the number of keys in the utxo_keys array (not the number of bytes)\n/// * wallet_out: the recovered wallet\n///\n/// # Safety\n///\n/// This function dereference raw pointers (password and wallet_out). Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n///\n/// # errors\n///\n/// The function may fail if:\n///\n/// * the `wallet_out` is null pointer\n///\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_import_keys(\n account_key: *const u8,\n wallet_out: *mut WalletPtr,\n) -> ErrorPtr {\n let r = wallet_import_keys(account_key, wallet_out as *mut *mut WalletRust);\n\n r.into_c_api() as ErrorPtr\n}\n\n/// get the wallet id\n///\n/// This ID is the identifier to use against the blockchain/explorer to retrieve\n/// the state of the wallet (counter, total value etc...)\n///\n/// # Parameters\n///\n/// * wallet: the recovered wallet (see recover function);\n/// * id_out: a ready allocated pointer to an array of 32bytes. If this array is not\n/// 32bytes this may result in a buffer overflow.\n///\n/// # Safety\n///\n/// This function dereference raw pointers (wallet, block0 and settings_out). Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n///\n/// the `id_out` needs to be ready allocated 32bytes memory. If not this will result\n/// in an undefined behavior, in the best scenario it will be a buffer overflow.\n///\n/// # Errors\n///\n/// On error the function returns a `ErrorPtr`. On success `NULL` is returned.\n/// The `ErrorPtr` can then be observed to gathered details of the error.\n/// Don't forget to call `iohk_jormungandr_wallet_delete_error` to free\n/// the `ErrorPtr` from memory and avoid memory leaks.\n///\n/// * this function may fail if the wallet pointer is null;\n///\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_id(\n wallet: WalletPtr,\n id_out: *mut u8,\n) -> ErrorPtr {\n wallet_id(wallet as *mut WalletRust, id_out).into_c_api() as ErrorPtr\n}\n\n/// get the current spending counters for the (only) account in this wallet\n///\n/// iohk_jormungandr_spending_counters_delete should be called to deallocate the memory when it's\n/// not longer needed\n///\n/// # Errors\n///\n/// * this function may fail if the wallet pointer is null;\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n///\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_spending_counters(\n wallet: WalletPtr,\n spending_counters_ptr: *mut SpendingCounters,\n) -> ErrorPtr {\n wallet_spending_counters(wallet as *mut WalletRust, spending_counters_ptr).into_c_api()\n as ErrorPtr\n}\n\n/// get the total value in the wallet\n///\n/// make sure to call `retrieve_funds` prior to calling this function\n/// otherwise you will always have `0`\n///\n/// After calling this function the results is returned in the `total_out`.\n///\n/// # Errors\n///\n/// * this function may fail if the wallet pointer is null;\n///\n/// On error the function returns a `ErrorPtr`. On success `NULL` is returned.\n/// The `ErrorPtr` can then be observed to gathered details of the error.\n/// Don't forget to call `iohk_jormungandr_wallet_delete_error` to free\n/// the `ErrorPtr` from memory and avoid memory leaks.\n///\n/// If the `total_out` pointer is null, this function does nothing\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n///\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_total_value(\n wallet: WalletPtr,\n total_out: *mut u64,\n) -> ErrorPtr {\n let r = wallet_total_value(wallet as *mut WalletRust, total_out);\n\n r.into_c_api() as ErrorPtr\n}\n\n/// update the wallet account state\n///\n/// this is the value retrieved from any jormungandr endpoint that allows to query\n/// for the account state. It gives the value associated to the account as well as\n/// the counter.\n///\n/// It is important to be sure to have an updated wallet state before doing any\n/// transactions otherwise future transactions may fail to be accepted by any\n/// nodes of the blockchain because of invalid signature state.\n///\n/// # Errors\n///\n/// * this function may fail if the wallet pointer is null;\n///\n/// On error the function returns a `ErrorPtr`. On success `NULL` is returned.\n/// The `ErrorPtr` can then be observed to gathered details of the error.\n/// Don't forget to call `iohk_jormungandr_wallet_delete_error` to free\n/// the `ErrorPtr` from memory and avoid memory leaks.\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n///\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_set_state(\n wallet: WalletPtr,\n value: u64,\n counters: SpendingCounters,\n) -> ErrorPtr {\n let r = wallet_set_state(wallet as *mut WalletRust, value, counters);\n\n r.into_c_api() as ErrorPtr\n}\n\n/// build the proposal object\n///\n/// # Errors\n///\n/// This function may fail if:\n///\n/// * `proposal_out` is null.\n/// * `num_choices` is out of the allowed range.\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though the function checks if\n/// the pointers are null. Mind not to put random values in or you may see\n/// unexpected behaviors.\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_vote_proposal_new_public(\n vote_plan_id: *const u8,\n index: u8,\n num_choices: u8,\n proposal_out: *mut ProposalPtr,\n) -> ErrorPtr {\n let r = vote::proposal_new(\n vote_plan_id,\n index,\n num_choices,\n vote::ProposalPublic,\n proposal_out as *mut *mut ProposalRust,\n );\n\n r.into_c_api() as ErrorPtr\n}\n\n/// build the proposal object\n///\n/// * `vote_encryption_key`: a null terminated string (c-string) with the bech32\n/// representation of the encryption vote key\n///\n/// # Errors\n///\n/// This function may fail if:\n///\n/// * `proposal_out` is null.\n/// * `num_choices` is out of the allowed range.\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though the function checks if\n/// the pointers are null. Mind not to put random values in or you may see\n/// unexpected behaviors.\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_vote_proposal_new_private(\n vote_plan_id: *const u8,\n index: u8,\n num_choices: u8,\n vote_encryption_key: *const std::os::raw::c_char,\n proposal_out: *mut ProposalPtr,\n) -> ErrorPtr {\n let bech32_str = CStr::from_ptr(vote_encryption_key);\n\n let r = vote::proposal_new(\n vote_plan_id,\n index,\n num_choices,\n vote::ProposalPrivate(bech32_str),\n proposal_out as *mut *mut ProposalRust,\n );\n\n r.into_c_api() as ErrorPtr\n}\n\n/// build the vote cast transaction\n///\n/// # Errors\n///\n/// This function may fail upon receiving a null pointer or a `choice` value\n/// that does not fall within the range specified in `proposal`.\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though the function checks if\n/// the pointers are null. Mind not to put random values in or you may see\n/// unexpected behaviors.\n///\n/// Don't forget to remove `transaction_out` with\n/// `iohk_jormungandr_waller_delete_buffer`.\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_vote_cast(\n wallet: WalletPtr,\n settings: SettingsPtr,\n proposal: ProposalPtr,\n choice: u8,\n valid_until: BlockDate,\n lane: u8,\n transaction_out: *mut TransactionOut,\n) -> ErrorPtr {\n let r = wallet_vote_cast(\n wallet as *mut WalletRust,\n settings as *mut SettingsRust,\n proposal as *mut ProposalRust,\n choice,\n valid_until,\n lane,\n transaction_out,\n );\n\n r.into_c_api() as ErrorPtr\n}\n\n/// decrypt payload of the wallet transfer protocol\n///\n/// Parameters\n///\n/// password: byte buffer with the encryption password\n/// password_length: length of the password buffer\n/// ciphertext: byte buffer with the encryption password\n/// ciphertext_length: length of the password buffer\n/// plaintext_out: used to return a pointer to a byte buffer with the decrypted text\n/// plaintext_out_length: used to return the length of decrypted text\n///\n/// The returned buffer is in the heap, so make sure to call the delete_buffer function\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though the function checks if\n/// the pointers are null. Mind not to put random values in or you may see\n/// unexpected behaviors.\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_symmetric_cipher_decrypt(\n password: *const u8,\n password_length: usize,\n ciphertext: *const u8,\n ciphertext_length: usize,\n plaintext_out: *mut *const u8,\n plaintext_out_length: *mut usize,\n) -> ErrorPtr {\n let r = symmetric_cipher_decrypt(\n password,\n password_length,\n ciphertext,\n ciphertext_length,\n plaintext_out,\n plaintext_out_length,\n );\n\n r.into_c_api() as ErrorPtr\n}\n\n/// Get a string describing the error, this will return an allocated\n/// null terminated string describing the error.\n///\n/// If the given error is a `NULL` pointer, the string is and always\n/// is `\"success\"`. This string still need to be deleted with the\n/// `iohk_jormungandr_wallet_delete_string` function.\n///\n/// This function returns an allocated null terminated pointer. Don't\n/// forget to free the memory with: `iohk_jormungandr_wallet_delete_string`.\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n///\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_error_to_string(error: ErrorPtr) -> *mut c_char {\n if let Some(error) = (error as *mut ErrorRust).as_ref() {\n CString::new(error.to_string()).unwrap().into_raw()\n } else {\n CString::new(b\"success\".to_vec()).unwrap().into_raw()\n }\n}\n\n/// Get a string describing the error, this will return an allocated\n/// null terminated string providing extra details regarding the source\n/// of the error.\n///\n/// If the given error is a `NULL` pointer, the string is and always\n/// is `\"success\"`. If no details are available the function will return\n/// `\"no more details\"`. This string still need to be deleted with the\n/// `iohk_jormungandr_wallet_delete_string` function.\n///\n/// This function returns an allocated null terminated pointer. Don't\n/// forget to free the memory with: `iohk_jormungandr_wallet_delete_string`.\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n///\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_error_details(error: ErrorPtr) -> *mut c_char {\n if let Some(error) = (error as *mut ErrorRust).as_ref() {\n if let Some(details) = error.details() {\n CString::new(details.to_string()).unwrap().into_raw()\n } else {\n CString::new(b\"no more details\".to_vec())\n .unwrap()\n .into_raw()\n }\n } else {\n CString::new(b\"success\".to_vec()).unwrap().into_raw()\n }\n}\n\n/// deserialize a fragment from bytes\n///\n/// # Parameters\n///\n/// * `buffer` -- a pointer to the serialized fragment bytes.\n/// * `buffer_length` -- the length of the serialized fragment bytes array.\n/// * `fragment` -- the location of the pointer to the deserialized fragemnt.\n///\n/// # Errors\n///\n/// This functions may fail if:\n///\n/// * `buffer` is a null pointer.\n/// * `fragment` is a null pointer.\n/// * `buffer` contains invalid fragment bytes.\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n///\n/// Don't forget to delete the fragment object with `iohk_jormungandr_delete_fragment`.\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_fragment_from_raw(\n buffer: *const u8,\n buffer_length: usize,\n fragment_out: *mut FragmentPtr,\n) -> ErrorPtr {\n fragment_from_raw(\n buffer,\n buffer_length,\n fragment_out as *mut *mut FragmentRust,\n )\n .into_c_api() as ErrorPtr\n}\n\n/// get the ID of the provided fragment\n///\n/// # Parameters\n///\n/// * `fragment` -- a pointer to fragment.\n/// * `fragment_id_out` -- a pointer to a pre-allocated 32 bytes array.\n///\n/// # Errors\n///\n/// This function would return an error if either of the provided pointers is null.\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors.\n///\n/// `fragment_id_out` is expected to be an already allocated 32 byte array. Doing otherwise may\n/// potentially result into an undefined behavior.\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_fragment_id(\n fragment: FragmentPtr,\n fragment_id_out: *mut u8,\n) -> ErrorPtr {\n fragment_id(fragment as *mut FragmentRust, fragment_id_out).into_c_api() as ErrorPtr\n}\n\n/// Delete a null terminated string that was allocated by this library\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n///\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_delete_string(ptr: *mut c_char) {\n if !ptr.is_null() {\n let cstring = CString::from_raw(ptr);\n std::mem::drop(cstring)\n }\n}\n\n/// Delete a binary buffer that was returned by this library alongside with its\n/// length.\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_delete_buffer(ptr: *mut u8, length: usize) {\n if !ptr.is_null() {\n let data = std::slice::from_raw_parts_mut(ptr, length);\n let data = Box::from_raw(data as *mut [u8]);\n std::mem::drop(data);\n }\n}\n\n/// delete the pointer and free the allocated memory\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n///\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_delete_error(error: ErrorPtr) {\n wallet_delete_error(error as *mut ErrorRust)\n}\n\n/// delete the pointer and free the allocated memory\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n///\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_delete_settings(settings: SettingsPtr) {\n wallet_delete_settings(settings as *mut SettingsRust)\n}\n\n/// delete the pointer, zero all the keys and free the allocated memory\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n///\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_delete_wallet(wallet: WalletPtr) {\n wallet_delete_wallet(wallet as *mut WalletRust)\n}\n\n/// delete the pointer\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n///\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_wallet_delete_proposal(proposal: ProposalPtr) {\n wallet_delete_proposal(proposal as *mut ProposalRust)\n}\n\n/// delete the pointer\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_delete_fragment(fragment: FragmentPtr) {\n fragment_delete(fragment as *mut FragmentRust);\n}\n\n/// delete the inner buffer that was allocated by this library\n///\n/// # Safety\n///\n/// This function dereference raw pointers. Even though\n/// the function checks if the pointers are null. Mind not to put random values\n/// in or you may see unexpected behaviors\n#[no_mangle]\npub unsafe extern \"C\" fn iohk_jormungandr_delete_spending_counters(\n spending_counters: SpendingCounters,\n) {\n spending_counters_delete(spending_counters);\n}\n" }, { "alpha_fraction": 0.6344339847564697, "alphanum_fraction": 0.6351078152656555, "avg_line_length": 28.098039627075195, "blob_id": "ac91dcb87d63c6e717bce6fe8bcf243350eb1a0a", "content_id": "4058cf3cc35cb98c3b4fbc83c37ae14f80df823d", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 2968, "license_type": "permissive", "max_line_length": 82, "num_lines": 102, "path": "/wallet/src/transaction/strategy.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "/// the default strategies, in order of importance, to apply\n/// when selecting inputs and outputs of a transaction\npub const DEFAULT_STRATEGIES: &[Strategy] = &[\n StrategyBuilder::most_private().build(),\n StrategyBuilder::most_efficient().build(),\n];\n\n#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]\npub enum InputStrategy {\n /// try to get the most optimise transaction consuming the\n /// wallet's utxos in the most efficient way.\n ///\n BestEffort,\n\n /// preserve the privacy of the UTxOs\n ///\n /// This means the transaction will be only composed of\n /// inputs of the same public key. If a change needs created\n /// it will create it to a different unused change, this may\n /// create dust\n ///\n /// This option is incompatible with the `UTXO_CHANGE_TO_ACCOUNT`\n PrivacyPreserving,\n}\n\n#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]\npub enum OutputStrategy {\n /// If the transaction needs to offload extra inputs in an\n /// extra change output then chose the best solution with the\n /// given circumstances\n ///\n /// if there are only single utxos as input the change will be\n /// offloaded to a new change output with a new utxo.\n ///\n /// if there's group inputs for the same key, the group account\n /// will be used to offload the change (order may matter, i.e.\n /// if there's multiple inputs with different account the first\n /// account will be used).\n BestEffort,\n\n /// Along with privacy preserving, this one will have the interesting\n /// property to redistribute the change into multiple distinct utxos\n ///\n /// however, if the change is only too small (less than 10x dust like):\n ///\n /// * if one of the inputs contain a group key, the change will be distributed\n /// to the group account\n /// * if there's no account, the change will go to a new utxo\n UtxoReshuffle,\n}\n\npub struct Strategy {\n input: InputStrategy,\n output: OutputStrategy,\n}\n\npub struct StrategyBuilder {\n input: InputStrategy,\n output: OutputStrategy,\n}\n\nimpl Strategy {\n pub fn input(&self) -> InputStrategy {\n self.input\n }\n\n pub fn output(&self) -> OutputStrategy {\n self.output\n }\n}\n\nimpl StrategyBuilder {\n pub const fn most_private() -> Self {\n Self {\n input: InputStrategy::PrivacyPreserving,\n output: OutputStrategy::UtxoReshuffle,\n }\n }\n\n pub const fn most_efficient() -> Self {\n Self {\n input: InputStrategy::BestEffort,\n output: OutputStrategy::BestEffort,\n }\n }\n\n pub const fn build(&self) -> Strategy {\n Strategy {\n input: self.input,\n output: self.output,\n }\n }\n}\n\nimpl Default for StrategyBuilder {\n fn default() -> Self {\n Self {\n input: InputStrategy::BestEffort,\n output: OutputStrategy::BestEffort,\n }\n }\n}\n" }, { "alpha_fraction": 0.7337461113929749, "alphanum_fraction": 0.7337461113929749, "avg_line_length": 20.53333282470703, "blob_id": "b166598e8e6711ef174c503c27a7a73195a72a69", "content_id": "c0809d4fc8286b84288e19e3a3b2f8d65c0ae774", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 323, "license_type": "permissive", "max_line_length": 61, "num_lines": 15, "path": "/wallet/src/lib.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "mod account;\nmod blockchain;\nmod password;\nmod scheme;\nmod states;\npub mod time;\npub mod transaction;\n\npub use self::{\n account::{Wallet, MAX_LANES},\n blockchain::Settings,\n password::{Password, ScrubbedBytes},\n transaction::{AccountWitnessBuilder, TransactionBuilder},\n};\npub use hdkeygen::account::AccountId;\n" }, { "alpha_fraction": 0.6002034544944763, "alphanum_fraction": 0.6322482228279114, "avg_line_length": 34.745452880859375, "blob_id": "010deed96f356924c0caac07b41db5d6f227e258", "content_id": "82548548fa46bc1cbc13da4af4e9055fc7215588", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 1966, "license_type": "permissive", "max_line_length": 95, "num_lines": 55, "path": "/wallet/src/transaction/witness_builder.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use chain_crypto::{Ed25519, Ed25519Extended, SecretKey, Signature};\nuse chain_impl_mockchain::{\n accounting::account::SpendingCounter,\n block::HeaderId,\n transaction::{TransactionSignDataHash, Witness, WitnessUtxoData},\n};\nuse ed25519_bip32::XPrv;\n\nuse hdkeygen::Key;\n\npub trait WitnessBuilder {\n fn build(&self, block0: &HeaderId, sign_data_hash: &TransactionSignDataHash) -> Witness;\n}\n\npub struct UtxoWitnessBuilder<K>(pub K);\npub enum AccountWitnessBuilder {\n Ed25519(SecretKey<Ed25519>, SpendingCounter),\n Ed25519Extended(SecretKey<Ed25519Extended>, SpendingCounter),\n}\n\nimpl<D> WitnessBuilder for UtxoWitnessBuilder<Key<XPrv, D>> {\n fn build(&self, block0: &HeaderId, sign_data_hash: &TransactionSignDataHash) -> Witness {\n let xprv = &self.0;\n Witness::new_utxo(block0, sign_data_hash, |data| {\n Signature::from_binary(xprv.sign::<WitnessUtxoData, &[u8]>(data.as_ref()).as_ref())\n .unwrap()\n })\n }\n}\n\nimpl WitnessBuilder for UtxoWitnessBuilder<SecretKey<Ed25519Extended>> {\n fn build(&self, block0: &HeaderId, sign_data_hash: &TransactionSignDataHash) -> Witness {\n let key = &self.0;\n Witness::new_utxo(block0, sign_data_hash, |data| {\n Signature::from_binary(key.sign(data).as_ref()).unwrap()\n })\n }\n}\n\nimpl WitnessBuilder for AccountWitnessBuilder {\n fn build(&self, block0: &HeaderId, sign_data_hash: &TransactionSignDataHash) -> Witness {\n match self {\n AccountWitnessBuilder::Ed25519(key, spending_counter) => {\n Witness::new_account(block0, sign_data_hash, *spending_counter, |data| {\n key.sign(data)\n })\n }\n AccountWitnessBuilder::Ed25519Extended(key, spending_counter) => {\n Witness::new_account(block0, sign_data_hash, *spending_counter, |data| {\n key.sign(data)\n })\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5468084812164307, "alphanum_fraction": 0.5492021441459656, "avg_line_length": 29.079999923706055, "blob_id": "42d8c458a0d143e688cad8112bdd797e18f820d5", "content_id": "de27da27ac6a55748144ae3e473cb50fe58fc2a6", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 3760, "license_type": "permissive", "max_line_length": 91, "num_lines": 125, "path": "/chain-path-derivation/src/rindex.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "//! # Random Index scheme\n//!\n//! here the address is supposed to be 2 level only. It is not clear\n//! what is supposed to be the structure of the addressing so no assumption\n//! is made here.\n//!\n//! assumptions is that the two level of derivations are: `m / account / address`\n//!\n\nuse crate::{AnyScheme, Derivation, DerivationPath, ParseDerivationPathError};\nuse std::str::{self, FromStr};\n\n#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct Rindex<P>(std::marker::PhantomData<P>);\n\n#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct Root;\n#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct Account;\n#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct Address;\n\nconst INDEX_ACCOUNT: usize = 0;\nconst INDEX_ADDRESS: usize = 1;\n\n#[inline]\npub fn new() -> DerivationPath<Rindex<Root>> {\n DerivationPath::new_empty()\n}\n\nimpl DerivationPath<Rindex<Root>> {\n pub fn account(&self, derivation: Derivation) -> DerivationPath<Rindex<Account>> {\n let mut a = self.clone();\n a.push(derivation);\n a.coerce_unchecked()\n }\n}\n\nimpl DerivationPath<Rindex<Account>> {\n pub fn address(&self, derivation: Derivation) -> DerivationPath<Rindex<Address>> {\n let mut a = self.clone();\n a.push(derivation);\n a.coerce_unchecked()\n }\n}\n\nimpl DerivationPath<Rindex<Address>> {\n #[inline]\n pub fn account(&self) -> Derivation {\n self.get_unchecked(INDEX_ACCOUNT)\n }\n #[inline]\n pub fn address(&self) -> Derivation {\n self.get_unchecked(INDEX_ADDRESS)\n }\n}\n\n/* FromStr ***************************************************************** */\n\nmacro_rules! mk_from_str_dp_rindex {\n ($t:ty, $len:expr) => {\n impl FromStr for DerivationPath<$t> {\n type Err = ParseDerivationPathError;\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n let dp = s.parse::<DerivationPath<AnyScheme>>()?;\n\n if dp.len() == $len {\n Ok(dp.coerce_unchecked())\n } else {\n Err(ParseDerivationPathError::InvalidNumberOfDerivations {\n actual: dp.len(),\n expected: $len,\n })\n }\n }\n }\n };\n}\n\nmk_from_str_dp_rindex!(Rindex<Root>, 0);\nmk_from_str_dp_rindex!(Rindex<Account>, 1);\nmk_from_str_dp_rindex!(Rindex<Address>, 2);\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use quickcheck::{Arbitrary, Gen};\n\n macro_rules! mk_arbitrary_dp_rindex {\n ($t:ty, $len:expr) => {\n impl Arbitrary for DerivationPath<$t> {\n fn arbitrary<G: Gen>(g: &mut G) -> Self {\n let dp = std::iter::repeat_with(|| Derivation::arbitrary(g))\n .take($len)\n .collect::<DerivationPath<AnyScheme>>();\n dp.coerce_unchecked()\n }\n }\n };\n }\n\n mk_arbitrary_dp_rindex!(Rindex<Root>, 0);\n mk_arbitrary_dp_rindex!(Rindex<Account>, 1);\n mk_arbitrary_dp_rindex!(Rindex<Address>, 2);\n\n macro_rules! mk_quickcheck_dp_rindex {\n ($t:ty) => {\n paste::item! {\n #[quickcheck]\n #[allow(non_snake_case)]\n fn [< fmt_parse $t>](derivation_path: DerivationPath<Rindex<$t>>) -> bool {\n let s = derivation_path.to_string();\n let v = s.parse::<DerivationPath<Rindex<$t>>>().unwrap();\n\n v == derivation_path\n }\n }\n };\n }\n\n mk_quickcheck_dp_rindex!(Root);\n mk_quickcheck_dp_rindex!(Account);\n mk_quickcheck_dp_rindex!(Address);\n}\n" }, { "alpha_fraction": 0.728038489818573, "alphanum_fraction": 0.7292418479919434, "avg_line_length": 26.700000762939453, "blob_id": "bdb958511ad52fc1fafd49e7a1658a592b0334ae", "content_id": "04d3c69de4f5daed66ca58aa8277ba0706b64980", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 831, "license_type": "permissive", "max_line_length": 79, "num_lines": 30, "path": "/bindings/wallet-c/check_header.sh", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env sh\nset -e\n\n# the find command is used mostly so this work from the root directory\n# and from the wallet-c directory\n\nEXCLUDE='-not -path \"*/target\" -not -path \"*/.git\" -not -path \"*/node_modules\"'\nCONFIG=$(find . -name \"cbindgen.toml\" $EXCLUDE)\nHEADER_FILEPATH=$(find . -name \"wallet.h\" $EXCLUDE)\n\n# remove this line, as it contains the cbindgen version, causing PR's to fail\n# when cbindgen releases a new version.\n\nstrip_line_with_version() {\n sed -i '/Generated with cbindgen/d' $1\n}\n\nACTUAL_HEADER=$(mktemp)\nGENERATED_HEADER=$(mktemp)\n\ncat $HEADER_FILEPATH >$ACTUAL_HEADER\ncbindgen --config $CONFIG --crate jormungandrwallet >$GENERATED_HEADER\n\nstrip_line_with_version $ACTUAL_HEADER\nstrip_line_with_version $GENERATED_HEADER\n\ndiff $GENERATED_HEADER $ACTUAL_HEADER\n\nrm \"$ACTUAL_HEADER\"\nrm \"$GENERATED_HEADER\"\n" }, { "alpha_fraction": 0.548527181148529, "alphanum_fraction": 0.550981879234314, "avg_line_length": 25.883249282836914, "blob_id": "a5f8eaca87d913396cc75eedbbc4e72e460f988e", "content_id": "a2c5bbfbb6c66bdcfbe85ee760e0eb8930993ca4", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 5296, "license_type": "permissive", "max_line_length": 97, "num_lines": 197, "path": "/wallet/src/states.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use hashlink::LinkedHashMap;\nuse std::{borrow::Borrow, hash::Hash};\n\n#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\npub enum Status {\n Confirmed,\n Pending,\n}\n\n#[derive(Debug)]\npub struct StateRef<S> {\n state: S,\n status: Status,\n}\n\npub struct States<K, S> {\n states: LinkedHashMap<K, StateRef<S>>,\n}\n\nimpl<K: std::fmt::Debug, S: std::fmt::Debug> std::fmt::Debug for States<K, S> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_list().entries(self.iter()).finish()\n }\n}\n\nimpl<S> StateRef<S> {\n fn new(state: S, status: Status) -> Self {\n Self { state, status }\n }\n\n pub fn is_confirmed(&self) -> bool {\n matches!(self.status, Status::Confirmed)\n }\n\n pub fn is_pending(&self) -> bool {\n matches!(self.status, Status::Pending)\n }\n\n pub fn state(&self) -> &S {\n &self.state\n }\n\n fn confirm(&mut self) {\n self.status = Status::Confirmed\n }\n}\n\nimpl<K, S> States<K, S>\nwhere\n K: Hash + Eq,\n{\n /// create a new States with the given initial state\n ///\n /// by default this state is always assumed confirmed\n pub fn new(key: K, state: S) -> Self {\n let state = StateRef::new(state, Status::Confirmed);\n let mut states = LinkedHashMap::new();\n states.insert(key, state);\n\n Self { states }\n }\n\n /// check wether the given state associate to this key is present\n /// in the States\n pub fn contains<Q: ?Sized>(&self, key: &Q) -> bool\n where\n K: Borrow<Q>,\n Q: Hash + Eq,\n {\n self.states.contains_key(key)\n }\n\n /// push a new **unconfirmed** state in the States\n pub fn push(&mut self, key: K, state: S) {\n let state = StateRef::new(state, Status::Pending);\n\n assert!(self.states.insert(key, state).is_none());\n }\n\n pub fn confirm<Q: ?Sized>(&mut self, key: &Q)\n where\n K: Borrow<Q>,\n Q: Hash + Eq,\n {\n if let Some(state) = self.states.get_mut(key) {\n state.confirm();\n }\n\n self.pop_old_confirmed_states()\n }\n\n fn pop_old_confirmed_states(&mut self) {\n // the first state in the list is always confirmed, so it is fine to skip it in the first\n // iteration.\n while self\n .states\n .iter()\n .nth(1)\n .map(|(_, state)| state.is_confirmed())\n .unwrap_or(false)\n {\n self.states.pop_front();\n }\n\n debug_assert!(self.states.front().unwrap().1.is_confirmed());\n }\n}\n\nimpl<K, S> States<K, S> {\n /// iterate through the states from the confirmed one up to the most\n /// recent one.\n ///\n /// there is always at least one element in the iterator (the confirmed one).\n pub fn iter(&self) -> impl Iterator<Item = (&K, &StateRef<S>)> {\n self.states.iter()\n }\n\n pub fn unconfirmed_states(&self) -> impl Iterator<Item = (&K, &StateRef<S>)> {\n self.states.iter().filter(|(_, s)| s.is_pending())\n }\n\n /// access the confirmed state of the store verse\n pub fn confirmed_state(&self) -> &StateRef<S> {\n self.states.front().map(|(_, v)| v).unwrap()\n }\n\n /// get the last state of the store\n pub fn last_state(&self) -> &StateRef<S> {\n self.states.back().unwrap().1\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n impl PartialEq for StateRef<()> {\n fn eq(&self, other: &Self) -> bool {\n self.status.eq(&(other.status))\n }\n }\n\n impl PartialOrd for StateRef<()> {\n fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {\n self.status.partial_cmp(&(other.status))\n }\n }\n\n impl StateRef<()> {\n fn new_confirmed() -> Self {\n Self {\n state: (),\n status: Status::Confirmed,\n }\n }\n\n fn new_pending() -> Self {\n Self {\n state: (),\n status: Status::Pending,\n }\n }\n }\n\n #[test]\n fn confirmed_state() {\n let mut multiverse = States::new(0u8, ());\n assert_eq!(&StateRef::new_confirmed(), multiverse.confirmed_state());\n\n assert_eq!(&StateRef::new_confirmed(), multiverse.last_state());\n\n multiverse.push(1, ());\n assert_eq!(&StateRef::new_confirmed(), multiverse.confirmed_state());\n assert_eq!(&StateRef::new_pending(), multiverse.last_state());\n\n multiverse.push(2, ());\n multiverse.push(3, ());\n multiverse.push(4, ());\n assert_eq!(&StateRef::new_confirmed(), multiverse.confirmed_state());\n assert_eq!(&StateRef::new_pending(), multiverse.last_state());\n\n multiverse.confirm(&1);\n assert_eq!(&StateRef::new_confirmed(), multiverse.confirmed_state());\n assert_eq!(&StateRef::new_pending(), multiverse.last_state());\n\n multiverse.confirm(&4);\n assert_eq!(&StateRef::new_confirmed(), multiverse.confirmed_state());\n\n assert_eq!(&StateRef::new_confirmed(), multiverse.last_state());\n\n multiverse.confirm(&3);\n multiverse.confirm(&2);\n assert_eq!(&StateRef::new_confirmed(), multiverse.confirmed_state());\n\n assert_eq!(&StateRef::new_confirmed(), multiverse.last_state());\n }\n}\n" }, { "alpha_fraction": 0.5750881433486938, "alphanum_fraction": 0.5903642773628235, "avg_line_length": 36, "blob_id": "908dfc3cb02cf672752ca539a640ce21f71b94dd", "content_id": "131de4bf8978487bfbd1819ff6676d598bf97271", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4297, "license_type": "permissive", "max_line_length": 122, "num_lines": 115, "path": "/README.md", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "# chain-wallet-libs\n\n[![MIT licensed][mit-badge]][mit-url]\n[![C.I. Integration][ci-integration-badge]][ci-integration-url]\n[![C.I. Checks][ci-check-badge]][ci-check-url]\n[![Release][release-badge]][release-url]\n\n[mit-badge]: https://img.shields.io/badge/license-MIT%2FApache--2.0-blue\n[mit-url]: LICENSE\n[ci-integration-badge]: https://github.com/input-output-hk/chain-wallet-libs/workflows/C.I.%20Integration/badge.svg\n[ci-integration-url]: https://github.com/input-output-hk/chain-wallet-libs/actions?query=workflow%3A%22C.I.+Integration%22\n[ci-check-badge]: https://github.com/input-output-hk/chain-wallet-libs/workflows/C.I.%20Checks/badge.svg\n[ci-check-url]: https://github.com/input-output-hk/chain-wallet-libs/actions?query=workflow%3A%22C.I.+Checks%22\n[release-badge]: https://github.com/input-output-hk/chain-wallet-libs/workflows/Release/badge.svg\n[release-url]: https://github.com/input-output-hk/chain-wallet-libs/actions?query=workflow%3ARelease\n\nChain Wallet libs is a set of library, written in [rust-lang], to use to build application for [Jörmungandr].\n\n## released binaries\n\nCurrently we provide support for many platforms of the high level wallet library.\n\n**Releases can be found there: [link][release-latest]**\n\n### Android\n\n| Target | released binaries |\n| ------------------------- | :---------------: |\n| `aarch64-linux-android` | ✓ |\n| `arm-linux-androideabi` | ✓ |\n| `armv7-linux-androideabi` | ✓ |\n| `i686-linux-android` | ✓ |\n| `x86_64-linux-android` | ✓ |\n\nThis includes bindings for Android Kotlin already packaged in a AAR package.\n\n### Cordova plugin\n\n| Platform | supported |\n| -------- | :-------: |\n| android | ✓ |\n| ios | ✓ |\n\n### iOS\n\n| Target | released binaries |\n| ------------------- | :---------------: |\n| `aarch64-apple-ios` | ✓ |\n| `x86_64-apple-ios` | ✓ |\n\n_Swift package in development..._\n\n### Linux\n\n| Target | released binaries |\n| ---------------------------------- | :---------------: |\n| `aarch64-unknown-linux-gnu` | ✓ |\n| `arm-unknown-linux-gnueabi` | ✓ |\n| `armv7-unknown-linux-gnueabihf` | ✓ |\n| `mips64el-unknown-linux-gnueabi64` | ✓ |\n| `powerpc64el-unknown-linux-gnu` | ✓ |\n| `x86_64-unknown-linux-gnu` | ✓ |\n| `x86_64-unknown-linux-musl` | ✓ |\n\n### MacOS\n\n| Target | released binaries |\n| --------------------- | :---------------: |\n| `x86_64-apple-darwin` | ✓ |\n\n### Wasm (and JavaScript)\n\n| Target | released binaries |\n| ------------------------ | :---------------: |\n| `wasm32-unknown-unknown` | ✓ |\n\nThis include Javascript generated binaries (with typescript annotations)\nfor webjs and nodejs.\n\n### Windows\n\n| Target | released binaries |\n| ------------------------ | :---------------: |\n| `x86_64-pc-windows-gnu` | ✓ |\n| `x86_64-pc-windows-msvc` | ✓ |\n\n# Development\n\nYou can find the main rust libraries at the top level of this repository. These\nare the core elements and offer prime support for all the different `bindings`\nimplemented in the `bindings` directory.\n\nFor the Cordova plugin, check out the [readme in the plugin's\ndirectory](bindings/wallet-cordova/README.md).\n\n## Code formatting\n\nIn order to avoid long lasting discussions and arguments about how code should\nbe formatted for better readability all must be formatted with `rustfmt`.\n\n## Clippy\n\nCargo clippy is ran on this repository at every PRs. This will come in handy to\nprevent some readability issues but also potential mistakes in the C bindings\nwhen manipulating raw pointers.\n\n## Documentation\n\n- [Wallet Cryptography and Encoding](doc/CRYPTO.md)\n- [Enhanced Mnemonic Encoding (EME)](doc/EME.md)\n- [Cordova plugin](bindings/wallet-cordova/README.md)\n\n[rust-lang]: https://www.rust-lang.org/\n[Jörmungandr]: https://input-output-hk.github.io/jormungandr\n[release-latest]: https://github.com/input-output-hk/chain-wallet-libs/releases/latest\n" }, { "alpha_fraction": 0.6709988117218018, "alphanum_fraction": 0.6763417720794678, "avg_line_length": 30.52503776550293, "blob_id": "eeb9693f6526c03bcffb91dc4f2b0f2064f4e061", "content_id": "e5a9de0091fdcc7ccdc3247f666b03c084bda61d", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 20776, "license_type": "permissive", "max_line_length": 108, "num_lines": 659, "path": "/bindings/wallet-c/wallet.h", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "/**\n * Wallet for Jörmungandr blockchain\n *\n * Provide support for recovering funds from both Yoroi and Daedalus wallets.\n *\n * Copyright 2020, Input Output HK Ltd\n * Licensed with: MIT OR Apache-2.0\n */\n\n#ifndef IOHK_CHAIN_WALLET_LIBC_\n#define IOHK_CHAIN_WALLET_LIBC_\n\n/* Generated with cbindgen:0.20.0 */\n\n/* Warning, this file is autogenerated by cbindgen. Don't modify this manually. */\n\n#include <stdarg.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdlib.h>\n\ntypedef enum Discrimination\n{\n Discrimination_Production = 0,\n Discrimination_Test,\n} Discrimination;\n\ntypedef struct Error\n{\n\n} Error;\n\ntypedef struct Error *ErrorPtr;\n\ntypedef struct Settings\n{\n\n} Settings;\n\ntypedef struct BlockDate\n{\n uint32_t epoch;\n uint32_t slot;\n} BlockDate;\n\ntypedef struct Fragment\n{\n\n} Fragment;\n\ntypedef struct Fragment *FragmentPtr;\n\ntypedef struct SpendingCounters\n{\n uint32_t *data;\n uintptr_t len;\n} SpendingCounters;\n\ntypedef struct Proposal\n{\n\n} Proposal;\n\ntypedef struct Proposal *ProposalPtr;\n\ntypedef struct Settings *SettingsPtr;\n\ntypedef struct Wallet\n{\n\n} Wallet;\n\ntypedef struct Wallet *WalletPtr;\n\ntypedef struct PerCertificateFee\n{\n uint64_t certificate_pool_registration;\n uint64_t certificate_stake_delegation;\n uint64_t certificate_owner_stake_delegation;\n} PerCertificateFee;\n\ntypedef struct PerVoteCertificateFee\n{\n uint64_t certificate_vote_plan;\n uint64_t certificate_vote_cast;\n} PerVoteCertificateFee;\n\n/**\n * Linear fee using the basic affine formula\n * `COEFFICIENT * bytes(COUNT(tx.inputs) + COUNT(tx.outputs)) + CONSTANT + CERTIFICATE*COUNT(certificates)`.\n */\ntypedef struct LinearFee\n{\n uint64_t constant;\n uint64_t coefficient;\n uint64_t certificate;\n struct PerCertificateFee per_certificate_fees;\n struct PerVoteCertificateFee per_vote_certificate_fees;\n} LinearFee;\n\ntypedef uint32_t Epoch;\n\ntypedef uint64_t Slot;\n\ntypedef struct TimeEra\n{\n Epoch epoch_start;\n Slot slot_start;\n uint32_t slots_per_epoch;\n} TimeEra;\n\ntypedef struct SettingsInit\n{\n struct LinearFee fees;\n enum Discrimination discrimination;\n /**\n * block_0_initial_hash is assumed to point to 32 bytes of readable memory\n */\n const uint8_t *block0_initial_hash;\n /**\n * Unix timestamp of the genesis block.\n * Provides an anchor to compute block dates from calendar date/time.\n */\n uint64_t block0_date;\n uint8_t slot_duration;\n struct TimeEra time_era;\n uint8_t transaction_max_expiry_epochs;\n} SettingsInit;\n\ntypedef struct TransactionOut\n{\n const uint8_t *data;\n uintptr_t len;\n} TransactionOut;\n\n/**\n * This function dereference raw pointers. Even though the function checks if\n * the pointers are null. Mind not to put random values in or you may see\n * unexpected behaviors.\n *\n * # Arguments\n *\n * *settings*: the blockchain settings previously allocated with this library.\n * *date*: desired date of expiration for a fragment. It must be expressed in seconds since the\n * unix epoch.\n * *block_date_out*: pointer to an allocated BlockDate structure, the memory should be writable.\n *\n * # Safety\n *\n * pointers should be allocated by this library and be valid.\n * null pointers are checked and will result in an error.\n *\n */\nErrorPtr iohk_jormungandr_block_date_from_system_time(const struct Settings *settings,\n uint64_t date,\n struct BlockDate *block_date_out);\n\n/**\n * delete the pointer\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors\n */\nvoid iohk_jormungandr_delete_fragment(FragmentPtr fragment);\n\n/**\n * delete the inner buffer that was allocated by this library\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors\n */\nvoid iohk_jormungandr_delete_spending_counters(struct SpendingCounters spending_counters);\n\n/**\n * deserialize a fragment from bytes\n *\n * # Parameters\n *\n * * `buffer` -- a pointer to the serialized fragment bytes.\n * * `buffer_length` -- the length of the serialized fragment bytes array.\n * * `fragment` -- the location of the pointer to the deserialized fragemnt.\n *\n * # Errors\n *\n * This functions may fail if:\n *\n * * `buffer` is a null pointer.\n * * `fragment` is a null pointer.\n * * `buffer` contains invalid fragment bytes.\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors\n *\n * Don't forget to delete the fragment object with `iohk_jormungandr_delete_fragment`.\n */\nErrorPtr iohk_jormungandr_fragment_from_raw(const uint8_t *buffer,\n uintptr_t buffer_length,\n FragmentPtr *fragment_out);\n\n/**\n * get the ID of the provided fragment\n *\n * # Parameters\n *\n * * `fragment` -- a pointer to fragment.\n * * `fragment_id_out` -- a pointer to a pre-allocated 32 bytes array.\n *\n * # Errors\n *\n * This function would return an error if either of the provided pointers is null.\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors.\n *\n * `fragment_id_out` is expected to be an already allocated 32 byte array. Doing otherwise may\n * potentially result into an undefined behavior.\n */\nErrorPtr iohk_jormungandr_fragment_id(FragmentPtr fragment,\n uint8_t *fragment_id_out);\n\n/**\n * This function dereference raw pointers. Even though the function checks if\n * the pointers are null. Mind not to put random values in or you may see\n * unexpected behaviors.\n *\n * # Arguments\n *\n * *settings*: the blockchain settings previously allocated with this library.\n * *current_time*: Current real time. It must be expressed in seconds since the unix epoch.\n * *block_date_out*: pointer to an allocated BlockDate structure, the memory should be writable.\n *\n * # Safety\n *\n * pointers should be allocated by this library and be valid.\n * null pointers are checked and will result in an error.\n *\n */\nErrorPtr iohk_jormungandr_max_expiration_date(const struct Settings *settings,\n uint64_t current_time,\n struct BlockDate *block_date_out);\n\n/**\n * decrypt payload of the wallet transfer protocol\n *\n * Parameters\n *\n * password: byte buffer with the encryption password\n * password_length: length of the password buffer\n * ciphertext: byte buffer with the encryption password\n * ciphertext_length: length of the password buffer\n * plaintext_out: used to return a pointer to a byte buffer with the decrypted text\n * plaintext_out_length: used to return the length of decrypted text\n *\n * The returned buffer is in the heap, so make sure to call the delete_buffer function\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though the function checks if\n * the pointers are null. Mind not to put random values in or you may see\n * unexpected behaviors.\n */\nErrorPtr iohk_jormungandr_symmetric_cipher_decrypt(const uint8_t *password,\n uintptr_t password_length,\n const uint8_t *ciphertext,\n uintptr_t ciphertext_length,\n const uint8_t **plaintext_out,\n uintptr_t *plaintext_out_length);\n\n/**\n * build the proposal object\n *\n * * `vote_encryption_key`: a null terminated string (c-string) with the bech32\n * representation of the encryption vote key\n *\n * # Errors\n *\n * This function may fail if:\n *\n * * `proposal_out` is null.\n * * `num_choices` is out of the allowed range.\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though the function checks if\n * the pointers are null. Mind not to put random values in or you may see\n * unexpected behaviors.\n */\nErrorPtr iohk_jormungandr_vote_proposal_new_private(const uint8_t *vote_plan_id,\n uint8_t index,\n uint8_t num_choices,\n const char *vote_encryption_key,\n ProposalPtr *proposal_out);\n\n/**\n * build the proposal object\n *\n * # Errors\n *\n * This function may fail if:\n *\n * * `proposal_out` is null.\n * * `num_choices` is out of the allowed range.\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though the function checks if\n * the pointers are null. Mind not to put random values in or you may see\n * unexpected behaviors.\n */\nErrorPtr iohk_jormungandr_vote_proposal_new_public(const uint8_t *vote_plan_id,\n uint8_t index,\n uint8_t num_choices,\n ProposalPtr *proposal_out);\n\n/**\n * Delete a binary buffer that was returned by this library alongside with its\n * length.\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors\n */\nvoid iohk_jormungandr_wallet_delete_buffer(uint8_t *ptr, uintptr_t length);\n\n/**\n * delete the pointer and free the allocated memory\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors\n *\n */\nvoid iohk_jormungandr_wallet_delete_error(ErrorPtr error);\n\n/**\n * delete the pointer\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors\n *\n */\nvoid iohk_jormungandr_wallet_delete_proposal(ProposalPtr proposal);\n\n/**\n * delete the pointer and free the allocated memory\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors\n *\n */\nvoid iohk_jormungandr_wallet_delete_settings(SettingsPtr settings);\n\n/**\n * Delete a null terminated string that was allocated by this library\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors\n *\n */\nvoid iohk_jormungandr_wallet_delete_string(char *ptr);\n\n/**\n * delete the pointer, zero all the keys and free the allocated memory\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors\n *\n */\nvoid iohk_jormungandr_wallet_delete_wallet(WalletPtr wallet);\n\n/**\n * Get a string describing the error, this will return an allocated\n * null terminated string providing extra details regarding the source\n * of the error.\n *\n * If the given error is a `NULL` pointer, the string is and always\n * is `\"success\"`. If no details are available the function will return\n * `\"no more details\"`. This string still need to be deleted with the\n * `iohk_jormungandr_wallet_delete_string` function.\n *\n * This function returns an allocated null terminated pointer. Don't\n * forget to free the memory with: `iohk_jormungandr_wallet_delete_string`.\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors\n *\n */\nchar *iohk_jormungandr_wallet_error_details(ErrorPtr error);\n\n/**\n * Get a string describing the error, this will return an allocated\n * null terminated string describing the error.\n *\n * If the given error is a `NULL` pointer, the string is and always\n * is `\"success\"`. This string still need to be deleted with the\n * `iohk_jormungandr_wallet_delete_string` function.\n *\n * This function returns an allocated null terminated pointer. Don't\n * forget to free the memory with: `iohk_jormungandr_wallet_delete_string`.\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors\n *\n */\nchar *iohk_jormungandr_wallet_error_to_string(ErrorPtr error);\n\n/**\n * get the wallet id\n *\n * This ID is the identifier to use against the blockchain/explorer to retrieve\n * the state of the wallet (counter, total value etc...)\n *\n * # Parameters\n *\n * * wallet: the recovered wallet (see recover function);\n * * id_out: a ready allocated pointer to an array of 32bytes. If this array is not\n * 32bytes this may result in a buffer overflow.\n *\n * # Safety\n *\n * This function dereference raw pointers (wallet, block0 and settings_out). Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors\n *\n * the `id_out` needs to be ready allocated 32bytes memory. If not this will result\n * in an undefined behavior, in the best scenario it will be a buffer overflow.\n *\n * # Errors\n *\n * On error the function returns a `ErrorPtr`. On success `NULL` is returned.\n * The `ErrorPtr` can then be observed to gathered details of the error.\n * Don't forget to call `iohk_jormungandr_wallet_delete_error` to free\n * the `ErrorPtr` from memory and avoid memory leaks.\n *\n * * this function may fail if the wallet pointer is null;\n *\n */\nErrorPtr iohk_jormungandr_wallet_id(WalletPtr wallet,\n uint8_t *id_out);\n\n/**\n * recover a wallet from an account and a list of utxo keys\n *\n * You can also use this function to recover a wallet even after you have\n * transferred all the funds to the new format (see the _convert_ function)\n *\n * The recovered wallet will be returned in `wallet_out`.\n *\n * # parameters\n *\n * * account_key: the Ed25519 extended key used wallet's account address private key\n * in the form of a 64 bytes array.\n * * utxo_keys: an array of Ed25519 extended keys in the form of 64 bytes, used as utxo\n * keys for the wallet\n * * utxo_keys_len: the number of keys in the utxo_keys array (not the number of bytes)\n * * wallet_out: the recovered wallet\n *\n * # Safety\n *\n * This function dereference raw pointers (password and wallet_out). Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors\n *\n * # errors\n *\n * The function may fail if:\n *\n * * the `wallet_out` is null pointer\n *\n */\nErrorPtr iohk_jormungandr_wallet_import_keys(const uint8_t *account_key,\n WalletPtr *wallet_out);\n\n/**\n * update the wallet account state\n *\n * this is the value retrieved from any jormungandr endpoint that allows to query\n * for the account state. It gives the value associated to the account as well as\n * the counter.\n *\n * It is important to be sure to have an updated wallet state before doing any\n * transactions otherwise future transactions may fail to be accepted by any\n * nodes of the blockchain because of invalid signature state.\n *\n * # Errors\n *\n * * this function may fail if the wallet pointer is null;\n *\n * On error the function returns a `ErrorPtr`. On success `NULL` is returned.\n * The `ErrorPtr` can then be observed to gathered details of the error.\n * Don't forget to call `iohk_jormungandr_wallet_delete_error` to free\n * the `ErrorPtr` from memory and avoid memory leaks.\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors\n *\n */\nErrorPtr iohk_jormungandr_wallet_set_state(WalletPtr wallet,\n uint64_t value,\n struct SpendingCounters counters);\n\n/**\n * # Safety\n *\n * This function assumes block0_hash points to 32 bytes of valid memory\n * This function also assumes that settings is a valid pointer previously\n * obtained with this library, a null check is performed, but is important that\n * the data it points to is valid\n */\nErrorPtr iohk_jormungandr_wallet_settings_block0_hash(SettingsPtr settings,\n uint8_t *block0_hash);\n\n/**\n * # Safety\n *\n * This function also assumes that settings is a valid pointer previously\n * obtained with this library, a null check is performed, but is important that\n * the data it points to is valid\n *\n * discrimination_out must point to valid writable memory, a null check is\n * performed\n */\nErrorPtr iohk_jormungandr_wallet_settings_discrimination(SettingsPtr settings,\n enum Discrimination *discrimination_out);\n\n/**\n * # Safety\n *\n * This function also assumes that settings is a valid pointer previously\n * obtained with this library, a null check is performed, but is important that\n * the data it points to is valid\n *\n * linear_fee_out must point to valid writable memory, a null check is\n * performed\n */\nErrorPtr iohk_jormungandr_wallet_settings_fees(SettingsPtr settings,\n struct LinearFee *linear_fee_out);\n\n/**\n * # Safety\n *\n * settings_out must point to valid writable memory\n * block_0_hash is assumed to point to 32 bytes of readable memory\n */\nErrorPtr iohk_jormungandr_wallet_settings_new(struct SettingsInit settings_init,\n SettingsPtr *settings_out);\n\n/**\n * get the current spending counters for the (only) account in this wallet\n *\n * iohk_jormungandr_spending_counters_delete should be called to deallocate the memory when it's\n * not longer needed\n *\n * # Errors\n *\n * * this function may fail if the wallet pointer is null;\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors\n *\n */\nErrorPtr iohk_jormungandr_wallet_spending_counters(WalletPtr wallet,\n struct SpendingCounters *spending_counters_ptr);\n\n/**\n * get the total value in the wallet\n *\n * make sure to call `retrieve_funds` prior to calling this function\n * otherwise you will always have `0`\n *\n * After calling this function the results is returned in the `total_out`.\n *\n * # Errors\n *\n * * this function may fail if the wallet pointer is null;\n *\n * On error the function returns a `ErrorPtr`. On success `NULL` is returned.\n * The `ErrorPtr` can then be observed to gathered details of the error.\n * Don't forget to call `iohk_jormungandr_wallet_delete_error` to free\n * the `ErrorPtr` from memory and avoid memory leaks.\n *\n * If the `total_out` pointer is null, this function does nothing\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though\n * the function checks if the pointers are null. Mind not to put random values\n * in or you may see unexpected behaviors\n *\n */\nErrorPtr iohk_jormungandr_wallet_total_value(WalletPtr wallet,\n uint64_t *total_out);\n\n/**\n * build the vote cast transaction\n *\n * # Errors\n *\n * This function may fail upon receiving a null pointer or a `choice` value\n * that does not fall within the range specified in `proposal`.\n *\n * # Safety\n *\n * This function dereference raw pointers. Even though the function checks if\n * the pointers are null. Mind not to put random values in or you may see\n * unexpected behaviors.\n *\n * Don't forget to remove `transaction_out` with\n * `iohk_jormungandr_waller_delete_buffer`.\n */\nErrorPtr iohk_jormungandr_wallet_vote_cast(WalletPtr wallet,\n SettingsPtr settings,\n ProposalPtr proposal,\n uint8_t choice,\n struct BlockDate valid_until,\n uint8_t lane,\n struct TransactionOut *transaction_out);\n\n#endif /* IOHK_CHAIN_WALLET_LIBC_ */\n" }, { "alpha_fraction": 0.5599699020385742, "alphanum_fraction": 0.5648653507232666, "avg_line_length": 28.02185821533203, "blob_id": "69d4852898974884fd38a8454b91c5633ba61df4", "content_id": "cdf01db225a4b23def7daf669f24c82545411eaf", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 5311, "license_type": "permissive", "max_line_length": 100, "num_lines": 183, "path": "/wallet/src/transaction/builder.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use super::witness_builder::WitnessBuilder;\nuse crate::Settings;\nuse chain_addr::Address;\nuse chain_impl_mockchain::{\n block::BlockDate,\n fee::FeeAlgorithm as _,\n transaction::{\n Balance, Input, Output, Payload, SetAuthData, SetIOs, SetTtl, SetWitnesses, Transaction,\n TxBuilderState,\n },\n value::Value,\n};\nuse thiserror::Error;\n\n#[derive(Debug, Error)]\n#[error(\"Cannot balance the transaction\")]\npub struct BalancingError;\n\npub struct TransactionBuilder<'settings, P: Payload> {\n settings: &'settings Settings,\n payload: P,\n validity: BlockDate,\n outputs: Vec<Output<Address>>,\n inputs: Vec<Input>,\n witness_builders: Vec<Box<dyn WitnessBuilder>>,\n}\n\npub enum AddInputStatus {\n Added,\n Skipped(Input),\n NotEnoughSpace,\n}\n\nimpl<'settings, P: Payload> TransactionBuilder<'settings, P> {\n /// create a new transaction builder with the given settings and outputs\n pub fn new(settings: &'settings Settings, payload: P, validity: BlockDate) -> Self {\n Self {\n settings,\n payload,\n validity,\n outputs: Vec::with_capacity(255),\n inputs: Vec::with_capacity(255),\n witness_builders: Vec::with_capacity(255),\n }\n }\n\n #[inline]\n pub fn inputs(&self) -> &[Input] {\n &self.inputs\n }\n\n #[inline]\n pub fn outputs(&self) -> &[Output<Address>] {\n &self.outputs\n }\n\n #[inline]\n pub fn inputs_value(&self) -> Value {\n self.inputs().iter().map(|i| i.value()).sum()\n }\n\n #[inline]\n pub fn outputs_value(&self) -> Value {\n self.outputs().iter().map(|i| i.value).sum()\n }\n\n #[inline]\n pub fn estimate_fee_with(&self, extra_inputs: u8, extra_outputs: u8) -> Value {\n self.settings.fees.calculate(\n self.payload\n .payload_data()\n .borrow()\n .into_certificate_slice(),\n self.inputs.len() as u8 + extra_inputs,\n self.outputs.len() as u8 + extra_outputs,\n )\n }\n\n #[inline]\n pub fn estimate_fee(&self) -> Value {\n self.estimate_fee_with(0, 0)\n }\n\n pub fn add_input_if_worth<B: WitnessBuilder + 'static>(\n &mut self,\n input: Input,\n witness_builder: B,\n ) -> AddInputStatus {\n if self.settings.is_input_worth(&input) {\n match self.add_input(input, witness_builder) {\n true => AddInputStatus::Added,\n false => AddInputStatus::NotEnoughSpace,\n }\n } else {\n AddInputStatus::Skipped(input)\n }\n }\n\n pub fn add_input<B: WitnessBuilder + 'static>(\n &mut self,\n input: Input,\n witness_builder: B,\n ) -> bool {\n match self.inputs.len().cmp(&255) {\n std::cmp::Ordering::Less => {\n self.inputs.push(input);\n self.witness_builders.push(Box::new(witness_builder));\n true\n }\n _ => false,\n }\n }\n\n pub fn add_output(&mut self, output: Output<Address>) -> bool {\n if self.outputs().len() < 255 {\n self.outputs.push(output);\n true\n } else {\n false\n }\n }\n\n pub fn check_balance(&self) -> Balance {\n self.check_balance_with(0, 0)\n }\n\n pub fn check_balance_with(&self, extra_inputs: u8, extra_outputs: u8) -> Balance {\n let total_in = self.inputs_value();\n let total_out = self.outputs_value();\n let total_fee = self.estimate_fee_with(extra_inputs, extra_outputs);\n\n let total_out = total_out.saturating_add(total_fee);\n\n match total_in.cmp(&total_out) {\n std::cmp::Ordering::Greater => {\n Balance::Positive(total_in.checked_sub(total_out).unwrap())\n }\n std::cmp::Ordering::Equal => Balance::Zero,\n std::cmp::Ordering::Less => Balance::Negative(total_out.checked_sub(total_in).unwrap()),\n }\n }\n\n pub fn finalize_tx(self, auth: <P as Payload>::Auth) -> Result<Transaction<P>, BalancingError> {\n if !matches!(self.check_balance(), Balance::Zero) {\n return Err(BalancingError);\n }\n\n let builder = TxBuilderState::new();\n let builder = builder.set_payload(&self.payload);\n\n let builder = self.set_validity(builder);\n let builder = self.set_ios(builder);\n let builder = self.set_witnesses(builder);\n\n Ok(builder.set_payload_auth(&auth))\n }\n\n fn set_validity(&self, builder: TxBuilderState<SetTtl<P>>) -> TxBuilderState<SetIOs<P>> {\n builder.set_expiry_date(self.validity)\n }\n\n fn set_ios(&self, builder: TxBuilderState<SetIOs<P>>) -> TxBuilderState<SetWitnesses<P>> {\n builder.set_ios(&self.inputs, &self.outputs)\n }\n\n fn set_witnesses(\n &self,\n builder: TxBuilderState<SetWitnesses<P>>,\n ) -> TxBuilderState<SetAuthData<P>>\n where\n P: Payload,\n {\n let header_id = self.settings.block0_initial_hash;\n let auth_data = builder.get_auth_data_for_witness().hash();\n let witnesses: Vec<_> = self\n .witness_builders\n .iter()\n .map(|wb| wb.build(&header_id, &auth_data))\n .collect();\n\n builder.set_witnesses(&witnesses)\n }\n}\n" }, { "alpha_fraction": 0.7441520690917969, "alphanum_fraction": 0.7441520690917969, "avg_line_length": 21.064516067504883, "blob_id": "f065e6ff4d88505caa9212bf254713c20fccc490", "content_id": "c4cb424f94781a692fc0b95553ea76a2d92e63fb", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 684, "license_type": "permissive", "max_line_length": 76, "num_lines": 31, "path": "/bindings/wallet-js/README.md", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "# Jormungandr wallet SDK for JavaScript\n\nThis crate provides a wasm package with JavaScript and TypeScript bindings\nfor the Jormungandr wallet client library.\n\nSee the `Wallet` class for a starting point in the API documentation.\n\n## Building the package\n\n[wasm-pack](https://github.com/rustwasm/wasm-pack) is required.\n\n```\nwasm-pack build -d pkg\n```\n\nUse the `--target` option to select the target environment for the package. \n\nFor a quicker, but unoptimized build:\n\n```\nwasm-pack build --dev\n```\n\n## Documentation\n\nThe API documentation can be generated from the built JavaScript bindings\nwith the following command:\n\n```\njsdoc pkg -c ../../jsdoc.json -d pkg/doc -R README.md\n```\n" }, { "alpha_fraction": 0.5473542213439941, "alphanum_fraction": 0.5568146109580994, "avg_line_length": 27.291175842285156, "blob_id": "94d3b6e51b4cc2cdb82af16fc4c05e6c1de29258", "content_id": "3dcb9c4e3b14a68bf271d8cbaeb4bc2c5f511f05", "detected_licenses": [ "Apache-2.0", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 9619, "license_type": "permissive", "max_line_length": 99, "num_lines": 340, "path": "/chain-path-derivation/src/derivation_path.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use crate::Derivation;\nuse std::{\n fmt::{self, Display},\n hash::{Hash, Hasher},\n ops::Deref,\n str::{self, FromStr},\n};\nuse thiserror::Error;\n\n/// any derivation path scheme\n#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Default)]\npub struct AnyScheme;\n\n/// a derivation path with a tagged scheme (for example [`Bip44`]).\n///\n/// This allows following the specific set of rules for a derivation\n/// path, preventing some errors. For example, the Bip44 scheme enforce\n/// the 3 first derivation to be hard derivation indices and the 2 last\n/// ones to be soft derivation indices.\n///\n/// [`Bip44`]: ./struct.Bip44.html\n#[derive(Debug)]\npub struct DerivationPath<S> {\n path: Vec<Derivation>,\n _marker: std::marker::PhantomData<S>,\n}\n\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct DerivationPathRange<S, R, T>\nwhere\n R: Iterator<Item = T>,\n T: Into<Derivation>,\n{\n root: DerivationPath<S>,\n range: R,\n}\n\nimpl<S> DerivationPath<S> {\n /// Iterate through every derivation indices of the given derivation path\n ///\n pub fn iter(&self) -> std::slice::Iter<'_, Derivation> {\n self.path.iter()\n }\n\n /// create a new derivation path with appending the new derivation\n /// index to the current derivation path\n ///\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n pub fn append_unchecked(&self, derivation: Derivation) -> Self {\n let mut cloned = self.clone();\n cloned.path.push(derivation);\n cloned\n }\n\n /// create a range of derivation path with the given derivation range\n ///\n /// this will create an iterator of DerivationPath with the first derivation\n /// indices being the one fo the given derivation path and the append indices\n /// the one from the range.\n ///\n /// i.e. if the derivation path is `m/'1/42` and the range is `..20` it will\n /// create an iterator of derivation path for all: `m/'1/42/0` `m/'1/42/1`\n /// `m/'1/42/2` ... `m/'1/42/19`.\n pub fn sub_range<R, T>(&self, range: R) -> DerivationPathRange<S, R, T>\n where\n R: Iterator<Item = T>,\n T: Into<Derivation>,\n {\n let root = self.clone();\n\n DerivationPathRange { root, range }\n }\n\n pub(crate) fn new_empty() -> Self {\n Self {\n path: Vec::new(),\n _marker: std::marker::PhantomData,\n }\n }\n\n pub(crate) fn push(&mut self, derivation: Derivation) {\n self.path.push(derivation)\n }\n\n #[inline]\n pub(crate) fn get_unchecked(&self, index: usize) -> Derivation {\n if let Some(v) = self.get(index).copied() {\n v\n } else {\n unsafe { std::hint::unreachable_unchecked() }\n }\n }\n\n pub fn coerce_unchecked<T>(self) -> DerivationPath<T> {\n DerivationPath {\n path: self.path,\n _marker: std::marker::PhantomData,\n }\n }\n}\n\nimpl DerivationPath<AnyScheme> {\n pub fn new() -> Self {\n DerivationPath::new_empty()\n }\n}\n\nimpl<S> Deref for DerivationPath<S> {\n type Target = [Derivation];\n fn deref(&self) -> &Self::Target {\n self.path.deref()\n }\n}\n\n/* Default ***************************************************************** */\n\nimpl Default for DerivationPath<AnyScheme> {\n fn default() -> Self {\n Self::new()\n }\n}\n\n/* Comparison ************************************************************** */\n\nimpl<T1, T2> PartialEq<DerivationPath<T1>> for DerivationPath<T2> {\n fn eq(&self, other: &DerivationPath<T1>) -> bool {\n self.path.eq(&other.path)\n }\n}\n\nimpl<T> Eq for DerivationPath<T> {}\n\nimpl<T1, T2> PartialOrd<DerivationPath<T1>> for DerivationPath<T2> {\n fn partial_cmp(&self, other: &DerivationPath<T1>) -> Option<std::cmp::Ordering> {\n self.path.partial_cmp(&other.path)\n }\n}\n\nimpl<T> Ord for DerivationPath<T> {\n fn cmp(&self, other: &Self) -> std::cmp::Ordering {\n self.path.cmp(&other.path)\n }\n}\n\n/* Hasher ****************************************************************** */\n\nimpl<T> Hash for DerivationPath<T> {\n fn hash<H: Hasher>(&self, state: &mut H) {\n self.path.hash(state);\n self._marker.hash(state);\n }\n}\n\n/* Iterator **************************************************************** */\n\nimpl<S, R, T> Iterator for DerivationPathRange<S, R, T>\nwhere\n R: Iterator<Item = T>,\n T: Into<Derivation>,\n{\n type Item = DerivationPath<S>;\n\n fn next(&mut self) -> Option<Self::Item> {\n let next = self.range.next()?.into();\n let path = self.root.append_unchecked(next);\n Some(path)\n }\n}\n\nimpl<S, R, T> ExactSizeIterator for DerivationPathRange<S, R, T>\nwhere\n R: Iterator<Item = T> + ExactSizeIterator,\n T: Into<Derivation>,\n{\n fn len(&self) -> usize {\n self.range.len()\n }\n}\n\nimpl<S, R, T> DoubleEndedIterator for DerivationPathRange<S, R, T>\nwhere\n R: Iterator<Item = T> + DoubleEndedIterator,\n T: Into<Derivation>,\n{\n fn next_back(&mut self) -> Option<Self::Item> {\n let next = self.range.next_back()?.into();\n let path = self.root.append_unchecked(next);\n Some(path)\n }\n}\n\nimpl<S, R, T> std::iter::FusedIterator for DerivationPathRange<S, R, T>\nwhere\n R: Iterator<Item = T> + std::iter::FusedIterator,\n T: Into<Derivation>,\n{\n}\n\nimpl<S> IntoIterator for DerivationPath<S> {\n type Item = Derivation;\n type IntoIter = std::vec::IntoIter<Self::Item>;\n\n fn into_iter(self) -> Self::IntoIter {\n self.path.into_iter()\n }\n}\n\nimpl<'a, S> IntoIterator for &'a DerivationPath<S> {\n type Item = &'a Derivation;\n type IntoIter = std::slice::Iter<'a, Derivation>;\n\n fn into_iter(self) -> Self::IntoIter {\n self.iter()\n }\n}\n\n/* FromIterator ************************************************************ */\n\nimpl std::iter::FromIterator<Derivation> for DerivationPath<AnyScheme> {\n fn from_iter<T: IntoIterator<Item = Derivation>>(iter: T) -> Self {\n let mut dp = Self::new_empty();\n dp.path = iter.into_iter().collect();\n dp\n }\n}\n\n/* Display ***************************************************************** */\n\nimpl<S> Display for DerivationPath<S> {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"m\")?;\n for derivation in self.iter() {\n write!(f, \"/{}\", derivation)?;\n }\n Ok(())\n }\n}\n\n/* FromStr ***************************************************************** */\n\n#[derive(Debug, Error)]\npub enum ParseDerivationPathError {\n #[error(\"Derivation Path should start with 'm'\")]\n NotValidRoot,\n\n #[error(\"Invalid derivation at index '{index}'\")]\n NotValidDerivation {\n index: usize,\n #[source]\n source: crate::ParseDerivationError,\n },\n\n #[error(\"Invalid number of derivation ({actual}), expected {expected}\")]\n InvalidNumberOfDerivations { actual: usize, expected: usize },\n}\n\nimpl FromStr for DerivationPath<AnyScheme> {\n type Err = ParseDerivationPathError;\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n let mut derivations = s.split('/');\n\n let m = derivations\n .next()\n .ok_or(ParseDerivationPathError::NotValidRoot)?;\n if m != \"m\" {\n return Err(ParseDerivationPathError::NotValidRoot);\n }\n\n let mut path = Self::new_empty();\n for (index, derivation) in derivations.enumerate() {\n let derivation = derivation\n .parse()\n .map_err(|source| ParseDerivationPathError::NotValidDerivation { index, source })?;\n path.push(derivation);\n }\n\n Ok(path)\n }\n}\n\n/* Clone ******************************************************************* */\n\nimpl<S> Clone for DerivationPath<S> {\n fn clone(&self) -> Self {\n Self {\n path: self.path.clone(),\n _marker: std::marker::PhantomData,\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use quickcheck::{Arbitrary, Gen};\n\n const MAX_DERIVATION_PATH_ANY_SCHEME_LENGTH: usize = 24;\n\n impl Arbitrary for DerivationPath<AnyScheme> {\n fn arbitrary<G: Gen>(g: &mut G) -> Self {\n let path_len = usize::arbitrary(g) % MAX_DERIVATION_PATH_ANY_SCHEME_LENGTH;\n\n std::iter::repeat_with(|| Derivation::arbitrary(g))\n .take(path_len)\n .collect()\n }\n }\n\n #[test]\n fn to_string() {\n let mut path = DerivationPath::<AnyScheme>::new_empty();\n assert_eq!(path.to_string(), \"m\");\n path.push(Derivation::new(0x0000_0000));\n assert_eq!(path.to_string(), \"m/0\");\n path.push(Derivation::new(0x0000_0007));\n assert_eq!(path.to_string(), \"m/0/7\");\n path.push(Derivation::new(0x8000_0001));\n assert_eq!(path.to_string(), \"m/0/7/'1\");\n path.push(Derivation::new(0x8000_000a));\n assert_eq!(path.to_string(), \"m/0/7/'1/'10\");\n }\n\n #[test]\n fn invalid_parse() {\n assert!(\"\".parse::<DerivationPath<AnyScheme>>().is_err());\n assert!(\"a\".parse::<DerivationPath<AnyScheme>>().is_err());\n assert!(\"M\".parse::<DerivationPath<AnyScheme>>().is_err());\n assert!(\"m/a\".parse::<DerivationPath<AnyScheme>>().is_err());\n assert!(\"m/\\\"1\".parse::<DerivationPath<AnyScheme>>().is_err());\n }\n\n #[quickcheck]\n fn fmt_parse(derivation_path: DerivationPath<AnyScheme>) -> bool {\n let s = derivation_path.to_string();\n let v = s.parse::<DerivationPath<AnyScheme>>().unwrap();\n\n v == derivation_path\n }\n}\n" }, { "alpha_fraction": 0.543915867805481, "alphanum_fraction": 0.5477625131607056, "avg_line_length": 26.85357093811035, "blob_id": "a868f6129ed3fbf07b731cb0ef9bd565a4810286", "content_id": "853d7cca15760e09c5d8d16fe0adc6b5acb85dc4", "detected_licenses": [ "MIT", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 7799, "license_type": "permissive", "max_line_length": 95, "num_lines": 280, "path": "/hdkeygen/src/key.rs", "repo_name": "input-output-hk/chain-wallet-libs", "src_encoding": "UTF-8", "text": "use chain_path_derivation::{\n Derivation, DerivationPath, DerivationRange, SoftDerivation, SoftDerivationRange,\n};\nuse ed25519_bip32::{DerivationScheme, Signature, XPrv, XPub};\nuse std::fmt::{self, Debug, Display};\n\n/// convenient wrapper around the `Key`.\n///\npub struct Key<K, P> {\n key: K,\n path: DerivationPath<P>,\n derivation_scheme: DerivationScheme,\n}\n\npub struct KeyRange<'a, K, DR, P, Q> {\n key: &'a Key<K, P>,\n range: DR,\n _marker: std::marker::PhantomData<Q>,\n}\n\nimpl<'a, K, DR, P, Q> KeyRange<'a, K, DR, P, Q> {\n pub(crate) fn new(key: &'a Key<K, P>, range: DR) -> Self {\n Self {\n key,\n range,\n _marker: std::marker::PhantomData,\n }\n }\n}\n\nimpl<K, P> Key<K, P> {\n /// create a `Key` with the given component\n ///\n /// does not guarantee that the derivation path is actually the one\n /// that lead to this key derivation.\n #[inline]\n pub fn new_unchecked(\n key: K,\n path: DerivationPath<P>,\n derivation_scheme: DerivationScheme,\n ) -> Self {\n Self {\n key,\n path,\n derivation_scheme,\n }\n }\n\n /// get the derivation path that lead to this key\n pub fn path(&self) -> &DerivationPath<P> {\n &self.path\n }\n\n pub fn coerce_unchecked<Q>(self) -> Key<K, Q> {\n Key {\n path: self.path.coerce_unchecked(),\n key: self.key,\n derivation_scheme: self.derivation_scheme,\n }\n }\n}\n\nimpl<P> Key<XPrv, P> {\n /// retrieve the associated public key of the given private key\n ///\n #[inline]\n pub fn public(&self) -> Key<XPub, P> {\n Key {\n key: self.key.public(),\n path: self.path.clone(),\n derivation_scheme: self.derivation_scheme,\n }\n }\n\n /// create a signature for the given message and associate the given type `T`\n /// to the signature type.\n ///\n #[inline]\n pub fn sign<T, B>(&self, message: B) -> Signature<T>\n where\n B: AsRef<[u8]>,\n {\n self.key.sign(message.as_ref())\n }\n\n /// verify the signature with the private key for the given message\n #[inline]\n pub fn verify<T, B>(&self, message: B, signature: &Signature<T>) -> bool\n where\n B: AsRef<[u8]>,\n {\n self.key.verify(message.as_ref(), signature)\n }\n\n /// get key's chain code\n #[inline]\n pub fn chain_code(&self) -> [u8; 32] {\n *self.key.chain_code()\n }\n\n /// derive the private key against the given derivation index and scheme\n ///\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n pub(crate) fn derive_unchecked<Q>(&self, derivation: Derivation) -> Key<XPrv, Q> {\n let derivation_scheme = self.derivation_scheme;\n let key = self.key.derive(derivation_scheme, *derivation);\n let path = self.path.append_unchecked(derivation).coerce_unchecked();\n Key {\n key,\n path,\n derivation_scheme,\n }\n }\n\n /// derive the private key against the given derivation index and scheme\n ///\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n pub(crate) fn derive_path_unchecked<'a, Q, I>(&'a self, derivation_path: I) -> Key<XPrv, Q>\n where\n I: IntoIterator<Item = &'a Derivation>,\n {\n let derivation_scheme = self.derivation_scheme;\n\n let mut key = self.key.clone();\n let mut path = self.path.clone().coerce_unchecked::<Q>();\n\n for derivation in derivation_path {\n key = key.derive(derivation_scheme, **derivation);\n path = path.append_unchecked(*derivation);\n }\n\n Key {\n key,\n path,\n derivation_scheme,\n }\n }\n}\n\nimpl<P> Key<XPub, P> {\n /// verify the signature with the public key for the given message\n #[inline]\n pub fn verify<T, B>(&self, message: B, signature: &Signature<T>) -> bool\n where\n B: AsRef<[u8]>,\n {\n self.key.verify(message.as_ref(), signature)\n }\n\n /// get the public key content without revealing the chaincode.\n #[inline]\n pub fn public_key_slice(&self) -> &[u8] {\n self.key.public_key_slice()\n }\n\n pub fn public_key(&self) -> &XPub {\n &self.key\n }\n\n pub fn pk(&self) -> chain_crypto::PublicKey<chain_crypto::Ed25519> {\n if let Ok(pk) = chain_crypto::PublicKey::from_binary(self.public_key_slice()) {\n pk\n } else {\n unsafe { std::hint::unreachable_unchecked() }\n }\n }\n\n /// derive the private key against the given derivation index and scheme\n #[must_use = \"this returns the result of the operation, without modifying the original\"]\n pub(crate) fn derive_unchecked<Q>(&self, derivation: SoftDerivation) -> Key<XPub, Q> {\n let derivation_scheme = self.derivation_scheme;\n let key = if let Ok(key) = self.key.derive(derivation_scheme, *derivation) {\n key\n } else {\n // cannot happen because we already enforced the derivation index\n // to be a soft derivation.\n unsafe { std::hint::unreachable_unchecked() }\n };\n let path = self\n .path\n .append_unchecked(derivation.into())\n .coerce_unchecked();\n Key {\n key,\n path,\n derivation_scheme,\n }\n }\n}\n\nimpl<P> Key<chain_crypto::SecretKey<chain_crypto::Ed25519Extended>, P> {\n /// create a signature for the given message and associate the given type `T`\n /// to the signature type.\n ///\n #[inline]\n pub fn sign<T, B>(&self, message: B) -> Signature<T>\n where\n B: AsRef<[u8]>,\n {\n Signature::from_slice(self.key.sign(&message.as_ref()).as_ref()).unwrap()\n }\n\n pub fn pk(&self) -> chain_crypto::PublicKey<chain_crypto::Ed25519> {\n self.key.to_public()\n }\n}\n\nimpl<'a, P, Q> Iterator for KeyRange<'a, XPub, SoftDerivationRange, P, Q> {\n type Item = Key<XPub, Q>;\n\n fn next(&mut self) -> Option<Self::Item> {\n self.range\n .next()\n .map(|next| self.key.derive_unchecked(next))\n }\n}\n\nimpl<'a, P, Q> Iterator for KeyRange<'a, XPrv, DerivationRange, P, Q> {\n type Item = Key<XPrv, Q>;\n\n fn next(&mut self) -> Option<Self::Item> {\n self.range\n .next()\n .map(|next| self.key.derive_unchecked(next))\n }\n}\n\nimpl<K, P> AsRef<K> for Key<K, P> {\n fn as_ref(&self) -> &K {\n &self.key\n }\n}\n\nimpl<K: Clone, P> Clone for Key<K, P> {\n fn clone(&self) -> Self {\n Self {\n key: self.key.clone(),\n path: self.path.clone(),\n derivation_scheme: self.derivation_scheme,\n }\n }\n}\n\nimpl<K, P> Debug for Key<K, P>\nwhere\n K: Debug,\n{\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(&format!(\n \"Key<{}, {}>\",\n std::any::type_name::<K>(),\n std::any::type_name::<P>()\n ))\n .field(\"path\", &self.path.to_string())\n .field(\"key\", &self.key)\n .field(\"scheme\", &self.derivation_scheme)\n .finish()\n }\n}\n\nimpl<P> Display for Key<XPrv, P> {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.write_fmt(format_args!(\n \"<private-key> ({path} - {scheme:?})\",\n path = self.path,\n scheme = self.derivation_scheme\n ))\n }\n}\n\nimpl<P> Display for Key<XPub, P> {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.write_fmt(format_args!(\n \"{key} ({path} - {scheme:?})\",\n key = self.key,\n path = self.path,\n scheme = self.derivation_scheme,\n ))\n }\n}\n" } ]
84
haiyanzzz/rbac
https://github.com/haiyanzzz/rbac
784b6ad87ef660a5df5e11f2bdf4f27eb415f872
d77bf381c65ca23c5aef446c5073d4efda01fbb4
3043161c2dbb636f8c5b61f2696f2d5ae323951e
refs/heads/master
2021-05-06T11:22:28.411077
2017-12-14T08:26:08
2017-12-14T08:26:08
114,223,206
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.47099769115448, "alphanum_fraction": 0.48375868797302246, "avg_line_length": 22.97222137451172, "blob_id": "a6b1b717c9927b3b313cbb8dc7409f1acce411f9", "content_id": "0266fc30d9e12c07274e8f254b7c3412404a37a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 906, "license_type": "no_license", "max_line_length": 123, "num_lines": 36, "path": "/测试2.py", "repo_name": "haiyanzzz/rbac", "src_encoding": "UTF-8", "text": "#!usr/bin/env python\n# -*- coding:utf-8 -*-\nmenu_dict = {\n\t1: {'id': 1, 'title': '用户列表', 'url': '/userinfo/', 'menu_gp_id': None, 'menu_id': 2, 'menu_title': '菜单二', 'active': True},\n\t5: {'id': 5, 'title': '订单列表', 'url': '/order/', 'menu_gp_id': None, 'menu_id': 1, 'menu_title': '菜单一'}\n}\nresult = {}\nactive = False\nfor item in menu_dict.values():\n result[\"menu_id\"] = {\n \"menu_id\":item[\"menu_id\"],\n \"title\":item[\"title\"],\n \"active\":active,\n \"children\":[\n {'url': item[\"url\"], 'active': True}\n ]\n }\nprint(result)\n# {\n# \t1:{\n# \t\tmenu_id:1\n# \t\tmenu_title:\n# \t\tactive:True\n# \t\tchildren:[\n# \t\t\t{'title': '用户列表', 'url': '/userinfo/', 'menu_gp_id': None}\n# \t\t]\n# \t }\n# \t 2:{\n# \t\tmenu_id:1\n# \t\tmenu_title:\n# \t\tactive:True\n# \t\tchildren:[\n# \t\t\t{'title': '用户列表', 'url': '/userinfo/', 'menu_gp_id': None}\n# \t\t]\n# \t }\n# }" }, { "alpha_fraction": 0.508474588394165, "alphanum_fraction": 0.5296609997749329, "avg_line_length": 15.785714149475098, "blob_id": "cc0d87ca0496ccba51985b235093c2106f60f596", "content_id": "ae8b4af67595d044e2f0914cdf02211c6fee06c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 236, "license_type": "no_license", "max_line_length": 28, "num_lines": 14, "path": "/测试.py", "repo_name": "haiyanzzz/rbac", "src_encoding": "UTF-8", "text": "#!usr/bin/env python\n# -*- coding:utf-8 -*-\ndic = {\n 1:{\"id\":1,\"name\":\"hds\"},\n 2:{\"id\":2,\"name\":\"dss\"}\n}\nfor item in dic.items():\n print(item)\n\nfor k,v in dic.items():\n print(k,v)\n\nfor item in dic.values():\n print(item)\n\n" }, { "alpha_fraction": 0.627299964427948, "alphanum_fraction": 0.6315789222717285, "avg_line_length": 25.86206817626953, "blob_id": "3dafc09a038793b624b86affd37be08a2c07a649", "content_id": "92270fb668d93c76617044e730419daf1c7c42d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2389, "license_type": "no_license", "max_line_length": 101, "num_lines": 87, "path": "/app01/views.py", "repo_name": "haiyanzzz/rbac", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect, HttpResponse\nfrom django.conf import settings\n# Create your views here.\nfrom rbac import models\nimport re\nfrom rbac.service.init_permission import init_permission\nclass BasePagPermission(object):\n def __init__(self, code_list):\n self.code_list = code_list\n\n def has_add(self):\n if \"add\" in self.code_list:\n return True\n\n def has_del(self):\n if \"del\" in self.code_list:\n return True\n\n def has_edit(self):\n if \"edit\" in self.code_list:\n return True\n\n\ndef login(request):\n if request.method == \"GET\":\n return render(request, \"login.html\")\n else:\n username = request.POST.get(\"username\")\n password = request.POST.get(\"password\")\n user = models.UserInfo.objects.filter(name=username, password=password).first()\n if user:\n init_permission(user, request)\n return redirect(\"/userinfo/\")\n else:\n return render(request, \"login.html\")\n\n\ndef index(request):\n return render(request, \"index.html\")\n\n\ndef userinfo(request):\n pagpermission = BasePagPermission(request.permission_code_url) # 实例化\n # print(\"code......\", request.permission_code_url)\n data_list = [\n {\"id\": 1, \"name\": \"haiyan1\"},\n {\"id\": 2, \"name\": \"haiyan2\"},\n {\"id\": 3, \"name\": \"haiyan3\"},\n {\"id\": 4, \"name\": \"haiyan4\"},\n {\"id\": 5, \"name\": \"haiyan5\"},\n ]\n #print(\"data_list\",data_list)\n #print(\"pagpermission\",pagpermission)\n return render(request, \"userinfo.html\", {\"data_list\": data_list, \"pagpermission\": pagpermission})\n\n\ndef userinfo_add(request):\n if request.method == \"GET\":\n return render(request,\"userinfo_add.html\")\n else:\n return redirect(\"/userinfo/\")\n\n\ndef userinfo_del(request, nid):\n return HttpResponse(\"删除用户\")\n\n\ndef userinfo_edit(request, nid):\n return HttpResponse(\"编辑用户\")\n\n\ndef order(request):\n pagpermission = BasePagPermission(request.permission_code_url) # 实例化\n print(\"code......\", request.permission_code_url)\n return render(request,\"order.html\",{\"pagpermission\":pagpermission})\n\n\ndef order_add(request):\n return HttpResponse(\"添加订单\")\n\n\ndef order_del(request, nid):\n return HttpResponse(\"删除订单\")\n\n\ndef order_edit(request, nid):\n return HttpResponse(\"编辑订单\")\n" }, { "alpha_fraction": 0.5460606217384338, "alphanum_fraction": 0.5624242424964905, "avg_line_length": 34.869564056396484, "blob_id": "458cfcab229da18277632cead33beebd0099eeff", "content_id": "b993c51553aa65ddf7471e5d8e952fbb42c09828", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1694, "license_type": "no_license", "max_line_length": 160, "num_lines": 46, "path": "/rbac/migrations/0002_auto_20171110_1007.py", "repo_name": "haiyanzzz/rbac", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.6 on 2017-11-10 02:07\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('rbac', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Permission',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=32, verbose_name='权限名')),\n ('url', models.CharField(max_length=32, verbose_name='带正则的url')),\n ('codes', models.CharField(max_length=32, verbose_name='代码')),\n ('group', models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to='rbac.Group', verbose_name='所属组')),\n ('menu_group', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='aaa', to='rbac.Permission')),\n ],\n options={\n 'verbose_name_plural': '权限表',\n },\n ),\n migrations.RemoveField(\n model_name='perssion',\n name='group',\n ),\n migrations.RemoveField(\n model_name='role',\n name='perssions',\n ),\n migrations.DeleteModel(\n name='Perssion',\n ),\n migrations.AddField(\n model_name='role',\n name='permissions',\n field=models.ManyToManyField(blank=True, to='rbac.Permission', verbose_name='拥有权限的角色'),\n ),\n ]\n" } ]
4
galselo/polare
https://github.com/galselo/polare
305772e52612600652f8d0c51785437393d23b93
189146d42efb2730a568276847ab86ff85214dc2
707c3d0ab7ab40038bc60c4ccf217d50ffd86527
refs/heads/master
2020-12-14T12:57:49.410338
2020-01-18T15:07:39
2020-01-18T15:07:39
234,752,136
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5644270777702332, "alphanum_fraction": 0.5904279947280884, "avg_line_length": 27.207792282104492, "blob_id": "7d4f943fe45d01b5f4de935d46e813561f68d504", "content_id": "e56a9f66369d77197df66525758e7e128715002c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4346, "license_type": "no_license", "max_line_length": 86, "num_lines": 154, "path": "/poles.py", "repo_name": "galselo/polare", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport pygrib as pg\nimport pickle\nimport os\nfrom tqdm import tqdm\nimport matplotlib\n\n# configure backend\nmatplotlib.use('Agg')\n\n# https://jswhit.github.io/pygrib/docs/\n\ndatafile = \"data.grib\"\nlat_max = 66. # max absolute latitude, map from +/-90 to +/-lat_max\nvmin = -12. # min temperature range, C\nvmax = 12. # max temperature range, C\nncols = 12 # number of columns in the plot\ncolormap = 'coolwarm' # define colormap\nyear_min = 1981 # min year for average (included)\nyear_max = 2010 # max year for average (included)\nhemisphere = \"N\" # N/S\n\n# month names array, 1-based\nmonths = \"# Gen Feb Mar Apr Mag Giu Lug Ago Set Ott Nov Dic\".split(\" \")\n\n# load data\na = pg.open(datafile)\n\n# get time series size\nntot = a.messages\nprint(\"Number of time-series points: %d\" % ntot)\n\n\n# check if pickle for average is present, if so load from pickle\n# NOTE: remove pickles if lat_max changed, or if year_min, year_max changed\nif os.path.isfile(\"avg_N.pickle\"):\n print(\"loading averages from pickle\")\n avg_N = pickle.load(open(\"avg_N.pickle\",\"rb\"))\n avg_S = pickle.load(open(\"avg_S.pickle\",\"rb\"))\nelse:\n\n # loop on time series to compute average\n for i in tqdm(range(ntot)):\n\n # read next descriptor\n b = a.read(1)[0]\n\n # load data both hemispheres\n data_N, lats_N, lons_N = b.data(lat1=lat_max, lat2=90., lon1=0., lon2=359.9)\n data_S, lats_S, lons_S = b.data(lat1=-90., lat2=-lat_max, lon1=0., lon2=359.9)\n\n # get month and year from current dataset info\n msg = \"%s\" % b\n date = msg.split(\" \")[-1]\n year = int(date[:4])\n month = int(date[4:6])\n\n # init average array to zero, one per month\n if i == 0:\n xx_N, yy_N = data_N.shape\n xx_S, yy_S = data_S.shape\n avg_count = 0\n avg_N = np.zeros((12, xx_N, yy_N))\n avg_S = np.zeros((12, xx_S, yy_S))\n\n # sum for the average only if in year range\n if year_min <= year <= year_max:\n avg_N[month-1, :, :] += data_N\n avg_S[month-1, :, :] += data_S\n\n\n # compute average\n avg_count = year_max - year_min + 1\n avg_N /= avg_count\n avg_S /= avg_count\n\n # save to pickles, TODO: single function\n pickle_out = open(\"avg_N.pickle\", \"wb\")\n pickle.dump(avg_N, pickle_out)\n pickle_out.close()\n\n # same as above\n pickle_out = open(\"avg_S.pickle\", \"wb\")\n pickle.dump(avg_S, pickle_out)\n pickle_out.close()\n\nprint(\"Number of rows: %d\" % (ntot // ncols))\n\n# init\nmin_anomaly = 999.\nmax_anomaly = -999.\n\n# define plotting grid\nfig = plt.figure(figsize=(ncols, ntot // ncols))\ngs = gridspec.GridSpec(ntot // ncols, ncols, # width_ratios=np.ones(ncols),\n wspace=0.0, hspace=0.0)\n\n# rewind data\na.seek(0)\n\n# loop to plot\nfor i in tqdm(range(ntot)):\n\n # select grid\n ax = plt.subplot(gs[i // ncols, i % ncols], projection=\"polar\")\n\n # move to next descriptor\n b = a.read(1)[0]\n\n # find year, month for labelling\n msg = \"%s\" % b\n date = msg.split(\" \")[-1]\n year = int(date[:4])\n month = int(date[4:6])\n\n # load data, TODO: use data already loaded\n if hemisphere == \"N\":\n data_N, lats_N, lons_N = b.data(lat1=lat_max, lat2=90., lon1=0., lon2=359.9)\n anomaly = data_N - avg_N[month-1, :, :]\n lons_range = lons_N / 180.*np.pi\n lat_range = (90. - lats_N) / 180. * np.pi\n else:\n data_S, lats_S, lons_S = b.data(lat1=-90., lat2=-lat_max, lon1=0., lon2=359.9)\n anomaly = data_S - avg_S[month-1, :, :]\n lons_range = lons_S / 180.*np.pi\n lat_range = (90. + lats_S) / 180. * np.pi\n\n # store min/max anomaly\n min_anomaly = min(min_anomaly, np.amin(anomaly))\n max_anomaly = max(max_anomaly, np.amax(anomaly))\n\n # do plot\n plt.pcolormesh(lons_range,\n lat_range,\n anomaly,\n vmin=vmin,\n vmax=vmax,\n cmap=colormap)\n\n # remove tick labels\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n\n # remove black circle\n ax.spines['polar'].set_visible(False)\n\nprint(\"Anomaly range:\", min_anomaly, max_anomaly)\nprint(\"Current range:\", vmin, vmax)\n\n# save figure\nplt.tight_layout()\nplt.savefig(\"grid_%s.png\" % hemisphere)\n\n\n" } ]
1
askachen/LeetCode
https://github.com/askachen/LeetCode
099b68481e181c77c4942e650c887bbb986f0785
5549a2afdaa5eb4aba9d7e7e17243eecfa698354
7abd71cafe432b3356c9305a0201294c0ea7bf14
refs/heads/master
2020-03-07T18:23:47.622082
2018-04-02T14:04:05
2018-04-02T14:04:05
127,637,132
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4932795763015747, "alphanum_fraction": 0.5161290168762207, "avg_line_length": 21.1875, "blob_id": "a94252c1d3e27a761c6c2e0919ab4c67c560119e", "content_id": "e845adaf3e4a98323527d2843dd66cc0198b9c0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 744, "license_type": "no_license", "max_line_length": 36, "num_lines": 32, "path": "/Python/LC104.py", "repo_name": "askachen/LeetCode", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node.\r\nclass TreeNode(object):\r\n def __init__(self, x):\r\n self.val = x\r\n self.left = None\r\n self.right = None\r\n\r\nclass Solution(object):\r\n def maxDepth(self, root):\r\n \"\"\"\r\n :type root: TreeNode\r\n :rtype: int\r\n \"\"\"\r\n return self.dig(root)\r\n\r\n def dig(self, node):\r\n if node is None:\r\n return 0\r\n l = self.dig(node.left)\r\n r = self.dig(node.right)\r\n return max(l, r) + 1\r\n \r\n#---------------------------\r\na = Solution()\r\nt1 = TreeNode(3)\r\nt1.left = TreeNode(9)\r\nt1.right = TreeNode(20)\r\nt1.right.left = TreeNode(15)\r\nt1.right.right = TreeNode(7)\r\nt1.right.right.left = TreeNode(4)\r\n\r\nprint a.maxDepth(t1)\r\n\r\n" }, { "alpha_fraction": 0.390595018863678, "alphanum_fraction": 0.4097888767719269, "avg_line_length": 24.71794891357422, "blob_id": "5290514dcafd878a89f41338a2f9a17f1a51808b", "content_id": "ca3acaa0c0c4509fad3ea5e24691da6b84daa689", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1042, "license_type": "no_license", "max_line_length": 74, "num_lines": 39, "path": "/Python/LC283.py", "repo_name": "askachen/LeetCode", "src_encoding": "UTF-8", "text": "import time\r\n\r\nclass Solution(object):\r\n def moveZeroes(self, nums):\r\n \"\"\"\r\n :type nums: List[int]\r\n :rtype: void Do not return anything, modify nums in-place instead.\r\n \"\"\"\r\n \"\"\" # SOLUTION #1\r\n # switch w/ next none zero\r\n length = len(nums)\r\n for i in range(length):\r\n if nums[i] != 0:\r\n continue\r\n for j in range (i+1, length):\r\n if nums[j] != 0:\r\n nums[i], nums[j] = nums[j], 0 # magic!\r\n break\r\n \"\"\"\r\n\r\n # SOLUTION 2\r\n i = 0\r\n length = len(nums)\r\n while (i < length):\r\n if nums[i] is 0:\r\n nums.pop(i)\r\n nums.append(0)\r\n length = length - 1\r\n else:\r\n i = i + 1\r\n \r\n print nums\r\n\r\n#---------------------------\r\na = Solution()\r\nstart_time = time.time()\r\nprint a.moveZeroes([0, 1, 0, 3, 12])\r\nprint a.moveZeroes([0, 0, 1])\r\nprint time.time() - start_time\r\n" }, { "alpha_fraction": 0.38863489031791687, "alphanum_fraction": 0.4506858289241791, "avg_line_length": 30.5744686126709, "blob_id": "5544a666dc97f8e6409ea09f3485eac23f0d6702", "content_id": "a6649a9f86c507d74a4d40e1917a333367683f88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1531, "license_type": "no_license", "max_line_length": 67, "num_lines": 47, "path": "/Python/LC004.py", "repo_name": "askachen/LeetCode", "src_encoding": "UTF-8", "text": "class Solution(object):\r\n def findMedianSortedArrays(self, nums1, nums2):\r\n \"\"\"\r\n :type nums1: List[int]\r\n :type nums2: List[int]\r\n :rtype: float\r\n \"\"\"\r\n len1 = len(nums1)\r\n len2 = len(nums2)\r\n max_len = max(len1, len2)\r\n mid_len = (len1 + len2) // 2\r\n mid_odd = (len1 + len2) % 2\r\n\r\n count = 0\r\n prev = 0\r\n \r\n while (True):\r\n if count >= mid_len:\r\n break;\r\n if not nums1:\r\n prev = nums2.pop(0)\r\n elif not nums2:\r\n prev = nums1.pop(0)\r\n elif nums1[0] > nums2[0]:\r\n prev = nums2.pop(0)\r\n elif nums1[0] < nums2[0]:\r\n prev = nums1.pop(0)\r\n else:\r\n prev = nums1.pop(0)\r\n count = count + 1\r\n\r\n if not nums1:\r\n return nums2[0] if mid_odd > 0 else (nums2[0]+prev)/2.0\r\n elif not nums2:\r\n return nums1[0] if mid_odd > 0 else (nums1[0]+prev)/2.0\r\n elif nums1[0] < nums2[0]:\r\n return nums1[0] if mid_odd > 0 else (nums1[0]+prev)/2.0\r\n elif nums1[0] > nums2[0]:\r\n return nums2[0] if mid_odd > 0 else (nums2[0]+prev)/2.0\r\n else:\r\n return nums1[0] if mid_odd > 0 else (nums1[0]+prev)/2.0\r\n \r\n#---------------------------\r\na = Solution()\r\nprint a.findMedianSortedArrays([1, 3], [2])\r\nprint a.findMedianSortedArrays([1, 2], [3, 4])\r\nprint a.findMedianSortedArrays([1, 2], [1, 2])\r\n" }, { "alpha_fraction": 0.3543955981731415, "alphanum_fraction": 0.37454211711883545, "avg_line_length": 24.634145736694336, "blob_id": "d458d817b11bf8c3fea4412c9758493df2e28833", "content_id": "bc804a7f8d26119394f076d6dde1ba75f634c1f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1092, "license_type": "no_license", "max_line_length": 61, "num_lines": 41, "path": "/Python/LC121.py", "repo_name": "askachen/LeetCode", "src_encoding": "UTF-8", "text": "class Solution(object):\r\n def maxProfit(self, prices):\r\n \"\"\"\r\n :type prices: List[int]\r\n :rtype: int\r\n \"\"\"\r\n\r\n \"\"\"\r\n buy = 0\r\n sell = 0\r\n profit = 0\r\n length = len(prices)\r\n for i in range(0, length-1):\r\n if prices[i+1] <= prices[i]:\r\n continue\r\n \r\n for j in range(i+1, length):\r\n if prices[j] - prices[i] > profit:\r\n buy = i\r\n sell = j\r\n profit = prices[j] - prices[i]\r\n \r\n return profit\r\n \"\"\"\r\n\r\n buy = 0\r\n profit = 0\r\n length = len(prices)\r\n for i in range(1, length):\r\n if prices[i] > prices[i-1]: #up\r\n profit = max(profit, prices[i] - prices[buy])\r\n else : #down\r\n if prices[i] < prices[buy]:\r\n buy = i; \r\n \r\n return profit\r\n\r\n#---------------------------\r\na = Solution()\r\nprint a.maxProfit([7, 1, 5, 3, 6, 4])\r\nprint a.maxProfit([7, 6, 4, 3, 1])\r\n" }, { "alpha_fraction": 0.35169491171836853, "alphanum_fraction": 0.354519784450531, "avg_line_length": 33.400001525878906, "blob_id": "4f58209d4dd4ad9c084bc3ad9d9a8de7315d5c58", "content_id": "9dfcf0566408dd44652df574353a319120193675", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 708, "license_type": "no_license", "max_line_length": 181, "num_lines": 20, "path": "/Python/LC804.py", "repo_name": "askachen/LeetCode", "src_encoding": "UTF-8", "text": "class Solution(object):\r\n def uniqueMorseRepresentations(self, words):\r\n \"\"\"\r\n :type words: List[str]\r\n :rtype: int\r\n \"\"\"\r\n s = set()\r\n MorseCode = [\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"]\r\n for word in words:\r\n key = \"\"\r\n for char in word:\r\n key += MorseCode[ord(char) - ord('a')]\r\n s.add(key)\r\n\r\n return len(s)\r\n \r\n#---------------------------\r\na = Solution()\r\nprint a.uniqueMorseRepresentations([\"gin\", \"zen\", \"gig\", \"msg\"])\r\n#print a.uniqueMorseRepresentations([1,2])\r\n" }, { "alpha_fraction": 0.3701978921890259, "alphanum_fraction": 0.3888242244720459, "avg_line_length": 20.605262756347656, "blob_id": "9d8570b469747b2e2bbf542079dd47180d8bb898", "content_id": "972359da9e466968bb063ac249cb44c2ca5f5e46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 859, "license_type": "no_license", "max_line_length": 45, "num_lines": 38, "path": "/Python/LC136.py", "repo_name": "askachen/LeetCode", "src_encoding": "UTF-8", "text": "import time\r\n\r\nclass Solution(object):\r\n def singleNumber(self, nums):\r\n \"\"\"\r\n :type nums: List[int]\r\n :rtype: int\r\n \"\"\"\r\n\r\n \"\"\"# SOLUTION 1\r\n nums.sort()\r\n i = 0\r\n length = len(nums)\r\n while (i < length - 1):\r\n if nums[i] != nums[i+1]:\r\n return nums[i]\r\n i = i + 2\r\n return nums[length - 1]\r\n \"\"\"\r\n\r\n # SOLUTION 2\r\n s = set()\r\n for num in nums:\r\n if num in s:\r\n s.remove(num)\r\n else:\r\n s.add(num)\r\n return s.pop()\r\n \r\n \"\"\"# SOLUTION 3\r\n return 2 * sum(set(nums)) - sum(nums)\r\n \"\"\"\r\n\r\n#---------------------------\r\na = Solution()\r\nstart_time = time.time()\r\nprint a.singleNumber([2, 1, 7, 1, 3, 2, 7])\r\nprint time.time() - start_time\r\n" }, { "alpha_fraction": 0.472920686006546, "alphanum_fraction": 0.511605441570282, "avg_line_length": 21.953489303588867, "blob_id": "9c75c9e306d878b32e418c3b3d2f536e877b3339", "content_id": "739a0de21fa188b685ddf3c82b901daf17ece824", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1034, "license_type": "no_license", "max_line_length": 48, "num_lines": 43, "path": "/Python/LC617.py", "repo_name": "askachen/LeetCode", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node.\r\nclass TreeNode(object):\r\n def __init__(self, x):\r\n self.val = x\r\n self.left = None\r\n self.right = None\r\n\r\nclass Solution(object):\r\n def mergeTrees(self, t1, t2):\r\n \"\"\"\r\n :type t1: TreeNode\r\n :type t2: TreeNode\r\n :rtype: TreeNode\r\n \"\"\" \r\n return self.merge(t1, t2)\r\n\r\n def merge(self, n1, n2):\r\n if n1 is None and n2 is None:\r\n return None\r\n if n1 is None:\r\n return n2\r\n if n2 is None:\r\n return n1\r\n n = TreeNode(n1.val + n2.val)\r\n n.left = self.merge(n1.left, n2.left)\r\n n.right = self.merge(n1.right, n2.right)\r\n return n\r\n \r\n#---------------------------\r\n \r\na = Solution()\r\nt1 = TreeNode(1)\r\nt1.left = TreeNode(3)\r\nt1.left.left = TreeNode(5)\r\nt1.right = TreeNode(2)\r\n\r\nt2 = TreeNode(2)\r\nt2.left = TreeNode(1)\r\nt2.left.right = TreeNode(4)\r\nt2.right = TreeNode(3)\r\nt2.right.right = TreeNode(7)\r\n\r\nprint a.mergeTrees(t1, t2)\r\n\r\n\r\n" }, { "alpha_fraction": 0.5848101377487183, "alphanum_fraction": 0.5898734331130981, "avg_line_length": 30.91666603088379, "blob_id": "6888a5cd26822f95ffbd32431d2d2114256e6b7d", "content_id": "bc34e1e10113c5a1a70149eecbcdb5477d53ca81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 790, "license_type": "no_license", "max_line_length": 292, "num_lines": 24, "path": "/Python/LC344.py", "repo_name": "askachen/LeetCode", "src_encoding": "UTF-8", "text": "import time\r\n\r\nclass Solution(object):\r\n def reverseString(self, s):\r\n \"\"\"\r\n :type s: str\r\n :rtype: str\r\n \"\"\"\r\n #SOLUTION 1\r\n #return s[::-1]\r\n\r\n #SOLUTION 2\r\n rs = list(\"\")\r\n length = len(s)\r\n for i in range(length):\r\n rs.append(s[length-i-1])\r\n return \"\".join(rs)\r\n\r\n#---------------------------\r\na = Solution()\r\nstart_time = time.time()\r\nprint a.reverseString(\"hello\")\r\nprint a.reverseString(\"Tesla is accelerating the world's transition to sustainable energy, offering the safest, quickest electric cars on the road and integrated energy solutions. Tesla products work together to power your home and charge your electric car with clean energy, day and night.\")\r\nprint time.time() - start_time\r\n" }, { "alpha_fraction": 0.35472577810287476, "alphanum_fraction": 0.37456241250038147, "avg_line_length": 23.969696044921875, "blob_id": "49475e8de206be45db32aeab71f0346b65a5f15e", "content_id": "a695c32351109b9faf1c548a962c266974128b69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 857, "license_type": "no_license", "max_line_length": 59, "num_lines": 33, "path": "/Python/LC122.py", "repo_name": "askachen/LeetCode", "src_encoding": "UTF-8", "text": "class Solution(object):\r\n def maxProfit(self, prices):\r\n \"\"\"\r\n :type prices: List[int]\r\n :rtype: int\r\n \"\"\"\r\n buy = -1\r\n profit = 0\r\n length = len(prices)\r\n \r\n for i in range(length-1):\r\n # go down\r\n if prices[i+1] <= prices[i]:\r\n if buy != -1:\r\n profit += prices[i] - prices[buy] #sell\r\n buy = -1 #empty hand\r\n continue\r\n \r\n # go up\r\n if buy == -1:\r\n buy = i\r\n print 'buy:', buy\r\n\r\n # sell last stock\r\n if buy != -1:\r\n profit += prices[length-1] - prices[buy] #sell\r\n \r\n return profit\r\n\r\n#---------------------------\r\na = Solution()\r\nprint a.maxProfit([7, 1, 5, 3, 6, 4])\r\nprint a.maxProfit([1,2])\r\n" }, { "alpha_fraction": 0.41316527128219604, "alphanum_fraction": 0.4257703125476837, "avg_line_length": 22.620689392089844, "blob_id": "8687196e3dd8ef36e158f9828422d31d3c0a6e04", "content_id": "84adb26f1783f1818792ca4a43b8543ff3efc434", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 714, "license_type": "no_license", "max_line_length": 49, "num_lines": 29, "path": "/Python/LC412.py", "repo_name": "askachen/LeetCode", "src_encoding": "UTF-8", "text": "import time\r\n\r\nclass Solution(object):\r\n def fizzBuzz(self, n):\r\n \"\"\"\r\n :type n: int\r\n :rtype: List[str]\r\n \"\"\"\r\n rs = list(\"\")\r\n for i in range(1, n+1):\r\n three = True if i % 3 == 0 else False\r\n five = True if i % 5 == 0 else False\r\n if three and five:\r\n rs.append(\"FizzBuzz\")\r\n elif three:\r\n rs.append(\"Fizz\")\r\n elif five:\r\n rs.append(\"Buzz\")\r\n else:\r\n rs.append(str(i))\r\n return rs\r\n\r\n\r\n#---------------------------\r\na = Solution()\r\nstart_time = time.time()\r\nprint a.fizzBuzz(15)\r\nprint a.fizzBuzz(1)\r\nprint time.time() - start_time\r\n" }, { "alpha_fraction": 0.40716612339019775, "alphanum_fraction": 0.4299674332141876, "avg_line_length": 25.81818199157715, "blob_id": "32ede3107072e5ea39a58ea74330c37467ff6371", "content_id": "ee8997f7b57658574544af3633e8fd0fe60b7699", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 614, "license_type": "no_license", "max_line_length": 47, "num_lines": 22, "path": "/Python/LC001.py", "repo_name": "askachen/LeetCode", "src_encoding": "UTF-8", "text": "class Solution(object):\r\n def twoSum(self, nums, target):\r\n \"\"\"\r\n :type nums: List[int]\r\n :type target: int\r\n :rtype: List[int]\r\n \"\"\"\r\n length = len(nums)\r\n\r\n my_dict = dict()\r\n for i in range(0, length):\r\n compliment = target - nums[i]\r\n if my_dict.has_key(compliment):\r\n return [my_dict[compliment], i]\r\n else:\r\n my_dict[nums[i]] = i\r\n #print my_dict\r\n\r\n#---------------------------\r\na = Solution()\r\nprint a.twoSum([2, 7, 11, 15], 9)\r\nprint a.twoSum([-1,-2,-3,-4,-5], -8)\r\n\r\n" }, { "alpha_fraction": 0.3214285671710968, "alphanum_fraction": 0.3459821343421936, "avg_line_length": 20.200000762939453, "blob_id": "c14e6cebe27b4d98c33f3dd9a5b87a9df6b4159f", "content_id": "2fdb6d93fbce4694577c93bb7f3c90af71ce250a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 448, "license_type": "no_license", "max_line_length": 36, "num_lines": 20, "path": "/Python/LC461.py", "repo_name": "askachen/LeetCode", "src_encoding": "UTF-8", "text": "class Solution(object):\r\n def hammingDistance(self, x, y):\r\n \"\"\"\r\n :type x: int\r\n :type y: int\r\n :rtype: int\r\n \"\"\"\r\n c = 0 \r\n z = x^y\r\n while (z != 0):\r\n if z & 1:\r\n c = c + 1\r\n z = z >> 1\r\n\r\n return c\r\n \r\n#---------------------------\r\na = Solution()\r\nassert a.hammingDistance(1, 4) == 2\r\nassert a.hammingDistance(3, 1) == 1\r\n\r\n\r\n" } ]
12
nbhatta34/Neplabs
https://github.com/nbhatta34/Neplabs
b834801d57320fc7fbfb8839160f0dd794ac035c
557d60ac1e87e5d4c845bb12a202abde3738a984
9562ea3f36e851ff8b6d8f029a6b3b99b32a3886
refs/heads/main
2023-08-14T16:38:04.982510
2021-06-13T04:58:24
2021-06-13T04:58:24
376,439,048
0
3
null
null
null
null
null
[ { "alpha_fraction": 0.6938775777816772, "alphanum_fraction": 0.6938775777816772, "avg_line_length": 13.142857551574707, "blob_id": "3e96765a6ae64b49a509661731c213a4ec1883d7", "content_id": "65d0c8c73e8b25877710416a6c88576e60b05cdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 98, "license_type": "no_license", "max_line_length": 30, "num_lines": 7, "path": "/index/urls.py", "repo_name": "nbhatta34/Neplabs", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom .import views\n\n\nurlpatterns = [\n path('', views.index_page)\n]" } ]
1
ibrahim-elshar/Dynamic-Airline-Pricing
https://github.com/ibrahim-elshar/Dynamic-Airline-Pricing
21c362fef4ef7cd1536d7273774c9390b535f398
0e880e3821493e12a7b42fa981ab42e8e2c8fd8a
f1fef17779f35970db535c25fe11473fefed871f
refs/heads/main
2023-01-18T21:06:40.916849
2020-11-23T15:54:52
2020-11-23T15:54:52
315,360,107
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5482625365257263, "alphanum_fraction": 0.6081081032752991, "avg_line_length": 17.535715103149414, "blob_id": "f653533d772d85daaac8c2054f894cf0016512b3", "content_id": "fa670a2e6e964cd5b64b4f6120937e01a9f7d644", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 518, "license_type": "permissive", "max_line_length": 42, "num_lines": 28, "path": "/code/plots.py", "repo_name": "ibrahim-elshar/Dynamic-Airline-Pricing", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport matplotlib.pyplot as plt\n\nfrom mpl_toolkits.mplot3d import Axes3D \n\n\nz1 = []\nz2 = []\nfor i in range(m.num_stages):\n for j in range(101):\n z1.append(m.policy[i,j][0])\n z2.append(m.policy[i,j][1])\n \n\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nx = np.arange(12)\ny = np.arange(101)\nX, Y = np.meshgrid(y, x)\nz1 = np.array(z1)\nZ1 = z1.reshape(Y.shape)\nz2 = np.array(z2)\nZ2 = z2.reshape(Y.shape)\n\nax.plot_surface(Y, X, Z1)\nax.plot_surface(Y, X, Z2)" }, { "alpha_fraction": 0.506770670413971, "alphanum_fraction": 0.5245269536972046, "avg_line_length": 33.10397720336914, "blob_id": "1f3736740997e0480c196dd858f42ce5a4b404fb", "content_id": "40a90870dd3e6d35c7acdc9a7f3d2463f165326e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11151, "license_type": "permissive", "max_line_length": 103, "num_lines": 327, "path": "/code/run.py", "repo_name": "ibrahim-elshar/Dynamic-Airline-Pricing", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n'''\nThis file contains all the problem information.\n'''\nimport numpy as np\nfrom scipy.stats import geom, binom, gamma\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import mplot3d\nfrom mpl_toolkits.mplot3d import Axes3D \n\nimport matplotlib\nfont = {'family' : 'normal',\n #'weight' : 'bold',\n 'size' : 13}\n\nmatplotlib.rc('font', **font)\n\nnum_seats_def = 150\nprng = np.random.RandomState(1) #Pseudorandom number generator\ndemand_par_a_def = 60.2#prng.randint(100, size=1).astype(float)\ndemand_par_b_def = 10.0#prng.randint(5, size=1).astype(float)\ndemand_par_c_def = 1.0\nepsilons_support_def = 10\npmin_def = 1.0\n\np=0.3\nprob_eps_rem=(1-geom.cdf(epsilons_support_def+1, p))/(epsilons_support_def*2+1)\nprob_eps = []\nfor i in range(0, epsilons_support_def+1):\n if i ==0:\n prob_eps.append(geom.pmf(i+1, p) + prob_eps_rem)\n else:\n prob_eps.append(geom.pmf(i+1, p)/2 + prob_eps_rem)\n \nprob_eps_rev = prob_eps.copy()\nprob_eps_rev.reverse()\nprob_eps_rev.pop()\nprob_eps_def= prob_eps_rev + prob_eps \n\np_r_min_def = 0.8 * pmin_def\ngamma_def = 0.9\nnum_stages_def = 12\n\nclass MDP():\n '''\n Create problem parameter info, including number of seets,\n and the price-dependent-demand model.\n The demand models are assumed linear in price, of the form,\n D(p) = a - bp. Here a and b iare positive scalars.\n Epsilons are the additive demand noise. The full demand model is \n D_t(p_t) = a - b p_t + epsilon_t. \n '''\n def __init__(self, num_seats = num_seats_def ,\\\n demand_par_a = demand_par_a_def,\\\n demand_par_b = demand_par_b_def,\\\n epsilons_support = epsilons_support_def,\\\n pmin = pmin_def,\\\n prob_eps = prob_eps_def,\\\n p_r_min = p_r_min_def,\\\n gamma = gamma_def,\n num_stages = num_stages_def,\n demand_par_c = demand_par_c_def,\n ):\n \n self.t = 1\n self.num_seats = num_seats\n self.observation = self.num_seats\n self.nS = self.num_seats+1\n self.states = np.arange(self.num_seats+1)\n self.demand_par_a = demand_par_a\n self.demand_par_b = demand_par_b\n self.demand_par_c = demand_par_c\n self.epsilons_support = epsilons_support\n self.epsilons = np.arange(- self.epsilons_support, self.epsilons_support+1)\n self.nE = self.epsilons_support*2 +1\n self.pmin = pmin\n self.p_r_min = p_r_min\n self.pmax = (self.demand_par_a - self.epsilons_support +\\\n self.demand_par_c * self.p_r_min)/ self.demand_par_b\n# self.pmax = (self.demand_par_a - self.epsilons_support)/(self.demand_par_b -self.demand_par_c)\n self.p_r_max = 1*self.pmax\n self.dmin = self.D(self.pmax, self.p_r_min)\n self.dmax = self.D(self.pmin, self.p_r_max)\n self.d_range = self.dmax - self.dmin + 1\n self.prob_eps = prob_eps\n delta = 0.1\n self.p_range = np.round(np.arange(self.pmin,self.pmax+1e-3, delta), 1)\n self.p_r_range = np.round(np.arange(self.p_r_min,self.p_r_max+1e-3, delta), 1)\n self.prob_r_v = np.array([((p_r -0.9*self.p_r_min)/\n (self.p_r_max - 0.8*self.p_r_min))*0.95 for p_r in self.p_r_range])\n self.prob_r_ = dict(zip( self.p_r_range,self.prob_r_v ))\n \n temp=[]\n self.prob_r_dic={}\n n = np.arange(self.num_seats+1)\n for k in n:\n for p in self.p_r_range:\n temp.append(binom.pmf(np.arange(0,k+1),k,self.prob_r_[p]))\n self.prob_r_dic[k,p]= temp[-1]\n self.prob_r = np.array(temp)\n \n self.actions = np.array([(p, p_r) for p in self.p_range\\\n for p_r in self.p_r_range])\n \n self.nA = self.actions.shape[0]\n self.f=np.zeros((self.nS, self.nA, self.nE))\n self.gamma = gamma\n self.num_stages = num_stages_def\n \n def backward_step(self, t, s, p, pr, value):\n ''' Calculates one backward step \n '''\n if t == self.num_stages:\n d = self.D(p,pr)\n# print('d=',d)\n# print('p=',p)\n# print('pr=',pr)\n E = np.tile(self.epsilons,self.num_seats-s+1)\n R = np.arange(self.num_seats-s+1)\n R = np.repeat(R, self.nE)\n S = np.ones(self.nE * (self.num_seats-s+1)) * s\n D = np.ones(self.nE * (self.num_seats-s+1)) * d\n R_prob = np.repeat(self.prob_r_dic[self.num_seats-s,pr], self.nE)\n E_prob = np.tile(np.array(self.prob_eps), self.num_seats-s+1)\n W = np.minimum(S, D + E)\n \n# print(W)\n NS_DIC[s,d,pr] = (S + R - W).astype(int)\n# print(NS_DIC[s,d,pr][np.where(NS_DIC[s,d,pr]==101)])\n V_part = self.gamma * value[t, NS_DIC[s,d,pr]]\n RW_DIC[s,d,pr] = p * W - pr * R \n PROB_DIC[s,d,pr] = R_prob * E_prob\n V = np.dot(PROB_DIC[s,d,pr], RW_DIC[s,d,pr] + V_part)\n else:\n d = self.D(p,pr)\n V_part = self.gamma * value[t, NS_DIC[s,d,pr]]\n V = np.dot(PROB_DIC[s,d,pr], RW_DIC[s,d,pr] + V_part)\n \n return V\n \n def BI(self):\n '''\n Backward Induction\n '''\n global RW_DIC , PROB_DIC, NS_DIC\n RW_DIC = {}\n PROB_DIC = {}\n NS_DIC = {}\n value = np.zeros((self.num_stages+1, self.nS))\n policy = np.zeros((self.num_stages+1, self.nS, 2))\n for t in range(self.num_stages -1, -1, -1):\n print('t=',t)\n for s in self.states:\n v = []\n for a_idx in range(self.nA):\n a = self.actions[a_idx]\n v.append(self.backward_step(t+1, s, a[0], a[1], value))\n vmax = np.max(v)\n idx = np.where(vmax==v)#np.array([i for i,x in enumerate(v) if abs(vmax - x)<10e-8])\n a_max = np.max(self.actions[idx], axis=0)\n# if t==11 :\n# print('v[0]=',v[0],'v[-1]', v[-1],'vmax',vmax,'idx',idx, '\\n')\n \n# idx = np.argmax(v) \n# policy[t,s,:] = [self.P(self.actions[idx][0], self.actions[idx][1]),\n# self.actions[idx][1]]\n policy[t,s,:] = [a_max[0],a_max[1]]\n value[t,s] = vmax\n self.value = value\n self.policy = policy\n \n \n \n \n def D(self, p, pr):\n '''\n Deterministic demand function: returns a demand scalar (rounded to the \n nearest integer) coresponding to the demand for the \n given price input\n '''\n d= np.rint(self.demand_par_a - self.demand_par_b*p + self.demand_par_c*pr).astype(int)\n# d= self.demand_par_a - self.demand_par_b*p\n return d\n \n def P(self, d, pr):\n '''\n Returns a price vector of each station for the given vector demand input\n '''\n p=(self.demand_par_a - d +self.demand_par_c*pr)/self.demand_par_b\n return p \n \n def R(self, k,n, p_r):\n ''' Returns the probability of k out of n cutomers returning their tickets '''\n prob = ((p_r -0.9*self.p_r_min)/(self.p_r_max - 0.8*self.p_r_min))*0.95\n return binom.pmf(k,n,prob)\n \n def step(self,a):\n epsilon = prng.choice(self.epsilons , p=self.prob_eps)\n r = prng.choice(self.num_seats-self.observation+1,\n p=self.prob_r_dic[self.num_seats-self.observation,a[1]])\n self.observation += r - np.minimum(self.observation, a[0] + epsilon)\n self.observation = self.observation.astype(int)\n self.t +=1\n return r\n\n \n def reset(self):\n self.observation = self.num_seats\n self.t = 1\n \n def simulate_policy(self, policy):\n pol =policy.copy()\n times = 5000\n m = np.zeros((times,self.num_stages))\n rp = np.zeros((times,self.num_stages))\n S = np.zeros((times,self.num_stages+1))\n NR = np.zeros((times,self.num_stages+1))\n for i in range(times):\n self.reset()\n print('i=',i)\n p = []\n pr = []\n s = []\n nr = []\n s.append(self.observation)\n nr.append(0)\n while self.t <= int(self.num_stages):\n# print('t=',self.t)\n \n action = pol[self.t-1,int(self.observation)].copy()\n p.append(action[0])\n pr.append(action[1])\n \n action[0] = self.D(action[0],action[1])\n nr.append(self.step(action))\n s.append(self.observation)\n \n m[i,:]=p\n rp[i,:]=pr\n S[i,:]=s\n NR[i,:]=nr\n mean_p =np.mean(m, axis=0) \n mean_pr =np.mean(rp, axis=0) \n mean_s =np.mean(S, axis=0)\n mean_nr = np.mean(NR, axis=0)\n return mean_p , mean_pr, mean_s, mean_nr, m, rp, S, NR \n \nz1 = []\nz2 = []\nfor i in range(m.num_stages):\n for j in range(m.num_seats+1):\n z1.append(m.policy[i,j][0])\n z2.append(m.policy[i,j][1])\n \n\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nx = np.arange(1,m.num_stages+1)\ny = np.arange(m.num_seats+1)\nX, Y = np.meshgrid(y, x)\nz1 = np.array(z1)\nZ1 = z1.reshape(Y.shape)\nz2 = np.array(z2)\nZ2 = z2.reshape(Y.shape)\n\nax.plot_surface(Y, X, Z1, label='$p_t$')\nax.plot_surface(Y, X, Z2, label='$p_{rt}$')\nplt.xlabel('Stage')\nax.set_ylabel('No. of remaining seats')\nax.set_zlabel('Price units')\nax.set_title('Case 2: Policy Plots')\nplt.legend(loc='best') \n# \nfor t in range(m.num_stages):\n plt.plot(m.policy[t,:][:,0], label='$p_'+str(t)+'$')\n plt.plot(m.policy[t,:][:,1], label='$p_r'+str(t)+'$')\nplt.xlabel('Number of remaining seats')\nplt.ylabel('Price unit')\n#plt.title('Policy Plots')\nplt.legend(loc='best') \nplt.show\n#\n#\nmean_p , mean_pr, mean_s, mean_nr, mm, rp, S, NR =m.simulate_policy(m.policy)\n#\n#plt.plot(np.arange(1, len(mean_p)+1),mean_p, label='Mean $p_{t}$')\n#plt.plot(np.arange(1, len(mean_pr)+1),mean_pr, label='Mean $p_{rt}$')\n#plt.xlabel('Stage')\n#plt.ylabel('Price unit')\n#plt.title('Case 2: Average Optimal Price')\n#plt.legend(loc='best')\n##\n##\n#plt.plot(np.arange(0,m.num_seats),m.value[0,:])\n#plt.xlabel('Number of remaining seats')\n#plt.ylabel('Value')\n#plt.title('Case 2: Optimal Value Funtion')\n#plt.legend(loc='best')\n#\n#fig = plt.figure()\n#ax = plt.axes(projection='3d')\n#ax.plot3D(np.arange(m.num_stages), m.states, m.policy[:,:][:,0] )\n#x = []\n#y = []\n#z1 = []\n#z2 = []\n#for t in range(12):\n# for s in range(101):\n# x.append(t)\n# y.append(s)\n# z1.append(m.policy[t,s][0])\n# z2.append(m.policy[t,s][1])\n#\n# \n#fig = plt.figure()\n#ax = plt.axes(projection='3d')\n#ax.scatter(x,y,z1)\n#ax.plot3D(x,y,z1)\n\n#plt.plot(n.value[0,:])\n#plt.plot(m.value[0,:])\n#\n#plt.plot(m.policy[0,:][:,0])\n#plt.plot(m.policy[0,:][:,1])\n#plt.plot(n.policy[0,:][:,0])\n#plt.plot(n.policy[0,:][:,1])" }, { "alpha_fraction": 0.793005645275116, "alphanum_fraction": 0.796786367893219, "avg_line_length": 116.66666412353516, "blob_id": "84e3e11483481e351944cf7a8f698259f69855a8", "content_id": "3759dfc21eaf8d11518759b7d308150a7d0cb0e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1058, "license_type": "permissive", "max_line_length": 365, "num_lines": 9, "path": "/Readme.md", "repo_name": "ibrahim-elshar/Dynamic-Airline-Pricing", "src_encoding": "UTF-8", "text": "# Dynamic Airline Pricing\n\n### IE 3094 MDP Project\n\nWe study the problem of dynamic airline pricing when the customers can return their tickets for a posted price each period. The goal is to optimize the prices to set for flight tickets $p_t$ and the value of returned tickets $p_{rt}$ at the beginning of period t. \nNote that there is a trade-off in setting the prices for the demand. Setting low fares at the beginning of the planning horizon may result in a full booking but may be less profitable than following a strategic policy that sets the price to a certain threshold and then increase the price in each period.\n\nWe formulate the problem as an MDP and solve for the optimal policy.\nOur numerical examples show that, in the case where demand is affected by the flexible returned tickets price (even by a very small amount), the added value of having dynamic returned ticket price is significant and the optimal policy is no longer monotone decreasing in the price. Otherwise, it is always optimal to set the sale price higher than the return price." } ]
3
stepleton/lisa_io
https://github.com/stepleton/lisa_io
067b8f14f32e393f696400ba6aa374623d3c96bb
3503901db1636cf6d00ef1f847a4ed26ff9c5386
857b367949925cfe4aee2fedae3bd266f6fec0fa
refs/heads/master
2021-04-24T12:20:56.151583
2021-02-13T12:39:37
2021-02-13T12:39:37
250,117,475
3
0
null
null
null
null
null
[ { "alpha_fraction": 0.6107382774353027, "alphanum_fraction": 0.623766303062439, "avg_line_length": 42.67241287231445, "blob_id": "44e699ca9c54404a6ac9adfc798e68792651bb25", "content_id": "fcbd3d03f3eb0969e0f974e40b428e2784c92a38", "detected_licenses": [ "LicenseRef-scancode-public-domain", "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2533, "license_type": "permissive", "max_line_length": 79, "num_lines": 58, "path": "/README.md", "repo_name": "stepleton/lisa_io", "src_encoding": "UTF-8", "text": "`lisa_io` -- basic low-level I/O routines for Lisa\n==================================================\n\nThis repository is a library of several standalone assembly language software\ncomponents for accessing various standard input/output devices of the Apple\nLisa computer. \"Standalone\" means that no one component depends on any other.\nThis design aims to make it easier for programmers to use only the components\nthey need for their programs.\n\nAt time of writing, only some of the Lisa's standard I/O facilities, and only\nsome ways of using those facilities, are supported by this library. More may be\nadded as directed by need and spare time.\n\n\nDocumentation\n-------------\n\nBecause people might choose to package individual library components into their\nown software projects, nearly all important documentation---including\nreferences, acknowledgements, and release history---appears within the source\ncode files themselves.\n\n\nLibrary components\n------------------\n\n| Facility | Component | Notes |\n|--------------------------|---------------------------------|--------------|\n| Keyboard and mouse | [`lisa_console_kbmouse.x68`][1] | |\n| Text on the display | [`lisa_console_screen.x68`][2] | Needs a font |\n| Parallel-port hard drive | [`lisa_profile_io.x68`][3] | Relocatable |\n| Serial ports | -- | _TODO_ |\n| Floppy drive(s) | -- | _TODO_ |\n| Other parallel-port I/O | -- | _TODO_ |\n| AppleNet card | -- | _TODO_ |\n\n**Expanded notes:**\n\n- \"Needs a font\": `lisa_console_screen.x68` is mostly a macro library that\n creates display code for 8-pixel-wide fixed-width font data supplied by you.\n The file [`font_Lisa_Console.x68`][4] contains an example of the font data\n the library requires, along with documentation, of course. Additionally, the\n program [`bdf_to_lisa_console_screen_x68.py`][5] can convert some fixed-width\n BDF font files to the necessary format.\n\n[1]: lisa_console_kbmouse.x68\n[2]: lisa_console_screen.x68\n[3]: lisa_profile_io.x68\n[4]: font_Lisa_Console.x68\n[5]: bdf_to_lisa_console_screen_x68.py\n\n\nNobody owns `lisa_io`\n---------------------\n\nThis I/O library and any supporting programs, software libraries, and\ndocumentation distributed alongside it are released into the public domain\nwithout any warranty. See the [LICENSE](LICENSE) file for details.\n" }, { "alpha_fraction": 0.6067739725112915, "alphanum_fraction": 0.6174058318138123, "avg_line_length": 30.8067626953125, "blob_id": "0206bc068d02c3c87ee6e2649468026c31bfe9f2", "content_id": "8b823a931de03bb8e5c296074a1b7f6dcf0948cc", "detected_licenses": [ "LicenseRef-scancode-public-domain", "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6584, "license_type": "permissive", "max_line_length": 80, "num_lines": 207, "path": "/bdf_to_lisa_console_screen_x68.py", "repo_name": "stepleton/lisa_io", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"Convert a fixed-width BDF font to hex constants in Easy68k assembly.\n\nForfeited into the public domain with NO WARRANTY. Read LICENSE for details.\n\nBDF is an old, simple bitmap font file format. Editors for BDF fonts are still\naround, like `gbdfed` (http://sofia.nmsu.edu/~mleisher/Software/gbdfed/) and\n`fony` (http://hukka.ncn.fi/?fony).\n\nThis relatively slapdash script makes some effort to convert a fixed-width BDF\nfont to an Easy68k assembly language file that encodes the font glyphs as\nconstant data, and font metrics as `EQU` constants. If it succeeds, the file\nwill be suitable for use with the macros in `lisa_console_screen.x68`.\n\n\n## Revision history\n\nThis section records the development of this file as part of the `lisa_io`\nlibrary at <http://github.com/stepleton/lisa_io>.\n\n - 25 March 2020: Initial release.\n (Tom Stepleton, [email protected], London)\n\"\"\"\n\n\nimport argparse\nimport itertools\nimport math\nimport re\nimport textwrap\n\n\n# Command-line flags.\nflags = argparse.ArgumentParser(\n description='Convert a fixed-width BDF font to Easy68k hex constants')\n\nflags.add_argument('bdf_file',\n help=('BDF font file to convert; if unspecified, font data '\n 'is read from standard input'),\n type=argparse.FileType('r'),\n default='-')\n\nflags.add_argument('-v', '--vpad',\n help=('How many pixels of vertical padding to put above '\n 'characters.'),\n type=int,\n default=1)\n\nflags.add_argument('-o', '--output',\n help=('Where to write the resulting Easy68k code; if '\n 'unspecified, the code is written to standard out'),\n type=argparse.FileType('w'),\n default='-')\n\nFLAGS = flags.parse_args()\n\n\n# Constants:\nDISP_COLS = 720 # How many columns of pixels in the display?\nDISP_ROWS = 364 # How many rows of pixels in the display?\n\n\n# Argument checking\nif not 0 <= FLAGS.vpad <= DISP_ROWS: raise ValueError(\n f'Argument to --vpad should be between 0 and {DISP_ROWS}')\n\n\n# FSM State 0: Collect the font name.\nfor line in FLAGS.bdf_file:\n line = line.rstrip()\n m = re.match(r'FONT .+', line)\n if m:\n FONT_NAME = ''.join(w.capitalize() for w in m[0].split('-')[2].split(' '))\n break\nelse:\n raise RuntimeError('No FONT record found!')\n\n\n# FSM State 1: Check font is a size we handle. Gather other config info.\nfor line in FLAGS.bdf_file:\n line = line.rstrip()\n m = re.fullmatch(r'FONTBOUNDINGBOX ([-\\d]+) ([-\\d]+) ([-\\d]+) ([-\\d]+)', line)\n if m:\n COLS, ROWS = int(m[1]), int(m[2])\n BL_COL, BL_ROW = int(m[3]), int(m[4]) # BL = bottom left\n break\nelse:\n raise RuntimeError('No FONTBOUNDINGBOX record found!')\n\n\n# Print some top-level data and metrics for this font.\nFLAGS.output.write(textwrap.dedent(f\"\"\"\\\n ; The {FONT_NAME} font.\n kFont{FONT_NAME}GlyphBytes EQU {ROWS * math.ceil(COLS / 8)}\n kFont{FONT_NAME}GlyphCols EQU {COLS}\n kFont{FONT_NAME}GlyphRows EQU {ROWS}\n kFont{FONT_NAME}VertPad EQU {FLAGS.vpad}\n kFont{FONT_NAME}ScreenCols EQU {DISP_COLS // COLS}\n kFont{FONT_NAME}ScreenRows EQU {DISP_ROWS // (ROWS + FLAGS.vpad)}\n\n\n define{FONT_NAME} MACRO\n mFont8 {FONT_NAME},1,9\n ENDM\n\n\n font{FONT_NAME}:\n \"\"\"))\n \n\n\n# All other FSM states are executed sequentially to process character records.\nfor expected_codepoint in itertools.count():\n\n\n # FSM STATE 2: Await STARTCHAR or end-of-file.\n for line in FLAGS.bdf_file:\n line = line.rstrip()\n m = re.match(r'STARTCHAR (.+)', line)\n if m:\n CURR_CHAR = m[1]\n break\n else:\n break # End of file reached.\n\n\n # FSM STATE 3: Await ENCODING. Check it matches the character we expect now.\n for line in FLAGS.bdf_file:\n line = line.rstrip()\n m = re.match(r'ENCODING (\\d+)', line)\n if m:\n if int(m[1]) != expected_codepoint: raise RuntimeError(\n 'Expected character {}, found {}'.format(expected_codepoint, m[1]))\n break\n else:\n raise RuntimeError('No ENCODING record for \"{}\"'.format(CURR_CHAR))\n\n\n # FSM STATE 4: Await BBX. Check fit and alignment to character bounds.\n for line in FLAGS.bdf_file:\n line = line.rstrip()\n m = re.match(r'BBX ([-\\d]+) ([-\\d]+) ([-\\d]+) ([-\\d]+)', line)\n if m:\n # Collect character bounds.\n C_COLS, C_ROWS = int(m[1]), int(m[2])\n C_BL_COL, C_BL_ROW = int(m[3]), int(m[4])\n\n # Check character bounds.\n C_COL_MIN = C_BL_COL - BL_COL\n C_COL_MAX = C_BL_COL - BL_COL + C_COLS\n C_ROW_MIN = C_BL_ROW - BL_ROW\n C_ROW_MAX = C_BL_ROW - BL_ROW + C_ROWS\n if (C_COL_MIN < 0 or C_COL_MAX > COLS or\n C_ROW_MIN < 0 or C_ROW_MAX > ROWS): raise RuntimeError(\n 'Uncontained bbox \"{}\" for \"{}\"'.format(m[0], CURR_CHAR))\n\n # Now, when we read the bitmap, here are the rows we'll fill.\n C_ROW_INDS = list(\n ROWS - 1 - c for c in reversed(range(C_ROW_MIN, C_ROW_MAX)))\n\n break\n else:\n raise RuntimeError('No BBX record for \"{}\"'.format(CURR_CHAR))\n\n\n # FSM STATE 5: Await BITMAP.\n for line in FLAGS.bdf_file:\n if line.rstrip() == 'BITMAP': break\n else:\n raise RuntimeError('No BITMAP header for \"{}\"'.format(CURR_CHAR))\n\n\n # FSM STATE 6: Fill character bitmap.\n BITMAP = [0] * ROWS\n for r in C_ROW_INDS:\n row_bits = int(next(FLAGS.bdf_file), 16)\n BITMAP[r] = row_bits >> C_COL_MIN\n\n\n # FSM STATE 7: Note end of character bitmap.\n if next(FLAGS.bdf_file).rstrip() != 'ENDCHAR': raise RuntimeError(\n 'No ENDCHAR footer for \"{}\"'.format(CURR_CHAR))\n\n\n # Print character data for this character bitmap.\n # Regrettably we can't define per-glyph symbols because Easy68k can't deal\n # with 21st-century lengths.\n print('* glyph' + FONT_NAME + ''.join(\n w.capitalize() for w in CURR_CHAR.split(' ')) + ':', file=FLAGS.output)\n row_byte_text = []\n for row_bits in BITMAP:\n # Print bits as a comment.\n row_bit_chars = '{{:{}b}}'.format(COLS).format(row_bits)\n print(' ;', ''.join(\n '#' if c == '1' else '.' for c in row_bit_chars), file=FLAGS.output)\n\n # Collect bits into hex bytes.\n while row_bit_chars:\n this_byte_chars, row_bit_chars = row_bit_chars[:8], row_bit_chars[8:]\n this_byte_chars += '0' * (8 - len(this_byte_chars))\n row_byte_text.append('${:02X}'.format(int(this_byte_chars, 2)))\n\n print(' DC.B {}'.format(','.join(row_byte_text)), file=FLAGS.output)\n print('', file=FLAGS.output)\n\n\nprint(' ; End of font.', file=FLAGS.output)\n" } ]
2
CaptainLazarus/Trackball-Detection
https://github.com/CaptainLazarus/Trackball-Detection
6e3fb9817b341ce3f66068afdae07a4feae4f17e
1c09e656a304c65f472f5d99fc6bad442b19103e
ee06fd045a2e248768f9db242cf6c44de5c31dfc
refs/heads/master
2022-04-17T19:34:34.443224
2020-04-18T13:53:07
2020-04-18T13:53:07
256,734,271
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5006211400032043, "alphanum_fraction": 0.5440993905067444, "avg_line_length": 26.454545974731445, "blob_id": "43c60a6e552a0542451a65ad12016780f373bbd1", "content_id": "836a180bde8d94686a1d3f480f63bf2e767a2da8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2415, "license_type": "no_license", "max_line_length": 90, "num_lines": 88, "path": "/index.py", "repo_name": "CaptainLazarus/Trackball-Detection", "src_encoding": "UTF-8", "text": "import cv2\nfrom imutils.video import VideoStream\nfrom collections import deque\nimport numpy as np \nimport time\nimport argparse\nimport imutils\n\ndef initArgs():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-v\" , \"--video\" , help=\"Path to video file\")\n parser.add_argument(\"-b\" , \"--buffer\" , help=\"Buffer size\" , type=int , default=64)\n return vars(parser.parse_args())\n\nif __name__ == \"__main__\":\n args = initArgs()\n\n # colorLower = (29, 86, 6)\n # colorUpper = (64, 255, 255)\n\n colorUpper = (110,50,50)\n colorLower = (130,255,255)\n\n pts = deque(maxlen=args[\"buffer\"])\n\n if not args.get(\"video\" , False):\n vs = VideoStream(src=0).start()\n\n else:\n vs = cv2.VideoCapture(args[\"video\"])\n\n # not really necessary\n time.sleep(2.0)\n\n while True:\n frame = vs.read()\n\n # print(frame)\n\n frame = frame[1] if args.get(\"video\",False) else frame\n\n if frame is None:\n break\n\n frame = imutils.resize(frame , width=600)\n blurred = cv2.GaussianBlur(frame , (11,11) , 0)\n hsv = cv2.cvtColor(blurred , cv2.COLOR_BGR2HSV)\n\n mask = cv2.inRange(hsv , colorUpper , colorLower)\n mask = cv2.erode(mask , None , iterations=1)\n mask = cv2.dilate(mask , None , iterations=1)\n\n cnts = cv2.findContours(mask.copy() , cv2.RETR_EXTERNAL , cv2.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n center=None\n\n if len(cnts) > 0:\n c = max(cnts , key = cv2.contourArea)\n ((x,y) , radius) = cv2.minEnclosingCircle(c)\n M = cv2.moments(c)\n center = (int(M['m10']/M['m00']) , int(M['m01']/M['m00']))\n\n if radius > 20:\n cv2.circle(frame , (int(x),int(y)) , int(radius) , (0,255,255) , 2)\n cv2.circle(frame , center , 5 , (0,255,0) , -1)\n\n pts.append(center)\n\n for i in range(1,len(pts)):\n if pts[i-1] is None or pts[i] is None:\n continue\n\n thickness = int(np.sqrt(args[\"buffer\"]/float(i+1)) * 2.5)\n cv2.line(frame , pts[i-1] , pts[i] , (255,0,0) , thickness)\n\n cv2.imshow(\"Frame\" , frame)\n key = cv2.waitKey(1) & 0xFF\n\n if key == ord('q'):\n break\n\n if not args.get('video' , False):\n vs.stop()\n\n else:\n vs.release()\n\n cv2.destroyAllWindows()" } ]
1
Anyulund/computer-vision
https://github.com/Anyulund/computer-vision
5a5bb55d159c492f9d2e905501c58f75847f5842
8fb8309576062621b18d861e68750d1a7c6b7632
f1ab12531483b65f90d75fbb381b90d129a5a9d0
refs/heads/master
2022-11-19T14:25:34.960434
2020-07-24T00:01:38
2020-07-24T00:01:38
257,826,553
1
2
null
null
null
null
null
[ { "alpha_fraction": 0.4878048896789551, "alphanum_fraction": 0.6097561120986938, "avg_line_length": 34.875, "blob_id": "1bac1b89c1a6220a349030fbdeeaad4bdaf9deae", "content_id": "31a52b264ace22a57dd656d643826f2a4ceb1071", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 287, "license_type": "no_license", "max_line_length": 143, "num_lines": 8, "path": "/quiz.py", "repo_name": "Anyulund/computer-vision", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\n\ndata = {'prodID': ['101', '102', '103', '104', '104'],'prodname': ['a', 'b', 'c', 'd', 'e'],'profit': ['2738', '2727', '3497', '7347', '3743']}\ndataframe = pd.DataFrame(data)\ndataframe\ngrouped_data = dataframe.groupby('prodID')\ngrouped_data.max()\n" }, { "alpha_fraction": 0.7123287916183472, "alphanum_fraction": 0.7520196437835693, "avg_line_length": 33.719512939453125, "blob_id": "cd06eccbc46a47065ffe0fba6e17dcc7f9369567", "content_id": "3f730ce10a409c966afefd9c92981fdab740c18c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2847, "license_type": "no_license", "max_line_length": 93, "num_lines": 82, "path": "/Computer Vision I/application_necklace_filter_practice.py", "repo_name": "Anyulund/computer-vision", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.rcParams['figure.figsize'] = (6.0, 6.0)\nmatplotlib.rcParams['image.cmap'] = 'gray'\n\nDATA_PATH ='/home/anna/Desktop/OpenCVcourse/Computer Vision I/'\n\n# Load the Face Image\nfaceImagePath = os.path.join(DATA_PATH,\"images/anna.png\")\nfaceImage = cv2.imread(faceImagePath)\n\n# plt.imshow(faceImage[:,:,::-1]);plt.title(\"Face\")\n# plt.show()\n\n# Load the necklace image with Alpha channel\nnecklaceimagePath = os.path.join(DATA_PATH,\"images/necklace2.png\")\nnecklacePNG = cv2.imread(necklaceimagePath,-1)\n\n#Resize the image to fit over the neck region\nnecklacePNG = cv2.resize(necklacePNG,(400,80))\nprint(\"image Dimension ={}\".format(necklacePNG.shape))\n\n# Separate the Color and alpha channels\nnecklaceBGR = necklacePNG[:,:,0:3]\n\nnecklaceMask1 = necklacePNG[:,:,3]\n'''\n# Display the images for clarity\nplt.figure(figsize=[15,15])\nplt.subplot(121);plt.imshow(necklaceBGR[:,:,::-1]);plt.title('Necklace Color channels');\nplt.subplot(122);plt.imshow(necklaceMask1,cmap = 'gray');plt.title('Necklace Alpha channel');\n# plt.show()\n'''\n# Make a copy\nfaceWithNecklaceNaive = faceImage.copy()\n\n# Replace the eye region with the sunglass image\nfaceWithNecklaceNaive[570:650,230:630]=necklaceBGR\n\n# plt.imshow(faceWithNecklaceNaive[...,::-1])\n# plt.show()\n\n# Make the dimensions of the mask same as the input image.\n# Since Face Image is a 3-channel image, we create a 3 channel image for the mask\nnecklaceMask = cv2.merge((necklaceMask1, necklaceMask1, necklaceMask1))\n\n# Make the values [0,1] since we are using arithmetic operations\nnecklaceMask = np.uint8(necklaceMask/255)\n\n# Make a copy\nfaceWithNecklaceArithmetic = faceImage.copy()\n\n#Get the eye region from the face image\nneckROI = faceWithNecklaceArithmetic[570:650,230:630]\n\n# Use the mask to create the masked neck region\nmaskedNeck = cv2.multiply(neckROI,(1- necklaceMask ))\n\n#Use the mask to create the masked necklace region\nmaskedNecklace = cv2.multiply(necklaceBGR, necklaceMask)\n\n#Conbine the Necklace in the neck region to get the augmented image\nneckRoiFinal = cv2.add(maskedNeck, maskedNecklace)\n'''\n#Display the intermediate results\nplt.figure(figsize=[20,20])\nplt.subplot(131);plt.imshow(maskedNeck[...,::-1]);plt.title(\"Masked Neck Region\")\nplt.subplot(132);plt.imshow(maskedNecklace[...,::-1]);plt.title(\"Masked Necklace Region\")\nplt.subplot(133);plt.imshow(neckRoiFinal[...,::-1]);plt.title(\"Augmented Neck and Necklace\")\n# plt.show()\n'''\n# Replace the neck ROI with the output form the code above\nfaceWithNecklaceArithmetic[570:650,230:630]=neckRoiFinal\n\n#Display the final result\nplt.figure(figsize=[20,20]);\nplt.subplot(121);plt.imshow(faceImage[...,::-1]);plt.title(\"Original Image\")\nplt.subplot(122);plt.imshow(faceWithNecklaceArithmetic[...,::-1]);plt.title(\"With Necklace\")\nplt.show()\n" }, { "alpha_fraction": 0.6477681398391724, "alphanum_fraction": 0.7023482322692871, "avg_line_length": 34.276119232177734, "blob_id": "a295ff5fd14bb7fb558a04630b37fcf115a05d72", "content_id": "455613d3fa410d44f08cd5a1c897c6634c24fc22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4727, "license_type": "no_license", "max_line_length": 117, "num_lines": 134, "path": "/Computer Vision I/basic_math_operations_practice.py", "repo_name": "Anyulund/computer-vision", "src_encoding": "UTF-8", "text": "# Import libraries\nimport cv2\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\n\nDATA_PATH ='/home/anna/Desktop/OpenCVcourse/Computer Vision I/'\n\n# Read image\nimage = cv2.imread(os.path.join(DATA_PATH,\"images/the-tooth-fairy.jpg\"))\n\n#-------------------Datatype Conversion----------------------------------------\nscalingFactor = 1/255.0\n\n#Convert unsigned int to float\nimage = np.float32(image)\n# Scale the values so that they lie between [0,1]\nimage = image*scalingFactor\n\n#Convert back to unsigned int\nimage = image*(1.0/scalingFactor)\nimage = np.uint8(image)\n\n#-------------------Contrast Enhancement----------------------------------------\n'''\ncontrastPercentage = 30\n\n# Multiply with scaling factor to increase contrast\ncontrastHigh = image*(1+contrastPercentage/100)\n\n# Display the outputs\nplt.figure(figsize=[20,20])\nplt.subplot(121);plt.imshow(image[...,::-1]);plt.title(\"Original Image\");\nplt.subplot(122);plt.imshow(contrastHigh[...,::-1]);plt.title(\"High Contrast Image\");\nplt.show()\n\nprint(\"Original Image Datatype : {}\".format(image.dtype))\nprint(\"Contrast Image Datatype : {}\".format(contrastHigh.dtype))\nprint(\"Original Image Highest Pixel Intensity : {}\".format(image.max()))\nprint(\"Contrast Image Highest Pixel Intensity : {}\".format(contrastHigh.max()))\n\n#Clip the values to [0, 255] and change it back to uint8 for display\ncontrastImage = image*(1+contrastPercentage/100)\nclippedContrastImage = np.clip(contrastImage, 0, 255)\ncontrastHighClippedUint8 = np.uint8(clippedContrastImage)\n\n#Convert the range to [0,1] and keep it in float format\ncontrastHighFloat = image*(1+contrastPercentage/100.0)\nmaxValue = image.max()\ncontrastHighNormalized01 = contrastHighFloat/maxValue\n\nplt.figure(figsize=[20,20])\nplt.subplot(131);plt.imshow(image[...,::-1]);plt.title(\"Original Image\");\nplt.subplot(132);plt.imshow(contrastHighClippedUint8[...,::-1]); plt.title(\"Converted back to uint8\");\nplt.subplot(133);plt.imshow(contrastHighNormalized01[...,::-1]);plt.title(\"Normalized float to [0,1]\");\nplt.show()\n'''\n#---------------------Brightness Enhancement------------------------------------\nbrightnessOffset = 50\n'''\n# Add the offset for increasing brightness\nbrightHigh = image + brightnessOffset\n\n# Display the outputs\nplt.figure(figsize=[20,20])\nplt.subplot(121);plt.imshow(image[...,::-1]);plt.title(\"Original Image\");\nplt.subplot(122);plt.imshow(brightHigh[...,::-1]);plt.title(\"High Brightness\");\nplt.show();\n\nprint(\"Original Image Datatype : {}\".format(image.dtype))\nprint(\"Brightness Image Datatype : {}\".format(brightHigh.dtype))\n\nprint(\"Original Image Highest Pixel Intensity : {}\".format(image.max()))\nprint(\"Brightness Image Highest Pixel Intensity : {}\".format(brightHigh.max()))\n\na = np.array([[110,100],[120,130]],dtype='uint8')\nprint(a)\n\n# Add 130 so that the last element encounters overflow\n# print(a+130)\nprint(a-130)\nprint(a+(-130))\n\n# Due to overflow and underflow problems, use OpenCV instead of Numpy to do mathematical operands\nprint(cv2.add(a,130)) #Clipping\n\n# Convert to int32/int64 then clip\na_int32 = np.int32(a)\nb = a_int32+130\nprint(b)\n\nprint(b.clip(0,255))\nb_uint8 = np.uint8(b.clip(0,255))\n\n#Convert to normalized float32/float64\na_float32 = np.float32(a)/255\nb = a_float32 + 130/255\nprint(b)\n\nc = b*255\nprint(\"Output = \\n{}\".format(c))\nprint(\"Clipped output= \\n{}\".format(c.clip(0,255)))\nb_uint8 = np.uint8(c.clip(0,255))\nprint(\"uint8 output() = \\n{}\".format(b_uint8)\n'''\n#-----------------------Final Solution-----------------------------------------\n\nbrightnessOffset = 50\n\n# Add the offset for increasing brightness\nbrightHighOpenCV = cv2.add(image, np.ones(image.shape,dtype='uint8')*brightnessOffset)\n\nbrightHighInt32 = np.int32(image) + brightnessOffset\nbrightHighInt32Clipped = np.clip(brightHighInt32,0,255)\n\n# Display the outputs\nplt.figure(figsize=[20,20])\nplt.subplot(131);plt.imshow(image[...,::-1]);plt.title(\"original Image\");\nplt.subplot(132);plt.imshow(brightHighOpenCV[...,::-1]);plt.title(\"Using cv2.add function\");\nplt.subplot(133);plt.imshow(brightHighInt32Clipped[...,::-1]);plt.title(\"Using numpy and clipping\");\nplt.show()\n\n# Add the offset for increasing brightness\nbrightHighFloat32 = np.float32(image) + brightnessOffset\nbrightHighFloat32NormalizedClipped = np.clip(brightHighFloat32/255,0,1)\n\nbrightHighFloat32ClippedUint8 = np.uint8(brightHighFloat32NormalizedClipped*255)\n\n# Display the outputs\nplt.figure(figsize=[20,20])\nplt.subplot(131);plt.imshow(image[...,::-1]);plt.title(\"original Image\");\nplt.subplot(132);plt.imshow(brightHighFloat32NormalizedClipped[...,::-1]);plt.title(\"Using np.float32 and clipping\");\nplt.subplot(133);plt.imshow(brightHighFloat32ClippedUint8[...,::-1]);plt.title(\"Using int->float->int and clipping\");\nplt.show()\n" }, { "alpha_fraction": 0.7435897588729858, "alphanum_fraction": 0.7435897588729858, "avg_line_length": 39, "blob_id": "be3dc2783fa974d98d7ad6cc6d8d3eced862acdb", "content_id": "5ee4f97e5f041b51b86035347b73fc193bb9aa94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 39, "license_type": "no_license", "max_line_length": 39, "num_lines": 1, "path": "/Computer Vision I/dataPath.py", "repo_name": "Anyulund/computer-vision", "src_encoding": "UTF-8", "text": "DATA_PATH=\"../resource/lib/publicdata/\"" }, { "alpha_fraction": 0.6478020548820496, "alphanum_fraction": 0.701237142086029, "avg_line_length": 31.47008514404297, "blob_id": "6cea27b31205b7953687998bb50896c5d4944fc6", "content_id": "6c25d453dbfa67c5a6cf5a1b6a3ba4982e518b13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3799, "license_type": "no_license", "max_line_length": 99, "num_lines": 117, "path": "/Computer Vision I/basic_image_operations_practice.py", "repo_name": "Anyulund/computer-vision", "src_encoding": "UTF-8", "text": "#Import libraries\nimport cv2\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.rcParams['figure.figsize'] = (6.0, 6.0)\nmatplotlib.rcParams['image.cmap'] = 'gray'\n\nDATA_PATH ='/home/anna/Desktop/OpenCVcourse/Computer Vision I/'\n\n#Read image\nimage = cv2.imread(os.path.join(DATA_PATH,\"images/the-tooth-fairy.jpg\"))\n\n#Let's see what image we are dealing with:\nplt.imshow(image[:,:,::-1])\nplt.show()\n\n#Create a new image by copying the already present image using the copy\nimageCopy = image.copy()\nplt.imshow(imageCopy[...,::-1])\nplt.show()\n'''\n#Create an empty matrix\nemptyMatrix = np.zeros((100,200,3),dtype = 'uint8')\n\nplt.imshow(emptyMatrix)\nplt.show()\n\n#Feel the matrix with white Pixels\n\nemptyMatrix = 255*np.ones((100,200,3),dtype='uint8')\nplt.imshow(emptyMatrix)\nplt.show()\n\n#Create an empty matrix of the same size as original image\nemptyOriginal = 100*np.ones_like(image)\nplt.imshow(emptyOriginal)\nplt.show()\n'''\n# Crop out a rectangle with a face\n# x coordinates = 225 to 375\n# y coordinates = 25 to 150\ncrop = image[25:150,225:375]\nplt.imshow(crop[:,:,::-1])\nplt.show()\n\n#Put crop on the left and the right sides of the original picture\n# Find height and width of the crop\ncropHeight, cropWidth = crop.shape[:2]\n\n# Copy to the left of the face\nimageCopy[25:25+cropHeight,50:50+cropWidth] = crop\n# Copy to the right of the face\nimageCopy[25:25+cropHeight,425:425+cropWidth] = crop\n\n# Display the output\nplt.figure(figsize=[15,15])\nplt.subplot(121);plt.imshow(image[...,::-1]);plt.title(\"Original Image\");\nplt.subplot(122);plt.imshow(imageCopy[...,::-1]);plt.title(\"Output Image\");\nplt.show()\n\n#-------------------Resizing the image---------------------------------------\n\n# -----Method 1 - Specify width and height\n#Set rows and columns\nresizeDownWidth = 400\nresizeDownHeight = 300\nresizedDown = cv2.resize(image,(resizeDownWidth,resizeDownHeight), interpolation= cv2.INTER_LINEAR)\n\n#Mess up with aspect ratio\nresizeUpWidth = 700\nresizeUpHeight = 900\nresizedUp = cv2.resize(image,(resizeUpWidth, resizeUpHeight),interpolation= cv2.INTER_LINEAR)\n\nplt.figure(figsize=[15,15])\nplt.subplot(131);plt.imshow(image[...,::-1]);plt.title(\"Original Image\");\nplt.subplot(132);plt.imshow(resizedDown[...,::-1]);plt.title(\"Resized Down Image\");\nplt.subplot(133);plt.imshow(resizedUp[...,::-1]);plt.title(\"Resized Up Image\");\nplt.show()\n\n#-------Method 2 - Specify scaling factor\n# Scaling Down the image 1.5 times by specifying both scaling factors\nscaleUpX = 1.5\nscaleUpY = 1.5\n\n#Scaling Down the image 0.6 times specifying a single scale factor\nscaleDown = 0.6\n\nscaledDown = cv2.resize(image, None, fx=scaleDown, fy=scaleDown, interpolation = cv2.INTER_LINEAR)\nscaledUp = cv2.resize(image, None, fx=scaleUpX, fy=scaleUpY, interpolation = cv2.INTER_LINEAR)\n\nplt.figure(figsize=[15,15])\nplt.subplot(121);plt.imshow(scaledDown[...,::-1]);plt.title(\"Scaled Down Image\");\nplt.subplot(122);plt.imshow(scaledUp[...,::-1]);plt.title(\"Scaled Up Image\");\nplt.show()\n\n#---------------Creating an Image Mask---------------------------------------\n#------Create a mask using coordinates\n# create an empty image of same size as the original\nmask1 = np.zeros_like(image)\nplt.imshow(mask1)\nplt.show()\n\nmask1[25:150,225:375] = 255\nplt.figure(figsize=[15,15])\nplt.subplot(121);plt.imshow(image[...,::-1]);plt.title(\"Original Image\");\nplt.subplot(122);plt.imshow(mask1[...,::-1]);plt.title(\"Mask\");\nplt.show()\n\n#------Create a mask using pixel intensity or color\n# Picking red as high intensity, green and blue are low intensity - BGR format\nmask2 = cv2.inRange(image,(150,0,0),(255,100,100))\nplt.figure(figsize=[15,15])\nplt.subplot(121);plt.imshow(image[...,::-1]);plt.title(\"Original Image\");\nplt.subplot(122);plt.imshow(mask2[...,::-1]);plt.title(\"Red Masked Image\");\nplt.show()\n" }, { "alpha_fraction": 0.7096773982048035, "alphanum_fraction": 0.7354838848114014, "avg_line_length": 18.375, "blob_id": "0dc79aea5aedcbaa535e7d42aaf1be0c71f02a99", "content_id": "8d1b0458a49dc82bd36bb04d1c7e2ce374c526c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 155, "license_type": "no_license", "max_line_length": 32, "num_lines": 8, "path": "/sampleCode.py", "repo_name": "Anyulund/computer-vision", "src_encoding": "UTF-8", "text": "# Import modules\nimport cv2\n\n# Read image in GrayScale mode\nimage = cv2.imread(\"boy.jpg\", 0)\n\n# Write the grayscale image\ncv2.imwrite(\"boyGray.jpg\",image)\n" }, { "alpha_fraction": 0.648181140422821, "alphanum_fraction": 0.696514904499054, "avg_line_length": 25.924657821655273, "blob_id": "43a700f4ad409b45e31be2e64f324c66d6547c1f", "content_id": "da7915273eb0d6d89c807c8d0c3e6f18299b184d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3931, "license_type": "no_license", "max_line_length": 90, "num_lines": 146, "path": "/Computer Vision I/getting_started_with_images_practice.py", "repo_name": "Anyulund/computer-vision", "src_encoding": "UTF-8", "text": "# Import Libraries\nimport cv2\nimport numpy as np\n#just name data path later in the file for simplicity\nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nmatplotlib.rcParams['figure.figsize'] =(6.0, 6.0)\nmatplotlib.rcParams['image.cmap'] = 'gray'\n\nDATA_PATH ='/home/anna/Desktop/OpenCVcourse/Computer Vision I/'\nimagePath = os.path.join(DATA_PATH,\"images/Hearts.jpg\")\n\n#-------------Part 1 - Image as a Matrix---------------\n'''\n#Read image in Grayscale format\ntestImage = cv2.imread(imagePath,cv2.IMREAD_GRAYSCALE)\n\n#Read image in Color format\n#testImage = cv2.imread(imagePath,cv2.IMREAD_COLOR)\n\n#Read image in Transparent format\n#testImage = cv2.imread(imagePath,cv2.IMREAD_UNCHANGED)\nprint(testImage)\nprint(\"Data type = {}\\n\".format(testImage.dtype))\nprint(\"Object type = {}\\n\".format(type(testImage)))\nprint(\"Image Dimensions = {}\\n.\".format(testImage.shape))\n'''\n\n#--------------Part 2 - Manipulating Pixels ------------\n'''\nprint(testImage[300,600])\n\ntestImage[0,0] = 0\nprint(testImage)\n\ntest_roi = testImage[0:2,0:4]\nprint(\"Original Matrix\\n{}\\n\".format(testImage))\nprint(\"Selected Region\\n{}\\n\".format(test_roi))\n\ntestImage[0:100,0:100] = 111\nprint(\"Modified Matrix\\n{}\\n\".format(testImage))\n\nplt.imshow(testImage)\nplt.colorbar()\nplt.show() # this line makes the plot show when called from command line\n\n#Save image to disk\ncv2.imwrite(\"Banana.jpg\",testImage)\n\n#-------------Part 3 - Color Images ---------------\ncolorimagePath = os.path.join(DATA_PATH,\"images/the-tooth-fairy.jpg\")\n\n#Read the image\nimg = cv2.imread(colorimagePath)\nprint(\"image Dimension ={}\".format(img.shape))\n\n#Display image\nplt.imshow(img)\nplt.title(\"Original Image\")\nplt.show()\n\n#Convert BGR to RGB colorspace\nimgRGB = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\nplt.imshow(imgRGB)\nplt.title(\"BGR to RGB conversion\")\nplt.show()\n\n#Reverse channels\nplt.imshow(img[:,:,::-1])\nplt.title(\"Channel reversal\")\nplt.show()\n\n#Show the channels\nplt.figure(figsize=[20,5])\n\nplt.subplot(131);plt.imshow(img[:,:,0]);plt.title(\"Blue Channel\");\nplt.subplot(132);plt.imshow(img[:,:,1]);plt.title(\"Green Channel\");\nplt.subplot(133);plt.imshow(img[:,:,2]);plt.title(\"Red Channel\");\nplt.show()\n\n#-----------Part 3.1 - Splitting and Merging channels\n\n#Split the image into the B,G,R components\nb,g,r = cv2.split(img)\n\n#Show the channels\nplt.figure(figsize=[20,5])\nplt.subplot(141);plt.imshow(b);plt.title(\"Blue Channel\");\nplt.subplot(142);plt.imshow(g);plt.title(\"Green Channel\");\nplt.subplot(143);plt.imshow(r);plt.title(\"Red Channel\");\n\nplt.show()\n\n#---------Part 3.2 - Manipulating Color Pixels\ntestImage = cv2.imread(imagePath,1)\nplt.imshow(testImage)\nplt.show()\n\n#Access Color Pixel\nprint(testImage[0,0])\n\nplt.figure(figsize=[20,20])\n\n#Yellow = Red + Green\ntestImage[0,0] = (0,255,255)\nplt.subplot(131);plt.imshow(testImage[:,:,::-1])\n\n#Cyan = Blue + Green\ntestImage[0,0] = (255,255,0)\nplt.subplot(132);plt.imshow(testImage[:,:,::-1])\n\n#Magenta = Red + Blue\ntestImage[0,0] = (255,0,255)\nplt.subplot(133);plt.imshow(testImage[:,:,::-1])\n\nplt.show()\n\n#Modify Region of Interest\ntestImage[0:100,0:100] = (255,0,0)\ntestImage[100:200,0:100] = (0,255,0)\ntestImage[200:300,0:100] = (0,0,255)\n\nplt.imshow(testImage[:,:,::-1])\nplt.show()\n'''\n\n#---------Part 3.3 - Images with Alpha Channel\npngimagePath = os.path.join(DATA_PATH,\"images/Polar-Bear.png\")\n\n#Read the image\n#Note that we are passing flag = -1 while reading the image (it will read the image as is)\nimgPNG = cv2.imread(pngimagePath, -1)\nimgRGB = cv2.cvtColor(imgPNG, cv2.COLOR_BGR2RGB)\nplt.imshow(imgRGB)\nplt.show()\nprint(\"image Dimension ={}\".format(imgPNG.shape))\n#First 3 channels will be combined to form BGR image\n#Mask is the alpha channel of the original image\nimgBGR = imgPNG[:,:,0:3]\nimgMask = imgPNG[:,:,3]\nplt.figure(figsize=[15,15])\nplt.subplot(121);plt.imshow(imgBGR[:,:,::-1]);plt.title('Color channels');\nplt.subplot(122);plt.imshow(imgMask,cmap='gray');plt.title('Alpha channel');\nplt.show()\n" } ]
7
dhesse/Blog
https://github.com/dhesse/Blog
87922f837ec63be8eb9b41034c44652c93b5c7fb
a1b3be32906c5da9137bacc5dd2559bf4d78b45d
aa9765d2d6e5c68c10c6199be1ac0126c2bff6c5
refs/heads/master
2020-04-06T05:02:52.564113
2016-11-16T16:27:16
2016-11-16T16:27:16
56,704,346
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5462678670883179, "alphanum_fraction": 0.5493353605270386, "avg_line_length": 31.289257049560547, "blob_id": "e6a894e08db1a0409edfaabf7aa4fad21d7eb030", "content_id": "59bbd748f755ff15e073c8297980c175261c7a25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3912, "license_type": "no_license", "max_line_length": 76, "num_lines": 121, "path": "/format.py", "repo_name": "dhesse/Blog", "src_encoding": "UTF-8", "text": "import argparse\nimport subprocess\nimport bs4\nimport json\nimport os\nimport re\nfrom collections import defaultdict\n\nTEMPLATE = '\\n[code language=\"{0}\"]\\n{1}\\n[/code]\\n'\nCONFIG = {'source_path': ''}\n\ndef absPath(filename):\n return os.path.expanduser(\n os.path.join(CONFIG['source_path'], filename))\n\ndef wordPressCode(fmt):\n def wpFmt(tag):\n return TEMPLATE.format(\n tag['language'],\n fmt(tag))\n return wpFmt\n\n@wordPressCode\ndef extractFromIpynb(t):\n with open(absPath(t['file'])) as jsonFile:\n nb = json.loads(jsonFile.read())\n for i, cell in enumerate(nb['cells']):\n if i == int(t['cell']):\n return \"\".join(cell['source'])\n\ndef insertFile(t):\n if t.has_attr('lines'):\n first, last = (int(i) for i in t['lines'].split('-'))\n else:\n first, last = 1, float('inf')\n with open(absPath(t['file'])) as sourceFile:\n return \"\".join(\n (line for i,line in enumerate(sourceFile, 1)\n if first <= i <= last)).strip()\n\n@wordPressCode\ndef extractFromFile(t):\n return insertFile(t)\n \ndef insertGist(t):\n return \"\\nhttps://gist.github.com/{0}/{1}\\n\".format(\n t['user'], t['id'])\n\ndef extractCode(t):\n code = {'nbcell': extractFromIpynb,\n 'source': extractFromFile,\n 'paste': insertFile,\n 'gist': insertGist}[t['kind']](t)\n return code\n\ndef detectLanguage(tag):\n if (not tag.has_attr('language')) and tag.has_attr('file'):\n extension = os.path.splitext(tag['file'])[1]\n tag['language'] = defaultdict(\n lambda : \"\",\n {'.py': 'python',\n '.sh': 'bash',\n '.R': 'r',\n '.html': 'html',\n '.htm': 'html',\n '.js': 'js',\n '.scala': 'scala',\n '.ipynb': 'python'})[extension]\n\nclass ReSub(object):\n def __init__(self, seek_pattern, match_list):\n self.seek_pattern = seek_pattern\n self.match_gen = (i for i in match_list)\n def _insert(self, _):\n return self.match_gen.next()\n def __call__(self, text):\n return re.sub(self.seek_pattern, self._insert, text)\n \nclass HandleLaTeX(object):\n def __init__(self):\n self.latex_groups = []\n self.pattern = \"insertLatex\"\n def _remember(self, match):\n self.latex_groups.append(\n re.sub(\"^\\$\", \"$latex \", match.group(0)))\n return self.pattern\n def __call__(self, text):\n return re.sub(\"(\\$.*?\\$)\", self._remember, text)\n def get_post(self):\n return ReSub(self.pattern, self.latex_groups)\n \nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"markdown_file\",\n help=\"The input file, in markdown.\")\n parser.add_argument(\"-p\", \"--source_path\",\n default=\"\",\n help=\"The path for source code.\")\n args = parser.parse_args()\n CONFIG['source_path'] = args.source_path\n with open(args.markdown_file) as input_file:\n input_file_contents = input_file.read()\n pre_filters = [HandleLaTeX()]\n for f in pre_filters:\n input_file_contents = f(input_file_contents)\n post_filters = [f.get_post() for f in pre_filters]\n pandoc_output = subprocess.Popen(\n [\"pandoc\", \"-t\", \"html\"],\n stdout=subprocess.PIPE,\n stdin=subprocess.PIPE).communicate(input=input_file_contents)[0]\n html = bs4.BeautifulSoup(pandoc_output, \"html.parser\")\n formatargs = []\n for i, r in enumerate(html.find_all('insert')):\n detectLanguage(r)\n r.string = \"{{{0}}}\".format(i)\n formatargs.append(extractCode(r))\n r.unwrap()\n result = unicode(html).format(*formatargs)\n for f in post_filters:\n result = f(result)\n print result\n \n" }, { "alpha_fraction": 0.7107217311859131, "alphanum_fraction": 0.7423522472381592, "avg_line_length": 44.80952453613281, "blob_id": "e1cba6eba6a228795c3317d78f1f10e1e0353be5", "content_id": "7fac99caa282a4476f08b222fbdf97e0c372fceb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6734, "license_type": "no_license", "max_line_length": 149, "num_lines": 147, "path": "/2016-07-10.md", "repo_name": "dhesse/Blog", "src_encoding": "UTF-8", "text": "% What Does It Take To Win The Euro 2016?\n\n**A tale of goals, passes, web scraping, and being the only German who\nis not into Soccer.**\n\nUsually, I'm a proud member of the small club of Germans who don't\ncare too much for soccer and make up for this by at least following\nthe national selection on big competitions, like this year's\n[Euro][euro]. After Germany has been\n[kicked out by the host France in the semi-finals][kickedout], it's\ntime for some soul searching and many a discussion was had about\nwhether the German style of playing (focusing on ball control and\nshort, safe passing) is as good as it seemed in the aftermath of the\nlast world cup, won by Germany.\n\nNot being the biggest Soccer enthusiast, I don't feel to qualified to\nenter this discussion, but maybe we can find interesting data we can\ncrunch to give us some insights.\n\n# Web Scraping 201 - What About JavaScript?\n\nIt's about time I talked about [web scraping][scraping]. Writing a\nspider that follows links and extracts useful information is an\nimportant way for any data scientist worth his or her salt to gather\ninteresting data. Now there are very nice frameworks around for this\ntask. If you like Python, you should look into\n[scrapy][scrapy]. Scala/Java users have with [JSoup][jsoup] a powerful\ntool at their hands to extract entities from HTML pages (similar to\n[beautifulsoup][bs4] for Python).\n\nAn important thing to keep in mind is that you should have a look at\nthe `robots.txt` page of the URL you want to extract information from\nto make sure they are okay with your spider grabbing data from their\nservers. Luckily, the UEFA does allow crawling their statistics on the\nEuro 2016 at the time of writing.\n\nThere is one more possible challenge though. Many pages are not\nstatic, but built at the time of viewing using JavaScript. This means\nthat we cannot simply use a tool like [scrapy][scrapy] to extract data\nsince it doesn't execute JavaScript. I had to write a set of Scala\nscripts using [Selenium][selenium] to get around this\nproblem. Selenium is actually a web testing tool, but very suitable\nfor jobs like this. Go check it out and play around with it. It's\nreally easy to use and a very handy tool to know.\n\n<insert kind=\"source\" file=\"example.scala\" />\n\n# Do Passes Matter?\n\nAfter spending some time extracting the data, let's look at some\nnumbers and graphs. And models, of course. UEFA provides us with lots\nof interesting information on players and teams, but in this post I'll\nfocus on two main indicators: Passes and attempts to score. Now just\ncomparing the total number of passes and attempts per team should take\nthe number of games into account as well as if or not the game was\ndecided in overtime (which is in turn only applicable after the group\nstage). As for passes, UEFA has good numbers on all teams that made it\npast the group stages. So let's look at those.\n\n<img class=\" wp-image-1637 aligncenter\" src=\"https://dataadventuresdotcom.files.wordpress.com/2016/07/apm.png\" alt=\"APM\" width=\"803\" height=\"483\" />\n\nThe bar chart above shows the passes per minute (PPM) per team,\naveraged over the players' individual PPM. The color indicates which\nis the highest stage that the team reached. Now this is an interesting\nplot, as it shows that there is virtually no correlation between if a\nteam passes the ball around a lot and when it was kicked out.\n\nBut what about goals? You can pass the ball around all you want, but\nyou won't win unless you score some goals. So let's repeat the last\nplot, but with the attempts to score per minute (APM) instead of the\nPPM.\n\n<img class=\" wp-image-1637 aligncenter\" src=\"https://dataadventuresdotcom.files.wordpress.com/2016/07/ppm.png\" alt=\"PPM\" width=\"803\" height=\"483\" />\n\nDue to some inconsistencies in the data, we now also have some teams\nthat were kicked out in the group stage in our plot, most notably at\nfirst and next to last position. The teams of Austria and Turkey, both\nkicked out at the group stage, have the highest and next to lowest\nnumber (only Italy had less attempts per minute) of APMs.\n\nI guess this is what makes soccer exciting. You can play very\nsuccessful with a number of strategies, passing a lot *or* very\nlittle, making many *or* few attempts to score. To some degree it's\nrandomness that keeps us at the edge of our seats.\n\n# Nerd Zone: Ordinal Logistic Regression\n\nSometimes it's just not enough to look at bar charts, but you have to\nquantify what you see. And since Germans take their soccer serious, I\nhave all intention to back my ramblings with some numbers.\n\nLet's make sure that there is really not connection between APM, PPM,\nand at what stage you get kicked out. In order to do so, we use\n[Ordinal Logistic Regression][olr], using the [MASS][MASS] R package\n(check the tutorial [here][rolr]). The model we build using gives as\nexpected a really bad [AIC][AIC] score.\n\n Call:\n polr(formula = Stage ~ AvgPPM + AvgAPM, data = features)\n \n Coefficients:\n Value Std. Error t value\n AvgPPM 3.288 2.635 1.2479\n AvgAPM -22.803 50.428 -0.4522\n \n Intercepts:\n Value Std. Error t value \n Group stage|Quarter-finals -0.3130 1.3682 -0.2288\n Quarter-finals|Round of 16 0.5285 1.3426 0.3936\n Round of 16|Semi-finals 2.3271 1.4676 1.5856\n \n Residual Deviance: 57.45138 \n AIC: 67.45138\n\nSo what does the null model say?\n\n Call:\n polr(formula = Stage ~ 1, data = features)\n \n No coefficients\n \n Intercepts:\n Value Std. Error t value\n Group stage|Quarter-finals -0.9808 0.4787 -2.0489\n Quarter-finals|Round of 16 -0.1823 0.4282 -0.4257\n Round of 16|Semi-finals 1.5040 0.5528 2.7209\n \n Residual Deviance: 59.05298 \n AIC: 65.05298 \n\nWe see that the features basically don't change the AIC score, as we\nexpected. So we can conclude that our PPM and APM values don't\ninfluence a team's success and all that is left is to wish both France\nand Portugal the best of luck for tonight's final. May the best team\nwin!\n\n[euro]: http://www.uefa.com/uefaeuro/index.html\n[kickedout]: http://www.dailymail.co.uk/sport/football/article-3679487/Germany-0-2-France-Antoine-Griezmann-s-double-sees-hosts-Euro-2016-final.html\n[scraping]: https://en.wikipedia.org/wiki/Web_scraping\n[scrapy]: http://scrapy.org/\n[jsoup]: https://jsoup.org/\n[selenium]: http://www.seleniumhq.org/\n[bs4]: https://www.crummy.com/software/BeautifulSoup/\n[olr]: https://en.wikipedia.org/wiki/Ordinal_regression\n[rolr]: http://www.ats.ucla.edu/stat/r/dae/ologit.htm\n[MASS]: https://cran.r-project.org/web/packages/MASS/index.html\n[AIC]: https://en.wikipedia.org/wiki/Akaike_information_criterion\n" }, { "alpha_fraction": 0.7598494291305542, "alphanum_fraction": 0.7688832879066467, "avg_line_length": 50.75324630737305, "blob_id": "501eff618fc9d0b041859d874b9f53c8ba84a78e", "content_id": "5e924b101814e128aa967a3934aebecb033d5cc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3985, "license_type": "no_license", "max_line_length": 106, "num_lines": 77, "path": "/2016-04-26.md", "repo_name": "dhesse/Blog", "src_encoding": "UTF-8", "text": "% Group Conflicts in Africa, Spark Edition\n\nIn the [last][rgrouping] [two][last] posts I did some exploration of a\nfascinating data set published by the *Armed Conflict Location & Event\nData Project* ([ACLED][acled]). You can find the code I used on\n[github][blog-code-github]. The ACLED data lists incidents in armed\nconflicts all over Africa and some countries in South and Southeast\nAsia, since 1997 and in great detail.\n\nAt first, we used [R][R] and [ggmap][ggmap] to plot the recorded\nincidents on a map. These can be *protests* or *riots*, but also\noutbursts of violence with many *fatalities*. To get a better overview\nwe then used [hierarchical clustering][hclust-wiki] to group those\nconflicts temporally and spatially. Something like this might be of\nvalue for a NGO or a news outlet in need a system that automatically\nassigns a reported incident to a conflict without human interference.\n\nWhile the clustering worked well, we had to play a little trick that\nyou might have noticed if you read the last post. In our code, we had\nthe following transformations applied to our data.\n\n<insert kind='source' file='clustering.R' lines='7-12'>\n\nThere, in line 2 you have it. We only considered incidents with more\nthan 10 fatalities. This might make sense if one is only interested in\n*armed* conflicts, but we did it only because of limited memory on the\ncomputer the code ran on. Time to bring out the *big(ish) guns*.\n\n[Apache Spark][spark] is currently my favorite big data tool. You can\nrun it on your laptop, on a small cluster, or on a warehouse. All with\nthe same code, on the same interface, with the same language (today,\nwe'll do [Python][python]). And it's *lightning fast*. The first step\nis to read the data into Spark. The ACLED set has some extra newlines\nin the description column, which is why we have to jump through some\nhoops (`csv` files usually use newlines as separator between\nrecords).\n\n<insert kind='nbcell' file='Cluster.ipynb' cell='1'>\n\nNow we're ready to cluster. Let's look at the clustering methods Spark\nsupports. In the [documentation][spark-clustering] of MLLib, Spark's\npreferred machine learning library, we find a number of choices. For\nsimplicity, let's stick to [k-means][k-means]. The advantage of\nk-means is that it's a very *simple* but *fast* algorithm, but we have\nto specify the number of clusters we want to find. This can be bad for\nsome applications, but since this is an educational post, let's go for\nit. Remember that we have to *scale* our inputs as discussed\n[last time][rgrouping], luckily Spark has a class that does just that\nfor us.\n\n<insert kind='nbcell' file='Cluster.ipynb' cell='2'>\n\nTo plot the data on a map, we use the amazing [basemap][basemap]\npackage in python. You can check the [notebook][notebook] I used for\nthis post if you are interested in the gory details. The result looks\nlike this.\n\n![](https://dataadventuresdotcom.files.wordpress.com/2016/04/africa15.png)\n\nAgain, the clustering looks sensible. A news outlet that wants to\nautomatically assign conflict identifiers to incident reports might\njust use a model like this. Next time, I would like to dive a bit\ndeeper into the data set and explore the individual clusters.\n\n[last]: http://data-adventures.com/2016/04/23/armed-conflicts-in-africa-illustrated-in-r\n[rgrouping]: https://data-adventures.com/2016/04/24/data-science-for-a-cause-grouping-conflicts-in-africa/\n[acled]: http://www.acleddata.com/\n[blog-code-github]: https://github.com/dhesse/BlogCode\n[spark-clustering]: http://spark.apache.org/docs/latest/mllib-clustering.html\n[notebook]: https://github.com/dhesse/BlogCode/blob/master/conflicts/Cluster.ipynb\n[hclust-wiki]: https://en.wikipedia.org/wiki/Hierarchical_clustering\n[R]: https://r-project.org\n[ggmap]: https://cran.r-project.org/web/packages/ggmap/index.html\n[spark]: http://spark.apache.org/\n[python]: https://www.python.org/\n[k-means]: https://en.wikipedia.org/wiki/K-means_clustering\n[basemap]: http://matplotlib.org/basemap/\n" }, { "alpha_fraction": 0.5494368076324463, "alphanum_fraction": 0.5644555687904358, "avg_line_length": 30.959999084472656, "blob_id": "626b4a2ddfc25138a872d2f7f47ac1d0c8b2ae77", "content_id": "19b6af34c98e8025a03e6276067e04463fea0fa2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 799, "license_type": "no_license", "max_line_length": 88, "num_lines": 25, "path": "/wpmath.py", "repo_name": "dhesse/Blog", "src_encoding": "UTF-8", "text": "from pandocfilters import toJSONFilter, Str, RawBlock\nimport re\nfrom itertools import islice\n\ndef getLines(attrs):\n lines_re = re.match(\"(\\d+)-(\\d+)\", attrs.get('lines', \"\"))\n if lines_re:\n return (int(lines_re.group(1)),\n int(lines_re.group(2)) + 1)\n return (0, None)\n\ndef wpmath(key, value, format, meta):\n if key == \"Math\":\n return Str(\"$LaTeX \" + value[1] + \"$\")\n if key == \"CodeBlock\":\n language = value[0][1]\n attrs = dict(value[0][2])\n if 'fromFile' in attrs:\n with open(attrs['fromFile']) as codeFile:\n return RawBlock(value[0], '\\n'.join(islice(codeFile, *getLines(attrs))))\n #print value\n #return RawBlock(value[0], str(value[1]))\n\nif __name__ == \"__main__\":\n toJSONFilter(wpmath)\n" }, { "alpha_fraction": 0.7522720694541931, "alphanum_fraction": 0.7654646635055542, "avg_line_length": 40.59756088256836, "blob_id": "985c94860d0f072c598498157cc2e31648655888", "content_id": "00e95f35ab906488b2ee8bace8937c0b1279ed55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3411, "license_type": "no_license", "max_line_length": 97, "num_lines": 82, "path": "/2016-06-29.md", "repo_name": "dhesse/Blog", "src_encoding": "UTF-8", "text": "% IoT 101 - Part 3: Dynamic Web Pages with AngularJS, Kafka and Flask\n\nIn the [last][iot1] [two episodes][iot2], we talked about creating a\nsimple IoT-like service, using [Kafka][kafka] to produce and consume\nmessages in real-time and [Flask][flask] to create a REST API to allow\nus producing messages via HTTP and consume them using server-sent\nevents ([SSE][sse]). [In the end][iot2], we managed to get our\nmessages pushed to clients using SSE, and now it is time to have a\ncloser look at the client code.\n\n# SSE and Javascript\n\nAssume you have a webpage that should react on events sent by your web\nserver. The first thing you'll have to do is add an *event\nlistener*. This is really easy and takes only a few lines of\nJavascript code.\n\n<insert kind=\"source\" file=\"listener.js\">\n\nAdding this into an HTML document should be enough to see messages you\nproduce with CURL, like we described [last time][iot2], logged to your\nbrowser's console. But this is not very exciting. You know what would\nbe exciting? If your webpage got *updated* automatically with new\nmessages. Enter Angular.\n\n# AngularJS\n\n[AngularJS][ng] is a complete, Javascript based implementation of the\n[model-view-controller][mvc] pattern, which is nerd-speak for saying\nthat it helps you write dynamic HTML pages with minimal effort and\nmaximal effect, separating completely the presentation of the user\ninterface from the program logic. Read the Wikipedia article linked\nabove if you're interested in why this is such a good idea.\n\nLet's dive right in. Assume you have a list of things that you want to\ndisplay on a web page, but maybe you want to update that list by, say,\nSSE in the future and hence don't want to hard-code it in HTML. How\nwould you go about it? Well, you write a Javascript file thusly.\n\n<insert kind=\"source\" file=\"app1.js\">\n\nThis tells Angular that we have an app called \"myApp\", and define the\nthe underlying controller. In the controller's scope, we have a single\nvariable, our list of messages. In our web page, we now have to load\nAngular, but instead of downloading it, we use an easier path prepared\nfor us by the kind people at [Google][glibs] who host a number of\npopular libraries for us. Our web page looks like this.\n\n<insert kind=\"source\" file=\"index.html\">\n\nIf everything went right, you should now see a list like this in your\nbrowser.\n\n- One\n- Two\n- Three\n\n# Putting Everything Together\n\nLet's put all the moving parts together. Our modified app will add the\nmessages sent by the server to the list and thus dynamically update\nthe web page with server-sent events.\n\n<insert kind=\"source\" file=\"app2.js\">\n\nKeep in mind that by default, the base URL of your SSE and your\nwebpage must be identical, so you'll have to host your static HTML and\nJavascript files through Flask or your web server should you use one\n(which is a good idea, at least in a production environment).\n\nI hope you've enjoyed this episode and stay tuned for the next data\nadventure.\n\n\n[iot1]: https://data-adventures.com/2016/06/22/iot-101-part-2-kafka-flask-and-server-sent-events/\n[iot2]: https://data-adventures.com/2016/06/20/iot-101-flask-and-kafka/\n[ng]: http://angularjs.org\n[mvc]: https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\n[glibs]: https://developers.google.com/speed/libraries/\n[kafka]: http://kafka.apache.org/\n[flask]: http://flask.pocoo.org/\n[sse]: https://en.wikipedia.org/wiki/Server-sent_events\n" }, { "alpha_fraction": 0.5061728358268738, "alphanum_fraction": 0.5061728358268738, "avg_line_length": 39.5, "blob_id": "1b8d411f6b73ef5c71751dca732fcfb5405dfe89", "content_id": "dbe4221b53e1cdcf918670319f8464c45a07ef31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 81, "license_type": "no_license", "max_line_length": 60, "num_lines": 2, "path": "/cl.sh", "repo_name": "dhesse/Blog", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\nfind . -name \\*.md | xargs grep -h '^\\[.*\\]: ' | sort | uniq\n" }, { "alpha_fraction": 0.7706909775733948, "alphanum_fraction": 0.7801822423934937, "avg_line_length": 48.69811248779297, "blob_id": "daf781927a91c8440b084d53ca462ff40c01bca5", "content_id": "1a1b8f90f216f00d1707f983a729708275b428e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2634, "license_type": "no_license", "max_line_length": 88, "num_lines": 53, "path": "/2016-04-24.md", "repo_name": "dhesse/Blog", "src_encoding": "UTF-8", "text": "% Data Science For a Cause, Grouping Conflicts in Africa\n\n[Last time][last] we started looking at a fascinating data set from\nthe *Armed Conflict Location & Event Data Project* ([ACLED][acled]),\nthat lists incidents in armed conflicts all over Africa and some\ncountries in South and Southeast Asia, since 1997 and in great\ndetail. Make sure you have a look, if you like you can download my\ncode [from github][blog-code-github] in order to get you started.\n\nWe will keep on using [R][R], with the excellent [dplyr][dplyr]\npackage for data wrangling and [ggmap][ggmap] for plotting maps. What\nwe want to do today is finding groups of incidents that are\ngeographically close together, as well as occurring at a similar\ntime. This is a quite straight-forward\n[unsupervised learning][unsupervised] problem in the class of\n[clustering][clustering]. We will in particular use the\n[hierarchical clustering][hclust-wiki] method, implemented in R in the\n[hclust][hclust] function.\n\nBefore we can apply it though, we should *normalize* our data. This is\nalways wise if you apply methods like clustering where you compare\nvariables measured in different ways. We can convert our date column\ninto a numerical value that is needed as input for the method in\ncharge of calculating the distance matrix (which in turn is input to\nthe clustering method) simply by calling\n\n<insert kind='source' file='clustering.R' lines='11-11'>\n\nNow if we didn't use `scale` scale function to remove the mean and\nbring the standard deviation to one, we would run into trouble when we\nstart comparing this column with latitude and longitude, which are\nmeasured in completely different units. Our code looks like this:\n\n<insert kind='source' file='clustering.R' lines='1-30'>\n\nNow let's look at the output.\n\n![Clusters, map data by Google](\nhttps://dataadventuresdotcom.files.wordpress.com/2016/04/africa_clusters.png)\n\nIt seems like the clustering algorithm does do a sensible job. Stay\ntuned for more in-depth analysis on the clusters.\n\n[last]: http://data-adventures.com/2016/04/23/armed-conflicts-in-africa-illustrated-in-r\n[acled]: http://www.acleddata.com/\n[ggmap]: https://cran.r-project.org/web/packages/ggmap/index.html\n[dplyr]: https://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html\n[blog-code-github]: https://github.com/dhesse/BlogCode\n[R]: https://r-project.org\n[hclust]: https://stat.ethz.ch/R-manual/R-devel/library/stats/html/hclust.html\n[hclust-wiki]: https://en.wikipedia.org/wiki/Hierarchical_clustering\n[unsupervised]: https://en.wikipedia.org/wiki/Unsupervised_learning\n[clustering]: https://en.wikipedia.org/wiki/Cluster_analysis\n" }, { "alpha_fraction": 0.7503015398979187, "alphanum_fraction": 0.7555287480354309, "avg_line_length": 39.77049255371094, "blob_id": "4df7838af5632ab16cd6cc75e8ef680a6b659056", "content_id": "7af2f02ecfbe87d8c54de37a1e1fd7e45ad53006", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2487, "license_type": "no_license", "max_line_length": 70, "num_lines": 61, "path": "/2016-06-22.md", "repo_name": "dhesse/Blog", "src_encoding": "UTF-8", "text": "% IoT 101 - Part 2: Kafka, Flask, and Server-Sent Events\n\nIn the [last episode][last], we wrote some simple code to produce\nmessages in [Apache Kafka][kafka] via a [RESTful API][rest],\nimplemented using the amazing [Flask][flask] framework. If you have\nfollowed the [post][last] and written some code yourself, you might\nnow want to put it into action. We assume you have Kafka fired up and\nwritten and started up a simple Flask app as described\n[before][last].\n\n## Testing Client\n\nTo give our setup a test drive, let's write a simple Kafka consumer in\n[Python][python] using the [pykafka][pykafka] package. For the sake of\nsimplicity, let's just consume all messages in the topic named \"test\",\nlike so:\n\n<insert kind=\"source\" file=\"client.py\" />\n\nRunning this script should print out all messages that get written to\nour test topic until the script is terminated. You can also use the\nconsole consumer (and producer) included with Kafka, but let's in the\nspirit of DIY not do that.\n\n## Producing Messages\n\nTo produce messages, we could write another Python script using\n[pykafka][pykafka], but this is not what we want. We wrote our Flask\napp such that we can produce messages using [http][http]. And being\ntrue hipsters, we will do it *old school*, using the console and\n[cURL][curl].\n\n<insert kind=\"source\" file=\"produce.sh\" />\n\nThis should trigger the output `Message: {{\"Hello\": \"World\"}}` from\nyour client script.\n\n## Consuming With Flask\n\nNow let's do something more exciting than writing messages to the\n*console*. Let's spit them out as\n[HTML5 server-sent events][sse]. This way we'll be able to consume\nthem later in a webpage using [javascript][js] and ultimately create a\nlive dashboard. This could be used to monitor temperatures of a\nmachine or something like that. For this we need to add one more route\nto our Flask app.\n\n<insert kind=\"source\" file=\"routes.py\" lines=\"21-27\" />\n\nI'll give you some time now to implement this and check in with you\nnext time when we'll write some javascript to consume our messages.\n\n[last]: https://wordpress.com/post/data-adventures.com/1622\n[kafka]: http://kafka.apache.org/\n[js]: https://en.wikipedia.org/wiki/JavaScript\n[rest]: https://en.wikipedia.org/wiki/Representational_state_transfer\n[flask]: http://flask.pocoo.org/\n[pykafka]: https://github.com/Parsely/pykafka\n[http]: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol\n[curl]: https://en.wikipedia.org/wiki/CURL\n[sse]: https://en.wikipedia.org/wiki/Server-sent_events\n" }, { "alpha_fraction": 0.7594977617263794, "alphanum_fraction": 0.7659369111061096, "avg_line_length": 42.74647903442383, "blob_id": "f3b72642e2115eda501e01b663fbf9bb800a2473", "content_id": "e39ef44b5ce75c9e5d3e651ce67dd18cf29cddf5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3106, "license_type": "no_license", "max_line_length": 84, "num_lines": 71, "path": "/2016-11-14.md", "repo_name": "dhesse/Blog", "src_encoding": "UTF-8", "text": "% Can't Buy Me Love: Hacking Dating Site Profiles\n\n### DISCLAIMER\n\nYou don't take things you read here seriously, do you? You really\nshouldn't. At least not by and large. I hope you'll get some neat\nideas and will be inspired to try out a technology you haven't used\nbefore every now and then, but it would be foolish to draw any\nconclusions from things I find in the datasets presented here. I mean,\nI'm a data scientist, and most of the methods I use in this blog are\npretty sound, but don't make life decisions based on things you read\nhere. Consider yourself warned.\n\n# The Wonderful World of Online Dating\n\nThe other day, I came across a [very neat data set][okcdata]\ncontaining approximately 60k anonymized profiles taken from the dating\nsite [OkCupid]. Users have entered things like salary, habits (e.g.\ndrinking, drug use, etc.), education, age, and a few more. One usually\nhas to be quite careful with self-reported numbers\n([social desirability bias][scb] comes to mind), and taking a sample\nfrom a dating website as representative for the population at large\ncertainly will introduce one hell of a [selection bias]. And yes, you\nshould be very aware of which kind of biases your data will likely\nexhibit. It can be hard to quantify biases (c.f. the polls and the US'\npresident-elect) but it's usually just a matter of common sense to\nidentify the worst ones you will likely have to deal with.\n\nBut then sometimes you can ask a question that just navigates around\nthe biases. Like this one: Assuming that a user being inactive for\nmore than 14 days indicates that one found true love, what features of\nthe profile make a person attractive? Age? Income? Education? Luckily,\nwe can find out.\n\nLet's first have a look at those 14 days. The histogram of inactive\ndays looks like this:\n\n![][dll]\n\nEven though 14 days inactivity meaning you found love is arbitrary and\npossibly overly optimistic, but looking at the graph it kind of makes\nsense (and I'm an optimist).\n\nSo what makes people being inactive? Let's fit a\n[logistic regression][glm] to the data. We shouldn't have any\nillusions about it's predictive power, but at least we will be able to\nanswer an important question: What makes people fall in love? Brains\nor money? Hence the call for my model looks like this (be warned,\nyou'll need to do some data cleansing before this will work):\n\n~~~\nmodel <- glm(active~age+income+education+sex,\n data = data,\n family=binomial(link='logit'))\n~~~\n\nPlotting the relevant variables gives us the following graph.\n\n![][fac]\n\nSo the romantics can rest assured, it's what's in your brain that\ncounts, not how deep your pockets are.\n\n\n[okcdata]: https://github.com/rudeboybert/JSE_OkCupid\n[OkCupid]: http://okcupid.com/\n[scb]: https://en.wikipedia.org/wiki/Social_desirability_bias\n[selection bias]: https://en.wikipedia.org/wiki/Selection_bias\n[dll]: https://dataadventuresdotcom.files.wordpress.com/2016/11/days_since_logon.png\n[fac]: https://dataadventuresdotcom.files.wordpress.com/2016/11/education.png\n[glm]: http://stat.ethz.ch/R-manual/R-patched/library/stats/html/glm.html\n" }, { "alpha_fraction": 0.7614291310310364, "alphanum_fraction": 0.7683442234992981, "avg_line_length": 39.0461540222168, "blob_id": "b02e2ef221d027d036f055cab82d8a8f56e15305", "content_id": "6957b6327def3e24d426ce9102c6eaf2b14d3680", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2603, "license_type": "no_license", "max_line_length": 78, "num_lines": 65, "path": "/2016-04-22.md", "repo_name": "dhesse/Blog", "src_encoding": "UTF-8", "text": "% Armed Conflicts in Africa, Illustrated in R\n\nSometimes (most of the time), a data scientist's life may seem like\nfun and games. But sometimes, we have to deal with the graver\ntopics in life. Like *armed conflicts*.\n\nOne of the most interesting public data sources around was created by\nthe *Armed Conflict Location & Event Data Project*\n([ACLED][acled]). They have very accurate and ever growing data of at\nthe time of this writing some 100k individual events around armed\nconflicts primarily in Africa, with the exception of a few in\ncountries in South and Southeast Asia. Their purpose is to\n\n- Recording acts of violence between rebels, militias and\n governments.\n- Record acts of violence against civilians.\n- Map out strongholds of armed groups.\n- Collect data on riots and protest.\n\nYou see, it's grave business. But at the same time extremely important\nwork. I'd encourage you to [check their website][acled]. The data range\nback to *1997* and contain for each event\n\n- The country.\n- The date.\n- The two main parties involved.\n- The geographical location.\n- The number of casulaties.\n- Notes about the conflict.\n\nSo what could one do with this kind of data? The first step is as\nusual to get an overview. We do this again in [R][R]. For displaying\ngeo-spatial data, we will the excellent [ggmap][ggmap] package.\n\nWe would like to plot *all* the incidents recorded on a map,\ndistinguishing the time of the events and number of fatalities. We\nwill represent each event by a dot, with the size representing the\nnumber of fatalities and the color indicating the year. All this can\nbe done with a few lines of R code. You can download the script [from\ngithub][blog-code-github].\n\n<insert\nkind=\"source\"\nfile=\"EDA.R\"\nlines=\"1-23\">\n\nYou see that we had to filter on the number of fatalities in line 17,\nwhich effectively just removes one sad event from the\n[First Congo War][congo-war] where a mass grave was found. I've warned\nyou that we're dealing with a grave topic. But now you know how to\nmake graphs like the one below and inform people what's going wrong in\nthe world and maybe do your part to help improving matters.\n\n![Conflicts, Data By Google Maps](\nhttps://dataadventuresdotcom.files.wordpress.com/2016/04/africa_conflicts.png)\n\nI think ACLED did an amazing job to provide us with a fascinating data\nset. Stay tuned for a deeper dive into it.\n\n\n[acled]: http://www.acleddata.com/\n[ggmap]: https://cran.r-project.org/web/packages/ggmap/index.html\n[R]: https://r-project.org\n[congo-war]: https://en.wikipedia.org/wiki/First_Congo_War\n[blog-code-github]: https://github.com/dhesse/BlogCode\n" }, { "alpha_fraction": 0.7470712065696716, "alphanum_fraction": 0.7683989405632019, "avg_line_length": 45.23611068725586, "blob_id": "7d0f18317d76d169c7d87acf7340ffff2faee815", "content_id": "bcd65912027279f55a587a3c2e10a599d43846e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3329, "license_type": "no_license", "max_line_length": 133, "num_lines": 72, "path": "/2016-06-20.md", "repo_name": "dhesse/Blog", "src_encoding": "UTF-8", "text": "% IoT 101 - Flask and Kafka\n\nThese days the internet of things (IoT) is virtually\n[everywhere][iot1] [you][iot2] [look][iot3]. And as it is often with\nthings approaching the peak of the [hype cycle][hypecycle], many seem\nto struggle to explain what the heck IoT really *is*. A common\ndenominator seems to be that in the future our fridge will talk to our\nphone to remind us to buy milk once we are in the supermarket and your\nhouse will turn the heat up/AC on when you're about to get home. Only\nthat the future is *now* and that some of those technologies are\n[here][fridge] [today][nest] (let's leave out the\n[discussion][econiot] that companies really struggle to actually sell\nthem to customers).\n\nStill, it's high time we start exploring all the wonderful real-time\nstreaming technologies out there and how to harness them in order to\nbuild cool stuff (like RESTful APIs, which are [awesome][rest]).\n\n## Flask\n\nThe amazing [flask][flask] framework allows you to build web\napplications in a matter of minutes. I highly recommend you check it\nout. The mandatory \"Hello, World\" example is literally under ten lines\nof code.\n\n<insert kind=\"source\" file=\"flask.py\">\n\n## Kafka\n\n[Apache Kafka][kafka] is a distributed publish-subscribe messaging\nsystem. Originally developed by [Linkedin][linkedin], it is commonly\nused for high-throughput messaging applications such as collecting\nuser clicks on webpages, aggregating logs, stream processing, and the\nlike. Since the IoT premise is that virtually every device will be\nlinked up to the internet and talking to whatever services are\nrelevant, Kafka seems like a solid choice. It's also really easy to\nset up and use. Once you've downloaded it, all you need to do\n(provided you have a JVM installed) is issue these commands.\n\n<insert kind=\"source\" file=\"startkafka.sh\" />\n\n## Putting it together\n\nLet's start simple. Assume you want to provide an API to list all\ntopics, it would be as easy as that (thanks to [pykafka][pykafka]):\n\n<insert kind=\"source\" file=\"routes.py\" lines=\"1-9\" />\n\nDon't forget to import `jsonify` from `flask`.\n\nLet's do something more exciting. Like writing to a topic. It's also\nreally easy, just a few lines of code including parsing.\n\n<insert kind=\"source\" file=\"routes.py\" lines=\"11-19\" />\n\nI hope you enjoyed this post and stay tuned for the next episode in\nwhich we will consume some messages. As usual, if you have any\nquestions or want me to talk about a certain topic that interests you,\nshoot me a message!\n\n[iot1]:http://www.wired.com/insights/2014/11/the-internet-of-things-bigger/\n[iot2]:http://www.forbes.com/sites/jacobmorgan/2014/05/13/simple-explanation-internet-things-that-anyone-can-understand/#2f8c05056828\n[iot3]:https://www.theguardian.com/technology/2015/may/06/what-is-the-internet-of-things-google\n[hypecycle]: https://en.wikipedia.org/wiki/Hype_cycle\n[fridge]: http://www.theverge.com/2016/1/4/10707894/samsung-smart-refrigerator-connected-fridge-iot-ces-2016\n[nest]: https://nest.com/\n[rest]: https://en.wikipedia.org/wiki/Representational_state_transfer\n[flask]: http://flask.pocoo.org/\n[kafka]: http://kafka.apache.org/\n[linkedin]: https://www.linkedin.com/\n[econiot]: http://www.economist.com/news/business/21700380-connected-homes-will-take-longer-materialise-expected-where-smart\n[pykafka]: https://github.com/Parsely/pykafka\n" }, { "alpha_fraction": 0.7613405585289001, "alphanum_fraction": 0.7670954465866089, "avg_line_length": 46.64516067504883, "blob_id": "111316c08d506d604cbed56d7e0f532b45e61298", "content_id": "5f2ae33c4cec4893947f49ab1f372cf723281ed7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2954, "license_type": "no_license", "max_line_length": 98, "num_lines": 62, "path": "/2016-04-21.md", "repo_name": "dhesse/Blog", "src_encoding": "UTF-8", "text": "% A Data Scientist's Toolbox, Part 3: Mock Your Data!\n\nAfter we've discussed the [importance of testing][last], you probably\nhave the feeling that it's a good idea, on general grounds, but *your*\ncode is *really* tough to test. You have all these *dependencies* and\nyour app writes to a database, and you have to load your data. So,\nyea. Not doable. Or so you think.\n\nWell, there are a few tricks you can apply. As for reading data, it's\nrather easy, actually. You can use the [StringIO][stringio] package to\n*mock* a file object and use that as an argument to the function that\nreads your data. Let's assume you have a `.csv` file that's actually\nnot *C*SV, but rather separated with the vertical bar \"|\" (or\n[Sheffer Stroke][sstroke]). You want to make sure this is taken into\naccount across the project, so you want to test for it (good\nidea!). It's as easy as this:\n\n<insert\nkind=\"source\"\nfile=\"mockdata.py\"\nlines=\"1-13\">\n\nThat thing we just did? The one where we used a file object as input\nrather than a string and then open the file object inside the\nfunction? That's a *very* good idea when writing code. It's called\n*flexibility*. You don't really care what object you get as an\nargument. It just needs to have a `read` function. You could even get\ninput from a REST API or some form of database in the future. This is\none of the neat things about testing. Making you code testable usually\nmakes it more modular and flexible.\n\nSpeaking of databases. What if we want to mock a database instead of a\nfile? We have to work a bit harder. Sometimes one can just use a local\ninstance of the database. But often it's better to make a mock object,\none that simulates the database (or whatever you need to mock) with\nlimited functionality. This way your tests can run on any machine,\neven if it has no access to a database of the right kind.\n\nOne instructive way to go is to hack your own. Let's assume you want\nto store configuration in a [MongoDB][mongodb] instance and need to\nmake sure that the `update` function of the right database in the\nright collection is called. You can do this e.g. thusly.\n\n<insert\nkind=\"source\"\nfile=\"mockdemo.py\"\nlines=\"1-39\">\n\nYou see that we have to jump through a bunch of hoops to get the\nmember lookup right, but well. That's how MongoDB behaves. In a\nreal-world application you would probably want something more\nindustry-grade. You can check the excellent selection of\n[mock frameworks on the python homepage][mock]. A mock framework makes\nthe creation of mock objects easy and often gives them some basic\nfunctionality, like watching and counting function calls. Happy\nmocking!\n\n[last]: https://data-adventures.com/2016/04/20/a-data-scientists-toolbox-part-2-testing-your-code/\n[mock]: https://wiki.python.org/moin/PythonTestingToolsTaxonomy#Mock_Testing_Tools\n[sstroke]: https://en.wikipedia.org/wiki/Sheffer_stroke\n[stringio]: https://docs.python.org/2/library/stringio.html\n[mongodb]: https://www.mongodb.org/\n" }, { "alpha_fraction": 0.7102147340774536, "alphanum_fraction": 0.7204495072364807, "avg_line_length": 37.9296875, "blob_id": "8b7dc552c3b6d78ea4a0ef5796f1521e317c5685", "content_id": "b7a4de02578d99d06d7f8f9db1354d76957bf554", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4984, "license_type": "no_license", "max_line_length": 100, "num_lines": 128, "path": "/neo4j.md", "repo_name": "dhesse/Blog", "src_encoding": "UTF-8", "text": "% Degrees of Rudi Völler - Neo4j Edition\n\nGraph databases are the [new][gdbarticle] [hot][ibmgraph]\n[thing][neo4jgraph]. Actually [not so new][wikigraph]. IBM, among\nothers, has been toying with them since the 1960s. In recent years\nthey have been popularized through\n[social media analysis][neo4jsocial] and people have realized that\nthey can be used for a lot of other interesting things like, but not\nlimited to:\n\n- Fraud detection.\n- Recommendation engines.\n- Graph based search.\n- Master data management.\n\nFor us data scientists graph databases are an important tool that all\nof us should have at least some familiarity with. They are no silver\nbullet, but used right they can lead to simpler solutions in\nsituations where traditional databases just won't cut it.\n\nEnough talk, let me walk you through an example in [Neo4j], centered\naround historical and current members of the\n[German national soccer team][desoccer]. I'll leave it as an exercise\nto the interested reader to make the connection to possible\napplications to fraud detection or recommendation engines.\n\nNeo4j provides a free community edition which works great and is\n[well documented][neo4jdoc]. It is very quick to set up, for testing\nand evaluation purposes all you have to do is download the latest\nrelease and run an executable. You can send queries to and inspect\nresults from Neo4j in your web browser, easy as pie.\n\n## Getting The Data - Web Scraping\n\nTo get some data we have, like so often, to do some [scraping]. I've\nmentioned [scrapy] and [beautifulsoup][bs4] several times before. They\nare great tools by themselves and virtually unbeatable together. You\ncan of course parse the DOM tree in pure scrapy (using CSS selectors\nor XPATH), which is fine for some simple applications, but I'd\nstrongly recommend using beautifulsoup for entity extraction in any\nserious application. In practice, your parsing function will then\nstart with something like this:\n\n~~~{.python}\ndef parse_tournament(self, response):\n soup = BeautifulSoup(response.text, \"lxml\")\n header = soup.find(\"span\",\n id=re.compile(\".*Germany.*\")).parent\n~~~\n\nAll you have to do is `yield` the extracted entities as dictionary and\nwrite the result into a CSV file. You can then load the CSV into Neo4j\nas described in their documentation and start having some fun.\n\n## Degrees of Rudi Völler\n\n[Rudi Völler][rv], one of the most prominent past national players,\nwill serve us as a worthy example. So, where did he play? Easy.\n\n~~~\nMATCH (:Player {name: 'Rudi Völler'})-[r:PLAYED]->(c:Club)\nRETURN *\n~~~\n\nThe cypher code above (Neo4j's internal language is call cypher, but\nis in contrast to the name's undertone quite easy to use) will give a\nresult like shown below.\n\n![](https://dataadventuresdotcom.files.wordpress.com/2016/10/voellersimple.png)\n\nNow this is nothing you couldn't easily do in SQL. Yes, in Neo4j's web\ninterface, you can play around with the blobs and arrows, but that's\nmore of a gimmick. So let's get more creative. Which are the national\nplayers that managed teams that Mr. Völler played in or managed?\n\n~~~\nMATCH (:Player {name: 'Rudi Völler'})-[r]->(c:Club)<-[s:MANAGED]-(p)\nRETURN *\n~~~\n\n![](https://dataadventuresdotcom.files.wordpress.com/2016/10/voellerfull.png)\n\nVoila. Since the human brain is so good at recognizing patterns\n(sometimes even if they're [not really there][pareidolia]), some fraud\nanalysts use tools like this to visualize suspected fraud rings. But\nwhat if you want to become more quantitative, asking questions like:\nWho played in the most clubs that Mr. Völler was either playing for or\nmanaging?\n\n~~~\nMATCH (:Player {name: 'Rudi Völler'})-[]->(c:Club)<-[r:PLAYED]-(p)\nRETURN p.name, COUNT(r)\nORDER BY -COUNT(r)\nLIMIT 5\n~~~\n\n+---------------+--------+\n|p.name |COUNT(r)|\n+===============+========+\n|Thomas Häßler |3 |\n+---------------+--------+\n|Oliver Neuville|2 |\n+---------------+--------+\n|Michael Ballack|2 |\n+---------------+--------+\n|André Schürrle |2 |\n+---------------+--------+\n|Stefan Kießling|2 |\n+---------------+--------+\n\n\nPretty nice, with a syntax easy enough that I tend to require far less\ngoogling that with some SQL dialects when I work with cypher. Now go\non your own data adventure and play around with Neo4j!\n\n[gdbarticle]: https://www.infoq.com/minibooks/emag-graph-databases\n[ibmgraph]: https://www.ibm.com/blogs/bluemix/2016/07/graph-databases-natural-way-to-represent-data/\n[neo4jgraph]: https://neo4j.com/blog/native-vs-non-native-graph-technology/\n[wikigraph]: https://en.wikipedia.org/wiki/Graph_database#History\n[neo4jsocial]: https://neo4j.com/use-cases/social-network/\n[Neo4j]: https://neo4j.com/\n[neo4jdoc]: https://neo4j.com/docs/developer-manual/current/\n[desoccer]: https://en.wikipedia.org/wiki/Germany_national_football_team\n[scrapy]: http://scrapy.org/\n[scraping]: https://en.wikipedia.org/wiki/Web_scraping\n[bs4]: https://www.crummy.com/software/BeautifulSoup/\n[rv]: https://en.wikipedia.org/wiki/Rudi_V%C3%B6ller\n[pareidolia]: https://en.wikipedia.org/wiki/Pareidolia\n" }, { "alpha_fraction": 0.7466443181037903, "alphanum_fraction": 0.7627037167549133, "avg_line_length": 42.91579055786133, "blob_id": "bcba2c5a5f74be1c3ae5bcb27cbac6100df73a85", "content_id": "c67c7de6bd7e5bb42964040b3bd537c6c3c2bd48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4172, "license_type": "no_license", "max_line_length": 86, "num_lines": 95, "path": "/2016-04-19.md", "repo_name": "dhesse/Blog", "src_encoding": "UTF-8", "text": "% A Data Scientist's Toolbox, part 2: Testing your code.\n\n[In the last post][tool1], I talked about the usefulness of\n[REPLs][repl] which indeed is hard to overstate. Exploratory data\nanalysis would be a lot of hassle without the read-evaluate-print\nloop. We had a closer look at [Jupyter][jupyter] in particular and\nfirst attempts at analyzing the data from the post\n[on food and inflation][fi] can be found [on github][toolrepo].\n\nSo REPLs are great tools. Really great. I mean, for exploratory\nanalysis. Most of it, that is. *Let me explain*. REPLs have one major\ndrawback. Code in e.g. a Jupyter notebook is *very hard to test* and\nthe thing about code that's hard to test is that it usually doesn't\nget tested. *At all*. It's just in our nature to be lazy, so if\nsomething is a hassle you usually just don't do it, unless it's\nstrictly required. And clearly your code will execute (after you\nfiddle with it until it *seems* to work alright, at which point you\nsave and slowly walk away from your computer) just fine without\ntests. But do you *know* it's doing the right thing?\n\nLet's take a minute to talk about test driven development (or\n[TDD][tdd]). Some argue that you don't need unit testing, for various\nreasons. Like it slows you down when coding. Or it gives you a *false*\nsense of security. And so on. All the arguments I've heard against TDD\nhave one thing in common though. They're *wrong*. I tend to agree\n[with Uncle Bob][tdddebate] on the matter. If you are unfamiliar with\nunit testing, I recommend you have a look at some\n[introductory material][tddrules].\n\nNow we're no software developers but data scientists. I don't *demand*\nthat you unit test every last line of your analysis. But I do believe\nit is a good idea to break out what you can from a notebook and write\nsome tests for it. Why? *Code reuse*! If you have that neat function\nin a separate file with some tests going on, you'll be more likely to\nre-use it. Why? Because you *trust* it. Because it's tested. Let's\nhave a look.\n\nLast time, we had a neat little function that would normalize a\nseries.\n\n<insert kind=\"nbcell\"\nfile=\"Notebook.ipynb\"\ncell=\"5\">\n\nAny function you write might be a good candidate to be but in a\nseparate file. Even tough this specific one might not be the best\nexample, but let's break it out and write a test. The\n[unittest][utest] package is one of the obvious and popular choices\nfor this task.\n\n<insert kind=\"source\"\nfile=\"normalize_basic.py\"\nlines=\"9-19\"\">\n\nNow, while writing the test you *should* notice a few strange\nthings. What happens if there is no year 2000 in our data frame? What\nhappens if we have it multiple times? This would break our code. Just\na few more lines and two more tests make the function much more\nreliable, and by proxy you much more likely to use it in a future\nanalysis.\n\n<insert kind=\"source\"\nfile=\"normalize.py\"\nlines=\"10-35\">\n\nOf course it's far from perfect, but you get the idea. Maybe you want\nto make it better as a homework? Now let's do the same with the\nreading and pre-processing of our data.\n\n<insert kind=\"source\"\nfile=\"read_data.py\"\nlines=\"4-62\">\n\nMuch more reliable, and more likely to be re-used. Imagine you're\nlooking at your team's repository. What parts of a colleague's code\nwould you rather use? The one with tests or the one without? Our\nnotebook becomes much more readable as well.\n\n<insert kind=\"gist\"\nuser=\"dhesse\"\nid=\"9dc6c01601e4f0d337f48a48786ac36c\">\n\nSo if you have a useful function in your EDA, be a good data\nscientist, put it in a separate file, test, refactor, and save\nyourself and your colleagues some time in the future.\n\n[tool1]: http://data-adventures.com/2016/04/18/a-data-scientists-toolbox-part-1-repls/\n[repl]: https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop\n[jupyter]: http://jupyter.org/\n[fi]: http://data-adventures.com/2016/04/17/food-and-inflation/\n[toolrepo]: http://github.com/dhesse/ToolsBlog\n[tdd]: https://en.wikipedia.org/wiki/Test-driven_development\n[tdddebate]: http://butunclebob.com/ArticleS.UncleBob.UntestedCodeDarkMatter\n[utest]: https://docs.python.org/2/library/unittest.html\n[tddrules]: http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd\n" }, { "alpha_fraction": 0.6622516512870789, "alphanum_fraction": 0.7152317762374878, "avg_line_length": 29, "blob_id": "216e55fd582b7d82efbbcaa739d0c7105346d83a", "content_id": "345143daca49d297eda90b9ca865677781e93974", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 151, "license_type": "no_license", "max_line_length": 100, "num_lines": 5, "path": "/README.md", "repo_name": "dhesse/Blog", "src_encoding": "UTF-8", "text": "# Blog Posts\n\nPandoc command to convert to HTML\n\n pandoc -t json 2016-09-26.md|python wpmath.py | pandoc -t html+tex_math_dollars -f json | pbcopy\n\n" }, { "alpha_fraction": 0.6253216862678528, "alphanum_fraction": 0.6930004954338074, "avg_line_length": 45.261905670166016, "blob_id": "a44c49f2ffd453f162acdaa543ccf353347a7049", "content_id": "4664da24c341cfcb6e07035ea310ad3fe9c925d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3886, "license_type": "no_license", "max_line_length": 98, "num_lines": 84, "path": "/2016-09-26.md", "repo_name": "dhesse/Blog", "src_encoding": "UTF-8", "text": "% Anomaly Detection in R: Euro 2016 Edition.\n\nI've been working a fair bit with anomaly detection in the last\nmonths, and browsing through\n[Andrew Ng's excellent machine learning course][ngml], I was curious\nto try out his anomaly detection algorithm. It reads a bit like this:\n\n1) Select a number of features $X_1, \\ldots, X_n$.\n\n2) If any variable $X_i$ does *not* look Gaussian enough (for some\n definition of \"Gaussian enough\"), find a suitable transformation\n $x'_i = g_i(x)$ with e.g. $g_i(x) = x^{0.5}$ and use the $X'_i$\n instead of $X_i$ where needed.\n\n3) Calculate the mean and standard deviation $\\mu_i$ and $\\sigma_i$ of\n your *new* features.\n\n4) Calculate the Gaussian density \n $f(x_i'|\\mu_i,\\sigma_i) = \\frac{1}{\\sqrt{2 \\pi \\sigma^2}} e^{-(x_i' - \\mu_i)^2 / (2 \\sigma^2)}$.\n\n5) Calculate the total density $F = \\prod_i f(x_i'|\\mu_i, \\sigma_i)$\n and call the observation an anomaly if $F < \\epsilon$ for some\n chosen $\\epsilon$.\n \nSo let's go back to our [soccer data][eu16], fire up our [R], and see\nwhat we can find. As our features, we use the passes per minute (PPM)\nand passes completed per minute (PCPM) for each player. In a\nreal-world anomaly detection scenario, one wouldn't only use two\nfeatures, and especially two that are so strongly correlated. But\nlet's have some fun with this. Applying some simple transformations\n(roots, basically), we find that both features can be made into\nsomething that looks at least somewhat Gaussian.\n\n![](https://dataadventuresdotcom.files.wordpress.com/2016/10/pcpm.png)\n![](https://dataadventuresdotcom.files.wordpress.com/2016/10/ppm.png)\n\nThe fitting is done easily with a few [dplyr] group-by-and-summarize\niterations and I'll leave the details to the eager reader (it's a good\nand easy exercise). The result will, plotted in [ggplot2] look\nsomething like this.\n\n![](https://dataadventuresdotcom.files.wordpress.com/2016/10/passespvals.png)\n\nNow, using two *independent* Gaussians to fit our data makes the edges\nof the plot look all wrong. Just the outer fringes are marked as\nanomalous while some points that look outlier-ish to the naked eye are\nnot. Also inspecting the points manually, one doesn't feel encouraged.\n\n| Name | PPM | PCPM | P |\n|----------------|-----------|-----------|--------------|\n| Toni Kroos | 1.1456140 | 1.0666667 | 1.480058e-08 |\n| Bruno Soriano | 1.0892857 | 1.0714286 | 3.962323e-08 |\n| Nuri Şahin | 1.0222222 | 0.9555556 | 1.123398e-06 |\n| Granit Xhaka | 1.0205128 | 0.9333333 | 1.684373e-06 |\n| Andrés Iniesta | 0.9888889 | 0.9083333 | 4.268718e-06 |\n| Lukas Podolski | 1.0000000 | 0.8888889 | 4.847362e-06 |\n\nThe long answer has to do with the fact that [density estimation] is\nhard. The short answer is using a *multivariate* Gaussian that allows\nfor correlations in the variables. I used the fantastic [mclust]\npackage to do mine. The results look way more interesting.\n\n![](https://dataadventuresdotcom.files.wordpress.com/2016/10/passesdensitymv.png)\n\nIf we look again at the players in the lowest-density regions, we\nactually see something that looks like anomalies (and just poor\npassing skills).\n\n| Name | PPM | PCPM |\n|------------------|------------|------------|\n| Divock Origi | 0.22222222 | 0.05555556 |\n| Conor McLaughlin | 0.17777778 | 0.08888889 |\n| Kyle Lafferty | 0.12322275 | 0.06635071 |\n\nThe topic of [density estimation] in general is quite interesting, I'd\nencourage you to read up on some of the techniques out there and play\naround with [mclust].\n\n[eu16]: https://data-adventures.com/2016/07/10/what-does-it-take-to-win-the-euro-2016/\n[ngml]: https://www.coursera.org/learn/machine-learning\n[dplyr]: https://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html\n[mclust]: https://cran.r-project.org/web/packages/mclust/index.html\n[density estimation]: https://en.wikipedia.org/wiki/Density_estimation\n[R]: https://r-project.org\n" } ]
16
ariafyy/streamlit-mediapipe-hands-tracking
https://github.com/ariafyy/streamlit-mediapipe-hands-tracking
313e89778b5d24d6db08290e5fd9f262e5334816
b564dac7a3a304eee6e2e6915d864613626e356b
c41e7fd69d7c3ce25c643686e0ba83f9d31c56df
refs/heads/main
2023-06-15T10:24:39.133721
2021-07-12T08:51:23
2021-07-12T08:51:23
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7678821682929993, "alphanum_fraction": 0.7748948335647583, "avg_line_length": 74.0526351928711, "blob_id": "76cdb5717a9442bdef7a2eb495c371c340c4e5e1", "content_id": "32a590ec652756fd9cb9e19e132ef1f020770309", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1426, "license_type": "no_license", "max_line_length": 268, "num_lines": 19, "path": "/README.md", "repo_name": "ariafyy/streamlit-mediapipe-hands-tracking", "src_encoding": "UTF-8", "text": "# streamlit-mediapipe-hands-tracking\nA [Streamlit](https://streamlit.io/) app for Google [MediaPipe Hands](https://google.github.io/mediapipe/solutions/hands). \n \n![App Demo Image](https://github.com/virtualramblas/streamlit-mediapipe-hands-tracking/blob/main/images/demo-image.PNG) \n \nMediaPipe is a suite of cross-platform, customizable ML solutions for live and streaming media. One of the provided solutions is an high-fidelity hand and finger tracking. \nThis Streamlit web app allows hands tracking in static images. Mediapipe supports also video and live hands-tracking, but these features aren't yet covered by this demo app. Mediapipe hands tracking can be configured through this app UI through the following params: \n* Max number of hands to track: Mediapipe can track up to 4 hands in a single image or frame. Default for this app is set to 2. \n* Minimum detection confidence. Default is set to 50%. \n* Show/Hide Mediapipe classification results (index, score and label in JSON format). Default is set to False. \n \n### Setup for running the app\nAnaconda and Python 3.7+ are required.\n\n* Clone this repo.\n* From the root directory of the project, create a conda virtual environment: *conda env create -f environment.yml*\n* Activate the newly created virtual environment: *conda activate streamlit-mediapipe-hands*\n* Run the app: *streamlit run app.py* \n* Open a web browser and go to http://localhost:8501\n" }, { "alpha_fraction": 0.6467951536178589, "alphanum_fraction": 0.6593455672264099, "avg_line_length": 43.63999938964844, "blob_id": "1c3ef85b9a5a2c783c2a28d45bec47e4478e0e4b", "content_id": "a515aa9f3baed7dc4f8b71fb69ee0b90326d5c49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2231, "license_type": "no_license", "max_line_length": 125, "num_lines": 50, "path": "/app.py", "repo_name": "ariafyy/streamlit-mediapipe-hands-tracking", "src_encoding": "UTF-8", "text": "import cv2\nimport mediapipe as mp\nimport numpy as np\nimport streamlit as st\nmp_drawing = mp.solutions.drawing_utils\nmp_hands = mp.solutions.hands\n\ndef track_hands_in_images(file_list, max_num_hands, min_detection_confidence):\n annotated_images = []\n multi_handednesses = []\n \n with mp_hands.Hands(\n static_image_mode=True,\n max_num_hands=max_num_hands,\n min_detection_confidence=min_detection_confidence) as hands:\n for uploaded_file in file_list:\n image = cv2.imdecode(np.frombuffer(uploaded_file.read(), np.uint8), 1)\n image = cv2.flip(image, 1)\n results = hands.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n if not results.multi_hand_landmarks:\n continue\n multi_handednesses.append(results.multi_handedness)\n annotated_image = image.copy()\n for hand_landmarks in results.multi_hand_landmarks:\n mp_drawing.draw_landmarks(\n annotated_image, hand_landmarks, mp_hands.HAND_CONNECTIONS)\n annotated_images.append(annotated_image)\n \n return annotated_images, multi_handednesses\n\nst.write(\n \"\"\" # Hand Tracking in Pictures Using Google's MediaPipe Hands \"\"\"\n)\n\nst.sidebar.info(\"General settings\")\nmax_num_hands = st.sidebar.slider('Max number of hands:', 1, 4, 2, 1)\nmin_detection_confidence = st.sidebar.slider('Minimum detection confidence:', 0.1, 1.0, 0.5, 0.1)\nst.sidebar.info(\"Input\")\nuploaded_files = st.sidebar.file_uploader(\"Upload JPG images of hands:\", type=['jpg'], accept_multiple_files=True)\nif len(uploaded_files) > 0:\n show_results = st.sidebar.checkbox('Show classification results')\n track_button = st.sidebar.button('Track Hands')\n if track_button:\n annotated_images, multi_handednesses = track_hands_in_images(uploaded_files, max_num_hands, min_detection_confidence)\n if len(annotated_images) > 0:\n for idx, annotated_image in enumerate(annotated_images):\n annotated_image = cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB)\n st.image(cv2.flip(annotated_image, 1))\n if show_results:\n st.write(str(multi_handednesses[idx]))" } ]
2
jaywizzy/simple-django-crud
https://github.com/jaywizzy/simple-django-crud
09451cf41fb67462f3ede8029887de4c9d3e8c0d
1fa8f1ee4f46cbea54aa0e3ccadc5d74ff38fd97
c68bec28b2d258f046ac25f89aaeeeb0fb5f7be7
refs/heads/master
2020-03-12T03:29:57.845332
2018-04-21T00:33:22
2018-04-21T00:33:22
130,425,763
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6887417435646057, "alphanum_fraction": 0.6887417435646057, "avg_line_length": 29.299999237060547, "blob_id": "d0734c3dcf547fe6be857462b464679bbbd0bf85", "content_id": "8a09c8d5ca99e85ab495faec79aefb65417c4f58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 302, "license_type": "no_license", "max_line_length": 65, "num_lines": 10, "path": "/app/urls.py", "repo_name": "jaywizzy/simple-django-crud", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom .views import *\n\nurlpatterns = [\n\tpath('', products_list, name='products_list'),\n\tpath('create', create_product, name='create_product'),\n\tpath('edit/<int:id>/', edit_product, name='update_product'),\n\tpath('delete/<int:id>/', delete_product, name='delete_product'),\n\t\n]" } ]
1
MrJlmeza/NFL-player-recogntion-ML
https://github.com/MrJlmeza/NFL-player-recogntion-ML
b2d775daae444fc4921acaabcb1358213c9ee263
f94be0dcfc3c339b4e932a6c30bcb6476728ba23
72852b35887ed8fada2cbee5436c3a88cff98042
refs/heads/main
2023-07-16T00:12:15.179604
2021-08-30T22:07:50
2021-08-30T22:07:50
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 14.333333015441895, "blob_id": "5cd39ae21cefaaf9a6fa5185e43efd6d783e4f4e", "content_id": "0c4cafea073bef0bea76df9f5121f996d1a57d9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 45, "license_type": "no_license", "max_line_length": 25, "num_lines": 3, "path": "/README.md", "repo_name": "MrJlmeza/NFL-player-recogntion-ML", "src_encoding": "UTF-8", "text": "# Group5-Project-3\n\nTHIS IS FROM PATEL BRANCH" }, { "alpha_fraction": 0.4856557250022888, "alphanum_fraction": 0.7049180269241333, "avg_line_length": 16.428571701049805, "blob_id": "23c411dcb00a1427e4bbd040dc592106ded49623", "content_id": "b84de0b6eaa4e93507c9d2d09a79b302cd333940", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 488, "license_type": "no_license", "max_line_length": 27, "num_lines": 28, "path": "/requirements.txt", "repo_name": "MrJlmeza/NFL-player-recogntion-ML", "src_encoding": "UTF-8", "text": "boto3==1.18.31\nbotocore==1.21.31\ncertifi==2021.5.30\nclick==8.0.1\ncolorama==0.4.4\nFlask==2.0.1\nFlask-SQLAlchemy==2.5.1\ngreenlet==1.1.1\ngunicorn==20.1.0\nimportlib-metadata==4.6.1\nitsdangerous==2.0.1\nJinja2==3.0.1\njmespath==0.10.0\nMarkupSafe==2.0.1\nnumpy==1.21.1\npandas==1.3.0\npsycopg2==2.9.1\npsycopg2-binary==2.9.1\npython-dateutil==2.8.2\npytz==2021.1\ns3transfer==0.5.0\nsix==1.16.0\nSQLAlchemy==1.3.23\ntyping-extensions==3.10.0.1\nurllib3==1.26.6\nWerkzeug==2.0.1\nwincertstore==0.2\nzipp==3.5.0\n" }, { "alpha_fraction": 0.6136783957481384, "alphanum_fraction": 0.6321626901626587, "avg_line_length": 29.05555534362793, "blob_id": "eda6d7e1a7f1a19f9b3e21af1dbeffab1de56dcd", "content_id": "9c126c00d64c12fb88bc0e134224250e32c57529", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 541, "license_type": "no_license", "max_line_length": 48, "num_lines": 18, "path": "/eagles_ml/models.py", "repo_name": "MrJlmeza/NFL-player-recogntion-ML", "src_encoding": "UTF-8", "text": "from .app import db\n\nclass Eagles_ML(db.Model):\n __tablename__ = 'eagles_ml'\n\n id = db.Column(db.Integer, primary_key=True)\n playername = db.Column(db.String(150))\n playernumber = db.Column(db.Integer)\n playerposition = db.Column(db.String(5))\n height = db.Column(db.String(10))\n weight = db.Column(db.Float)\n age = db.Column(db.Integer)\n experience = db.Column(db.String(5))\n college = db.Column(db.String(150))\n year = db.Column(db.Integer)\n\n def __repr__(self):\n return '<Pet %r>' % (self.name)\n" }, { "alpha_fraction": 0.739130437374115, "alphanum_fraction": 0.739130437374115, "avg_line_length": 14.333333015441895, "blob_id": "999b05d2ff71bf66141c13a4663ea9acc9b8b240", "content_id": "f0dc8b0c5c999b8f471a09757b29cf57f8a7c67a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 46, "license_type": "no_license", "max_line_length": 28, "num_lines": 3, "path": "/initdb.py", "repo_name": "MrJlmeza/NFL-player-recogntion-ML", "src_encoding": "UTF-8", "text": "from eagles_ml.app import db\n\ndb.create_all()\n" }, { "alpha_fraction": 0.8055555820465088, "alphanum_fraction": 0.8055555820465088, "avg_line_length": 36, "blob_id": "9a57f5773963194c30b03a46daf46fa71d43f43e", "content_id": "59391e85e5bff95e9862328006358a2a850a6edd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 36, "license_type": "no_license", "max_line_length": 36, "num_lines": 1, "path": "/run.sh", "repo_name": "MrJlmeza/NFL-player-recogntion-ML", "src_encoding": "UTF-8", "text": "FLASK_APP=eagles_ml/app.py flask run" }, { "alpha_fraction": 0.6401458382606506, "alphanum_fraction": 0.6531202793121338, "avg_line_length": 29.966777801513672, "blob_id": "40955b3b59708f5156e50d0da8e69c3dbc941157", "content_id": "f21ead0e28933358a1c635daf90866524480942f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9326, "license_type": "no_license", "max_line_length": 108, "num_lines": 301, "path": "/eagles_ml/app.py", "repo_name": "MrJlmeza/NFL-player-recogntion-ML", "src_encoding": "UTF-8", "text": "# import necessary libraries\nfrom re import I\nimport numpy as np\nimport os\nfrom flask import (\n Flask,\n render_template,\n jsonify,\n request,\n redirect,\n send_from_directory)\nimport csv\nimport boto3\nfrom sqlalchemy.sql.expression import true\n\n#################################################\n# Flask Setup\n#################################################\napp = Flask(__name__)\n\n#################################################\n# Database Setup\n#################################################\n\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import func\n\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', '') or \"sqlite:///db.sqlite\"\n\n# Remove tracking modifications\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n\ndef getCredentials():\n with open('./eagles_ml/static/credentials.csv','r') as input:\n next(input)\n reader = csv.reader(input)\n for line in reader:\n access_key_id = line[2]\n secret_access_key = line[3]\n access_key_id = access_key_id\n secret_access_key = secret_access_key\n return access_key_id, secret_access_key\n\ndef detect_text(photo, credentials):\n \n access_key_id = credentials[0]\n secret_access_key = credentials[1]\n \n with open(photo, 'rb') as source_image: \n source_bytes = source_image.read()\n \n client=boto3.client('rekognition',\n aws_access_key_id = access_key_id,\n aws_secret_access_key = secret_access_key,\n region_name='us-east-1')\n\n response=client.detect_text(Image = {'Bytes' : source_bytes})\n \n textDetections=response['TextDetections']\n listofDetectedStrings = []\n confidence = []\n for text in textDetections:\n listofDetectedStrings.append(text['DetectedText'])\n confidence.append(text['Confidence'])\n\n #Create a dictionary of texts detected and confidences\n resultDictionary = {listofDetectedStrings[i]: confidence[i] for i in range(len(listofDetectedStrings))}\n\n final_result = {}\n\n #Remove duplicate keys\n for key,value in resultDictionary.items():\n if key not in final_result.keys():\n final_result[key] = value\n\n return final_result\n\ndef detect_celebrities(photo, credentials):\n\n access_key_id = credentials[0]\n secret_access_key = credentials[1]\n \n client=boto3.client('rekognition',\n aws_access_key_id = access_key_id,\n aws_secret_access_key = secret_access_key,\n region_name='us-east-1')\n\n with open(photo, 'rb') as image:\n response = client.recognize_celebrities(Image={'Bytes': image.read()})\n\n print('Detected faces for ' + photo) \n listOfCelebs = []\n confidenceList = []\n for celebrity in response['CelebrityFaces']:\n listOfCelebs.append(celebrity['Name'])\n confidenceList.append(celebrity['Face']['Confidence'])\n\n #Create a dictionary of celebs and confidences\n resultDictionary = {listOfCelebs[i]: confidenceList[i] for i in range(len(listOfCelebs))}\n\n final_result = {}\n\n #Remove duplicate keys\n for key,value in resultDictionary.items():\n if key not in final_result.keys():\n final_result[key] = value\n\n return final_result\n\n\nfrom .models import Eagles_ML\n\n# create route that renders index.html template\[email protected](\"/\")\ndef home():\n return render_template(\"index.html\")\n\ndef getFinalResult(photo):\n results = db.session.query(Eagles_ML.playername, \n Eagles_ML.playernumber,\n Eagles_ML.playerposition,\n Eagles_ML.height,\n Eagles_ML.weight,\n Eagles_ML.age,\n Eagles_ML.experience,\n Eagles_ML.college,\n Eagles_ML.year).all()\n\n credentials = getCredentials()\n textsDictionary = detect_text(photo, credentials)\n celebDictionary = detect_celebrities(photo, credentials) \n\n eagles_ml_database = []\n final_result = []\n \n final_result.append(textsDictionary)\n final_result.append(celebDictionary)\n for playername, playernumber, playerposition, height, weight, age, experience, college, year in results:\n data_dict = {}\n data_dict[\"playername\"] = playername\n data_dict[\"playernumber\"] = playernumber\n data_dict[\"playerposition\"] = playerposition\n data_dict[\"height\"] = height\n data_dict[\"weight\"] = weight\n data_dict[\"age\"] = age\n data_dict[\"experience\"] = experience\n data_dict[\"college\"] = college\n data_dict[\"year\"] = year\n eagles_ml_database.append(data_dict)\n\n i = 0\n filteredPlayerList = []\n for databaseEntry in eagles_ml_database:\n for key_detected,value in textsDictionary.items():\n if(str(databaseEntry[\"playernumber\"]) == key_detected):\n filteredPlayerList.append(eagles_ml_database[i])\n i=i+1\n\n final_result.append(filteredPlayerList) \n return jsonify(final_result)\n\ndef getCelebResult(photo):\n credentials = getCredentials()\n celebDictionary = detect_celebrities(photo, credentials) \n final_result = []\n final_result.append(celebDictionary)\n return jsonify(final_result)\n\[email protected]('/')\ndef index():\n return render_template('index.html')\n\[email protected]('/celebs', methods=['GET', 'POST'])\ndef cool_form():\n return render_template('celebs.html')\n\[email protected](\"/api/eagles_ml/TestImages1\")\ndef get_TestImages1():\n return getFinalResult('./eagles_ml/static/assets/TestImages1.jpg')\n\[email protected](\"/api/eagles_ml/TestImages2\")\ndef get_TestImages2():\n return getFinalResult('./eagles_ml/static/assets/TestImages2.jpg')\n\[email protected](\"/api/eagles_ml/TestImages3\")\ndef get_TestImages3():\n return getFinalResult('./eagles_ml/static/assets/TestImages3.jpg')\n\[email protected](\"/api/eagles_ml/TestImages4\")\ndef get_TestImages4():\n return getFinalResult('./eagles_ml/static/assets/TestImages4.jpg')\n\[email protected](\"/api/eagles_ml/TestImages5\")\ndef get_TestImages5():\n return getFinalResult('./eagles_ml/static/assets/TestImages5.jpg')\n\[email protected](\"/api/eagles_ml/TestImages6\")\ndef get_TestImages6():\n return getFinalResult('./eagles_ml/static/assets/TestImages6.jpg')\n\[email protected](\"/api/eagles_ml/TestImages7\")\ndef get_TestImages7():\n return getFinalResult('./eagles_ml/static/assets/TestImages7.jpg')\n\[email protected](\"/api/eagles_ml/TestImages8\")\ndef get_TestImages8():\n return getFinalResult('./eagles_ml/static/assets/TestImages8.jpg')\n\[email protected](\"/api/eagles_ml/TestImages9\")\ndef get_TestImages9():\n return getFinalResult('./eagles_ml/static/assets/TestImages9.jpg')\n\[email protected](\"/api/eagles_ml/TestImages10\")\ndef get_TestImages10():\n return getFinalResult('./eagles_ml/static/assets/TestImages10.jpg')\n\[email protected](\"/api/eagles_ml/TestImages11\")\ndef get_TestImages11():\n return getFinalResult('./eagles_ml/static/assets/TestImages11.jpg')\n\[email protected](\"/api/eagles_ml/TestImages12\")\ndef get_TestImages12():\n return getFinalResult('./eagles_ml/static/assets/TestImages12.jpg')\n\[email protected](\"/api/eagles_ml/TestImages13\")\ndef get_TestImages13():\n return getFinalResult('./eagles_ml/static/assets/TestImages13.jpg')\n\[email protected](\"/api/eagles_ml/TestImages14\")\ndef get_TestImages14():\n return getFinalResult('./eagles_ml/static/assets/TestImages14.jpg')\n\[email protected](\"/api/eagles_ml/TestImages15\")\ndef get_TestImages15():\n return getFinalResult('./eagles_ml/static/assets/TestImages15.jpg')\n\n############### CELBRITY DETECTION ###############\n\n\[email protected](\"/api/eagles_ml/Celebs1\")\ndef get_Celebs1():\n return getCelebResult('./eagles_ml/static/assets/celebs/Celebs1.jpg')\n\n\[email protected](\"/api/eagles_ml/Celebs2\")\ndef get_Celebs2():\n return getCelebResult('./eagles_ml/static/assets/celebs/Celebs2.jpg')\n\n\[email protected](\"/api/eagles_ml/Celebs3\")\ndef get_Celebs3():\n return getCelebResult('./eagles_ml/static/assets/celebs/Celebs3.jpg')\n\n\[email protected](\"/api/eagles_ml/Celebs4\")\ndef get_Celebs4():\n return getCelebResult('./eagles_ml/static/assets/celebs/Celebs4.jpg')\n\n\[email protected](\"/api/eagles_ml/Celebs5\")\ndef get_Celebs5():\n return getCelebResult('./eagles_ml/static/assets/celebs/Celebs5.jpg')\n\n\[email protected](\"/api/eagles_ml/Celebs6\")\ndef get_Celebs6():\n return getCelebResult('./eagles_ml/static/assets/celebs/Celebs6.jpg')\n\n\[email protected](\"/api/eagles_ml/Celebs7\")\ndef get_Celebs7():\n return getCelebResult('./eagles_ml/static/assets/celebs/Celebs7.jpg')\n\n\[email protected](\"/api/eagles_ml/Celebs8\")\ndef get_Celebs8():\n return getCelebResult('./eagles_ml/static/assets/celebs/Celebs8.jpg')\n\n\[email protected](\"/api/eagles_ml/Celebs9\")\ndef get_Celebs9():\n return getCelebResult('./eagles_ml/static/assets/celebs/Celebs9.jpg')\n\n\[email protected](\"/api/eagles_ml/Celebs10\")\ndef get_Celebs10():\n return getCelebResult('./eagles_ml/static/assets/celebs/Celebs10.jpg')\n\n\[email protected](\"/api/eagles_ml/Celebs11\")\ndef get_Celebs11():\n return getCelebResult('./eagles_ml/static/assets/celebs/Celebs11.jpg')\n\[email protected](\"/api/eagles_ml/Celebs12\")\ndef get_Celebs12():\n return getCelebResult('./eagles_ml/static/assets/celebs/Celebs12.jpg')\n\nif __name__ == \"__main__\":\n app.run()\n \n" } ]
6
naman0105/pythonRegex
https://github.com/naman0105/pythonRegex
4e7af66402946cd5782ff27038f909794bc9f6d2
cda2961aa347315bb7e0638c4859da4b09ece71f
546f24b14f3c48f5dc11e46a5279a41997902c39
refs/heads/main
2023-05-08T02:42:40.424545
2021-05-31T16:40:53
2021-05-31T16:40:53
372,570,550
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5121457576751709, "alphanum_fraction": 0.52226722240448, "avg_line_length": 22.5238094329834, "blob_id": "efa30e2b529fda1e85c6bd2e079c5ff5c911a904", "content_id": "951b901c31bef459d59f2276b8cef797a080e9c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 494, "license_type": "no_license", "max_line_length": 56, "num_lines": 21, "path": "/re.py", "repo_name": "naman0105/pythonRegex", "src_encoding": "UTF-8", "text": "import re\n\ntxt = \"Th.rain.d.DF and.thou.will an\"\nexpr = \"\\w+\\.\\w+\\.\\w+(\\.\\w*)*\"\n\ndef modified(str):\n print(str.group())\n x = re.split(r\"\\.\", str.group())\n newstr = \"json_value(\" + x[0] + \".\" + x[1] + \", '$\"\n for i in range(2, len(x)):\n newstr = newstr + \".\" + x[i]\n newstr = newstr + \"')\"\n return newstr\n \n\nx = re.sub(expr, modified(re.search(expr, txt)), txt, 1)\nprint(x)\nwhile re.search(expr, x):\n x = re.sub(expr, modified(re.search(expr, x)), x, 1)\n\nprint(x)\n" }, { "alpha_fraction": 0.5186640620231628, "alphanum_fraction": 0.5284872055053711, "avg_line_length": 21.130434036254883, "blob_id": "60e7d5c391ed2345333ed6e13c313daab0427963", "content_id": "214eddab0bb6caf2693a59ecec1be79e3ad1ae09", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 509, "license_type": "no_license", "max_line_length": 56, "num_lines": 23, "path": "/README.md", "repo_name": "naman0105/pythonRegex", "src_encoding": "UTF-8", "text": "# pythonRegex\n\nimport re\n\ntxt = \"Th.rain.d.DF and.thou.will an\"\nexpr = \"\\w+\\.\\w+\\.\\w+(\\.\\w*)*\"\n\ndef modified(str):\n print(str.group())\n x = re.split(r\"\\.\", str.group())\n newstr = \"json_value(\" + x[0] + \".\" + x[1] + \", '$\"\n for i in range(2, len(x)):\n newstr = newstr + \".\" + x[i]\n newstr = newstr + \"')\"\n return newstr\n \n\nx = re.sub(expr, modified(re.search(expr, txt)), txt, 1)\nprint(x)\nwhile re.search(expr, x):\n x = re.sub(expr, modified(re.search(expr, x)), x, 1)\n\nprint(x)\n" } ]
2
simonschuang/dnnportal
https://github.com/simonschuang/dnnportal
cc72e94e65989b3b247896ad480a8b001c4cbcc3
fa24b50a796d39b8b9921ecbd3296dd9f5713a15
7b850befcce39776895d4481e9d7511dd4e39a3d
refs/heads/master
2021-08-08T11:45:24.232734
2017-11-10T08:40:52
2017-11-10T08:40:52
109,342,530
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5225988626480103, "alphanum_fraction": 0.5240113139152527, "avg_line_length": 27.280000686645508, "blob_id": "929de669ee2278b72dc40b7a19696f5674e51b2e", "content_id": "ee6ff94874064c4615ab0fc647952f9e56db8fa0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 708, "license_type": "permissive", "max_line_length": 75, "num_lines": 25, "path": "/dnnport/views.py", "repo_name": "simonschuang/dnnportal", "src_encoding": "UTF-8", "text": "\nfrom flask import Blueprint, render_template\n\n\nblueprint = Blueprint(__name__, __name__)\n\n\[email protected]('/', methods=['GET'])\ndef home(tab=2):\n new_dataset_options = {\n 'Images': {\n 'image-classification': {\n 'title': 'Classification',\n 'url': flask.url_for(\n 'dnnport.dataset.images.classification.views.new'),\n },\n },\n }\n new_model_options = {}\n load_model_options = {}\n return render_template(\n 'home.html',\n new_dataset_options = new_dataset_options,\n new_model_options = new_model_options,\n load_model_options = load_model_options,\n )\n" }, { "alpha_fraction": 0.6957494616508484, "alphanum_fraction": 0.7002236843109131, "avg_line_length": 17.625, "blob_id": "e64e0edf78ea8d8091fb04817ae1ac3831d58fb9", "content_id": "9d2f13b6a7db25032d21a087987b053527cf016b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 447, "license_type": "permissive", "max_line_length": 51, "num_lines": 24, "path": "/dnnport/webapp.py", "repo_name": "simonschuang/dnnportal", "src_encoding": "UTF-8", "text": "# from __future__ import absolute_import\n\nimport os\nfrom flask import Flask\n\n\ndef register_blueprints(app):\n \"\"\"Register all blueprint modules\n \"\"\"\n import dnnport.views # noqa\n app.register_blueprint(dnnport.views.blueprint)\n\n return None\n\n\n# Create Flask, Scheduler and SocketIO objects\napp = Flask(\"dnnport\")\n\napp.config.update(dict(\n DEBUG = True,\n SECRET_KEY = os.urandom(12).encode('hex'),\n))\n\nregister_blueprints(app)\n" }, { "alpha_fraction": 0.6167800426483154, "alphanum_fraction": 0.6179138422012329, "avg_line_length": 26.5625, "blob_id": "72555215eb9d0133a817da66c630acb475c10402", "content_id": "bf9bed2a3f0f8f06c566b38a7f3bc29899f2ce84", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 882, "license_type": "permissive", "max_line_length": 93, "num_lines": 32, "path": "/setup.py", "repo_name": "simonschuang/dnnportal", "src_encoding": "UTF-8", "text": "import os\nimport setuptools\n\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\n# Get current __version__\nversion_locals = {}\nexecfile(os.path.join(os.path.dirname(__file__),'dnnport', 'version.py'), {}, version_locals)\n\n\nsetuptools.setup(\n name = \"dnnport\",\n version=version_locals['__version__'],\n author = \"Simon Chuang\",\n author_email = \"[email protected]\",\n description = (\"An DNN training portal.\"),\n license = \"MIT\",\n keywords = \"dnn\",\n url = \"https://github.com/simonschuang/dnnportal\",\n packages=setuptools.find_packages(),\n long_description=read('README.md'),\n classifiers=[\n \"Framework :: Flask\",\n \"Development Status :: 3 - Alpha\",\n \"Topic :: Utilities\",\n \"License :: OSI Approved :: MIT License\",\n ],\n install_requires=read('requirements.txt'),\n scripts=['dnnport-server'],\n)\n" }, { "alpha_fraction": 0.6966292262077332, "alphanum_fraction": 0.7265917658805847, "avg_line_length": 32.375, "blob_id": "b7b1d527a4f4aa02e408b46005f38f1d30420846", "content_id": "bcc05615f6c8bea714292372926b38cbb31cd388", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 267, "license_type": "permissive", "max_line_length": 101, "num_lines": 8, "path": "/dnnport/config/gpu_list.py", "repo_name": "simonschuang/dnnportal", "src_encoding": "UTF-8", "text": "# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved.\nfrom __future__ import absolute_import\n\nfrom . import option_list\nimport dnnport.device_query\n\n\noption_list['gpu_list'] = ','.join([str(x) for x in xrange(len(dnnport.device_query.get_devices()))])\n" }, { "alpha_fraction": 0.8607594966888428, "alphanum_fraction": 0.8607594966888428, "avg_line_length": 8.875, "blob_id": "d461c0fc33d6de72927e6722e979f0ae8c3a1f7b", "content_id": "e6a6815a9436d9c2790022dfed61d9269a32bad1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 79, "license_type": "permissive", "max_line_length": 16, "num_lines": 8, "path": "/requirements.txt", "repo_name": "simonschuang/dnnportal", "src_encoding": "UTF-8", "text": "gevent\ngevent-websocket\nFlask\nFlask-WTF\nwtforms\nFlask-SocketIO\nsetuptools\nlmdb\n" }, { "alpha_fraction": 0.7314440011978149, "alphanum_fraction": 0.7314440011978149, "avg_line_length": 22.870967864990234, "blob_id": "1d39da24baf4355882f331295f19d2148b1d1419", "content_id": "c813577df6ffb229f53f12306ebb29c271cd3ff7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 741, "license_type": "permissive", "max_line_length": 86, "num_lines": 31, "path": "/dnnport/dataset/images/classification/view.py", "repo_name": "simonschuang/dnnportal", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\n\nimport os\nimport shutil\n\n# Find the best implementation available\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from StringIO import StringIO\n\nimport flask\n\nfrom .forms import ImageClassificationDatasetForm\n#from digits.utils.forms import fill_form_if_cloned, save_form_to_job\n\n\nblueprint = flask.Blueprint(__name__, __name__)\n\n\[email protected]('/new', methods=['GET'])\ndef new():\n \"\"\"\n Returns a form for a new ImageClassificationDatasetJob\n \"\"\"\n form = ImageClassificationDatasetForm()\n\n # Is there a request to clone a job with ?clone=<job_id>\n #fill_form_if_cloned(form)\n\n return flask.render_template('datasets/images/classification/new.html', form=form)\n\n" }, { "alpha_fraction": 0.5813953280448914, "alphanum_fraction": 0.604651153087616, "avg_line_length": 7.599999904632568, "blob_id": "fcd519e6ff7145b2eeff8c06e86782dc29cf7c13", "content_id": "dc5db45edbafed4bf8c927d13ca5cf843021567f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 43, "license_type": "permissive", "max_line_length": 21, "num_lines": 5, "path": "/dnnport-server", "repo_name": "simonschuang/dnnportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nset -e\n\npython2 -m dnnport $@\n" }, { "alpha_fraction": 0.5695067048072815, "alphanum_fraction": 0.5889387130737305, "avg_line_length": 21.299999237060547, "blob_id": "5fc9a35c8f8f6ce4fbb449982ba0a9c15b074e60", "content_id": "e5edbfc500b370f6ece99591cee3a4ade046af93", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 669, "license_type": "permissive", "max_line_length": 102, "num_lines": 30, "path": "/docker/Dockerfile", "repo_name": "simonschuang/dnnportal", "src_encoding": "UTF-8", "text": "FROM ubuntu:16.04\nMAINTAINER [email protected]\n\n\nENV DNNPORT_VERSION=master\nENV DNNPORT_ROOT=/opt/dnnport\n\nRUN apt-get update && apt-get install -y \\\n git \\\n liblcms2-dev \\\n libfreetype6-dev \\\n libjpeg8-dev \\\n libtiff5-dev \\\n libwebp-dev \\\n python-numpy \\\n python-pip \\\n python-tk \\\n tcl8.6-dev \\\n tk8.6-dev \\\n vim \\\n zlib1g-dev \\\n && rm -rf /var/lib/apt/lists/*\n\nRUN git clone -b ${DNNPORT_VERSION} https://github.com/simonschuang/dnnportal.git ${DNNPORT_ROOT} && \\\n pip install --upgrade pip && \\\n pip install -r ${DNNPORT_ROOT}/requirements.txt\n\nWORKDIR /workspace/\n\nCMD bash\n" }, { "alpha_fraction": 0.6580311059951782, "alphanum_fraction": 0.6994818449020386, "avg_line_length": 26.571428298950195, "blob_id": "224e3dc2eedd0283d3f2780e59efc7f1a66167c2", "content_id": "200693c62304ebbec3e97d894d81009bd8e9e125", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 193, "license_type": "permissive", "max_line_length": 68, "num_lines": 7, "path": "/dnnport/__init__.py", "repo_name": "simonschuang/dnnportal", "src_encoding": "UTF-8", "text": "# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved.\nfrom __future__ import absolute_import\n\nfrom .version import __version__\nfrom .webapp import app\n\n__all__ = ['__version__']\n" } ]
9
phv2312/anime_colorization
https://github.com/phv2312/anime_colorization
ebf0f9b2b2d7da497418db0491e768e7cadb8e21
16bf645d4a4fb81be7a7aea51e6e86d0fe5935d4
92f102edaa305a696bc1694a9e19d1d86de6e15c
refs/heads/master
2023-01-05T00:31:37.919868
2020-10-20T17:22:23
2020-10-20T17:22:23
279,765,147
4
0
null
null
null
null
null
[ { "alpha_fraction": 0.5199697017669678, "alphanum_fraction": 0.547037661075592, "avg_line_length": 31.0181827545166, "blob_id": "a9fd7e75fba407d0d0e244859d434da3249d203f", "content_id": "99b6ed566a2deb90afd015ee77b2c3e5552727c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5283, "license_type": "no_license", "max_line_length": 104, "num_lines": 165, "path": "/libs/dataset/anime_dataset_return_ske.py", "repo_name": "phv2312/anime_colorization", "src_encoding": "UTF-8", "text": "import os\nimport random\nfrom PIL import Image\nimport torch\nfrom torch.utils.data import Dataset\nimport torchvision.transforms as transforms\nfrom torchvision.transforms import functional as tvF\n\n\nclass RandomResizedCrop(transforms.RandomResizedCrop):\n def __init__(self, size, scale=(0.84, 0.9), ratio=(1.0, 1.0), interpolation=Image.BICUBIC):\n super(RandomResizedCrop, self).__init__(size, scale, ratio, interpolation)\n\n def __call__(self, img1, img2):\n assert img1.size == img2.size\n # fix parameter\n i, j, h, w = self.get_params(img1, self.scale, self.ratio)\n # return the image with the same transformation\n\n img1 = tvF.resized_crop(img1, i, j, h, w, self.size, self.interpolation)\n img2 = tvF.resized_crop(img2, i, j, h, w, self.size, self.interpolation)\n return img1, img2\n\n\nclass RandomHorizontalFlip(transforms.RandomHorizontalFlip):\n def __call__(self, img1, img2):\n assert img1.size == img2.size\n\n p = random.random()\n if p < 0.5:\n img1 = tvF.hflip(img1)\n if p < 0.5:\n img2 = tvF.hflip(img2)\n return img1, img2\n\n\nclass RandomVerticalFlip(transforms.RandomVerticalFlip):\n def __call__(self, img1, img2):\n assert img1.size == img2.size\n\n p = random.random()\n if p < 0.5:\n img1 = tvF.vflip(img1)\n if p < 0.5:\n img2 = tvF.vflip(img2)\n return img1, img2\n\n\nclass GeekDataset(Dataset):\n \"\"\"\n > root_dir\n > 001:\n > color: _1.png, _2.png, ...\n > sketch: _1.png, _2.png, ...\n > 002:\n > color: _1.png, _2.png, ...\n > sketch: _1.png, _2.png, ...\n \"\"\"\n\n def prepare_db(self, root):\n sub_dirs = os.listdir(root)\n print('Len sub_dir:', len(sub_dirs))\n\n sub_dir_dict = []\n sub_dir_idx = []\n corlor_fns = []\n _id = 0\n for sub_dir in sub_dirs:\n _sub_dir_full = os.path.join(root, sub_dir)\n\n _color_dir = os.path.join(_sub_dir_full, 'color_processed')\n if not os.path.exists(_color_dir): continue\n _color_fns = os.listdir(_color_dir)\n\n _sketch_dir = os.path.join(_sub_dir_full, 'sketch_processed')\n if not os.path.exists(_sketch_dir): continue\n _sketch_fns = os.listdir(_sketch_dir)\n\n assert len(_color_fns) == len(_sketch_fns)\n _color_fns = [os.path.join(_sub_dir_full, 'color_processed', _fn) for _fn in _color_fns]\n _sketch_fns = [os.path.join(_sub_dir_full, 'sketch_processed', _fn) for _fn in _sketch_fns]\n\n if len(_color_fns) >= 2:\n # adding ...\n corlor_fns += _color_fns\n sub_dir_idx += [_id] * len(_color_fns)\n\n sub_dir_dict += [{'color': _color_fns, 'sketch': _sketch_fns}]\n _id += 1\n\n return sub_dir_dict, corlor_fns, sub_dir_idx\n\n def __init__(self, root, resolution=256, pad_ratio=8):\n self.root = root\n self.min_crop_area = ((pad_ratio + 1) / (pad_ratio + 2)) ** 2\n\n #\n self.color_dir = os.path.join(self.root, 'color_processed')\n self.sketch_dir = os.path.join(self.root, 'sketch_processed')\n\n #\n self.sub_dirs, self.color_fns, self.sub_dir_idx = self.prepare_db(self.root)\n\n # transforms\n self.norm = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ])\n\n self.style_img_aug = transforms.Compose([\n transforms.RandomResizedCrop(resolution, scale=(self.min_crop_area, 1.0), ratio=(1.0, 1.0)),\n transforms.RandomHorizontalFlip(),\n transforms.RandomVerticalFlip(),\n ])\n\n self.paired_aug = [\n RandomResizedCrop(resolution, scale=(self.min_crop_area, 1.0), ratio=(1.0, 1.0)),\n RandomHorizontalFlip(),\n RandomVerticalFlip(),\n ]\n\n def __getitem__(self, idx):\n # idx = 3747 #2102\n # print (idx)\n \"\"\"\n returns s1, s2, s3, contour such that\n s1, s2 are in the same cluster\n s3, contour are paired icon and it's contour\n note that s3 can be in different cluster\n \"\"\"\n dir_id = self.sub_dir_idx[idx]\n dir_info = self.sub_dirs[dir_id]\n\n if len(dir_info['color']) < 2:\n return self.__getitem__((idx + 1) % len(self.color_fns))\n\n same_color_paths = random.choices(dir_info['color'], k=2)\n s1_path, s2_path = same_color_paths\n\n if random.uniform(0, 1) < 0.4:\n tmp = s1_path\n s1_path = s2_path\n s2_path = tmp\n\n contour_path = dir_info['sketch'][dir_info['color'].index(s1_path)]\n\n s1 = Image.open(s1_path).convert('RGB')\n s2 = Image.open(s2_path).convert('RGB')\n contour = Image.open(contour_path).convert('RGB')\n\n\n # for _debug_im in [s1, s2, s3, contour]:\n # \timgshow(_debug_im)\n\n s1 = self.style_img_aug(s1)\n s2 = self.style_img_aug(s2)\n\n s1 = self.norm(s1)\n s2 = self.norm(s2)\n contour = self.norm(contour)\n\n return contour[:1, :, :], s2, s1, {'G': None}\n\n def __len__(self):\n return len(self.color_fns)\n" }, { "alpha_fraction": 0.6005290746688843, "alphanum_fraction": 0.6111111044883728, "avg_line_length": 24.133333206176758, "blob_id": "2cb61ac4432549c2287cdeed9cfd486be2f55134", "content_id": "eedabaf2c024fb6bd2083679862e5c9c3e545685", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 378, "license_type": "no_license", "max_line_length": 47, "num_lines": 15, "path": "/libs/loss/gan_loss.py", "repo_name": "phv2312/anime_colorization", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn.functional as F\n\n# hinge loss\ndef dis_loss(D, real, fake):\n # remember to detach fake\n d_out_real = D(real)\n d_out_fake = D(fake.detach())\n loss_real = F.relu(1.0 - d_out_real).mean()\n loss_fake = F.relu(1.0 + d_out_fake).mean()\n return loss_real + loss_fake\n\ndef gen_loss(D, fake):\n d_out = D(fake)\n return -(d_out).mean()\n\n" }, { "alpha_fraction": 0.5313968658447266, "alphanum_fraction": 0.5809482932090759, "avg_line_length": 26.845237731933594, "blob_id": "7ce9cac7017597888d1549fc6e8335c3034932a9", "content_id": "b1e4a11dd6721fed9cc9e7777073e20b5329b18d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2341, "license_type": "no_license", "max_line_length": 87, "num_lines": 84, "path": "/libs/nn/tps_model.py", "repo_name": "phv2312/anime_colorization", "src_encoding": "UTF-8", "text": "import random\nimport numpy as np\nimport cv2\nimport PIL.Image as Image\nfrom math import floor\nfrom libs.nn.thinplate import numpy as tps\n\nimport matplotlib.pyplot as plt\ndef imgshow(im):\n plt.imshow(im)\n plt.show()\n\ndef warp_image_cv(img, c_src, c_dst, dshape=None):\n\n dshape = dshape or img.shape\n theta = tps.tps_theta_from_points(c_src, c_dst, reduced=True)\n\n grid = tps.tps_grid(theta, c_dst, dshape)\n mapx, mapy = tps.tps_grid_to_remap(grid, img.shape)\n return cv2.remap(img, mapx, mapy, cv2.INTER_CUBIC), theta\n\ndef random_cord():\n random.seed(2312)\n # initialize ...\n c_src = [\n [random.uniform(0, 0.15), random.uniform(0, 0.15)],\n [random.uniform(0.85, 1), random.uniform(0, 0.1)],\n [random.uniform(0.85, 1), random.uniform(0.85, 1)],\n [random.uniform(0, 0.15), random.uniform(0.85, 1)],\n ]\n\n c_dst = [\n [random.uniform(0, 0.15), random.uniform(0, 0.15)],\n [random.uniform(0.85, 1), random.uniform(0, 0.1)],\n [random.uniform(0.85, 1), random.uniform(0.85, 1)],\n [random.uniform(0, 0.15), random.uniform(0.85, 1)],\n ]\n\n #\n _src = [random.uniform(0.1, 0.4), random.uniform(0.1, 0.4)]\n\n k = random.uniform(1.1, 1.3)\n _dst = [_src[0] * k, _src[1] * k]\n\n c_src += [_src]\n c_dst += [_dst]\n\n #\n _src = [random.uniform(0.5, 0.8), random.uniform(0.5, 0.8)]\n\n k = random.uniform(0.8, 1.)\n _dst = [_src[0] * k, _src[1] * k]\n\n c_src += [_src]\n c_dst += [_dst]\n\n return np.array(c_src), np.array(c_dst)\n\nclass TPS:\n def augment(self, input_image):\n \"\"\"\n\n :param input_image: output image will have the same size as input image\n :return:\n \"\"\"\n is_pil = True if type(input_image) == Image.Image else False\n if is_pil:\n input_image = np.array(input_image)\n\n c_src, c_dst = random_cord()\n warp_image, theta = warp_image_cv(input_image, c_src, c_dst, dshape=(256, 256))\n\n if is_pil:\n warp_image = Image.fromarray(warp_image)\n\n return warp_image, theta, c_dst\n\nif __name__ == '__main__':\n input_image= cv2.imread(\"/home/kan/Desktop/visualize_282001.png\")\n input_image = cv2.resize(input_image, dsize=(256,256))\n\n tps_model = TPS()\n warped_image, _, _ = tps_model.augment(input_image)\n imgshow(warped_image)\n\n\n" }, { "alpha_fraction": 0.5962733030319214, "alphanum_fraction": 0.5962733030319214, "avg_line_length": 20.53333282470703, "blob_id": "8a51db927a4ff28720dca28ea1cf10da1ce28a89", "content_id": "50237ed1d315cd629fbed6a4eb873270c40d0d46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 322, "license_type": "no_license", "max_line_length": 56, "num_lines": 15, "path": "/libs/utils/dataset.py", "repo_name": "phv2312/anime_colorization", "src_encoding": "UTF-8", "text": "import os\nimport glob\nimport PIL.Image as Image\n\ndef read_im(im_path, pil_mode='RGB'):\n return Image.open(im_path).convert(pil_mode)\n\ndef load_file_from_dir(dir, exts=['.jpg', '.png']):\n fns = []\n\n for ext in exts:\n _fns = glob.glob(os.path.join(dir, \"*%s\" % ext))\n fns += list(_fns)\n\n return fns" }, { "alpha_fraction": 0.6040623188018799, "alphanum_fraction": 0.6196438670158386, "avg_line_length": 32.588783264160156, "blob_id": "d2762a27bfffb6305d7b75ff2e2f1301aeff11a0", "content_id": "332166849b2f0f0e86c00a856c5bd0cf742f3d23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3594, "license_type": "no_license", "max_line_length": 110, "num_lines": 107, "path": "/libs/loss/content_style_loss.py", "repo_name": "phv2312/anime_colorization", "src_encoding": "UTF-8", "text": "import copy\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport torchvision.transforms as transforms\nimport torchvision.models as models\n\ndef gram_matrix(input):\n a, b, c, d = input.size() # a=batch size(=1)\n # b=number of feature maps\n # (c,d)=dimensions of a f. map (N=c*d)\n\n features = input.view(a * b, c * d) # resise F_XL into \\hat F_XL\n\n G = torch.mm(features, features.t()) # compute the gram product\n\n # we 'normalize' the values of the gram matrix\n # by dividing by the number of element in each feature maps.\n return G.div(a * b * c * d)\n\nclass FeatureExtraction2(nn.Module):\n def __init__(self):\n super(FeatureExtraction2, self).__init__()\n\n model = models.vgg19(pretrained=True)\n self.layer = model.features\n\n self.extracted_layer_name = ['1', '6', '11', '20', '29']\n\n def forward(self, x):\n outputs = []\n for _id, module in self.layer._modules.items():\n x = module(x)\n if str(_id) in self.extracted_layer_name:\n outputs.append(x)\n\n return outputs\n\n\nclass FeatureExtraction(nn.Module):\n \"\"\"\n Feature extraction model for Perceptual Loss and Style Loss\n Use VGG19 to extract features.\n \"\"\"\n\n def __init__(self, model):\n super(FeatureExtraction, self).__init__()\n # For VGG19 network\n self.model = nn.Sequential(*list(*list(model.children())[:1])[:32])\n self.feature_blobs = []\n self.register_hook()\n\n # # freeze weights\n # for layer in self.model.parameters():\n # layer.requires_grad = False\n\n def hook_feature(self, module, input, output):\n self.feature_blobs.append(output.data)\n\n def register_hook(self):\n self.model._modules.get(\"1\").register_forward_hook(self.hook_feature)\n self.model._modules.get(\"6\").register_forward_hook(self.hook_feature)\n self.model._modules.get(\"11\").register_forward_hook(self.hook_feature)\n self.model._modules.get(\"20\").register_forward_hook(self.hook_feature)\n self.model._modules.get(\"29\").register_forward_hook(self.hook_feature)\n\n def forward(self, x):\n self.feature_blobs = []\n self.model(x)\n return self.feature_blobs\n\n\nclass L1StyleContentLoss(nn.Module):\n def __init__(self, content_layers=['conv_4'],\n style_layers=['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5']):\n super(L1StyleContentLoss, self).__init__()\n\n # desired depth layers to compute style/content losses :\n self.content_layers = content_layers\n self.style_layers = style_layers\n\n self.feature_extractor = FeatureExtraction2() #FeatureExtraction(models.vgg19(pretrained=True).eval())\n\n def forward(self, predict, target):\n \"\"\"\n\n :param predict: of size (b, c, h, w)\n :param target: of size (b, c, h, w)\n :return: style, perceptual, l1\n \"\"\"\n predict_features = self.feature_extractor(predict)\n target_features = self.feature_extractor(target)\n\n content_loss = 0.\n style_loss = 0.\n for predict_feature, target_feature in zip(predict_features, target_features):\n content_loss += F.l1_loss(predict_feature, target_feature)\n style_loss += F.l1_loss(gram_matrix(predict_feature), gram_matrix(target_feature))\n\n l1_loss = F.l1_loss(predict, target)\n\n return style_loss, content_loss, l1_loss\n\nif __name__ == '__main__':\n feature_extract = FeatureExtraction2().eval()\n feature_extract(torch.rand(size=(1,3,256,256)))\n" }, { "alpha_fraction": 0.5683881044387817, "alphanum_fraction": 0.5827856063842773, "avg_line_length": 32.29166793823242, "blob_id": "4502791339c4c0068ab13cca9ca54a4e39e0da29", "content_id": "7b72e8d6a9af4d7842ed6f21e5255962cf7f25c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3195, "license_type": "no_license", "max_line_length": 115, "num_lines": 96, "path": "/libs/dataset/anime_dataset_akari.py", "repo_name": "phv2312/anime_colorization", "src_encoding": "UTF-8", "text": "import torch.utils.data as data\nimport torchvision.transforms as transforms\nfrom natsort import natsorted\nimport glob\nimport os\nfrom PIL import Image, ImageCms\nimport random\n\ndef get_image_by_index(items, index):\n if index is None:\n return None\n path = items[index]\n image = Image.open(path).convert(\"RGB\")\n return image\n\n\ndef do_transform(load_size, method=Image.BICUBIC, same_image=False, grayscale=False, convert=True, resize=True):\n transform_list = []\n if grayscale:\n transform_list.append(transforms.Grayscale(1))\n if resize:\n transform_list.append(transforms.Resize(load_size, method))\n if same_image:\n transform_list.append(transforms.RandomAffine(degrees=24, translate=(0.1, 0.1), fillcolor=(255, 255, 255)))\n if convert:\n transform_list += [transforms.ToTensor()]\n if grayscale:\n transform_list += [transforms.Normalize((0.5,), (0.5,))]\n else:\n transform_list += [transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]\n return transforms.Compose(transform_list)\n\n\nclass AnimeDataset(data.Dataset):\n def __init__(self, root_dir, load_size=(256,256), num_rand=69):\n super(AnimeDataset, self).__init__()\n random.seed(num_rand)\n self.root_dir = root_dir\n self.load_size = load_size\n\n self.paths = {}\n self.lengths = {}\n dirs = natsorted(glob.glob(os.path.join(root_dir, \"*\")))\n\n for sub_dir in dirs:\n dir_name = os.path.basename(sub_dir)\n self.paths[dir_name] = {}\n\n for set_name in [\"sketch_v3\", \"color\"]:\n paths = []\n for sub_type in [\"png\", \"jpg\", \"tga\"]:\n paths.extend(glob.glob(os.path.join(sub_dir, set_name, \"*.%s\" % sub_type)))\n self.paths[dir_name][set_name] = natsorted(paths)\n\n self.lengths[dir_name] = len(self.paths[dir_name][\"color\"])\n\n return\n\n def __len__(self):\n total = 0\n for key, count in self.lengths.items():\n total += count\n return total\n\n def __getitem__(self, index):\n name = None\n\n for key, length in self.lengths.items():\n if index < length:\n name = key\n break\n index -= length\n\n # pick sketch's path for visualization purpose\n sketch_path = self.paths[name][\"sketch_v3\"][index]\n\n # pick ref index\n ref_index = random.randint(0, len(self.paths[name][\"color\"]) - 1)\n\n # get path of ref, sketch, groundtruth\n ref = get_image_by_index(self.paths[name][\"color\"], ref_index)\n sketch = get_image_by_index(self.paths[name][\"sketch_v3\"], index)\n gt = get_image_by_index(self.paths[name][\"color\"], index)\n\n color_tf = do_transform(self.load_size)\n sketch_tf = do_transform(self.load_size, grayscale=True)\n same_image_tf = do_transform(self.load_size, same_image=True)\n\n if ref_index == index:\n ref = same_image_tf(ref)\n else:\n ref = color_tf(ref)\n sketch = sketch_tf(sketch)\n gt = color_tf(gt)\n\n return sketch, gt, ref, {'sketch_path': sketch_path, 'G': []}" }, { "alpha_fraction": 0.521570086479187, "alphanum_fraction": 0.5436418652534485, "avg_line_length": 35.07692337036133, "blob_id": "1f1d013653c55811523266c9c3d3051d1995a48b", "content_id": "7b9a585ae8048db06f0a53af7da343f169f08d0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7974, "license_type": "no_license", "max_line_length": 180, "num_lines": 221, "path": "/libs/loss/triplet_loss.py", "repo_name": "phv2312/anime_colorization", "src_encoding": "UTF-8", "text": "import torch\nimport random\nimport numpy as np\nimport torch.nn as nn\nimport copy\nimport torch.nn.functional as F\n\nfrom libs.nn.thinplate import numpy as tps\n\ndef _calc_dot_product(elem1, elem2):\n return torch.matmul(elem1, elem2.t())\n\ndef _to_ys(idx):\n return [_[1] for _ in idx]\n\ndef _to_xs(idx):\n return [_[0] for _ in idx]\n\nclass GridVisualize():\n def __init__(self, org_size, feature_size):\n self.org_w, self.org_h = org_size\n self.feature_w, self.feature_h = feature_size\n self.r = self.org_w // self.feature_w\n\n def to_video(self, video_fn, list_images):\n out = cv2.VideoWriter(video_fn, cv2.VideoWriter_fourcc(*'DIVX'), 15, (self.org_w * 2, self.org_h))\n\n for i in range(len(list_images)):\n out.write(list_images[i])\n\n out.release()\n\n def visualize(self, color_image):\n from libs.nn.tps_model import TPS\n import cv2\n\n color_image = cv2.resize(color_image, dsize=(self.org_w, self.org_h))\n\n augment_color_image, theta, c_dist = TPS().augment(color_image)\n\n theta = theta[np.newaxis, :, :] # dummy batch size\n c_dist = c_dist[np.newaxis, :, :] # dummy batch size\n color_image = color_image[np.newaxis, :, :, :]\n augment_color_image = augment_color_image[np.newaxis, :, :, :]\n\n grid_process = GridProcessing(theta, c_dist, (self.feature_h, self.feature_w))\n positive_cords = grid_process.get_positive()\n\n list_image = []\n for (ac_b, ac_iy, ac_ix), (po_b, po_iy, po_ix) in positive_cords.items():\n _color_image = color_image[ac_b].copy()\n _augment_color_image = augment_color_image[po_b].copy()\n\n cv2.circle(_color_image, (int(ac_ix * self.r), int(ac_iy * self.r)), radius=8,\n color=(0, 0, 255), thickness=3)\n cv2.circle(_augment_color_image, (int(po_ix * self.r), int(po_iy * self.r)), radius=8,\n color=(0, 255, 0), thickness=3)\n\n list_image += [np.concatenate([_augment_color_image, _color_image], axis=1)]\n\n return list_image\n\nclass GridProcessing():\n def __init__(self, theta=None, c_dst=[], f_shape=(32, 32)):\n self.f_shape = f_shape\n\n self.G = tps.batch_tps_grid(theta, c_dst, dshape=f_shape) # (b,h,w,2~xy)\n\n self.G_new = self._decompose_G(self.G)\n\n def _decompose_G(self, G):\n B, H, W, _ = G.shape\n\n G *= np.array([W, H]).reshape((1, 1, 1, 2))\n\n G_xmin = np.floor(G[:, :, :, [0]]).astype(np.int32)\n G_xmax = G_xmin + 1\n G_ymin = np.floor(G[:, :, :, [1]]).astype(np.int32)\n G_ymax = G_ymin + 1\n\n \"\"\"\n 1 +++ 2\n +++++++\n 4 +++ 3\n \"\"\"\n\n G1 = np.concatenate([G_xmin, G_ymin], axis=-1)\n G2 = np.concatenate([G_xmax, G_ymin], axis=-1)\n G3 = np.concatenate([G_xmax, G_ymax], axis=-1)\n G4 = np.concatenate([G_xmin, G_ymax], axis=-1)\n\n G1_dist = np.linalg.norm(G - G1, ord=2, axis=-1)\n G2_dist = np.linalg.norm(G - G2, ord=2, axis=-1)\n G3_dist = np.linalg.norm(G - G3, ord=2, axis=-1)\n G4_dist = np.linalg.norm(G - G4, ord=2, axis=-1)\n\n G1 = np.concatenate([G1, G1_dist[:,:,:,np.newaxis]], axis=-1)\n G2 = np.concatenate([G2, G2_dist[:,:,:,np.newaxis]], axis=-1)\n G3 = np.concatenate([G3, G3_dist[:,:,:,np.newaxis]], axis=-1)\n G4 = np.concatenate([G4, G4_dist[:,:,:,np.newaxis]], axis=-1)\n\n G_new = np.stack([G1, G2, G3, G4], axis=3)\n return G_new\n\n def get_positive(self):\n B, H, W, _, _ = self.G_new.shape\n\n positive_pair = {} # key from sketch-anchor, value from reference\n for b in range(B):\n _G_new = self.G_new[b] # (H, W, 4, 3)\n\n # get_positive\n for h in range(H):\n for w in range(W):\n\n p1, p2, p3, p4 = _G_new[h, w, :, :2]\n p1_dist, p2_dist, p3_dist, p4_dist = _G_new[h, w, : ,-1]\n ps = []\n dists = []\n\n # filter\n for p_id, (p, dist) in enumerate(zip([p1, p2, p3, p4], [p1_dist, p2_dist, p3_dist, p4_dist])):\n if p[0] < 0 or p[1] < 0: continue #lower bound\n if p[0] > W - 1 or p[1] > H - 1: continue #upper bound\n ps += [p]; dists += [dist]\n\n if len(ps) > 0:\n\n dists = np.array(dists)\n probs = np.max(dists) - dists + 0.3\n probs = probs / np.sum(probs)\n\n p_pos_id = int(np.argmax(probs)) #np.random.choice(np.arange(len(ps)), p=probs)\n positive_pair[(b, int(ps[p_pos_id][1]), int(ps[p_pos_id][0]))] = (b, int(h), int(w))\n\n return positive_pair\n\nclass TripletLoss(nn.Module):\n def __init__(self, margin=1.0):\n super(TripletLoss, self).__init__()\n self.margin = margin\n\n def calc_cosine(self, x1, x2):\n return 1 - F.cosine_similarity(x1, x2)\n\n def forward(self, anchor, positive, negative, print_value=False) -> torch.Tensor:\n distance_positive = self.calc_cosine(anchor, positive)\n distance_negative = self.calc_cosine(anchor, negative)\n losses = torch.relu(distance_positive - distance_negative + self.margin)\n\n if print_value:\n print ('pos:', distance_positive)\n print ('neg:', distance_negative)\n\n return losses\n\ndef calculate_cosine_distance(sketch_f, ref_fs):\n \"\"\"\n sketch_f: of shape (D, 1),\n ref_fs: of shape (D, F_H F_W)\n \"\"\"\n D, F_H, F_W = ref_fs.shape\n ref_fs_flat = ref_fs.view(D, F_H * F_W)\n\n sim = F.cosine_similarity(sketch_f.T, ref_fs_flat.T)\n dis = torch.ones_like(sim) - sim\n\n return dis.view(F_H, F_W)\n\nclass SimilarityTripletLoss(nn.Module):\n def __init__(self):\n super(SimilarityTripletLoss, self).__init__()\n\n def forward(self, sketch_query_vectors, ref_key_vectors, theta, c_dst):\n \"\"\"\n :param sketch_query_vectors: of size (b, hw, n_dim)\n :param ref_key_vectors: of size (b, hw, n_dim)\n :param ...\n :return:\n \"\"\"\n B, C, F_H, F_W = sketch_query_vectors.size()\n grid_process = GridProcessing(theta.cpu().numpy(), c_dst.cpu().numpy(), (F_H, F_W))\n\n i = 0\n triplet_loss = 0\n positive_cords = grid_process.get_positive()\n\n pos_distances, neg_distances = [], []\n for (ac_b, ac_iy, ac_ix), (po_b, po_iy, po_ix) in positive_cords.items():\n sketch_ac_f = sketch_query_vectors[ac_b, :, [ac_iy], [ac_ix]]\n ref_po_f = ref_key_vectors[po_b, :, [po_iy], [po_ix]]\n\n # get negative\n distance = calculate_cosine_distance(sketch_ac_f, ref_key_vectors[po_b])\n ignore_pos = torch.zeros_like(distance)\n ignore_pos[po_iy, po_ix] = 2. # ignore positive\n\n min_distances = torch.topk(distance.flatten() + ignore_pos.flatten(), k=4, largest=False, dim=-1)[0]\n pos_distance = distance[po_iy, po_ix]\n\n neg_distances.append(min_distances)\n pos_distances.append(pos_distance)\n\n pos_distance = torch.mean(torch.stack(pos_distances, dim=-1))\n loss = pos_distance\n\n if len(neg_distances) > 0:\n neg_distances = torch.cat(neg_distances, dim=-1)\n neg_loss = torch.clamp(torch.full_like(neg_distances, 0.6) - neg_distances, min=0.0)\n neg_loss = torch.mean(neg_loss)\n loss = loss + neg_loss\n return loss\n\n\nif __name__ == '__main__':\n import cv2\n\n im_fn = \"/home/kan/Desktop/Cinnamon/gan/Adversarial-Colorization-Of-Icons-Based-On-Structure-And-Color-Conditions/geek/full_data/hor01_sample/color/hor01_018_021_k_A_A0002.png\"\n visualize = GridVisualize(org_size=(256,256), feature_size=(16, 16))\n list_image = visualize.visualize(color_image=cv2.imread(im_fn))\n visualize.to_video(\"./output.avi\", list_image)\n\n" }, { "alpha_fraction": 0.5830453634262085, "alphanum_fraction": 0.609066903591156, "avg_line_length": 33.40559387207031, "blob_id": "7b5ee3d654c993ea8373263ac0156ee877fdcafa", "content_id": "26d798c54dc3ed8db1d263009494b700ca3e979d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4919, "license_type": "no_license", "max_line_length": 189, "num_lines": 143, "path": "/infer.py", "repo_name": "phv2312/anime_colorization", "src_encoding": "UTF-8", "text": "import torch\nimport click\nimport numpy as np\nimport cv2\n\nfrom torchvision.transforms import transforms\nfrom scipy.spatial.distance import cdist\n\nfrom libs.nn.tps_model import TPS\nfrom libs.utils.flow import load_model, imgshow\nfrom libs.utils.dataset import read_im\nfrom libs.nn.color_model import ColorModel, Discriminator\n\ndef gen_reference_image(colored_image):\n augmented_image, _, _ = TPS().augment(colored_image)\n\n return augmented_image\n\ndef get_attention(sketch_queries_f, refer_key_f):\n \"\"\"\n\n :param sketch_queries_f: shape (1, dim, 32, 32) == (b,c,h,w)\n :param refer_key_f: shape (1, dim, 32, 32)\n :return:\n \"\"\"\n\n sketch_queries_f = sketch_queries_f.squeeze(0).transpose(1,2,0) # (h,w,d)\n refer_key_f = refer_key_f.squeeze(0).transpose(1,2,0) # (h,w,d)\n\n h, w, d = sketch_queries_f.shape\n\n sketch_queries_f = sketch_queries_f.reshape((h * w, d))\n refer_key_f = refer_key_f.reshape((h * w, d))\n\n matrix_dist = cdist(sketch_queries_f, refer_key_f, metric='cosine')\n min_refer_ids = np.argmin(matrix_dist, axis=-1)\n\n # #\n # _min_refer_ids = np.argsort(matrix_dist, axis=-1)\n # for sketch_id in range(len(matrix_dist)):\n # _matrix_dist = _min_refer_ids[sketch_id][:5]\n #\n # s_h, s_w = sketch_id // w, sketch_id % w\n #\n # r_hs = _matrix_dist // w\n # r_ws = _matrix_dist % w\n #\n # print ('Source:', (s_h, s_w))\n #\n # print ('Tagt:', (s_h, s_w), ',dist:', matrix_dist[sketch_id, sketch_id])\n # print (matrix_dist[sketch_id].mean(), matrix_dist[sketch_id].max())\n #\n # for _id, (r_h, r_w) in enumerate(zip(r_hs, r_ws)):\n # print ('Pred:', (r_h, r_w), ',dist:', matrix_dist[sketch_id, _matrix_dist[_id]])\n #\n #\n # input('press enter to continue ...')\n #\n #\n pair = {}\n\n\n\n for sketch_id, refer_id in enumerate(min_refer_ids):\n\n\n s_h, s_w = sketch_id // w, sketch_id % w\n r_h, r_w = refer_id // w, refer_id % w\n\n pair[(s_w, s_h)] = (r_w, r_h)\n\n print((s_h, s_w), (r_h, r_w), matrix_dist[sketch_id][refer_id])\n\n return pair\n\ndef to_video(video_fn, list_images):\n out = cv2.VideoWriter(video_fn, cv2.VideoWriter_fourcc(*'DIVX'), 15, (512, 256))\n\n for i in range(len(list_images)):\n out.write(list_images[i])\n\n out.release()\n\n# @click.command()\n# @click.option('--cfg', default='./exps/_simple.yaml', help='Path to Config Path')\n# @click.option('--weight_path', default=\"\", help=\"Path to weight\")\ndef main(cfg, weight_path, sketch_path, reference_path):\n # prepare model & transforms\n color_model = load_model(ColorModel(), weight_path).eval()\n color_model.cuda()\n\n infer_transforms = transforms.Compose([\n transforms.Resize(size=(256, 256)),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.5,), std=(0.5, ))\n ])\n\n # prepare input\n reference_image = gen_reference_image(read_im(reference_path))\n sketch_image = read_im(sketch_path)\n\n reference_input = infer_transforms(reference_image).unsqueeze(0).cuda()\n sketch_input = infer_transforms(sketch_image)[:1,:,:].unsqueeze(0).cuda()\n\n # infer ....\n mean, std = [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]\n with torch.no_grad():\n o_im, sketch_queries_f, refer_key_f = color_model(reference_input, sketch_input)\n\n o_im = o_im.squeeze(0).cpu()\n r_im = reference_input.squeeze(0).cpu()\n\n o_im = o_im * torch.tensor(data=std).view(3, 1, 1) + torch.tensor(data=mean).view(3, 1, 1)\n o_im = transforms.ToPILImage(mode='RGB')(o_im)\n r_im = r_im * torch.tensor(data=std).view(3, 1, 1) + torch.tensor(data=mean).view(3, 1, 1)\n r_im = transforms.ToPILImage(mode='RGB')(r_im)\n\n o_im = np.array(o_im)\n r_im = np.array(r_im)\n\n # visualize attention\n pair = get_attention(sketch_queries_f.cpu().numpy(), refer_key_f.cpu().numpy())\n r = 16\n list_image = []\n for (src_w, src_h), (tgt_w, tgt_h) in pair.items():\n print ((src_w, src_h), (tgt_w, tgt_h))\n\n _o_im = o_im.copy()\n _r_im = r_im.copy()\n\n cv2.circle(_o_im, (int(r * src_w), int(r * src_h)), radius=3, color=(255, 0, 0), thickness=2)\n cv2.circle(_r_im, (int(r * tgt_w), int(r * tgt_h)), radius=3, color=(255, 0, 0), thickness=2)\n\n list_image += [np.concatenate([_r_im, _o_im], axis=1)]\n\n to_video(\"./debug_vis_attn.avi\", list_image)\n\nif __name__ == '__main__':\n sketch_path = \"/home/kan/Desktop/Cinnamon/gan/Adversarial-Colorization-Of-Icons-Based-On-Structure-And-Color-Conditions/geek/full_data/hor01_sample_1/sketch/hor01_018_021_k_A_A0001.png\"\n refer_path = \"/home/kan/Desktop/Cinnamon/gan/Adversarial-Colorization-Of-Icons-Based-On-Structure-And-Color-Conditions/geek/full_data/hor01_sample_1/color/hor01_018_021_k_A_A0001.png\"\n weight_path = \"/home/kan/Desktop/Cinnamon/gan/self_augment_color/weights/00000520.G.pth\"\n\n main(None, weight_path, sketch_path, refer_path)" }, { "alpha_fraction": 0.5277309417724609, "alphanum_fraction": 0.5571488738059998, "avg_line_length": 31.261905670166016, "blob_id": "41ec9f4df7a47bf8c7270c902ffcaba74b3d7d99", "content_id": "17be67241428db16fa716026a168533ca8cf954b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9484, "license_type": "no_license", "max_line_length": 99, "num_lines": 294, "path": "/libs/nn/color_model.py", "repo_name": "phv2312/anime_colorization", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.utils.spectral_norm as spectral_norm\n\n\nclass Interpolate2D(nn.Module):\n def __init__(self, scale_factor, mode='nearest'):\n super(Interpolate2D, self).__init__()\n self.sf = scale_factor\n self.mode = mode\n\n def forward(self, x):\n return F.interpolate(x, scale_factor=self.sf, mode=self.mode)\n\n\nclass Flatten(nn.Module):\n def forward(self, input):\n return input.view(input.size(0), -1)\n\n\nclass ResidulBlock(nn.Module):\n def __init__(self, inc, outc, sample='none'):\n super(ResidulBlock, self).__init__()\n self.conv1 = spectral_norm(nn.Conv2d(inc, outc, 3, 1, 1))\n self.conv2 = spectral_norm(nn.Conv2d(outc, outc, 3, 1, 1))\n self.conv_sc = spectral_norm(nn.Conv2d(inc, outc, 1, 1, 0)) if inc != outc else False\n\n if sample == 'up':\n self.sample = Interpolate2D(scale_factor=2)\n else:\n self.sample = None\n\n self.bn1 = nn.BatchNorm2d(inc)\n self.bn2 = nn.BatchNorm2d(outc)\n\n self.act = nn.LeakyReLU(0.2)\n\n def forward(self, x):\n h = self.act(self.bn1(x))\n\n if self.sample:\n h = self.sample(h)\n x = self.sample(x)\n\n h = self.conv1(h)\n h = self.act(self.bn2(h))\n h = self.conv2(h)\n\n if self.conv_sc:\n x = self.conv_sc(x)\n return x + h\n\nclass EncoderS(nn.Module):\n def __init__(self):\n super(EncoderS, self).__init__()\n base_dim = 16\n ch_style = 1\n self.hook_features = []\n self.hook_convs = []\n\n self.model = nn.Sequential(\n spectral_norm(nn.Conv2d(ch_style, base_dim * 1, 3, 1, 1)),\n nn.BatchNorm2d(base_dim * 1),\n nn.LeakyReLU(0.2, inplace=True),\n nn.AvgPool2d(2),\n spectral_norm(nn.Conv2d(base_dim * 1, base_dim * 2, 3, 1, 1)),\n nn.BatchNorm2d(base_dim * 2),\n nn.LeakyReLU(0.2, inplace=True),\n nn.AvgPool2d(2),\n spectral_norm(nn.Conv2d(base_dim * 2, base_dim * 4, 3, 1, 1)),\n nn.BatchNorm2d(base_dim * 4),\n nn.LeakyReLU(0.2, inplace=True),\n nn.AvgPool2d(2),\n spectral_norm(nn.Conv2d(base_dim * 4, base_dim * 4, 3, 1, 1)),\n nn.BatchNorm2d(base_dim * 4),\n nn.LeakyReLU(0.2, inplace=True),\n nn.AvgPool2d(2),\n )\n\n # add hook\n for idx in [3, 7, 11]:\n self.model[idx].register_forward_hook(self.hook_f)\n\n for idx in [0, 4, 8, 12]:\n self.model[idx].register_forward_hook(self.hook_c)\n\n def hook_f(self, model, input, output):\n self.hook_features += [output]\n\n def hook_c(self, model, input, output):\n self.hook_convs += [output]\n\n def forward(self, image):\n self.hook_features = []\n self.hook_convs = []\n\n last_feature = self.model(image)\n b, c, h, w = last_feature.size()\n\n # aggregate\n previous_features = [F.interpolate(feature, size=(h, w)) for feature in self.hook_features]\n all_features = previous_features + [last_feature]\n output = torch.cat(all_features, dim=1)\n\n return output, self.hook_convs\n\nclass EncoderR(nn.Module):\n def __init__(self):\n super(EncoderR, self).__init__()\n base_dim = 16\n ch_style = 3\n self.hook_features = []\n self.hook_convs = []\n\n self.model = nn.Sequential(\n spectral_norm(nn.Conv2d(ch_style, base_dim * 1, 3, 1, 1)),\n nn.BatchNorm2d(base_dim * 1),\n nn.LeakyReLU(0.2, inplace=True),\n nn.AvgPool2d(2),\n spectral_norm(nn.Conv2d(base_dim * 1, base_dim * 2, 3, 1, 1)),\n nn.BatchNorm2d(base_dim * 2),\n nn.LeakyReLU(0.2, inplace=True),\n nn.AvgPool2d(2),\n spectral_norm(nn.Conv2d(base_dim * 2, base_dim * 4, 3, 1, 1)),\n nn.BatchNorm2d(base_dim * 4),\n nn.LeakyReLU(0.2, inplace=True),\n nn.AvgPool2d(2),\n spectral_norm(nn.Conv2d(base_dim * 4, base_dim * 4, 3, 1, 1)),\n nn.BatchNorm2d(base_dim * 4),\n nn.LeakyReLU(0.2, inplace=True),\n nn.AvgPool2d(2),\n )\n\n # add hook\n for idx in [3, 7, 11]:\n self.model[idx].register_forward_hook(self.hook_f)\n\n for idx in [0, 4, 8, 12]:\n self.model[idx].register_forward_hook(self.hook_c)\n\n def hook_f(self, model, input, output):\n self.hook_features += [output]\n\n def hook_c(self, model, input, output):\n self.hook_convs += [output]\n\n def forward(self, image):\n self.hook_features = []\n self.hook_convs = []\n\n last_feature = self.model(image)\n b, c, h, w = last_feature.size()\n\n # aggregate\n previous_features = [F.interpolate(feature, size=(h, w)) for feature in self.hook_features]\n all_features = previous_features + [last_feature]\n output = torch.cat(all_features, dim=1)\n\n return output, self.hook_convs\n\n# generator2\nclass ColorModel(nn.Module):\n def __init__(self):\n super(ColorModel, self).__init__()\n\n self.encoderG = EncoderR()\n self.encoderS = EncoderS()\n self.decoderS = DecoderS()\n\n hid_dim = 176\n self.tokeys = nn.Linear(hid_dim, hid_dim, bias=False)\n self.toqueries = nn.Linear(hid_dim, hid_dim, bias=False)\n self.tovalues = nn.Linear(hid_dim, hid_dim, bias=False)\n\n def forward(self, reference, sketch):\n ref_features, ref_all_convs = self.encoderG(reference)\n ske_features, ske_all_convs = self.encoderS(sketch)\n\n # do self attention\n b, c, h, w = ref_features.size()\n reference_features_ = ref_features.view(b, c, h * w).contiguous().permute(0, 2, 1)\n sketch_features_ = ske_features.view(b, c, h * w).contiguous().permute(0, 2, 1)\n\n ske_features, keys, queries = self.attention(reference_features_, sketch_features_)\n\n #\n ske_features = ske_features.permute(0, 2, 1).contiguous().view(b, c, h, w)\n\n keys = keys.permute(0, 2, 1).contiguous().view(b, c, h, w)\n queries = queries.permute(0, 2, 1).contiguous().view(b, c, h, w)\n\n #\n output = self.decoderS(ske_features, ske_all_convs)\n\n return output, queries, keys\n\n def attention(self, reference_features_, sketch_features_):\n d = reference_features_.size()[-1]\n\n keys = self.tokeys(reference_features_)\n queries = self.toqueries(sketch_features_)\n values = self.tovalues(reference_features_)\n\n queries = queries / (d ** (1 / 4))\n keys = keys / (d ** (1 / 4))\n\n dot = torch.bmm(queries, keys.transpose(1, 2))\n dot = F.softmax(dot, dim=2)\n\n out = torch.bmm(dot, values)\n\n return out + sketch_features_, keys, queries\n\n\ndef up_conv(in_channels, out_channels):\n return nn.Sequential(\n spectral_norm(nn.Conv2d(in_channels, out_channels, 3, padding=1)),\n nn.LeakyReLU(0.2, inplace=True),\n )\n\n# discriminator\nclass DecoderS(nn.Module):\n def __init__(self):\n super(DecoderS, self).__init__()\n base_dim = 16\n\n self.resblock_h = ResidulBlock(176, base_dim * 4)\n self.dconv_up4 = up_conv(in_channels=base_dim * 8, out_channels=base_dim * 4)\n self.dconv_up3 = up_conv(in_channels=base_dim * 8, out_channels=base_dim * 4)\n self.dconv_up2 = up_conv(in_channels=base_dim * 6, out_channels=base_dim * 2)\n self.dconv_up1 = up_conv(in_channels=base_dim * 3, out_channels=base_dim)\n self.dconv_last = nn.Sequential(\n spectral_norm(nn.Conv2d(base_dim, 3, 3, 1, 1)),\n nn.Tanh()\n )\n\n self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n\n def forward(self, h, sketch_all_convs):\n conv1, conv2, conv3, conv4 = sketch_all_convs\n # b, 2b, 4b, 4b\n\n x = self.resblock_h(h)\n x = self.upsample(x)\n x = torch.cat([x, conv4], dim = 1)\n\n x = self.dconv_up4(x)\n x = self.upsample(x)\n x = torch.cat([x, conv3], dim=1)\n\n x = self.dconv_up3(x)\n x = self.upsample(x)\n x = torch.cat([x, conv2], dim=1)\n\n x = self.dconv_up2(x)\n x = self.upsample(x)\n x = torch.cat([x, conv1], dim=1)\n\n x = self.dconv_up1(x)\n out = self.dconv_last(x)\n\n return out\n\n# discriminator\nclass Discriminator(nn.Module):\n def __init__(self, ch_input):\n super(Discriminator, self).__init__()\n base_dim = 64\n self.net = nn.Sequential(\n spectral_norm(nn.Conv2d(ch_input, base_dim * 1, 3, 2, 1)),\n nn.LeakyReLU(0.2, inplace=True),\n spectral_norm(nn.Conv2d(base_dim * 1, base_dim * 2, 3, 2, 1)),\n nn.LeakyReLU(0.2, inplace=True),\n spectral_norm(nn.Conv2d(base_dim * 2, base_dim * 4, 3, 2, 1)),\n nn.LeakyReLU(0.2, inplace=True),\n spectral_norm(nn.Conv2d(base_dim * 4, base_dim * 8, 3, 1, 1)),\n nn.LeakyReLU(0.2, inplace=True),\n spectral_norm(nn.Conv2d(base_dim * 8, 1, 3, 1, 1)),\n )\n\n def forward(self, x):\n return self.net(x)\n\nif __name__ == '__main__':\n from torchsummary import summary\n\n model = ColorModel()\n\n sketch = torch.randn((1,1,256,256))\n ref_color = torch.rand((1,3,256,256))\n\n output, _, _ = model(ref_color, sketch)\n print (output.size())" }, { "alpha_fraction": 0.5560747385025024, "alphanum_fraction": 0.5901201367378235, "avg_line_length": 41.82857131958008, "blob_id": "63ca223cd23d8208c4dce0685810c40cc8116e35", "content_id": "b02d9cd6eafab1731cc9235ea959daef94496be5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1498, "license_type": "no_license", "max_line_length": 110, "num_lines": 35, "path": "/libs/nn/sketch_model.py", "repo_name": "phv2312/anime_colorization", "src_encoding": "UTF-8", "text": "from keras.models import load_model\nfrom .sketch_keras.helper import *\n\nclass SketchModel:\n def __init__(self, weight_path):\n self.mod = load_model(weight_path)\n\n def process(self, input_image):\n width = float(input_image.shape[1])\n height = float(input_image.shape[0])\n new_width = 0\n new_height = 0\n if (width > height):\n from_mat = cv2.resize(input_image, (512, int(512 / width * height)), interpolation=cv2.INTER_AREA)\n new_width = 512\n new_height = int(512 / width * height)\n else:\n from_mat = cv2.resize(input_image, (int(512 / height * width), 512), interpolation=cv2.INTER_AREA)\n new_width = int(512 / height * width)\n new_height = 512\n # cv2.imshow('raw', from_mat)\n # cv2.imwrite('raw.jpg',from_mat)\n from_mat = from_mat.transpose((2, 0, 1))\n light_map = np.zeros(from_mat.shape, dtype=np.float)\n for channel in range(3):\n light_map[channel] = get_light_map_single(from_mat[channel])\n light_map = normalize_pic(light_map)\n light_map = resize_img_512_3d(light_map)\n line_mat = self.mod.predict(light_map, batch_size=1)\n line_mat = line_mat.transpose((3, 1, 2, 0))[0]\n line_mat = line_mat[0:int(new_height), 0:int(new_width), :]\n # show_active_img_and_save('sketchKeras_colored', line_mat, 'sketchKeras_colored.jpg')\n line_mat = np.amax(line_mat, 2)\n\n return line_mat" }, { "alpha_fraction": 0.617977499961853, "alphanum_fraction": 0.6270732879638672, "avg_line_length": 31.789474487304688, "blob_id": "366d55308fef1ab9ec02805ac09a93cc2eb283ff", "content_id": "4e1816ca5780f1e1b986c8863480f32c6b9a5b56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1869, "license_type": "no_license", "max_line_length": 93, "num_lines": 57, "path": "/libs/dataset/anime_dataset.py", "repo_name": "phv2312/anime_colorization", "src_encoding": "UTF-8", "text": "import numpy as np\nimport random\nimport os\nfrom torch.utils import data\nimport PIL.Image as Image\n\nfrom libs.utils.dataset import load_file_from_dir, read_im\nfrom libs.nn.tps_model import TPS\n\ndef _random_noise_per_channel(image):\n is_pil = False\n if type(image) == Image.Image:\n image = np.array(image)\n is_pil = True\n\n image = image + np.random.randint(-50, 50, (1, 1, 3)).astype(np.uint8)\n image = np.clip(image, 0, 255)\n\n if is_pil:\n image = Image.fromarray(image)\n\n return image\n\nclass OneImageAnimeDataset(data.Dataset):\n def __init__(self, input_dir, transform=None, is_train=True):\n self.color_dir = os.path.join(input_dir, 'color')\n self.sketch_dir = os.path.join(input_dir, 'sketch')\n\n self.color_fns = load_file_from_dir(self.color_dir, exts=['.png', '.jpg'])\n self.sketch_fns = load_file_from_dir(self.sketch_dir, exts=['.png', '.jpg'])\n\n print (\"Load total: %s files ...\" % len(self.color_fns))\n\n self.transform = transform if transform is not None else lambda k:k\n self.is_train = is_train\n\n self.TPS = TPS()\n\n def __len__(self):\n return len(self.color_fns)\n\n def __getitem__(self, idx):\n color_fn = self.color_fns[idx]\n sketch_fn = self.sketch_fns[idx]\n\n color_image = read_im(im_path=color_fn)\n #if random.uniform(0, 1.) < 0.3: color_image = _random_noise_per_channel(color_image)\n\n augment_color_image, theta, c_dst = self.TPS.augment(color_image)\n sketch_image = read_im(im_path=sketch_fn)\n\n if self.transform is not None:\n augment_color_image = self.transform(augment_color_image)\n sketch_image = self.transform(sketch_image)\n color_image = self.transform(color_image)\n\n return sketch_image[:1,:,:], color_image, augment_color_image, theta, c_dst\n" }, { "alpha_fraction": 0.5947287082672119, "alphanum_fraction": 0.6046551465988159, "avg_line_length": 33.57987976074219, "blob_id": "09e5f7e905752ec9650d8ddf5ea4469105f08121", "content_id": "ea0c78c655062864970b618e0a43d135ce6e330a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5843, "license_type": "no_license", "max_line_length": 133, "num_lines": 169, "path": "/train.py", "repo_name": "phv2312/anime_colorization", "src_encoding": "UTF-8", "text": "import click\nimport torch\nimport os\nimport yaml\n\nfrom torch.utils import data\nfrom torch.utils.tensorboard import SummaryWriter\nimport torch.optim as optim\n\nfrom libs.utils.flow import to_device, create_train_transform, save_model, save_image_local, save_image_tensorboard\nfrom libs.loss.gan_loss import dis_loss, gen_loss\nfrom libs.loss.content_style_loss import L1StyleContentLoss\nfrom libs.loss.triplet_loss import SimilarityTripletLoss\nfrom libs.nn.color_model import ColorModel, Discriminator\nfrom libs.dataset.anime_dataset import OneImageAnimeDataset as AnimeDataset\n\ndef ensure_loss(loss):\n assert loss.requires_grad == True, 'Loss without gradient'\n\[email protected]()\[email protected]('--cfg', default='./exps/_simple.yaml', help='Path to Config Path')\ndef main(cfg):\n cfg = yaml.load(open(cfg, 'r'))\n train_cfg = cfg['TRAIN']\n model_cfg = cfg['MODELS']\n\n # writer\n writer= SummaryWriter(log_dir='color')\n vis_dir, weight_dir = 'samples', 'weights'\n\n # dataset\n train_dataset = AnimeDataset(input_dir=train_cfg['INPUT_DIR'], is_train=True, transform=create_train_transform(cfg))\n train_loader = data.DataLoader(train_dataset, batch_size=train_cfg['BATCH_SIZE'], shuffle=True, num_workers=train_cfg['N_WORK'])\n\n # model\n color_model = ColorModel()\n disc_model = Discriminator(ch_input=4)\n\n color_model.cuda()\n disc_model.cuda()\n\n # loss\n train_cfg = cfg['LOSSES']\n l1_style_content_loss = L1StyleContentLoss().cuda()\n sim_triplet_loss = SimilarityTripletLoss().cuda()\n loss_weights = {}\n\n # optimizer\n color_optim = optim.Adam(color_model.parameters(), lr=cfg['TRAIN']['G_LR'], betas=(0.5, 0.999))\n disc_optim = optim.Adam(disc_model.parameters(), lr=cfg['TRAIN']['D_LR'], betas=(0.5, 0.999))\n\n # lr scheduler\n color_scheduler = optim.lr_scheduler.StepLR(color_optim, step_size=1000, gamma=0.1)\n disc_scheduler = optim.lr_scheduler.StepLR(disc_optim, step_size=1000, gamma=0.1)\n\n os.makedirs(vis_dir, exist_ok=True)\n os.makedirs(weight_dir, exist_ok=True)\n for epoch_id in range(cfg['TRAIN']['EPOCH']):\n print ('>> Epoch:', epoch_id + 1)\n\n train(train_loader,\n (color_model, disc_model), #models\n (l1_style_content_loss, sim_triplet_loss), #losses\n loss_weights, #loss_weights\n (color_optim, disc_optim), #optimizer\n vis_dir, weight_dir, writer, cfg) # other stuffs\n\n color_scheduler.step(epoch_id + 1)\n disc_scheduler.step(epoch_id + 1)\n\n writer.close()\n\nglobal_iter = 0\ndef train(loader, models, losses, loss_weights, optimizers, vis_dir, weight_dir, writer, cfg):\n global global_iter\n\n # models\n color_model, disc_model = models\n color_model.train()\n disc_model.train()\n\n # optimizer\n color_optimzier, disc_optimizer = optimizers\n\n # losses & weights\n l1_style_content_loss, sim_triplet_loss = losses\n loss_weight_cfg = cfg['LOSSES']['WEIGHTS']\n lws = {\n 'triplet': loss_weight_cfg['TRIPLET'],\n 'l1': loss_weight_cfg['L1'],\n 'gan_gen': loss_weight_cfg['GAN_G'],\n 'style': loss_weight_cfg['STYLE'],\n 'content': loss_weight_cfg['CONTENT']\n }\n\n for batch_id, batch_info in enumerate(loader):\n s_im, ref_im, ref_augment_im, theta, c_dst = batch_info\n s_im = to_device(s_im)\n ref_im = to_device(ref_im)\n ref_augment_im = to_device(ref_augment_im)\n\n # predict\n o_im, sketch_queries_f, refer_key_f = color_model(ref_augment_im, s_im)\n\n # loss\n ### >> for discriminator\n input_real = torch.cat([ref_im, s_im], dim=1)\n input_fake = torch.cat([o_im, s_im], dim=1)\n\n disc_optimizer.zero_grad()\n gan_dis_score = dis_loss(disc_model, input_real, input_fake)\n gan_dis_score.backward()\n disc_optimizer.step()\n\n ### >> for style, content, l1\n color_optimzier.zero_grad()\n style_score, content_score, l1_score = l1_style_content_loss(o_im, ref_im)\n\n ### >> for attention & gan generator\n sim_triplet_score = sim_triplet_loss(sketch_queries_f, refer_key_f, theta, c_dst)\n gan_gen_score = gen_loss(disc_model, input_fake)\n\n #\n #[ensure_loss(l) for l in [style_score, content_score, l1_score, gan_gen_score, gan_dis_score]]\n\n style_score *= lws['style']\n content_score *= lws['content']\n l1_score *= lws['l1']\n sim_triplet_score *= lws['triplet']\n gan_gen_score *= lws['gan_gen']\n\n total_loss = style_score + content_score + l1_score + sim_triplet_score + gan_gen_score\n\n total_loss.backward()\n color_optimzier.step()\n\n global_iter += 1\n print('\\t[Iter]: %d, [Style]:%.3f, [Content]:%.3f, [L1]:%.3f, [TRIPLET]:%.3f, [GAN_G]:%.3f, [GAN_D]:%.3f' %\n (global_iter, style_score.item() , content_score.item(), l1_score.item(), sim_triplet_score.item(),\n gan_gen_score.item(), gan_dis_score.item())\n )\n\n if global_iter % 10 == 0:\n \"\"\"\n >> Save weights\n \"\"\"\n save_model(global_iter, weight_dir, color_model, disc_model, color_optimzier, disc_optimizer)\n\n \"\"\"\n >> Visualize \n \"\"\"\n color_model.eval()\n\n with torch.no_grad():\n o_im, _, _ = color_model(ref_augment_im, s_im)\n\n color_model.train()\n\n save_image_local(global_iter, writer,\n style_score, content_score, l1_score,sim_triplet_score, gan_gen_score, gan_dis_score,\n o_im, s_im, ref_augment_im, ref_im)\n\n \"\"\"\n Tensor-board\n \"\"\"\n save_image_tensorboard(global_iter, vis_dir, o_im, s_im, ref_augment_im, ref_im)\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6303088665008545, "alphanum_fraction": 0.6435006260871887, "avg_line_length": 48.31745910644531, "blob_id": "de63a2eeebbb66b3ea576719acc1f307202575b9", "content_id": "951c8443dcd5372e161680763e2b366285240d6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3108, "license_type": "no_license", "max_line_length": 114, "num_lines": 63, "path": "/libs/utils/flow.py", "repo_name": "phv2312/anime_colorization", "src_encoding": "UTF-8", "text": "import torch\nimport os\nfrom torchvision.transforms import transforms\nfrom torchvision import utils as vutils\nimport matplotlib.pyplot as plt\n\ndef imgshow(im):\n plt.imshow(im)\n plt.show()\n\ndef create_train_transform(cfg):\n return transforms.Compose([\n transforms.Resize(size=(cfg['MODELS']['INPUT_HEIGHT'], cfg['MODELS']['INPUT_WEIGHT'])),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))\n ])\n\ndef create_test_transform(cfg):\n return create_train_transform(cfg)\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\ndef to_device(x):\n return x.to(device)\n\ndef load_model(model, weight_path):\n model.load_state_dict(torch.load(weight_path, map_location='cpu'))\n return model\n\nfrom copy import deepcopy\ndef save_model(global_iter, weight_dir, color_model, disc_model, color_optimizer, disc_optimizer):\n save_G_path = os.path.join(weight_dir, '{:08d}.G.pth'.format(global_iter))\n save_D_path = os.path.join(weight_dir, '{:08d}.D.pth'.format(global_iter))\n save_optimG_path = os.path.join(weight_dir, '{:08d}.optimG.pth'.format(global_iter))\n save_optimD_path = os.path.join(weight_dir, '{:08d}.optimD.pth'.format(global_iter))\n\n torch.save(color_model.state_dict(), save_G_path)\n torch.save(disc_model.state_dict(), save_D_path)\n torch.save(color_optimizer.state_dict(), save_optimG_path)\n torch.save(disc_optimizer.state_dict(), save_optimD_path)\n\ndef save_image_tensorboard(global_iter, vis_dir, o_im, s_im, ref_augment_im, ref_im):\n save_output_path = os.path.join(vis_dir, '{:08d}.output.png'.format(global_iter))\n save_sketch_path = os.path.join(vis_dir, '{:08d}.sketch.png'.format(global_iter))\n save_ref_augment_path = os.path.join(vis_dir, '{:08d}.ref_augment.png'.format(global_iter))\n save_target_path = os.path.join(vis_dir, '{:08d}.target.png'.format(global_iter))\n\n vutils.save_image(o_im, save_output_path, normalize=True, range=(-1, 1))\n vutils.save_image(s_im, save_sketch_path, normalize=True, range=(-1, 1))\n vutils.save_image(ref_augment_im, save_ref_augment_path, normalize=True, range=(-1, 1))\n vutils.save_image(ref_im, save_target_path, normalize=True, range=(-1, 1))\n\ndef save_image_local(global_iter, writer,\n style_score, content_score, l1_score, sim_triplet_score, gan_gen_score, gan_dis_score,\n o_im, s_im, ref_augment_im, ref_im):\n for _loss_name, _loss_val in zip(['style', 'content', 'l1', 'triplet', 'gan_g', 'gan_d'],\n [style_score, content_score, l1_score, sim_triplet_score, gan_gen_score,\n gan_dis_score]):\n writer.add_scalar('train/loss/%s' % _loss_name, _loss_val, global_iter)\n\n for _image_name, _image_tensor in zip(['output', 'sketch', 'reference', 'target'],\n [o_im, s_im, ref_augment_im, ref_im]):\n writer.add_image('train/%s' % _image_name, vutils.make_grid(_image_tensor, normalize=True, range=(-1, 1)),\n global_iter)\n\n" } ]
13
kennanseno/Cloud-Computing
https://github.com/kennanseno/Cloud-Computing
34c2e99f4bc01c7bd9962fa92e6a34c12f1105ae
bdd0b49e72664342e327aa0c40fe37266302ae48
d845dfcee5bae2f39a6024e180317a552d5044d2
refs/heads/master
2021-01-18T15:37:28.900146
2015-12-26T11:14:27
2015-12-26T11:14:27
43,005,377
0
0
null
2015-09-23T14:16:13
2015-10-14T16:03:29
2015-11-18T11:20:44
Python
[ { "alpha_fraction": 0.5990098714828491, "alphanum_fraction": 0.6089109182357788, "avg_line_length": 17.363636016845703, "blob_id": "72d6b790773bd51bf3082aaf391c25f4527608c5", "content_id": "974b516f7bdc69a9093aa16feb9643dcbbdea8a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 404, "license_type": "no_license", "max_line_length": 38, "num_lines": 22, "path": "/lab4-Docker/lab5/my_application/server.py", "repo_name": "kennanseno/Cloud-Computing", "src_encoding": "UTF-8", "text": "from flask import Flask\napp = Flask(__name__)\n\[email protected](\"/index\")\ndef index():\n\treturn \"Index File\"\n\[email protected](\"/hello\")\ndef hello():\n return \"Hello World!\"\n\[email protected](\"/user/<user>\")\ndef show_user_profile(user):\n\treturn \"Hello %s, \" % user\n\[email protected](\"/post/<int:post_id>\")\ndef show_pos(post_id):\n\treturn \"Post %d \" % post_id \n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\",debug=True)\n" }, { "alpha_fraction": 0.7071622610092163, "alphanum_fraction": 0.7361740469932556, "avg_line_length": 27.256410598754883, "blob_id": "c20bd5c6a5d68d19ce239379b1edebf09a2c0f89", "content_id": "81834c991e7ebee007fa21db11f0ac13ffe910cf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1103, "license_type": "permissive", "max_line_length": 120, "num_lines": 39, "path": "/Lab11/count-aws-msgs.py", "repo_name": "kennanseno/Cloud-Computing", "src_encoding": "UTF-8", "text": "# This script created a queue\n#\n# Author - Paul Doyle Nov 2015\n#\n#\nimport boto.sqs\nimport boto.sqs.queue\nfrom boto.sqs.message import Message\nfrom boto.sqs.connection import SQSConnection\nfrom boto.exception import SQSError\nimport sys\nimport urllib2\n\n# Get the keys from a specific url and then use them to connect to AWS Service\n\nresponse = urllib2.urlopen('http://ec2-52-30-7-5.eu-west-1.compute.amazonaws.com:81/key')\n\nhtml=response.read()\n\nresult = html.split(':')\n\n#print (result[0])\n#print (result[1])\n\naccess_key_id = result[0]\nsecret_access_key = result[1]\n\n#print (access_key_id,secret_access_key)\n# Set up a connection to the AWS service.\nconn = boto.sqs.connect_to_region(\"eu-west-1\", aws_access_key_id=access_key_id, aws_secret_access_key=secret_access_key)\n\nstudent_number = 'D14123582_'\n#conn.delete_queue(sys.argv[1])\n\n# Set up a connection to the AWS service. \nconn = boto.sqs.connect_to_region(\"eu-west-1\", aws_access_key_id=access_key_id, aws_secret_access_key=secret_access_key)\n\nmy_queue = conn.get_queue(student_number+sys.argv[1])\nprint \"Messages in the queue = \" + str(my_queue.count())\n\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.699999988079071, "avg_line_length": 26.25, "blob_id": "b6663d70aa231ce0d67888d2bed30ae450d3f45b", "content_id": "a504fa739b648be9774841e8240670080b46a94f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 220, "license_type": "no_license", "max_line_length": 45, "num_lines": 8, "path": "/Lab3/palindrome.py", "repo_name": "kennanseno/Cloud-Computing", "src_encoding": "UTF-8", "text": "myString = raw_input(\"Enter a String: \")\n# reverse the string\nrevString = reversed(myString)\n# check if the string is equal to its reverse\nif list(myString) == list(revString):\n print(\"True\")\nelse:\n print(\"False\")\n\n\n" }, { "alpha_fraction": 0.6748971343040466, "alphanum_fraction": 0.7242798209190369, "avg_line_length": 16.214284896850586, "blob_id": "e06d0f2b4f3e91928bf1809e4121a1ae01445201", "content_id": "2a98c0367f0c269d3bed936ba516f18deca62b48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 243, "license_type": "permissive", "max_line_length": 89, "num_lines": 14, "path": "/Lab11/verify-boto-and-keys.py", "repo_name": "kennanseno/Cloud-Computing", "src_encoding": "UTF-8", "text": "\n#some code goes here\nimport boto\nimport urllib2\n\nresponse = urllib2.urlopen('http://ec2-52-30-7-5.eu-west-1.compute.amazonaws.com:81/key')\n\nhtml=response.read()\n\nresult = html.split(':')\n\nfor line in result:\n\tprint line\n\nprint(boto.Version)\n\n" } ]
4
Armegi/connect
https://github.com/Armegi/connect
cfba4b4badbe12cdb777407a33846aa90582d2ce
a65d4f35b7e64209f118f4e104778d615ef0e12d
e8e9e1ab5308ef4cff7e86edd9a375b806a169d1
refs/heads/master
2023-04-23T17:40:14.814641
2021-04-27T22:42:58
2021-04-27T22:42:58
362,263,992
0
1
null
2021-04-27T22:08:33
2021-04-27T22:52:50
2021-05-04T10:19:58
Python
[ { "alpha_fraction": 0.6551921963691711, "alphanum_fraction": 0.6560527682304382, "avg_line_length": 25.610687255859375, "blob_id": "fd47572ac9fb53de685a958d41c241ac3047d91a", "content_id": "1ffbe72379d1c94f1215253b0663598e12ca2cd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3486, "license_type": "no_license", "max_line_length": 87, "num_lines": 131, "path": "/website/views.py", "repo_name": "Armegi/connect", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import JsonResponse\nimport json\nimport datetime\nfrom .models import *\nfrom .utils import cookieCart, cartData, guestOrder\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic import ListView, DetailView\nfrom django.core.mail import send_mail\nfrom django.conf import settings\n\n\ndef home(request):\n return render(request, 'home.html', {})\n\n\ndef about(request):\n return render(request, 'about.html', {})\n\n\n@csrf_exempt\ndef shop(request):\n data = cartData(request)\n cartItems = data['cartItems']\n\n products = Product.objects.all()\n context = {'products': products, 'cartItems': cartItems}\n return render(request, 'shop.html', context)\n\n\n@csrf_exempt\ndef contact(request):\n if request.method == 'POST':\n contact = Contact()\n email = request.POST.get('email')\n name = request.POST.get('name')\n subject = request.POST.get('subject')\n comment = request.POST.get('comment')\n contact.name = name\n contact.email = email\n contact.subject = subject\n contact.comment = comment\n contact.save()\n return render(request, 'contact.html', {})\n\n\n@csrf_exempt\ndef cart(request):\n data = cartData(request)\n cartItems = data['cartItems']\n order = data['order']\n items = data['items']\n\n context = {'items': items, 'order': order, 'cartItems': cartItems}\n return render(request, 'cart.html', context)\n\n\ndef blog(request):\n return render(request, 'blog.html', {})\n\n\n@csrf_exempt\ndef checkout(request):\n data = cartData(request)\n cartItems = data['cartItems']\n order = data['order']\n items = data['items']\n\n context = {'items': items, 'order': order, 'cartItems': cartItems}\n\n return render(request, 'checkout.html', context)\n\n\n@csrf_exempt\ndef update_item(request):\n data = json.loads(request.body)\n product_id = data['productId']\n action = data['action']\n\n print('action: ', action)\n print('product_id: ', product_id)\n\n customer = request.user.customer\n product = Product.objects.get(id=product_id)\n\n order, created = Order.objects.get_or_create(customer=customer, complete=False)\n orderitem, created = OrderItem.objects.get_or_create(order=order, product=product)\n\n if action == 'add':\n orderitem.quantity += 1\n elif action == 'remove':\n orderitem.quantity -= 1\n\n orderitem.save()\n\n if orderitem.quantity <= 0:\n orderitem.delete()\n\n return JsonResponse('Item was added.', safe=False)\n\n\n@csrf_exempt\ndef process_order(request):\n transaction_id = datetime.datetime.now().timestamp()\n data = json.loads(request.body)\n\n if request.user.is_authenticated:\n customer = request.user.customer\n order, created = Order.objects.get_or_create(customer=customer, complete=False)\n else:\n customer, order = guestOrder(request, data)\n\n total = float(data['form']['total'])\n order.transaction_id = transaction_id\n\n if total == order.get_cart_total:\n order.complete = True\n order.save()\n\n if order.shipping:\n ShippingAddress.objects.create(\n customer=customer,\n order=order,\n address=data['shipping']['address'],\n city=data['shipping']['city'],\n state=data['shipping']['state'],\n zipcode=data['shipping']['zipcode'],\n )\n\n return JsonResponse('Payment submitted..', safe=False)\n" }, { "alpha_fraction": 0.6504504680633545, "alphanum_fraction": 0.6504504680633545, "avg_line_length": 38.64285659790039, "blob_id": "1b21c0fe9187989016685d3b0288baa9ac864e42", "content_id": "426f620dbdba9511a08aa3386e1a1f50e050fdb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 555, "license_type": "no_license", "max_line_length": 70, "num_lines": 14, "path": "/website/urls.py", "repo_name": "Armegi/connect", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name=\"home\"),\n path('about.html', views.about, name=\"about\"),\n path('shop.html', views.shop, name=\"shop\"),\n path('contact.html', views.contact, name=\"contact\"),\n path('cart.html', views.cart, name=\"cart\"),\n path('blog.html', views.blog, name=\"blog\"),\n path('checkout.html', views.checkout, name=\"checkout\"),\n path('update_item/', views.update_item, name=\"update_item\"),\n path('process_order/', views.process_order, name=\"process_order\"),\n]\n" } ]
2
domopets/food-servo
https://github.com/domopets/food-servo
1c3e895cda44a2525f8058b5cc1fef2eddd6e480
34da26a494bfc5d1bb74f14528a62846837bb6da
178e46d08baebfd8d52635b8dffaa0567a521713
refs/heads/master
2021-09-04T00:46:38.133678
2018-01-13T14:39:38
2018-01-13T14:39:38
106,106,040
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5789473652839661, "alphanum_fraction": 0.6315789222717285, "avg_line_length": 11.666666984558105, "blob_id": "8a91d6e51bc476de0223ebda543de97000bbe697", "content_id": "3713fb13a42d67acf8aba720f00a3b8488b11f1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 38, "license_type": "no_license", "max_line_length": 25, "num_lines": 3, "path": "/open-food", "repo_name": "domopets/food-servo", "src_encoding": "UTF-8", "text": "#! /bin/sh\n\n~/food-servo/set-angle 86\n" }, { "alpha_fraction": 0.6734693646430969, "alphanum_fraction": 0.7210884094238281, "avg_line_length": 13.699999809265137, "blob_id": "01324a3461d8ca602328929ffa5748b4a833be87", "content_id": "3c7848bc59b72b2279c9609f89926fde17bc7c50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 294, "license_type": "no_license", "max_line_length": 29, "num_lines": 20, "path": "/set-angle", "repo_name": "domopets/food-servo", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport RPi.GPIO as GPIO\nimport time\nimport sys\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(18, GPIO.OUT)\nGPIO.setwarnings(False)\n\ndegree = int(sys.argv[1])\nduty = float(degree) / 10 + 5\n\npwm=GPIO.PWM(18,100)\npwm.start(5)\n\npwm.ChangeDutyCycle(duty)\ntime.sleep(0.8)\n\nGPIO.cleanup()\n" } ]
2
stheakanath/lytro
https://github.com/stheakanath/lytro
d3c8c78425e8678c83519b057266d02273c0846d
153b515648ba14a4199b17a2a0a8afafc1227de1
cc273d6823b7d73d6ec6d8cfa67398ec55185f61
refs/heads/master
2021-01-10T03:30:55.450712
2016-01-06T14:58:46
2016-01-06T14:58:46
48,511,727
3
0
null
null
null
null
null
[ { "alpha_fraction": 0.7705696225166321, "alphanum_fraction": 0.7737341523170471, "avg_line_length": 59.14285659790039, "blob_id": "1f0e723afe89abbcaecd4b7f159f8fe55369dc07", "content_id": "50b70c5f6aa34b653d8c852f4f72c23d7f325b14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1264, "license_type": "no_license", "max_line_length": 601, "num_lines": 21, "path": "/README.md", "repo_name": "stheakanath/lytro", "src_encoding": "UTF-8", "text": "# lytro\n\nMimicking the Lytro camera effect by capturing multiple images over a plane orthogonal to the optical axis.\n\n![Image](http://i.imgur.com/azQmcwK.gif)\n\n## Background and Algorithm\n\nWe use the paper by Ren Ng of Stanford University (the founder of the Lytro camera and professor at Berkeley) [http://graphics.stanford.edu/papers/lfcamera/lfcamera-150dpi.pdf]. In this he describes the method of autofocusing to certain aspects of the image. The basic idea is that we can refocus to certain parts of an image by shifting an array of images (that are slightly shifted in an axis), by a predefined amount. As this amount changes, we can shift to a different part of an image. This is the basic idea of Lytro. They take several images at the same time, shifting each by a certain amount.\n\n## Running Code\n\nNote that there is no sample data as it takes around 1 GB of data. To access it view the Stanford Light Field Archive: http://lightfield.stanford.edu/lfs.html \n\nTo run the code just run \n```\npython main.py\n```\nWith a size.png image on the same folder as main.py and a rectefied folder in the same directory as main.py.\n\nTo adjust the parameters, scroll to the bottom of the main.py and then uncomment the code as follows. Add in the paramters as needed. \n" }, { "alpha_fraction": 0.6205673813819885, "alphanum_fraction": 0.646276593208313, "avg_line_length": 28.710525512695312, "blob_id": "3790adf32854475545542d63f2d173cdb99be2de", "content_id": "65048a2091617cc1207187cc38efb37216476c2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1128, "license_type": "no_license", "max_line_length": 71, "num_lines": 38, "path": "/main.py", "repo_name": "stheakanath/lytro", "src_encoding": "UTF-8", "text": "# Kuriakose Sony Theakanath\n# Depth Refocusing\n\nimport numpy as np\nimport glob\nfrom PIL import Image\nimport sys\nsys.path.append('/usr/local/lib/python2.7/site-packages')\nimport cv2\n\nLOTS = 290\n\ndef depthRefocusing(path, SCALE):\n\tw, h = Image.open(\"size.png\").size\n\tarr = np.zeros((h, w, 3),np.float)\n\tfor fname in glob.glob(path):\n\t\tprint fname\n\t\tx, y = int(fname.split(\"_\")[1]), int(fname.split(\"_\")[2])\n\t\tshiftx, shifty = (8 - x) * SCALE, (8 - y) * SCALE\n\t\tprint(shiftx, shifty)\n\t\tM = np.float32([[1, 0, shifty], [0, 1, shiftx]])\n\t\titem = np.array(Image.open(fname), dtype=np.float)\n\t\tdst = cv2.warpAffine(item, M, (w, h))\n\t\tarr = arr + dst / LOTS\n\tarr = np.array(np.round(arr), dtype=np.uint8)\n\tImage.fromarray(arr, mode=\"RGB\").save(\"-1.png\")\n\ndef aperture(path, num):\n\tw, h = Image.open(\"size.png\").size\n\tarr = np.zeros((h, w, 3),np.float)\n\tfor fname in glob.glob(path):\n\t\titem = np.array(Image.open(fname), dtype=np.float)\n\t\tarr = arr + item / num\n\tarr = np.array(np.round(arr), dtype=np.uint8)\n\tImage.fromarray(arr, mode=\"RGB\").save(\"aperture_\" + str(num) + \".png\")\n\n# depthRefocusing(\"rectified/*.png\", -1)\naperture(\"apeture209/*.png\", 209)" } ]
2
VictorNguyenCS/Budgeting
https://github.com/VictorNguyenCS/Budgeting
8f62db3c5bf69d4d5585128a136f74df37a07c67
797d329126d0567ad493e6f63ba9ef2333ca728b
7f99cfa7b46a25399e8fe7307823655b76252b77
refs/heads/master
2022-09-22T13:15:10.395701
2020-03-29T21:37:07
2020-03-29T21:37:07
231,520,792
0
0
null
2020-01-03T05:50:03
2020-03-29T21:49:19
2022-09-16T18:20:43
Python
[ { "alpha_fraction": 0.6927536129951477, "alphanum_fraction": 0.6975845694541931, "avg_line_length": 28.600000381469727, "blob_id": "ef5faf1eed400ceced2e59d5620d8230f6ade0cc", "content_id": "d63c609818f8451ada6a9ee16335ccf5428545f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1035, "license_type": "no_license", "max_line_length": 73, "num_lines": 35, "path": "/app/models.py", "repo_name": "VictorNguyenCS/Budgeting", "src_encoding": "UTF-8", "text": "from app import db\nfrom werkzeug.security import generate_password_hash, check_password_hash\nfrom flask_login import UserMixin\nfrom app import login\n\ndb.create_all()\n\nclass User(UserMixin, db.Model):\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(64), index=True, unique=True)\n password_hash = db.Column(db.String(128))\n\nclass Goals(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n sid = db.Column(db.Integer)\n goal = db.Column(db.Text)\n cost = db.Column(db.Integer)\n\nclass NetWorth(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n sid = db.Column(db.Integer)\n description = db.Column(db.Text)\n amount = db.Column(db.Integer)\n category = db.Column(db.Text)\n\nclass WeeklyExpenses(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n sid = db.Column(db.Integer)\n description = db.Column(db.Text)\n amount = db.Column(db.Integer)\n category = db.Column(db.Text)\n\[email protected]_loader\ndef load_user(id):\n return User.query.get(int(id))" } ]
1
avijeet95/OpenCV-Scripts
https://github.com/avijeet95/OpenCV-Scripts
c25eae3d4ab58f4898d89d7d7e7d580e0eae7f55
df3ecacee4e83190e55a327b21c5bccec33f75b3
a64194983ae45b5c57b4e1217c3be274b4363bac
refs/heads/master
2021-01-10T14:01:52.141412
2016-04-15T11:29:59
2016-04-15T11:29:59
55,781,044
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6398963928222656, "alphanum_fraction": 0.681347131729126, "avg_line_length": 23.10416603088379, "blob_id": "bffbb475c74b176f025586100a62515dd5ab58c9", "content_id": "53cc1f3f1077608dd57be7327a78f88f03ff41bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1158, "license_type": "no_license", "max_line_length": 71, "num_lines": 48, "path": "/skindetector.py", "repo_name": "avijeet95/OpenCV-Scripts", "src_encoding": "UTF-8", "text": "#Python Script To detect skin color from camera\nimport numpy as np\nimport cv2\n\ndef resize(image, width = None, height = None, inter = cv2.INTER_AREA):\n\n\tdim = None\n\t(h, w) = image.shape[:2]\n \n\tif width is None and height is None:\n\t\treturn image\n\n\tif width is None:\n\t\tr = height / float(h)\n\t\tdim = (int(w * r), height)\n\n\telse:\n\t\tr = width / float(w)\n\t\tdim = (width, int(h * r))\n\n\tresized = cv2.resize(image, dim, interpolation = inter)\n\treturn resized\n\n\n#Colour Range for Skin\nlower = np.array([0,48,80], dtype='uint8')\nupper = np.array([20,255,255], dtype='uint8')\n\ncamera = cv2.VideoCapture(0)\n\nwhile True:\n\t(grabbed, frame) = camera.read()\n\tframe=resize(frame,width=400)\n\tconverted = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)\n\tmask = cv2.inRange(converted,lower,upper)\n\n\tkernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))\n\tmask = cv2.erode(mask, kernel, iterations = 2)\n\tmask = cv2.dilate(mask, kernel, iterations = 2)\n\n\tmask = cv2.GaussianBlur(mask, (3,3) , 0)\n\tskin = cv2.bitwise_and(frame,frame,mask=mask)\n\tcv2.imshow(\"images\",np.hstack([frame,skin]))\n\tif cv2.waitKey(1) & 0xFF ==ord(\"q\"):\n\t\tbreak\n\ncamera.release()\ncv2.destroyAllWindows()\n\n" }, { "alpha_fraction": 0.8307692408561707, "alphanum_fraction": 0.8307692408561707, "avg_line_length": 31.5, "blob_id": "d4d19928d99e7f2b1c7e902f329ef23689b4e858", "content_id": "195e04db7d3bff1beb447408b8c5009278b0bf45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 65, "license_type": "no_license", "max_line_length": 47, "num_lines": 2, "path": "/README.md", "repo_name": "avijeet95/OpenCV-Scripts", "src_encoding": "UTF-8", "text": "# OpenCV-Scripts\nContains Scripts written in Python using OpenCV\n" } ]
2
nihar9938/WebFun
https://github.com/nihar9938/WebFun
d00a72a73672d451279ba3a8d7ee7ae766bb656d
41c8706902d10f8c105bf6ec2ed81a522116659b
90a99687638210916dadb612bd8262a6c13f3afd
refs/heads/master
2022-12-05T05:14:28.334163
2020-08-18T19:06:37
2020-08-18T19:06:37
288,541,191
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7362637519836426, "alphanum_fraction": 0.7362637519836426, "avg_line_length": 21.5, "blob_id": "a595181c21ba99e6cc9089aececa829c4b44f98f", "content_id": "64b56052cfad9ddff3626ab0a122cf92973c0fcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 91, "license_type": "no_license", "max_line_length": 31, "num_lines": 4, "path": "/myApi/models.py", "repo_name": "nihar9938/WebFun", "src_encoding": "UTF-8", "text": "\n\nfrom django.db import models\n\nclass MyFile(models.Model):\n image = models.ImageField()" }, { "alpha_fraction": 0.7950310707092285, "alphanum_fraction": 0.7950310707092285, "avg_line_length": 13.636363983154297, "blob_id": "706ba7830575294efff747f592213c316e5595f3", "content_id": "979d76a0623aaca49a0acd2c2a17f9d61762460a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 161, "license_type": "no_license", "max_line_length": 32, "num_lines": 11, "path": "/myApi/admin.py", "repo_name": "nihar9938/WebFun", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.contrib import admin\nfrom myApi.models import MyFile\n\n\nadmin.site.register(MyFile)\n\n\n\n\n# Register your models here.\n" } ]
2
TheCyberAtom/E-Voting-Using-Aadhar-Verification
https://github.com/TheCyberAtom/E-Voting-Using-Aadhar-Verification
e8e4734ee0b13a7a1eef60945f3c4f308c9b3c2d
1d2c63680e7f1f3777b0e6999fefd1bb9fed0248
a67ac20e1f847d7c60990efbf8150274889c4473
refs/heads/master
2023-05-13T17:09:48.703092
2021-06-07T08:08:21
2021-06-07T08:08:21
349,957,240
1
2
null
null
null
null
null
[ { "alpha_fraction": 0.5074183940887451, "alphanum_fraction": 0.5598417520523071, "avg_line_length": 27.08333396911621, "blob_id": "d895fbad9e91d0ccb6cdf78ad98a92ddc024a712", "content_id": "fdd23603c1849fde2a0d8c9223b33206c3690df9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1011, "license_type": "no_license", "max_line_length": 94, "num_lines": 36, "path": "/Evoting_app/migrations/0004_auto_20210321_1604.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-03-21 10:34\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Evoting_app', '0003_auto_20210321_0133'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='candidate',\n name='aadhar_number',\n field=models.IntegerField(default=0),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='candidate',\n name='gender',\n field=models.CharField(default='', max_length=50),\n ),\n migrations.AddField(\n model_name='candidate',\n name='mobile',\n field=models.IntegerField(default=0),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='candidate',\n name='register_date',\n field=models.DateField(default=datetime.datetime(2021, 3, 21, 16, 3, 16, 102553)),\n ),\n ]\n" }, { "alpha_fraction": 0.49170437455177307, "alphanum_fraction": 0.5927602052688599, "avg_line_length": 26.625, "blob_id": "f481571e1f78de7887049a42461702a504933d37", "content_id": "a525124b168ef0bb7a36d3dd486cd67bcf2fc3ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 663, "license_type": "no_license", "max_line_length": 94, "num_lines": 24, "path": "/Evoting_app/migrations/0015_auto_20210406_1431.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-06 09:01\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Evoting_app', '0014_auto_20210404_1236'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='candidate',\n name='register_date',\n field=models.DateField(default=datetime.datetime(2021, 4, 6, 14, 31, 36, 771772)),\n ),\n migrations.AlterField(\n model_name='voter',\n name='register_date',\n field=models.DateField(default=datetime.datetime(2021, 4, 6, 14, 31, 36, 771772)),\n ),\n ]\n" }, { "alpha_fraction": 0.49451887607574463, "alphanum_fraction": 0.5773447155952454, "avg_line_length": 27.310344696044922, "blob_id": "b214c4bca60881a1a96bd894f4dc6b488ecb2e06", "content_id": "06a72ef95359702a1cec3723f30c3a676133812f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 821, "license_type": "no_license", "max_line_length": 94, "num_lines": 29, "path": "/Evoting_app/migrations/0014_auto_20210404_1236.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-04 07:06\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Evoting_app', '0013_merge_20210404_1216'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='candidate',\n name='vote_count',\n field=models.IntegerField(default=0),\n ),\n migrations.AlterField(\n model_name='candidate',\n name='register_date',\n field=models.DateField(default=datetime.datetime(2021, 4, 4, 12, 36, 58, 372145)),\n ),\n migrations.AlterField(\n model_name='voter',\n name='register_date',\n field=models.DateField(default=datetime.datetime(2021, 4, 4, 12, 36, 58, 373142)),\n ),\n ]\n" }, { "alpha_fraction": 0.4626334607601166, "alphanum_fraction": 0.6298932433128357, "avg_line_length": 19.071428298950195, "blob_id": "056fbd502f215779480e29bdaf77bc8882c3fba7", "content_id": "efc2c772370f4ef6e27723201d66d4f39bb79cfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 281, "license_type": "no_license", "max_line_length": 51, "num_lines": 14, "path": "/Evoting_app/migrations/0010_merge_20210329_0337.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-03-28 22:07\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Evoting_app', '0007_auto_20210321_1629'),\n ('Evoting_app', '0009_auto_20210321_1628'),\n ]\n\n operations = [\n ]\n" }, { "alpha_fraction": 0.49170437455177307, "alphanum_fraction": 0.5927602052688599, "avg_line_length": 26.625, "blob_id": "6ca594b2a54c55320277cde36347260ca6772ba0", "content_id": "dd3a208f1ee190ee0fe5ffd1049779b8b4c1c262", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 663, "license_type": "no_license", "max_line_length": 94, "num_lines": 24, "path": "/Evoting_app/migrations/0016_auto_20210406_1432.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-06 09:02\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Evoting_app', '0015_auto_20210406_1431'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='candidate',\n name='register_date',\n field=models.DateField(default=datetime.datetime(2021, 4, 6, 14, 32, 31, 312840)),\n ),\n migrations.AlterField(\n model_name='voter',\n name='register_date',\n field=models.DateField(default=datetime.datetime(2021, 4, 6, 14, 32, 31, 313826)),\n ),\n ]\n" }, { "alpha_fraction": 0.7633477449417114, "alphanum_fraction": 0.7633477449417114, "avg_line_length": 37.44444274902344, "blob_id": "bf81ed1d8ce3d18ba39fb8bf87ee407d205cf8e0", "content_id": "2e224ac83ddf9f542c404e7adb5f39de05e546ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 693, "license_type": "no_license", "max_line_length": 55, "num_lines": 18, "path": "/static/js/register.js", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "const signUpButton = document.getElementById('signUp');\nconst signInButton = document.getElementById('signIn');\nconst container = document.getElementById('container');\nconst name = document.getElementById('name');\nconst mobile = document.getElementById('mobile');\nconst state = document.getElementById('state');\nconst date = document.getElementById('date');\n// const form = document.getElementById('form');\nconst status = false;\n\n\nsignUpButton.addEventListener('click', () => {\n\tcontainer.classList.add(\"right-panel-active\");\n});\n\nconst loginscan = document.getElementById('scanform');\nfunction handleForm(event) { event.preventDefault(); } \nloginscan.addEventListener('submit', handleForm);\n\n" }, { "alpha_fraction": 0.7604166865348816, "alphanum_fraction": 0.7604166865348816, "avg_line_length": 18.200000762939453, "blob_id": "ceaa16fc8c8d3d92a1e561111b33be2fda231e65", "content_id": "06be6f805da454020068bedcb34e79d266b5af88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 96, "license_type": "no_license", "max_line_length": 34, "num_lines": 5, "path": "/Evoting_app/apps.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass EvotingAppConfig(AppConfig):\n name = 'Evoting_app'\n" }, { "alpha_fraction": 0.4931921362876892, "alphanum_fraction": 0.5915279984474182, "avg_line_length": 26.54166603088379, "blob_id": "9b9c9f850d9c8ee04e5205850d2191fab417fa52", "content_id": "2e904feba06b7c37639c17a6be85c477eab9ea77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 661, "license_type": "no_license", "max_line_length": 93, "num_lines": 24, "path": "/Evoting_app/migrations/0017_auto_20210406_1434.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-06 09:04\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Evoting_app', '0016_auto_20210406_1432'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='candidate',\n name='register_date',\n field=models.DateField(default=datetime.datetime(2021, 4, 6, 14, 34, 3, 636712)),\n ),\n migrations.AlterField(\n model_name='voter',\n name='register_date',\n field=models.DateField(default=datetime.datetime(2021, 4, 6, 14, 34, 3, 636712)),\n ),\n ]\n" }, { "alpha_fraction": 0.4626334607601166, "alphanum_fraction": 0.6298932433128357, "avg_line_length": 19.071428298950195, "blob_id": "71b6c65d6236e1e416abbe9538eb229085af44ba", "content_id": "86156f4b6c9cb9f6d6852174685df773f4bf358b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 281, "license_type": "no_license", "max_line_length": 51, "num_lines": 14, "path": "/Evoting_app/migrations/0010_merge_20210327_0128.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-03-26 19:58\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Evoting_app', '0009_auto_20210321_1628'),\n ('Evoting_app', '0007_auto_20210321_1629'),\n ]\n\n operations = [\n ]\n" }, { "alpha_fraction": 0.4924698770046234, "alphanum_fraction": 0.5933734774589539, "avg_line_length": 26.66666603088379, "blob_id": "87c82e440f70a7a3d4872512ec41e6ae4f129cf8", "content_id": "c8c50f86a7a0533db6284df2f59a0939ec9d14c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 664, "license_type": "no_license", "max_line_length": 94, "num_lines": 24, "path": "/Evoting_app/migrations/0011_auto_20210329_0337.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-03-28 22:07\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Evoting_app', '0010_merge_20210329_0337'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='candidate',\n name='register_date',\n field=models.DateField(default=datetime.datetime(2021, 3, 29, 3, 37, 56, 259775)),\n ),\n migrations.AlterField(\n model_name='voter',\n name='register_date',\n field=models.DateField(default=datetime.datetime(2021, 3, 29, 3, 37, 56, 259775)),\n ),\n ]\n" }, { "alpha_fraction": 0.7605633735656738, "alphanum_fraction": 0.7605633735656738, "avg_line_length": 27.600000381469727, "blob_id": "4f2a676d596ee3e15e69032d8e268b79c1c85c04", "content_id": "99cc4289f5a0cdc10264a9f17bb8a6ae7d4be5dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 142, "license_type": "no_license", "max_line_length": 78, "num_lines": 5, "path": "/Evoting/views.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "from django.shortcuts import HttpResponse\n\n\ndef index(request):\n return HttpResponse('<script> document.location=\"/Evoting_app\" </script>')" }, { "alpha_fraction": 0.4645390212535858, "alphanum_fraction": 0.631205677986145, "avg_line_length": 19.14285659790039, "blob_id": "b067f0d2b6472e59f756353246f80397f94da271", "content_id": "c27523cae4021cd3473d96b4d2ba0ca3080b7d9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 282, "license_type": "no_license", "max_line_length": 52, "num_lines": 14, "path": "/Evoting_app/migrations/0013_merge_20210404_1216.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-04 06:46\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Evoting_app', '0012_auto_20210329_0342'),\n ('Evoting_app', '0010_merge_20210327_0128'),\n ]\n\n operations = [\n ]\n" }, { "alpha_fraction": 0.7460317611694336, "alphanum_fraction": 0.7460317611694336, "avg_line_length": 32.411766052246094, "blob_id": "6b3ab7decee5e10a6dc62f11edc2cb6fe0dc3ff3", "content_id": "e654cb59a24a475f33bca0b5a9d495953fb3f8bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 567, "license_type": "no_license", "max_line_length": 83, "num_lines": 17, "path": "/Evoting_app/admin.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\n# Register your models here.\nfrom .models import Candidate,Voter,Official,Voted\n\nclass CandidatetAdmin(admin.ModelAdmin):\n # a list of displayed columns name.\n list_display = ['name', 'party_name', 'district', 'vote_count']\n\nclass VoterAdmin(admin.ModelAdmin):\n # a list of displayed columns name.\n list_display = ['name', 'gender', 'district', 'mobile', 'aadhar_number', 'dob']\n\nadmin.site.register(Candidate,CandidatetAdmin)\nadmin.site.register(Voter,VoterAdmin)\nadmin.site.register(Official)\nadmin.site.register(Voted)" }, { "alpha_fraction": 0.49398624897003174, "alphanum_fraction": 0.5584192276000977, "avg_line_length": 35.375, "blob_id": "71a0d743b0d1865eff4b86b7de31189bf988b474", "content_id": "14cf4a946393c60d63a4dec6a918fd7eed217943", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1164, "license_type": "no_license", "max_line_length": 114, "num_lines": 32, "path": "/Evoting_app/migrations/0006_auto_20210321_1626.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-03-21 10:56\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Evoting_app', '0005_auto_20210321_1612'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Voters',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=50)),\n ('district', models.CharField(default='', max_length=50)),\n ('gender', models.CharField(default='', max_length=50)),\n ('mobile', models.IntegerField()),\n ('aadhar_number', models.CharField(max_length=12)),\n ('register_date', models.DateField(default=datetime.datetime(2021, 3, 21, 16, 26, 57, 93495))),\n ('dob', models.DateField()),\n ],\n ),\n migrations.AlterField(\n model_name='candidate',\n name='register_date',\n field=models.DateField(default=datetime.datetime(2021, 3, 21, 16, 26, 57, 92512)),\n ),\n ]\n" }, { "alpha_fraction": 0.5781387090682983, "alphanum_fraction": 0.5952590107917786, "avg_line_length": 38.6260871887207, "blob_id": "958574baf45a5489af80e8b622f63020d0c726f6", "content_id": "73d2090697c264312dc7cf4b2ceb08d622e463ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4556, "license_type": "no_license", "max_line_length": 132, "num_lines": 115, "path": "/Evoting_app/views.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "from django.shortcuts import render,HttpResponse\nfrom .models import Candidate,Voter,Official,Voted\nimport pytesseract\nimport cv2\nfrom time import sleep\nfrom django.db.models import F\n\n# Scanning image to extract aadhar number from aadhar card\ndef aadharscanning():\n key = cv2. waitKey(1)\n webcam = cv2.VideoCapture(0)\n sleep(2)\n def process_image(iamge_name, lang_code):\n return pytesseract.image_to_string(iamge_name, lang=lang_code)\n i=0\n aadhar_num = {}\n while i<50:\n i+=1\n try:\n check, frame = webcam.read()\n cv2.waitKey(1)\n img = cv2.resize(frame, (800, 600), fx = 0.1, fy = 0.1)\n img = cv2.rectangle(img, (200,400),(600,475), (0,255,0),2)\n cv2.imshow(\"Capturing\", img)\n img = img[400:475,200:600]\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]\n word = process_image(img, \"eng\")\n if word=='':\n pass\n else:\n word=''.join(i for i in word if i.isdigit())\n if word in aadhar_num:\n aadhar_num[word] += 1\n else:\n aadhar_num[word] = 1\n except(KeyboardInterrupt):\n print(\"Turning off camera.\")\n webcam.release()\n print(\"Camera off.\")\n print(\"Program ended.\")\n cv2.destroyAllWindows()\n break\n # for key,value in aadhar_num.items():\n # print(key,'---:---',value)\n final_aadhar_num=max(aadhar_num,key=aadhar_num.get)\n print(\"\\nFinal Result : \",final_aadhar_num)\n cv2.destroyAllWindows()\n return final_aadhar_num\n\n# Rendering main page.\ndef index(request):\n return render(request,'index.html')\n\n# Officer login after verification.\ndef officerlogin(request):\n usn,pwd = '',''\n flag = False\n if request.method == \"POST\":\n usn = request.POST.get('usn')\n pwd = request.POST.get('pwd')\n usn = Official.objects.filter(username=usn)\n pwd = Official.objects.filter(password=pwd)\n if ((len(usn)!=0) and (len(pwd)!=0)):\n flag = True\n return render(request,'register.html',{'flag':flag})\n else:\n return render(request, 'officer.html')\n return render(request, 'officer.html')\n\n# Registering new user\ndef register(request):\n if request.method == \"POST\":\n name = request.POST.get('name')\n mobile = request.POST.get('mobile')\n district = request.POST.get('district')\n date = request.POST.get('date')\n sex = request.POST.get('sex')\n aadhar = request.POST.get('aadharnum')\n # print(name, mobile, state, date, sex, aadhar)\n test_data = Voter.objects.filter(aadhar_number=aadhar)\n if len(test_data)==0:\n data = Voter(name=name.lower(),district=district.lower(),gender=sex.lower(),mobile=mobile,aadhar_number=aadhar,dob=date)\n data.save()\n else:\n print('Aadhar already registered')\n return HttpResponse('<script> alert(\"Aadhar already registered\") </script>')\n return render(request,'register.html')\n\n# Voter login after scanning aadhar number\ndef voterlogin(request):\n if request.method == \"POST\":\n try:\n final_aadhar_num = aadharscanning()\n test_data = Voter.objects.values('id','district','aadhar_number','name').get(aadhar_number=final_aadhar_num)\n # print(test_data)\n voted_candidate = Voted.objects.filter(name='{}{}'.format(test_data['id'],test_data['name']))\n if (test_data) and (len(voted_candidate)==0):\n candidates = Candidate.objects.values('name','party_name','district').filter(district=test_data['district'])\n Voted(name='{}{}'.format(test_data['id'],test_data['name'])).save()\n return render(request, 'voting.html', {'flag':True, 'candidate':candidates,'cname':test_data['name']})\n else:\n return HttpResponse(\"<h1>You already voted.</h1>\")\n except Exception as e:\n print(e)\n cv2.destroyAllWindows()\n return render(request, 'voting.html', {'flag':False})\n return render(request,'voterlogin.html')\n\n# Voting page after everything either fails or success.\ndef voting(request):\n if request.method == \"POST\":\n name = request.POST.get('name')\n Candidate.objects.filter(name=name).update(vote_count=F('vote_count') + 1)\n return render(request,\"thankyou.html\")" }, { "alpha_fraction": 0.4960474371910095, "alphanum_fraction": 0.5662055611610413, "avg_line_length": 30.625, "blob_id": "5a0e98351cbfcc008a9861f2e5c0567477f84c1f", "content_id": "0dc216d125b6bf601b3118682bc7c77bfac8117c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1012, "license_type": "no_license", "max_line_length": 114, "num_lines": 32, "path": "/Evoting_app/migrations/0012_auto_20210329_0342.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-03-28 22:12\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Evoting_app', '0011_auto_20210329_0337'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Official',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('username', models.CharField(max_length=50)),\n ('password', models.CharField(max_length=50)),\n ],\n ),\n migrations.AlterField(\n model_name='candidate',\n name='register_date',\n field=models.DateField(default=datetime.datetime(2021, 3, 29, 3, 42, 24, 415311)),\n ),\n migrations.AlterField(\n model_name='voter',\n name='register_date',\n field=models.DateField(default=datetime.datetime(2021, 3, 29, 3, 42, 24, 415311)),\n ),\n ]\n" }, { "alpha_fraction": 0.5265200734138489, "alphanum_fraction": 0.5769728422164917, "avg_line_length": 29.920000076293945, "blob_id": "26b37541c17a1befc2f84bf7584d49559c8746a8", "content_id": "21b2b51f4871efa90f6172c72a19d7627e4c5d1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 773, "license_type": "no_license", "max_line_length": 116, "num_lines": 25, "path": "/Evoting_app/migrations/0001_initial.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-03-20 19:46\n\nimport datetime\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='Candidate',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=50)),\n ('party_name', models.CharField(default='', max_length=50)),\n ('district', models.CharField(default='', max_length=50)),\n ('register_date', models.DateField(verbose_name=datetime.datetime(2021, 3, 21, 1, 16, 10, 820389))),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5557324886322021, "alphanum_fraction": 0.6050955653190613, "avg_line_length": 25.16666603088379, "blob_id": "fa07f640d34e3e4c97aa4df7d20452b1027556ed", "content_id": "17f6b64fdf2e33b2d4bc1f7b0e082104d5e13200", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 628, "license_type": "no_license", "max_line_length": 70, "num_lines": 24, "path": "/Evoting_app/migrations/0016_auto_20210406_0034.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-05 19:04\n\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Evoting_app', '0015_auto_20210405_0032'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='candidate',\n name='register_date',\n field=models.DateField(default=django.utils.timezone.now),\n ),\n migrations.AlterField(\n model_name='voter',\n name='register_date',\n field=models.DateField(default=django.utils.timezone.now),\n ),\n ]\n" }, { "alpha_fraction": 0.49067315459251404, "alphanum_fraction": 0.5515003800392151, "avg_line_length": 34.228572845458984, "blob_id": "dcc8ba3665e427b4c088c772813c3d1bfcd2749a", "content_id": "ae5bc6678d3a80d125660f179d5a751455d8c630", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1233, "license_type": "no_license", "max_line_length": 114, "num_lines": 35, "path": "/Evoting_app/migrations/0007_auto_20210321_1629.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-03-21 10:59\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Evoting_app', '0006_auto_20210321_1626'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Voter',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=50)),\n ('district', models.CharField(default='', max_length=50)),\n ('gender', models.CharField(default='', max_length=50)),\n ('mobile', models.IntegerField()),\n ('aadhar_number', models.CharField(max_length=12)),\n ('register_date', models.DateField(default=datetime.datetime(2021, 3, 21, 16, 29, 7, 370725))),\n ('dob', models.DateField()),\n ],\n ),\n migrations.DeleteModel(\n name='Voters',\n ),\n migrations.AlterField(\n model_name='candidate',\n name='register_date',\n field=models.DateField(default=datetime.datetime(2021, 3, 21, 16, 29, 7, 370725)),\n ),\n ]\n" }, { "alpha_fraction": 0.4931921362876892, "alphanum_fraction": 0.5915279984474182, "avg_line_length": 26.54166603088379, "blob_id": "ac37c609938a3a0a89988b20936f82da13ee3df6", "content_id": "6b1547d4d013eb49a784a5aa6392989d1ccf3fed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 661, "license_type": "no_license", "max_line_length": 93, "num_lines": 24, "path": "/Evoting_app/migrations/0015_auto_20210405_0032.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-04 19:02\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Evoting_app', '0014_auto_20210404_1236'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='candidate',\n name='register_date',\n field=models.DateField(default=datetime.datetime(2021, 4, 5, 0, 32, 30, 382906)),\n ),\n migrations.AlterField(\n model_name='voter',\n name='register_date',\n field=models.DateField(default=datetime.datetime(2021, 4, 5, 0, 32, 30, 382906)),\n ),\n ]\n" }, { "alpha_fraction": 0.8108108043670654, "alphanum_fraction": 0.8108108043670654, "avg_line_length": 36, "blob_id": "9fcfcc571f1079f897134666cdaa73ffdbada744", "content_id": "a6a7c759d5391132e68c9e2a7211db80214f00fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 37, "license_type": "no_license", "max_line_length": 36, "num_lines": 1, "path": "/README.md", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# E-Voting-Using-Aadhar-Verification\n" }, { "alpha_fraction": 0.7258687019348145, "alphanum_fraction": 0.7258687019348145, "avg_line_length": 38.92307662963867, "blob_id": "0d10aea46fe2f8776345c2e3129b16d1738049fb", "content_id": "c33526e7bfea8f1aeaf604f577101e01bee43897", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 518, "license_type": "no_license", "max_line_length": 65, "num_lines": 13, "path": "/Evoting_app/urls.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\nurlpatterns = [\n path('',views.index, name=\"index\"),\n path('home',views.index, name=\"home\"),\n path('voterlogin',views.voterlogin, name=\"voterlogin\"),\n path('officerlogin',views.officerlogin, name=\"officerlogin\"),\n path('register',views.register, name=\"register\"),\n path('voting',views.voting, name=\"voting\"),\n]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)" }, { "alpha_fraction": 0.6734833121299744, "alphanum_fraction": 0.6891615390777588, "avg_line_length": 31.622222900390625, "blob_id": "0fd1994557ee85edcfd2ac6b61cf08633dbb34b8", "content_id": "4cd7a400cdfc93672b10471eda3d02bfd280d08f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1467, "license_type": "no_license", "max_line_length": 60, "num_lines": 45, "path": "/Evoting_app/models.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.utils import timezone\n# Create your models here.\nclass Candidate(models.Model):\n id = models.AutoField\n name = models.CharField(max_length=50)\n party_name = models.CharField(max_length=50, default=\"\")\n district = models.CharField(max_length=50, default=\"\")\n gender = models.CharField(max_length=50,default=\"\")\n mobile = models.IntegerField()\n aadhar_number = models.IntegerField()\n register_date = models.DateField(default=timezone.now)\n vote_count = models.IntegerField(default=0)\n\n def __str__(self):\n return self.name+\" \"+str(self.vote_count)\n\nclass Voter(models.Model):\n id = models.AutoField\n name = models.CharField(max_length=50)\n district = models.CharField(max_length=50, default=\"\")\n gender = models.CharField(max_length=50,default=\"\")\n mobile = models.IntegerField()\n aadhar_number = models.CharField(max_length=12)\n register_date = models.DateField(default=timezone.now)\n dob = models.DateField()\n\n def __str__(self):\n return self.name\n\nclass Official(models.Model):\n id= models.AutoField\n username = models.CharField(max_length=50)\n password = models.CharField(max_length=50)\n\n def __str__(self):\n return self.username\n\nclass Voted(models.Model):\n id=models.AutoField\n name = models.CharField(max_length=50)\n created_date = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return self.name" }, { "alpha_fraction": 0.49870800971984863, "alphanum_fraction": 0.5839793086051941, "avg_line_length": 20.5, "blob_id": "ebff6bcfe0e9ac56a8624e43c706da1bd96dcee4", "content_id": "4510d5d7b12e108fac6187489dc975a7b7464b2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 387, "license_type": "no_license", "max_line_length": 51, "num_lines": 18, "path": "/Evoting_app/migrations/0021_auto_20210406_2055.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-06 15:25\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Evoting_app', '0020_auto_20210406_2041'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='voted',\n name='name',\n field=models.CharField(max_length=50),\n ),\n ]\n" }, { "alpha_fraction": 0.4626334607601166, "alphanum_fraction": 0.6298932433128357, "avg_line_length": 19.071428298950195, "blob_id": "ea7899a6b513dccbd265875a822f949a758e0c66", "content_id": "e9fe159916ff036e95656843cd30bb1c33a2cb2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 281, "license_type": "no_license", "max_line_length": 51, "num_lines": 14, "path": "/Evoting_app/migrations/0018_merge_20210406_1959.py", "repo_name": "TheCyberAtom/E-Voting-Using-Aadhar-Verification", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-06 14:29\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Evoting_app', '0017_auto_20210406_1434'),\n ('Evoting_app', '0016_auto_20210406_0034'),\n ]\n\n operations = [\n ]\n" } ]
25
Niuzhengnan/Test
https://github.com/Niuzhengnan/Test
7b947c885bca0d9c7a988ad12112608526176d97
9a39dcff0dfe6099dff6332fbde2580fd44b50cb
699964389a30fcfab97b728369ad9491ae8ea8b8
refs/heads/master
2020-07-24T18:42:38.422031
2019-09-12T09:26:21
2019-09-12T09:26:21
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5827590227127075, "alphanum_fraction": 0.6120178699493408, "avg_line_length": 41.41538619995117, "blob_id": "3bf827421e88269466ddd2d2fe0702a02a9b815a", "content_id": "3940bbae6f94764e4b9062810b4e2fd893d6aa9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8275, "license_type": "no_license", "max_line_length": 139, "num_lines": 195, "path": "/data_preprocess.py", "repo_name": "Niuzhengnan/Test", "src_encoding": "UTF-8", "text": " # -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 8 15:45:51 2019\n\n@author: niuzhengnan\n\"\"\"\n\nimport wave as we\nimport numpy as np\nimport matplotlib.pyplot as plt\n#import tensorflow as tf \n\ndef wave_as_array(wav_path):\n wavfile = we.open(wav_path,'rb')\n params = wavfile.getparams()\n #number of channels, 1 or 2\n #Sampling accuracy (byte width per frame)\n #sample rate(Hz)\n #number of audio frames\n channels, sampwidth, framesra, frameswav = params[0], params[1], params[2], params[3]\n datawav = wavfile.readframes(frameswav)\n wavfile.close()\n datause = np.fromstring(datawav, dtype = np.short)\n datause.shape = -1,channels\n datause = datause.T\n return datause, channels, sampwidth, framesra, frameswav\n\n# Time in s\ndef array2input(datause,channels,framesra, time):\n nframes = time * framesra\n if channels != 1 and channels != 2:\n return None\n elif channels == 2: \n channel1 = datause[0][:nframes]\n channel2 = datause[1][:nframes]\n else: \n channel1 = datause[:nframes]\n channel2 = channel1\n res = np.append(channel1, channel2)\n if len(res)<nframes*2:\n print(\"r u there?\")\n diff = nframes*2-len(res)\n for k in range(diff):\n res = np.append(res,0)\n if len(res)>nframes*2:\n print(\"r u there??\")\n res = res[:nframes*2]\n return res\n\n#if max_label = 10, then label should be 0 - 9 (totally 10)\ndef add_into_Trainset(res, label, path_x_Train = \"x_train.npy\" , path_y_Train = \"y_train.npy\"):\n try:\n x_train = np.load(path_x_Train)\n np.save(path_x_Train,np.concatenate([res[np.newaxis,:],x_train]))\n except FileNotFoundError:\n np.save(path_x_Train, res[np.newaxis,:])\n \n #if not 0<=label<=max_label:\n # print(\"label error!\")\n #else:\n # label_array = np.zeros(max_label,)\n # label_array[label] = 1 \n \n try:\n y_train = np.load(path_y_Train).tolist()\n y_train[0].append(label)\n np.save(path_y_Train, y_train)\n except FileNotFoundError:\n np.save(path_y_Train, [[label]])\n \n return None\n\ndef add_into_Testset(res, label, path_x_Test = \"x_test.npy\" , path_y_Test = \"y_test.npy\"):\n try:\n x_test = np.load(path_x_Test)\n np.save(path_x_Test,np.concatenate([res[np.newaxis,:],x_test]))\n except FileNotFoundError:\n np.save(path_x_Test, res[np.newaxis,:])\n \n #if not 0<=label<=max_label:\n # print(\"label error!\")\n #else:\n # label_array = np.zeros(max_label,)\n # label_array[label] = 1 \n \n try:\n y_test = np.load(path_y_Test).tolist()\n y_test[0].append(label)\n np.save(path_y_Test, y_test)\n except FileNotFoundError:\n np.save(path_y_Test, [[label]])\n \n return None\n\n#if __name__ == \"__main__\": \n# label 0 : Bike 110/18\n# for i in range(1,110):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Bike\\Bike_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Trainset(res, 0, path_x_Train = \"x_train.npy\" , path_y_Train = \"y_train.npy\")\n# for i in range(111,128):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Bike\\Bike_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Testset(res, 0, path_x_Test = \"x_test.npy\" , path_y_Test = \"y_test.npy\") \n# label 1 : Car 125/20 \n# for i in range(1,125):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Car\\Car_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Trainset(res, 1, path_x_Train = \"x_train.npy\" , path_y_Train = \"y_train.npy\")\n# for i in range(125,145):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Car\\Car_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Testset(res, 1, path_x_Test = \"x_test.npy\" , path_y_Test = \"y_test.npy\")\n# label 2: Emergency vehicle (107/13)\n \n# for i in range(1,108):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Emergencyvehicle\\Emergencyvehicle_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Trainset(res, 2, path_x_Train = \"x_train.npy\" , path_y_Train = \"y_train.npy\")\n# for i in range(108,121):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Emergencyvehicle\\Emergencyvehicle_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Testset(res, 2, path_x_Test = \"x_test.npy\" , path_y_Test = \"y_test.npy\")\n \n # Label 3:Horn 141/30\n \n# for i in range(1,142):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Horn\\Horn_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Trainset(res, 3, path_x_Train = \"x_train.npy\" , path_y_Train = \"y_train.npy\")\n# for i in range(142,172):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Horn\\Horn_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Testset(res, 3, path_x_Test = \"x_test.npy\" , path_y_Test = \"y_test.npy\")\n \n \n # Label 4 : Motorcycle 107/13\n \n# for i in range(1,108):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Motorcycle\\Motorcycle_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Trainset(res, 4, path_x_Train = \"x_train.npy\" , path_y_Train = \"y_train.npy\")\n# for i in range(142,121):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Motorcycle\\Motorcycle_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Testset(res, 4, path_x_Test = \"x_test.npy\" , path_y_Test = \"y_test.npy\") \n# \n# # Label 5 : Noise 147/30\n# \n# for i in range(1,148):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Noise\\\\Noise_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Trainset(res, 5, path_x_Train = \"x_train.npy\" , path_y_Train = \"y_train.npy\")\n# for i in range(148,178):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Noise\\\\Noise_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Testset(res, 5, path_x_Test = \"x_test.npy\" , path_y_Test = \"y_test.npy\") \n# \n# # Label 6 : rail 110/13\n# \n# for i in range(1,111):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Rail\\\\rail_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Trainset(res, 6, path_x_Train = \"x_train.npy\" , path_y_Train = \"y_train.npy\")\n# for i in range(111,124):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Rail\\\\rail_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n # add_into_Testset(res, 6, path_x_Test = \"x_test.npy\" , path_y_Test = \"y_test.npy\") \n# for i in range(1,8):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Car\\Car_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Trainset(res, 1, path_x_Train = \"x_train.npy\" , path_y_Train = \"y_train.npy\")\n\n# for i in range(9,101):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Car\\Car_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Trainset(res, 1, path_x_Train = \"x_train.npy\" , path_y_Train = \"y_train.npy\")\n \n \n \n \n \n \n \n \n \n \n#datause, channels, sampwidth, framesra, frameswav = wave_as_array('dzq.wav')\n#time = np.arange(0,frameswav) * (1.0/framesra)\n#plt.title(\"frames\")\n#plt.subplot(211)\n#plt.plot(time,datause[0],color='green')\n#plt.subplot(212)\n#plt.plot(time,datause[1],color='red') \n#plt.show()" }, { "alpha_fraction": 0.5691350698471069, "alphanum_fraction": 0.5961093306541443, "avg_line_length": 44.94352340698242, "blob_id": "94fa4f684a47bf502e88359570a43752d32f0b28", "content_id": "a2ee2cffdaaf33dafca9cd152ab14aaca9afa4e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13828, "license_type": "no_license", "max_line_length": 139, "num_lines": 301, "path": "/sound_recognition_model.py", "repo_name": "Niuzhengnan/Test", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 8 16:44:14 2019\n\n@author: niuzhengnan\n\"\"\"\n\nimport math\nimport numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\nfrom tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict\nimport scipy\nfrom PIL import Image\nfrom scipy import ndimage\nfrom data_preprocess import *\n\ndef create_placeholders(n_x, n_y):\n \"\"\"\n Creates the placeholders for the tensorflow session.\n \n Arguments:\n n_x -- scalar, size of an image vector (num_px * num_px = 64 * 64 * 3 = 12288)\n n_y -- scalar, number of classes (from 0 to 5, so -> 6)\n \n Returns:\n X -- placeholder for the data input, of shape [n_x, None] and dtype \"float\"\n Y -- placeholder for the input labels, of shape [n_y, None] and dtype \"float\"\n \n \"\"\"\n X = tf.compat.v1.placeholder(tf.float32, [n_x, None], name=\"X\")\n Y = tf.compat.v1.placeholder(tf.float32, [n_y, None], name=\"Y\") \n return X, Y\n\ndef initialize_parameters(n_l1, n_l2, n_l3, length_of_sample):\n \"\"\"\n Initializes parameters to build a neural network with tensorflow. The shapes are:\n W1 : [n_l1, length_of_sample]\n b1 : [n_l1, 1]\n W2 : [n_l2, n_l1]\n b2 : [n_l2, 1]\n W3 : [n_l3, n_l2]\n b3 : [n_l3, 1]\n \n Returns:\n parameters -- a dictionary of tensors containing W1, b1, W2, b2, W3, b3\n \"\"\" \n \n W1 = tf.compat.v1.get_variable(\"W1\", [n_l1, length_of_sample], initializer = tf.contrib.layers.xavier_initializer(seed=1))\n b1 = tf.compat.v1.get_variable(\"b1\", [n_l1, 1], initializer = tf.zeros_initializer())\n W2 = tf.compat.v1.get_variable(\"W2\", [n_l2, n_l1], initializer = tf.contrib.layers.xavier_initializer(seed=1))\n b2 = tf.compat.v1.get_variable(\"b2\", [n_l2, 1], initializer = tf.zeros_initializer())\n W3 = tf.compat.v1.get_variable(\"W3\", [n_l3, n_l2], initializer = tf.contrib.layers.xavier_initializer(seed=1))\n b3 = tf.compat.v1.get_variable(\"b3\", [n_l3, 1], initializer = tf.zeros_initializer())\n\n parameters = {\"W1\": W1,\n \"b1\": b1,\n \"W2\": W2,\n \"b2\": b2,\n \"W3\": W3,\n \"b3\": b3}\n \n return parameters\n\ndef forward_propagation(X, parameters):\n \"\"\"\n Implements the forward propagation for the model: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SOFTMAX\n \n Arguments:\n X -- input dataset placeholder, of shape (input size, number of examples)\n parameters -- python dictionary containing your parameters \"W1\", \"b1\", \"W2\", \"b2\", \"W3\", \"b3\"\n the shapes are given in initialize_parameters\n\n Returns:\n Z3 -- the output of the last LINEAR unit\n \"\"\" \n # Retrieve the parameters from the dictionary \"parameters\" \n W1 = parameters['W1']\n b1 = parameters['b1']\n W2 = parameters['W2']\n b2 = parameters['b2']\n W3 = parameters['W3']\n b3 = parameters['b3'] \n # Numpy Equivalents:\n Z1 = tf.add(tf.matmul(W1, X), b1) # Z1 = np.dot(W1, X) + b1\n A1 = tf.nn.relu(Z1) # A1 = relu(Z1)\n Z2 = tf.add(tf.matmul(W2, A1), b2) # Z2 = np.dot(W2, a1) + b2\n A2 = tf.nn.relu(Z2) # A2 = relu(Z2)\n Z3 = tf.add(tf.matmul(W3, A2), b3) # Z3 = np.dot(W3,Z2) + b3 \n return Z3\n\ndef compute_cost(Z3, Y):\n \"\"\"\n Computes the cost\n \n Arguments:\n Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (6, number of examples)\n Y -- \"true\" labels vector placeholder, same shape as Z3\n \n Returns:\n cost - Tensor of the cost function\n \"\"\"\n \n # to fit the tensorflow requirement for tf.nn.softmax_cross_entropy_with_logits(...,...)\n logits = tf.transpose(Z3)\n labels = tf.transpose(Y)\n \n cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels))\n \n return cost\n\ndef model(X_train, Y_train, X_test, Y_test, learning_rate =0.001,\n num_epochs = 10, minibatch_size = 32, print_cost = True, n_l1=25, n_l2=12, n_l3=7):\n \"\"\"learning_rate = 0.0001,\n Implements a three-layer tensorflow neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX.\n \n Arguments:\n X_train -- training set, of shape (input size, number of training examples)\n Y_train -- test set, of shape (output size, number of training examples)\n X_test -- training set, of shape (input size, number of training examples)\n Y_test -- test set, of shape (output size, number of test examples)\n learning_rate -- learning rate of the optimization\n num_epochs -- number of epochs of the optimization loop\n minibatch_size -- size of a minibatch\n print_cost -- True to print the cost every 100 epochs\n n_l3 depends on how many kinds of sound we want to recognize.\n \n Returns:\n parameters -- parameters learnt by the model. They can then be used to predict.\n \"\"\"\n \n ops.reset_default_graph() # to be able to rerun the model without overwriting tf variables\n# tf.set_random_seed(1) # to keep consistent results\n# seed = 3 # to keep consistent results\n (n_x, m) = X_train.shape # (n_x: input size, m : number of examples in the train set)\n n_y = Y_train.shape[0] # n_y : output size\n costs = [] # To keep track of the cost\n \n # Create Placeholders of shape (n_x, n_y)\n X, Y = create_placeholders(n_x, n_y)\n\n # Initialize parameters\n parameters = initialize_parameters(n_l1, n_l2, n_l3, n_x)\n \n # Forward propagation: Build the forward propagation in the tensorflow graph\n Z3 = forward_propagation(X, parameters)\n \n # Cost function: Add cost function to tensorflow graph\n cost = compute_cost(Z3, Y)\n \n # Backpropagation: Define the tensorflow optimizer. Use an AdamOptimizer.\n optimizer =tf.compat.v1.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n \n # Initialize all the variables\n init = tf.compat.v1.global_variables_initializer()\n\n # Start the session to compute the tensorflow graph\n with tf.Session() as sess:\n \n # Run the initialization\n sess.run(init)\n \n # Do the training loop\n for epoch in range(num_epochs):\n\n epoch_cost = 0. # Defines a cost related to an epoch\n num_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train set\n# seed = seed + 1\n minibatches = random_mini_batches(X_train, Y_train, minibatch_size)\n\n for minibatch in minibatches:\n\n # Select a minibatch\n (minibatch_X, minibatch_Y) = minibatch\n \n # IMPORTANT: The line that runs the graph on a minibatch.\n # Run the session to execute the \"optimizer\" and the \"cost\", the feedict should contain a minibatch for (X,Y).\n _ , minibatch_cost = sess.run([optimizer, cost], feed_dict={X: minibatch_X, Y: minibatch_Y})\n \n epoch_cost += minibatch_cost / num_minibatches\n\n # Print the cost every epoch\n if print_cost == True and epoch % 100 == 0:\n print (\"Cost after epoch %i: %f\" % (epoch, epoch_cost))\n if print_cost == True and epoch % 5 == 0:\n costs.append(epoch_cost)\n \n # plot the cost\n plt.plot(np.squeeze(costs))\n plt.ylabel('cost')\n plt.xlabel('iterations (per tens)')\n plt.title(\"Learning rate =\" + str(learning_rate))\n plt.show()\n\n # lets save the parameters in a variable\n parameters = sess.run(parameters)\n print (\"Parameters have been trained!\")\n\n # Calculate the correct predictions\n correct_prediction = tf.equal(tf.argmax(Z3), tf.argmax(Y))\n\n # Calculate accuracy on the test set\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n #test = sess.run(accuracy,feed_dict = {X: X_train, Y: Y_train})\n \n print (\"Train Accuracy:\", accuracy.eval({X: X_train, Y: Y_train}))\n print (\"Test Accuracy:\", accuracy.eval({X: X_test, Y: Y_test}))\n \n return parameters, accuracy\n \nif __name__ == \"__main__\": \n \n # label 0 : Bike 110/18\n# for i in range(1,110):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Bike\\Bike_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)#\n# add_into_Trainset(res, 0, path_x_Train = \"x_train.npy\" , path_y_Train = \"y_train.npy\")\n# for i in range(111,128):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Bike\\Bike_%d.wav'%i)\n # res = array2input(datause,channels,framesra, 10)\n# add_into_Testset(res, 0, path_x_Test = \"x_test.npy\" , path_y_Test = \"y_test.npy\") \n# label 1 : Car 125/20 \n# for i in range(1,125):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Car\\Car_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Trainset(res, 1, path_x_Train = \"x_train.npy\" , path_y_Train = \"y_train.npy\")\n# for i in range(125,145):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Car\\Car_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Testset(res, 1, path_x_Test = \"x_test.npy\" , path_y_Test = \"y_test.npy\")\n## label 2: Emergency vehicle (107/13)\n# \n## for i in range(1,108):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Emergencyvehicle\\Emergencyvehicle_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Trainset(res, 2, path_x_Train = \"x_train.npy\" , path_y_Train = \"y_train.npy\")\n# for i in range(108,121):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Emergencyvehicle\\Emergencyvehicle_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Testset(res, 2, path_x_Test = \"x_test.npy\" , path_y_Test = \"y_test.npy\")\n# \n# # Label 3:Horn 141/30\n# \n# for i in range(1,142):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Horn\\Horn_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Trainset(res, 3, path_x_Train = \"x_train.npy\" , path_y_Train = \"y_train.npy\")\n# for i in range(142,172):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Horn\\Horn_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Testset(res, 3, path_x_Test = \"x_test.npy\" , path_y_Test = \"y_test.npy\")\n \n \n # Label 4 : Motorcycle 107/13\n \n# for i in range(1,108):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Motorcycle\\Motorcycle_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Trainset(res, 4, path_x_Train = \"x_train.npy\" , path_y_Train = \"y_train.npy\")\n# for i in range(142,121):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Motorcycle\\Motorcycle_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Testset(res, 4, path_x_Test = \"x_test.npy\" , path_y_Test = \"y_test.npy\") \n \n # Label 5 : Noise 147/30\n \n# for i in range(1,148):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Noise\\\\Noise_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Trainset(res, 5, path_x_Train = \"x_train.npy\" , path_y_Train = \"y_train.npy\")\n# for i in range(148,178):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Noise\\\\Noise_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Testset(res, 5, path_x_Test = \"x_test.npy\" , path_y_Test = \"y_test.npy\") \n \n # Label 6 : rail 110/13\n \n# for i in range(1,111):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Rail\\\\rail_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Trainset(res, 6, path_x_Train = \"x_train.npy\" , path_y_Train = \"y_train.npy\")\n# for i in range(111,124):\n# datause, channels, sampwidth, framesra, frameswav = wave_as_array('D:\\\\training_data\\\\Rail\\\\rail_%d.wav'%i)\n# res = array2input(datause,channels,framesra, 10)\n# add_into_Testset(res, 6, path_x_Test = \"x_test.npy\" , path_y_Test = \"y_test.npy\") \n \n path_x_Train ='C:/Users/niuzhengnan/Desktop/sr/x_train.npy'\n x_train = np.load(path_x_Train)\n x_train = x_train.T\n path_y_Train = 'C:/Users/niuzhengnan/Desktop/sr/y_train.npy'\n y_train_orig = np.load(path_y_Train)\n y_train = convert_to_one_hot(y_train_orig, 7)\n path_x_Test ='C:/Users/niuzhengnan/Desktop/sr/x_test.npy'\n path_y_Test ='C:/Users/niuzhengnan/Desktop/sr/y_test.npy'\n x_test = np.load(path_x_Test)\n x_test = x_test.T\n y_test_orig = np.load(path_y_Test)\n y_test = convert_to_one_hot(y_test_orig, 7)\n parameters,accuracy = model(x_train, y_train, x_test, y_test,n_l3=7)" } ]
2
di2pra/Innovattic
https://github.com/di2pra/Innovattic
1737ded8d847557ce83228279dcd1d6b6e36d447
7c271f8b9359b51ae7b9a2e17772f00c2347baab
0f7ab1fa0f3df28e126512a79d60dd329b3e5119
refs/heads/master
2021-04-30T13:10:45.914773
2018-02-14T18:48:18
2018-02-14T18:48:18
121,288,491
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8001949191093445, "alphanum_fraction": 0.8040935397148132, "avg_line_length": 35.64285659790039, "blob_id": "103abbb6e140014fe0d7da2602ef0373c7192f60", "content_id": "cee8ddc2eda3384b0602bf49ffb8faf657cf4fc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1026, "license_type": "no_license", "max_line_length": 194, "num_lines": 28, "path": "/script.py", "repo_name": "di2pra/Innovattic", "src_encoding": "UTF-8", "text": "from classes.LanguageXMLConverter import LanguageXMLConverter\nfrom models.resources import resources\n\n\n\"\"\"\n Example #1 generate Italian property language file\n\"\"\"\n\nitalian = LanguageXMLConverter(resources, ['example/input/values-it/ads.xml', 'example/input/values-it/extra.xml', 'example/input/values-it/strings.xml', 'example/input/values-it/strings2.xml'])\n\nitalian.generateOutputFile('example/output/Italian.txt') #generate property type language output file\n\n\n\n\"\"\"\n Example #2 generate English property language file\n\"\"\"\n\n\nenglish = LanguageXMLConverter(resources) # init an instance of Language XML Converter with empty input file paths array\n\n# add input file paths to the instance\nenglish.addInputXMLFile('example/input/values/ads.xml')\nenglish.addInputXMLFile('example/input/values/extra.xml')\nenglish.addInputXMLFile('example/input/values/strings.xml')\nenglish.addInputXMLFile('example/input/values/strings2.xml')\n\nenglish.generateOutputFile('example/output/English.txt') #generate property type language output file\n" }, { "alpha_fraction": 0.8232323527336121, "alphanum_fraction": 0.8232323527336121, "avg_line_length": 23.875, "blob_id": "28fa06c135164a718a4fd91fb4480d4a39060e5d", "content_id": "079d4e86967fb88a02fb78c79d6502d675199198", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 198, "license_type": "no_license", "max_line_length": 38, "num_lines": 8, "path": "/models/resources.py", "repo_name": "di2pra/Innovattic", "src_encoding": "UTF-8", "text": "from xml.dom import minidom\nfrom models.domObject import domObject\nfrom models.plurals import plurals\nfrom models.string import string\n\nclass resources(domObject):\n\n\tchildObjects = [string, plurals]" }, { "alpha_fraction": 0.7928994297981262, "alphanum_fraction": 0.7928994297981262, "avg_line_length": 20.25, "blob_id": "ac8c387f775af487975b64ed3ef7d2c14f88eb7d", "content_id": "7e3912561daf8a4e026c0677879622607c01a2d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 169, "license_type": "no_license", "max_line_length": 38, "num_lines": 8, "path": "/models/plurals.py", "repo_name": "di2pra/Innovattic", "src_encoding": "UTF-8", "text": "from xml.dom import minidom\nfrom models.domObject import domObject\nfrom models.item import item\n\nclass plurals(domObject):\n\n\tchildObjects = [item]\n\tpropertyName = 'name'" }, { "alpha_fraction": 0.7860326766967773, "alphanum_fraction": 0.7904903292655945, "avg_line_length": 32.67499923706055, "blob_id": "a242809226693631f74efb0d9c7928fa3716559a", "content_id": "ac9afcb325029ababf6348d45d7a1d86e0c1de8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1346, "license_type": "no_license", "max_line_length": 194, "num_lines": 40, "path": "/README.md", "repo_name": "di2pra/Innovattic", "src_encoding": "UTF-8", "text": "# Innovattic\n\n## How to use?\n\nIn your script.py file import the LanguageXMLConverter python Class, and the model of object reflecting the schema of the XML. below the exemple file :\n```python\nfrom classes.LanguageXMLConverter import LanguageXMLConverter\nfrom models.resources import resources\n\n\n\"\"\"\n Example #1 generate Italian property language file\n\"\"\"\n\nitalian = LanguageXMLConverter(resources, ['example/input/values-it/ads.xml', 'example/input/values-it/extra.xml', 'example/input/values-it/strings.xml', 'example/input/values-it/strings2.xml'])\n\nitalian.generateOutputFile('example/output/Italian.txt') #generate property type language output file\n\n\n\n\"\"\"\n Example #2 generate English property language file\n\"\"\"\n\n\nenglish = LanguageXMLConverter(resources) # init an instance of Language XML Converter with empty input file paths array\n\n# add input file paths to the instance\nenglish.addInputXMLFile('example/input/values/ads.xml')\nenglish.addInputXMLFile('example/input/values/extra.xml')\nenglish.addInputXMLFile('example/input/values/strings.xml')\nenglish.addInputXMLFile('example/input/values/strings2.xml')\n\nenglish.generateOutputFile('example/output/English.txt') #generate property type language output file\n```\n\nOpen the command line tool in the main directory, and run the main python script. (Python 2.7\n```shell\npython script.py\n```" }, { "alpha_fraction": 0.7983193397521973, "alphanum_fraction": 0.7983193397521973, "avg_line_length": 19, "blob_id": "94c7964f5a7c96dd17bbc411a888bef78f5b58d1", "content_id": "d87807647b979d9c79b9af7d6c3fc83fac2af3a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 119, "license_type": "no_license", "max_line_length": 38, "num_lines": 6, "path": "/models/item.py", "repo_name": "di2pra/Innovattic", "src_encoding": "UTF-8", "text": "from xml.dom import minidom\nfrom models.domObject import domObject\n\nclass item(domObject):\n\t\n\tpropertyName = 'quantity'" }, { "alpha_fraction": 0.6790615320205688, "alphanum_fraction": 0.681717574596405, "avg_line_length": 33.18939208984375, "blob_id": "cfe693c36cfec75f28a9228f32011badeb08fe49", "content_id": "90599ec7c801c86ca75f203b5b69f9a035bfe4df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4518, "license_type": "no_license", "max_line_length": 183, "num_lines": 132, "path": "/classes/LanguageXMLConverter.py", "repo_name": "di2pra/Innovattic", "src_encoding": "UTF-8", "text": "class LanguageXMLConverter:\n\t\"\"\"A Simple Language Converter class: give an array of xml language files path, it will generate a single language property file\"\"\"\n\n\t\"\"\" Static parameters \"\"\"\n\tregexPattern = '([%][0-9]+[$]\\w)|(%d)' # regex pattern to replace property value in the output file\n\n\tdef __init__(self, schema, inputFilesPath = None):\n\t\t\"\"\" LanguageXMLConvert Class Initiator\n\t\t=====================\n\t\t@param:\n\t\t\tschema: required XML schema object (domObject)\n\t\t\tinputFiles([string]): optional array of string of input XML file paths\n\t\t@return: nothing\n\t\t=====================\"\"\"\n\t\tself.schema = schema\n\t\tself.inputFiles = [] if inputFilesPath is None else inputFilesPath # if the inputFilesPath is not defined, then set the array of file paths as empty\n\n\n\n\n\n\tdef addInputXMLFile(self, inputFilePath):\n\t\t\"\"\" Append a new XML file path to the existing filepath array\n\t\t=====================\n\t\t@param: inputFilePath(string): string of input XML file path to append\n\t\t@return: nothing\n\t\t=====================\"\"\"\n\t\tself.inputFiles.append(inputFilePath) # append the given file path to the existing array of input file paths\n\n\n\n\n\n\n\tdef generateOutputFile(self, outputFilePath):\n\t\t\"\"\" given the output file path, this method will generate the property language text file\n\t\t=====================\n\t\t@param: outputFilePath(string): string of input XML file path to append\n\t\t@return: nothing\n\t\t=====================\"\"\"\n\t\tfrom models.string import string\n\t\tfrom models.plurals import plurals\n\t\tfrom xml.dom import minidom #import python minimal dom implementation\n\n\t\ttry:\n\n\t\t\toutputFile = open(outputFilePath,'w') #generate empty output text file\n\t\t\n\t\t\tfor inputFile in self.inputFiles: # iterate for each input file paths\n\n\t\t\t\tfileName = LanguageXMLConverter.getFileNameFromPath(inputFile) # get the file name\n\t\t\t\txmldoc = minidom.parse(inputFile) #parse the XML input file given the path\n\n\t\t\t\tvalues = self.schema(xmldoc).generateValues(fileName) # add the fileName as the prepend for property names in order to distinguish same property name within different input files\n\n\t\t\t\tfor value in values:\n\t\t\t\t\toutputFile.write(LanguageXMLConverter.lineString(value[0], value[1]))\n\t\t\t\n\t\t\toutputFile.close() # close the generated file\n\n\t\t\tprint(\"File `\" + str(outputFilePath) + \"` succesfully generated\")\n\t\t\t\n\t\texcept IOError as e: #catch file error\n\t\t\tprint \"Unable to generate the output file. Error info: I/O error({0}) - {1}\".format(e.errno, e.strerror)\n\t\texcept UnicodeDecodeError as e: #catch encoding error\n\t\t\tprint \"Unable to generate the output file. Error info: UnicodeDecodeError - {0}\".format(e)\n\t\texcept Exception as e:\n\t\t\tprint \"Unable to generate the output file. Error info: Undefined error - {0}\".format(e)\n\n\n\n\n\n\t@staticmethod\n\tdef formatXmlCharacter(value):\n\t\t\"\"\" given the input string, this STATIC method will convert the string according to the regex, the position of the match and replace by `{position}` and return the converted string.\n\t\t=====================\n\t\t@param: value(string): string to convert\n\t\t@return: string : converted string\n\t\t=====================\"\"\"\n\n\t\timport re\n\n\t\ttry:\n\n\t\t\toutput = value\n\t\t\tmatches = re.findall(LanguageXMLConverter.regexPattern, value) # find all matches of the regex within the input string\t\t\n\n\t\t\tindex=0 # init the position to 0\n\n\t\t\tfor match in matches: #iterate for matches of the input string\n\t\t\t\tfor subMatch in match:\n\t\t\t\t\tif subMatch is not '':\n\t\t\t\t\t\toutput = output.replace(subMatch, '{'+str(index)+'}')\n\t\t\t\t\t\tindex += 1\n\t\t\t\t\n\n\t\t\treturn output # return the converted value\n\t\t\t\n\t\texcept Exception, e: #if we catch an exception during the formating method, return the initial string value\n\n\t\t\treturn value\n\n\n\n\n\n\t@staticmethod\n\tdef lineString(property, value):\n\t\t\"\"\" generate the property file line string given the property and value\n\t\t=====================\n\t\t@param:\n\t\t\t- property(string): string of the property name\n\t\t\t- value(string): string of the property value\n\t\t@return: (string) : return string format : `property = value`\n\t\t=====================\"\"\"\n\n\t\treturn property + ' = ' + LanguageXMLConverter.formatXmlCharacter(value) + '\\n'\n\n\n\n\t@staticmethod\n\tdef getFileNameFromPath(path):\n\t\t\"\"\" given the file path, this method will return the file name without the extension\n\t\t=====================\n\t\t@param:\n\t\t\t- path(string): full path of the file\n\t\t@return: (string) : filename\n\t\t=====================\"\"\"\n\t\timport ntpath #file path module\n\n\t\treturn ntpath.basename(path).split('.')[0] # getting the filename without the extension from the fullpath\n\n\n\n\n\n" }, { "alpha_fraction": 0.6771300435066223, "alphanum_fraction": 0.6786248087882996, "avg_line_length": 33.620689392089844, "blob_id": "73c197c82b973d46d1d34616bfa9bc748aa4223d", "content_id": "f97e08cee3afc64f7dd146b182bb30d1f419645a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2007, "license_type": "no_license", "max_line_length": 138, "num_lines": 58, "path": "/models/domObject.py", "repo_name": "di2pra/Innovattic", "src_encoding": "UTF-8", "text": "from xml.dom import minidom\n\nclass domObject(object):\n\t\"\"\"Main Dom Object Mapper\"\"\"\n\n\t\n\t\"\"\" Static parameters \"\"\"\n\tchildObjects = None # define if the current object as child dom object by default None\n\tpropertyName = None # define the property name of the dom object to get the property value, by default None\n\n\tdef __init__(self, xml):\n\t\t\"\"\" dom object class initiator\n\t\t=====================\n\t\t@param: xml(Node Element): XML node element\n\t\t@return: null\n\t\t=====================\"\"\"\n\t\tself.xml = xml\n\t\tself.tagName = self.__class__.__name__\n\n\n\n\n\n\n\tdef generateValues(self, prepend = None):\n\t\t\"\"\" generate the dom element property file line\n\t\t=====================\n\t\t@param: prepend(string): optional string to prepend the property name\n\t\t@return: [(name, value)] : return an array of tuplet composed by (name, value)\n\t\t=====================\"\"\"\n\n\t\tvalue = []\n\n\t\tdom = self.xml.getElementsByTagName(self.tagName) # get the list of items give the tag name\n\n\t\tfor domItem in dom: # for each dom item\n\n\t\t\tif self.childObjects == None: # if the childObject is null then generate directly the string\n\n\t\t\t\tprependStr = '' if (prepend == None) else (str(prepend) + '.')\n\t\t\t\tvalue.append((str(prependStr) + domItem.attributes[self.propertyName].value.encode('utf-8'), domItem.firstChild.data.encode('utf-8')))\n\n\t\t\telse: # otherwise generate recursivly with the child domObject and prepend the parent property value\n\n\t\t\t\tparentName = None if (self.propertyName == None) else domItem.attributes[self.propertyName].value.encode('utf-8')\n\n\t\t\t\tif parentName == None: # if parentName is None then prependStr is equel to prepend value\n\n\t\t\t\t\tprependStr = None if (prepend == None) else prepend\n\n\t\t\t\telse: # else append the parentName to the prepend Value\n\n\t\t\t\t\tprependStr = parentName if (prepend == None) else (str(prepend) + '.' + parentName)\n\n\t\t\t\tfor childObject in self.childObjects:\n\t\t\t\t\tvalue.extend(childObject(domItem).generateValues(prependStr)) # recursively call the method to process sub nodes\n\t\t\t\n\t\treturn value" }, { "alpha_fraction": 0.8017241358757019, "alphanum_fraction": 0.8017241358757019, "avg_line_length": 18.5, "blob_id": "b10fb2b2412e9d23813aefe4c48ded3ba394cc70", "content_id": "55a50c72f9b399d992002a73d4c43b089f9d1b69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 116, "license_type": "no_license", "max_line_length": 38, "num_lines": 6, "path": "/models/string.py", "repo_name": "di2pra/Innovattic", "src_encoding": "UTF-8", "text": "from xml.dom import minidom\nfrom models.domObject import domObject\n\nclass string(domObject):\n\n\tpropertyName = 'name'" } ]
8
brownsarahm/lecture_tools
https://github.com/brownsarahm/lecture_tools
0814db75571f7ad279f85813bde28eee096dd3c8
dfb964e5fe1d1f17f2f721bfebc99d5161bb31bd
8c5b6e0e45bf4bddc31376a0eac61315c9039421
refs/heads/main
2021-07-09T04:55:09.022222
2021-06-19T15:38:33
2021-06-19T15:38:33
245,562,296
0
0
NOASSERTION
2020-03-07T03:37:49
2021-06-19T13:35:59
2021-06-19T15:38:33
Python
[ { "alpha_fraction": 0.5554419755935669, "alphanum_fraction": 0.557996928691864, "avg_line_length": 24.58169937133789, "blob_id": "d0a871bc51e11a522cb73e00e064497e1e62c457", "content_id": "8cfaf1600d1897931f8709f4fdc951d93455b6fb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3914, "license_type": "permissive", "max_line_length": 81, "num_lines": 153, "path": "/lecture_tools/slides.py", "repo_name": "brownsarahm/lecture_tools", "src_encoding": "UTF-8", "text": "from IPython.display import display, Markdown, Latex\nfrom .segments import Slide\nimport os\n\n\nclass MarkdownSlide(Slide):\n '''\n '''\n\n def show(self):\n '''\n show a markdown slide saved in the slides folder with filename `title.md`\n\n Parameters\n ----------\n title : string\n file name with or without extension\n '''\n\n display(Markdown(self.body))\n\n\nclass ImageSlide(Slide):\n '''\n display an image that has the file name\n '''\n def __init__(self, slide_dict):\n super().__init__(slide_dict)\n self.imgdir = slide_dict['info']['imgdir']\n self.make_body()\n\n def make_body(self):\n '''\n make the body string so that it can be both displayed and printed\n '''\n # source_path = os.path.dirname(self.sourcefile)\n # img_path = os.path.join(self.imgdir,self.name+'.png')\n\n img_path = os.path.join('img',self.name+'.png')\n img_tmp = '<img src=\" {name}\" />'\n img_str = img_tmp.format(name = img_path)\n self.body = img_str\n\n def show(self):\n '''\n '''\n\n display(Markdown(self.body))\n\n\n\nclass ImageAnimateSlide(Slide):\n '''\n display a sequence of images in the same location to overlap\n '''\n def __init__(self, slide_dict):\n super().__init__(slide_dict)\n\n self.img_list = slide_dict['info']['img_list']\n\n # def show():\n def show(self):\n '''\n '''\n display(Markdown('<img src=\"./slides/' + self.name +'.png\" />'))\n\n\n\nclass BulletAnimateSlide(Slide):\n '''\n Slide where markdown points are displayed one at a time on sequential calls\n to show()\n\n set type to 'animate' and use `--` to separate parts of the slide that will\n be animated\n '''\n def __init__(self,slide_dict):\n super().__init__(slide_dict)\n self.shown_points = 0\n self.body = self.body.split('\\n--\\n')\n\n def show(self):\n '''\n '''\n if self.shown_points <=len(self.body):\n self.shown_points +=1\n\n cur_display = self.body[:self.shown_points]\n display(Markdown(''.join(cur_display)))\n\n\nclass HackmdExercise(Slide):\n '''\n an exercise typ that sends students to a hackmd file\n and then reads back the text from that markdown file to the notebook\n '''\n\n def __init__(self,slide_dict):\n super().__init__(slide_dict)\n self.url = slide_dict['info']['url']\n self.prompt_shown = False\n\n def show(self):\n '''\n '''\n if self.prompt_shown:\n self.show_response()\n else:\n self.prompt_shown = True\n self.show_prompt()\n\n\n def show_response(self):\n response_url = 'https://' + self.url + '/download/markdown'\n display(Markdown(response_url))\n\n def show_prompt(self):\n prompt_url = 'https://' + self.url + '?edit'\n prompt_link = '[Excercise](' + prompt_url + ')'\n display(Markdown(prompt_link))\n\n\nclass GridAppSlide(Slide):\n '''\n '''\n def __init__(self,slide_dict):\n super().__init__(slide_dict)\n self.appgrid = GridspecLayout(len(cur_slide),15)\n\n self.buttons = []\n\n self.slide_display = Output()\n with slide_display:\n display(Markdown(self.body[0]))\n\n self.appgrid[:,1:] = slide_display\n\n for i in range(len(self.body)-1):\n self.buttons.append(create_toggle(''))\n self.appgrid[i+1,0] = self.buttons[i]\n self.buttons[i].observe(reveal,names='value',)\n\n\n def reveal(b):\n sself.lide_display.clear_output()\n cur_lines = [0]\n cur_lines.extend([i+fixed_len for i,bt in enumerate(button) if bt.value])\n with self.slide_display:\n # display(Markdown(cur_lines))\n display(Markdown(''.join([self.body[l] for l in cur_lines])))\n\n def show(self):\n return self.appgrid\n" }, { "alpha_fraction": 0.6196078658103943, "alphanum_fraction": 0.6235294342041016, "avg_line_length": 30.875, "blob_id": "3900a34baff5930549a8b6f1d5382faa371a7f2b", "content_id": "4d33c30357ba84c249651297061aaba1b09af122", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 510, "license_type": "permissive", "max_line_length": 107, "num_lines": 16, "path": "/setup.py", "repo_name": "brownsarahm/lecture_tools", "src_encoding": "UTF-8", "text": "from setuptools import setup\n\nsetup(name='Lecture Tools',\n version='0.1',\n description='tools for teaching and presenting from markdown and notebooks with notebooks reveal.js',\n url='',\n author='Sarah M Brown',\n author_email='[email protected]',\n license='MIT',\n packages=['lecture_tools'],\n zip_safe=False,\n include_package_data = True,\n install_requires=['IPython'],\n entry_points = {\n 'console_scripts': ['lecture_repo=lecture_tools.lecture_repo:main'],}\n )\n" }, { "alpha_fraction": 0.686956524848938, "alphanum_fraction": 0.7043478488922119, "avg_line_length": 11.777777671813965, "blob_id": "d1eb606dd47029700af688ac64c016958405d8cc", "content_id": "944d586cf091788cd281d2be7118914040adcbaa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 115, "license_type": "permissive", "max_line_length": 37, "num_lines": 9, "path": "/test.md", "repo_name": "brownsarahm/lecture_tools", "src_encoding": "UTF-8", "text": "----\ntype:hackmd\nurl: hackmd.io/VHE7PhprQ8yOa_dVq-ULrg\nname: warmup\n---\n\n# Warmup Activity\n\n## add a question here\n" }, { "alpha_fraction": 0.6751412153244019, "alphanum_fraction": 0.6807909607887268, "avg_line_length": 22.600000381469727, "blob_id": "04c786fb458bc309f5fd46779327ec3cf19a5235", "content_id": "594dfc8064d888f259ba2506dc8bd935a36d74e9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 354, "license_type": "permissive", "max_line_length": 79, "num_lines": 15, "path": "/lecture_tools/lecture_repo.py", "repo_name": "brownsarahm/lecture_tools", "src_encoding": "UTF-8", "text": "from lecture_tools import Presentation\nimport sys\n\n\ndef main():\n '''\n takes two parameters: a markdown file as input and a directory to write the\n presentation out to\n\n generates a reveal.js compatible repo\n '''\n in_md = sys.argv[1]\n out_dir = sys.argv[2]\n lecture = Presentation(in_md)\n lecture.generate_lecture_repo(out_dir)\n" }, { "alpha_fraction": 0.7850000262260437, "alphanum_fraction": 0.7850000262260437, "avg_line_length": 46.05882263183594, "blob_id": "ab333c16ac2587e1d1f6a060d57a3308a8d0969f", "content_id": "5c2b39dab93c5251c86c50cc85bd0f7fd527810c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1600, "license_type": "permissive", "max_line_length": 139, "num_lines": 34, "path": "/README.md", "repo_name": "brownsarahm/lecture_tools", "src_encoding": "UTF-8", "text": "# Lecture Tools\n\na python package for delivering interactive lessons via a jupyter notebook or share via reveal.js, currently it makes a reveal presentation\nTo open lecture tools, download the file from github. \n\nAfter the download, you must install pip. Instructions for doing so are found here: https://pip.pypa.io/en/stable/installing/\n\nNext, jekyll needs to be installed. Instructions for doing so are found here: https://jekyllrb.com/docs/installation/\n\nNext, using the make html command on the terminal window, open up the file lecturetools on a browser.\n\nThe terminal will generate a local browser website html that allows for the user to view the slides.\n\nBy entering this link onto a browser window such as google chrome, the user will be able to open the presentation.\n\n<!-- To use this package, you write a lecture or activity using markdown or jupyter notebooks.\n\nThen in a notebook you can:\n- as instructor read in a lesson and display it slide by slide in a prespecified order or in a different order by calling slides by name\n- as a student read in a lesson and get worksheets to follow along in class and take notes both on your own and with instructor guidance\n\nThe command line tools allow you to:\n- parse a notebook into .py files to use with load magic\n- generate the student repo from the class prep repo\n\n\nThe class prep repo will include:\n- markdown files of lesson to be presented like slides\n- complete jupyter notebooks\n\nThe student repo will contain:\n- lesson snippets as markdown files\n- .py files with runnable code excerpts\n- .py files with fill in the blank slots -->\n" }, { "alpha_fraction": 0.5645161271095276, "alphanum_fraction": 0.5645161271095276, "avg_line_length": 7.857142925262451, "blob_id": "4002b32bc3a13a41ac63a94fcd8b5ede027a44dd", "content_id": "fe0a4dcc9c296b4e2348c4f783604dc61f5c943e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 62, "license_type": "permissive", "max_line_length": 15, "num_lines": 7, "path": "/lecture_tools/resources/pystrings/index.md", "repo_name": "brownsarahm/lecture_tools", "src_encoding": "UTF-8", "text": "---\nlayout: page\npermalink: ./\n---\n\n# {title}\n_{description}_\n" }, { "alpha_fraction": 0.6222222447395325, "alphanum_fraction": 0.6222222447395325, "avg_line_length": 10.25, "blob_id": "e3f5bbc6405a9b25dcc442aa77d010f24bbf4257", "content_id": "241b950e91ea9d0a6b5cbb46ae0e461d2abcf68f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 45, "license_type": "permissive", "max_line_length": 21, "num_lines": 4, "path": "/lecture_tools/resources/pystrings/slides.md", "repo_name": "brownsarahm/lecture_tools", "src_encoding": "UTF-8", "text": "---\nlayout: slides\nslideset: {slide_dir}\n---\n" }, { "alpha_fraction": 0.7096773982048035, "alphanum_fraction": 0.7096773982048035, "avg_line_length": 19.66666603088379, "blob_id": "21579d1a85ac1ee4f167df8336b653d00a5ef3b5", "content_id": "eccd05b6160ffb1a40db1e9c116930dcbb316d6e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 62, "license_type": "permissive", "max_line_length": 33, "num_lines": 3, "path": "/lecture_tools/__init__.py", "repo_name": "brownsarahm/lecture_tools", "src_encoding": "UTF-8", "text": "from .lecture import Presentation\n\n__all__ = ['Presentation']\n" }, { "alpha_fraction": 0.6498316526412964, "alphanum_fraction": 0.6717171669006348, "avg_line_length": 26, "blob_id": "0d4f89498d4b2e5d0f8e3b60281c5caa53025b7a", "content_id": "2f33db12f80e9cbeabbb1484f7273093d82bbe5d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 594, "license_type": "permissive", "max_line_length": 84, "num_lines": 22, "path": "/docs/source/index.rst", "repo_name": "brownsarahm/lecture_tools", "src_encoding": "UTF-8", "text": ".. Lecture Tools documentation master file, created by\n sphinx-quickstart on Fri Mar 27 19:35:04 2020.\n You can adapt this file completely to your liking, but it should at least\n contain the root `toctree` directive.\n\nWelcome to Lecture Tools's documentation!\n=========================================\nThis file contains the background for lecture tools. \n.. toctree::\n :maxdepth: 2\n :caption: Contents:\n\n\nTools for creating lectures, tutorials and presentations form markdown and notebooks\n\n\nIndices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n" }, { "alpha_fraction": 0.5970560908317566, "alphanum_fraction": 0.5970560908317566, "avg_line_length": 19.884614944458008, "blob_id": "3243cb494a1cedaac42ed8f8db87f05bef68e377", "content_id": "3a3b019df0104e3ffa7eb902d608c9e3101c1a72", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1087, "license_type": "permissive", "max_line_length": 77, "num_lines": 52, "path": "/lecture_tools/extra.py", "repo_name": "brownsarahm/lecture_tools", "src_encoding": "UTF-8", "text": "\ndef show_frame(title):\n '''\n show a markdown slide saved in the slides folder with filename `title.md`\n\n Parameters\n ----------\n title : string\n file name with or without extension\n '''\n\n\n slide_file = os.path.join('slides',md_file(title))\n\n\n with open(slide_file) as f:\n slide = f.read()\n\n display(Markdown(slide))\n\ndef show_slide(title,line):\n '''\n show a markdown slide saved in the slides folder with filename `title.md`\n\n Parameters\n ----------\n title : string\n file name with or without extension\n '''\n\n\n slide_file = os.path.join('slides',md_file(title))\n\n\n with open(slide_file) as f:\n slide = f.read_line()\n\n display(Markdown(slide))\n\ndef show_image(title):\n '''\n '''\n\n display(Markdown('<img src=\"./slides/' + title +'.png\" />'))\n\ndef show_response(base_url):\n response_url = base_url + '/download/markdown'\n display(Markdown())\n\ndef show_prompt(base_url):\n promp_url = base_url + '?edit'\n prompt_link = '[Excercise](' + propmp_url + ')'\n display(Markdown(prompt_link))\n" }, { "alpha_fraction": 0.49943801760673523, "alphanum_fraction": 0.5006422400474548, "avg_line_length": 34.58856964111328, "blob_id": "3c73dd7859ebd84c3d9f89d254b5a281d2ffadb1", "content_id": "a1a8ddf794fb43bbca6740c341a8fb30b362e93d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12456, "license_type": "permissive", "max_line_length": 102, "num_lines": 350, "path": "/lecture_tools/lecture.py", "repo_name": "brownsarahm/lecture_tools", "src_encoding": "UTF-8", "text": "import os, shutil\nfrom IPython.display import display, Markdown, Latex\nfrom numpy import inf\nfrom .slides import (MarkdownSlide, ImageSlide, ImageAnimateSlide,\n BulletAnimateSlide, HackmdExercise)\nfrom .segments import PreModule, PostModule\nimport pkg_resources as pkgrs\n\n\nsegment_shortnames = {'md':MarkdownSlide,\n 'img':ImageSlide,\n 'img-animate': ImageAnimateSlide,\n 'animate':BulletAnimateSlide,\n 'hackmd':HackmdExercise,\n 'canvas':PreModule,\n 'prereq':PreModule,\n 'postnotes':PostModule}\n\ncopy_path = os.path.join('resources','copy')\ncopy_files = pkgrs.resource_listdir(__name__,copy_path)\n\npystring_path = os.path.join('./resources','pystrings')\n\n\n\n\ndef md_file(name,ext='.md'):\n '''\n add md extention if not present\n '''\n\n if name[-2:] == ext:\n return name\n else:\n return name + ext\n\ndef ismd(name):\n return name[-2:] == '.md'\n\n# slide_types\n\nhandout_header = \"---\\nlayout: handouts\\nslideset :{}\\npermalink:handout/---\"\nslides_header = \"---\\nlayout:slides\\nslideset :{}\\npermalink:slides/---\"\n\nclass Presentation():\n\n def __init__(self,content_file):\n '''\n load a file and create the object\n '''\n\n self.title, _ = content_file.split('.')\n self.sourcefile = os.path.abspath(content_file)\n self.slides = {}\n self.slide_order_list = []\n self.slide_order_dict = {}\n self.supplementary = {}\n self.curslide = 0\n self.input_md(content_file)\n\n def input_md(self,file):\n '''\n '''\n\n with open(file) as mdf:\n lect_raw = mdf.read()\n\n\n # split slides\n segments_raw = lect_raw.split('----')\n meta = segments_raw[0]\n\n # meta data parsing\n meta = meta.split('\\n')\n #split all non empty ones at :\n meta = [m.split(':') for m in meta if len(m)>0]\n meta = {m[0].strip():m[1].strip() for m in meta}\n # make it absolute\n source_path = os.path.dirname(self.sourcefile)\n meta['imgdir'] = os.path.join(source_path,meta['imgdir'] )\n self.meta = meta\n\n\n # split header from body\n segments_header_body = [s.split('---') for s in segments_raw[1:]]\n # make one dict per slide and strucutre info into subdict\n segment_list = [{'info':{p[0].strip():p[1].strip()\n for p in [(kv.split(':')) for kv in s[0].strip().split('\\n')]},\n 'body':s[1]}\n for s in segments_header_body]\n\n # create a dictionary with name:SlideObject\n segments = {s['info']['name']:self.generate_object(s) for s in segment_list}\n slides = {s.name:s for s in segments.values() if s.is_slide()}\n supplementary = {s.name: s for s in segments.values() if not(s.is_slide())}\n\n # dictionaries do not preserve order\n title_list = [s['info']['name'] for s in segment_list]\n slide_order_list = [title for title in title_list\n if segments[title].is_slide() ]\n slide_order_dict = {title:i + len(self.slides)\n for i,title in enumerate(slide_order_list)}\n\n if len(set(slide_order_list)) < len(slide_order_list):\n raise NameError('Reused Slide Name')\n # append all (update is dictionary apped)\n self.slides.update(slides)\n self.supplementary.update(supplementary)\n self.slide_order_list.extend(slide_order_list)\n self.slide_order_dict.update(slide_order_dict)\n\n\n\n def generate_object(self,slide_dict):\n '''\n parse the dict to create the right type of object\n '''\n # complete the info fields\n if not('type' in slide_dict['info'].keys()):\n slide_dict['info']['type'] = 'md'\n\n slide_dict['info']['imgdir'] = self.meta['imgdir']\n\n # return the slide after parsing\n return segment_shortnames[slide_dict['info']['type']](slide_dict)\n\n def show(self,title):\n '''\n '''\n self.curslide = self.slide_order_dict[title]\n self.slides[title].show()\n\n def next(self):\n '''\n '''\n self.curslide += 1\n title = self.slide_order_list[self.curslide]\n self.slides[title].show()\n\n def __get_item__(self,key):\n '''\n '''\n self.slides[key].show()\n\n def generate_lecture_repo(self,repo_dir, slide_dir = '_slides'):\n '''\n generate repository that will work with reveal.js via the\n jekyll-reveal-deck-pack theme\n\n '''\n # copy files\n for file in copy_files:\n source_path = os.path.join(copy_path,file)\n source = pkgrs.resource_filename(__name__,source_path)\n # with open(source,'r') as f:\n # source_str = f.read()\n\n destination = os.path.join(repo_dir,file)\n shutil.copy(source,destination)\n # with open(destination,'r') as f:\n # f.write(source_str)\n\n # todo : copy images\n\n\n # ---------------------------------------------------------------------\n # process readme\n # ---------------------------------------------------------------------\n readme_path = os.path.join(pystring_path,'README.md')\n # read in readme template\n readme_file = pkgrs.resource_filename(__name__,readme_path)\n with open (readme_file,'r') as f:\n readme_template = f.read()\n\n # format readme\n readme = readme_template.format(title = self.meta['title'],\n description = self.meta['description'])\n\n # write readme\n with open(os.path.join(repo_dir,'README.md'),'w') as f:\n f.write(readme)\n\n # ---------------------------------------------------------------------\n # process index\n # ---------------------------------------------------------------------\n index_path = os.path.join(pystring_path,'index.md')\n # read in readme template\n index_file = pkgrs.resource_filename(__name__,index_path)\n with open (index_file,'r') as f:\n index_template = f.read()\n\n # format readme\n index = index_template.format(title = self.meta['title'],\n description = self.meta['description'])\n\n index += '\\n## [Slides]({{ site.baseurl }}{% link slides.md %})'\n index += '\\n## [Handout]({{ site.baseurl }}{% link handout.md %})'\n\n\n # write readme\n with open(os.path.join(repo_dir,'index.md'),'w') as f:\n f.write(index)\n\n\n # ---------------------------------------------------------------------\n # process handouts and info pages\n # ---------------------------------------------------------------------\n handout_template_path = os.path.join(pystring_path,'handout_header.md')\n # read in readme template\n handout_file = pkgrs.resource_filename(__name__,handout_template_path)\n with open (handout_file,'r') as f:\n handout_template = f.read()\n\n prereq_list = [s.content for s in self.supplementary.values() if s.is_prereq]\n prereqs = '\\n<hr>\\n'.join(prereq_list)\n # format lesson overall page\n lesson = handout_template.format(slide_dir = slide_dir.strip('_'),\n heading = prereqs, permalink='lesson')\n\n # write lesson ovearll page\n with open(os.path.join(repo_dir,'lesson.md'),'w') as f:\n f.write(lesson)\n\n # format handout\n handout = handout_template.format(slide_dir = slide_dir.strip('_'),\n heading = '',permalink='handout')\n\n # write handout\n with open(os.path.join(repo_dir,'handout.md'),'w') as f:\n f.write(handout)\n\n # format homework\n handout = handout_template.format(slide_dir = slide_dir.strip('_'),\n heading = '',permalink='postnotes')\n\n # write handout\n with open(os.path.join(repo_dir,'followup.md'),'w') as f:\n f.write(handout)\n # ---------------------------------------------------------------------\n # process slides\n # ---------------------------------------------------------------------\n slide_template_path = os.path.join(pystring_path,'slides.md')\n # read in readme template\n slides_file = pkgrs.resource_filename(__name__,slide_template_path)\n with open (slides_file,'r') as f:\n slides_template = f.read()\n\n # format readme\n slides = slides_template.format(slide_dir = slide_dir.strip('_'))\n\n # write readme\n with open(os.path.join(repo_dir,'slides.md'),'w') as f:\n f.write(slides)\n\n # ---------------------------------------------------------------------\n # process config\n # ---------------------------------------------------------------------\n config_template_path = os.path.join(pystring_path,'config_template.yml')\n # format config file\n config_template_file = pkgrs.resource_filename(__name__,config_template_path)\n with open (config_template_file,'r') as f:\n config_template = f.read()\n\n config = config_template.format(title = self.meta['title'],\n description = self.meta['description'],\n author = self.meta['author'],\n authorurl = self.meta['authorurl'])\n\n # write config\n with open(os.path.join(repo_dir,'_config.yml'),'w') as f:\n f.write(config)\n\n # format strings\n\n # write files\n slide_dir = os.path.join(repo_dir,slide_dir)\n self.generate_md_slides(slide_dir)\n\n def generate_md_slides(self,write_dir):\n '''\n write slides one per md file\n '''\n\n # iterate over slide titles in order\n for title in self.slide_order_list:\n # extract the current slide object\n cur_slide = self.slides[title]\n\n # convert the whole thing to a dictionary\n slide_dict = cur_slide.__dict__\n slide_dict.pop('content')\n\n # merge lists with newlines and -\n\n for k,v in slide_dict.items():\n if type(v) == list:\n slide_dict[k] = '\\n'.join(slide_dict[k])\n\n # if k == 'notes':\n # slide_dict[k] = '\\n-'.join(slide_dict[k])\n # else:\n\n\n # add order number\n slidenum = self.slide_order_dict[title] + 1\n slide_dict['slidenum'] = slidenum\n\n # remove presentation status feild\n if 'shown_points' in slide_dict.keys():\n slide_dict.pop('shown_points')\n\n # \"\" around notes\n slide_dict['notes'] = '\"' + slide_dict['notes'] + '\"'\n\n # make all strings\n for k,v in slide_dict.items():\n slide_dict[k] = str(v)\n\n # build the actual slide fiel content\n slide_parts = ['---']\n # merge the header info together to generate yaml\n slide_yaml = '\\n'.join([': '.join([k,v]) for k,v in slide_dict.items() if not(k=='body')])\n slide_parts.append(slide_yaml)\n slide_parts.append('---')\n # append the body after the ---\n slide_parts.append(slide_dict['body'])\n # merge with newlines to build string to write to file\n slide_file_str = '\\n'.join(slide_parts)\n\n #name the file\n slide_file_name = str(slidenum).zfill(3) + '-' + title + '.md'\n #make the directory if needed\n if not(os.path.isdir(write_dir)):\n os.makedirs(write_dir)\n\n # write the file\n with open(os.path.join(write_dir,slide_file_name) ,'w') as f:\n f.write(slide_file_str)\n\n\n def generate_md_worksheet(self,file):\n '''\n '''\n with open(file) as f:\n for title in self.slide_order_list:\n for line in self.slides[title].body:\n f.write()\n\n\n # def next_slide(self,title):\n" }, { "alpha_fraction": 0.7862595319747925, "alphanum_fraction": 0.7862595319747925, "avg_line_length": 36.42856979370117, "blob_id": "2dc510030fefd93db5e3686cb8fc9d746fa7184c", "content_id": "f3075354292d8963bb934d3824a6780a9302b9a6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 262, "license_type": "permissive", "max_line_length": 118, "num_lines": 7, "path": "/lecture_tools/resources/pystrings/README.md", "repo_name": "brownsarahm/lecture_tools", "src_encoding": "UTF-8", "text": "# {title}\n\n{description}\n\ngenerated from a single markdown file lesson plan via [lecture tools](https://github.com/brownsarahm/lecture_tools)\n\noverall site rendered with the [jekyll-reveal-deck-pack](https://github.com/brownsarahm/jekyll-reveal-deck-pack) theme\n" }, { "alpha_fraction": 0.5223450064659119, "alphanum_fraction": 0.5237866640090942, "avg_line_length": 19.19417381286621, "blob_id": "9a0b9d199314a1e6412feba0dcea8a632277d22a", "content_id": "27341c876001d36e247885a04e225de74e971c7a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2081, "license_type": "permissive", "max_line_length": 74, "num_lines": 103, "path": "/lecture_tools/segments.py", "repo_name": "brownsarahm/lecture_tools", "src_encoding": "UTF-8", "text": "\ndefault_parameters = {}\n\nclass Segment():\n '''\n '''\n def __init__(self,info_dict):\n '''\n set name and content, which can be split into notes and body\n '''\n self.name = info_dict['info']['name']\n self.content = info_dict['body'].split('\\n')\n\n\n def is_slide(self):\n return False\n\n\n\nclass Module(Segment):\n '''\n Modules have content, but no body\n\n '''\n def __init__(self,info_dict):\n super().__init__(info_dict)\n self.content = '\\n'.join(self.content)\n\n\nclass PreModule(Module):\n '''\n modules that provide information before the content of a lesson\n\n for example introductory remarks or required reading\n '''\n def is_prereq(self):\n return True\n\nclass PostModule(Module):\n '''\n modules that provide information after the content of a lesson\n\n for exmaple, summative assessment or further reading.\n '''\n\n def is_prereq(self):\n return False\n\n\n\nclass Slide(Segment):\n '''\n base class for Slides\n '''\n\n\n def __init__(self,slide_dict):\n '''\n Do segment requirements and strip notes\n '''\n super().__init__(slide_dict)\n self.strip_notes()\n\n # self.type = slide_dict['info']['type']\n\n def is_slide(self):\n '''\n Slides\n '''\n return True\n\n\n def is_prereq(self):\n '''\n Slides are not prereqs\n '''\n return False\n\n def strip_notes(self):\n '''\n remove lines that start with > from the body and separate into the\n notes feild\n '''\n\n body = []\n notes = []\n\n\n # iterate line by line and determine notes or text\n for item in self.content:\n if len(item)>0:\n if item[0] == '>':\n notes.append('- '+item[1:])\n else:\n body.append(item)\n\n # merge body back into one\n body = '\\n'.join(body)\n\n # merge notes back together\n notes = '\\n\\n'.join(notes)\n\n self.body = body\n self.notes = notes\n" }, { "alpha_fraction": 0.6707317233085632, "alphanum_fraction": 0.6707317233085632, "avg_line_length": 10.714285850524902, "blob_id": "049cc6f976215351396770124e00cfb1d995e65c", "content_id": "1a1c17a71ce0c60fc48c5a5357897a80d4d63c45", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 82, "license_type": "permissive", "max_line_length": 23, "num_lines": 7, "path": "/lecture_tools/resources/pystrings/handout_header.md", "repo_name": "brownsarahm/lecture_tools", "src_encoding": "UTF-8", "text": "---\nlayout: handouts\nslideset: {slide_dir}\npermalink: {permalink}/\n---\n\n{heading}\n" } ]
14
miketester1/nauka_pythona
https://github.com/miketester1/nauka_pythona
3d683c9a0110117d78a6f32ce6d78a0afd923bf0
20ea6738be01112e185479a3b20520950e1c9d2b
0576af0fdaadd4192eff4dbca8ce610bdeec055a
refs/heads/master
2022-08-27T19:07:24.377397
2022-07-19T18:48:15
2022-07-19T18:48:15
217,829,196
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6252045631408691, "alphanum_fraction": 0.6397526860237122, "avg_line_length": 39.43382263183594, "blob_id": "042f3a2a7e1ee350dd7612366e19395734c867e8", "content_id": "7715371be10bde21d39a5c3190cdd7caf70ae8f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5574, "license_type": "no_license", "max_line_length": 121, "num_lines": 136, "path": "/biblionetkav2.py", "repo_name": "miketester1/nauka_pythona", "src_encoding": "UTF-8", "text": "import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom time import sleep\nfrom faker import Faker\n\n\"\"\" 'pl_PL' jest niezbędne aby skorzystać z generowania danych do testów wykorzystujących np. polski numer nip\"\"\"\nfake = Faker(['en_US', 'pl_PL'])\n\nvalid_first_name = fake.first_name()\nvalid_last_name = fake.last_name()\nvalid_password = fake.password(length=5)\nvalid_email = fake.free_email()\ninvalid_date = str(fake.date_between(start_date='-123y', end_date='-123y'))\n\n\nclass BiblionetkaRegistration(unittest.TestCase):\n \"\"\"\n Scenariusz testowy: Rejestracja nowego użytkownika na stronie www.biblionetka.pl/\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Warunki wstępne:\n Przeglądarka otwarta na https://www.biblionetka.pl/\n \"\"\"\n self.driver = webdriver.Chrome()\n self.driver.maximize_window()\n self.driver.get(\"https://www.biblionetka.pl/\")\n self.driver.implicitly_wait(10)\n\n def tearDown(self):\n \"\"\" Sprzątanie po teście \"\"\"\n self.driver.quit()\n\n def test_invalid_date_of_birth(self):\n \"\"\"\n Rejestracja nowego użytkownika\n używając nieakceptowalnego roku urodzenia - dane niepoprawne\n (data urodzenia wcześniejsza niż rok 1900)\n \"\"\"\n driver = self.driver\n # KROKI:\n\n \"\"\"\n Wyłączam komunikat o ciasteczkach - \"zasłania\" on dolne pola formularza, przez co Selenium ich\n \"nie widzi\"\n\n Sposób bez użycia javascript:\n driver.find_element_by_xpath('//*[@id=\"ctl00_MCP_CUW___CustomNav0_StepNextButton\"]').send_keys(Keys.ENTER)\n \"\"\"\n # sleep(100)\n # Wyłączam komunikat o ciasteczkach z użyciem javascript\n # accept_cookies = driver.find_element(By.XPATH, '//*[@id=\"accept-cookies-checkbox\"]')\n accept_cookies = driver.find_element(By.XPATH, '// *[ @ id = \"qc-cmp2-ui\"] / div[2] / div / button[2] / span')\n # driver.execute_script(\"arguments[0].click();\", accept_cookies)\n driver.execute_script(\"arguments[0].click();\", accept_cookies)\n\n # // *[ @ id = \"qc-cmp2-ui\"] / div[2] / div / button[2] / span\n # // *[ @ id = \"qc-cmp2-ui\"] / div[2] / div / button[2]\n\n\n # 1. Kliknij w prawym górnym rogu ZAREJESTRUJ SIĘ\n\n rejestracja_button = driver.find_element(By.ID, 'ctl00_registrationLink')\n rejestracja_button.click()\n # sleep(10)\n # // *[ @ id = \"ctl00_registrationLink\"]\n # 2. Wprowadź login\n login_field = driver.find_element(By.NAME, \"ctl00$MCP$CUW$CreateUserStepContainer$UserName\")\n login_field.send_keys(valid_first_name + valid_last_name)\n\n # 3. Wprowadź hasło\n # password_field = driver.find_element_by_xpath('//input[@placeholder=\"xxxx\"]')\n password_field = driver.find_element(By.XPATH, '//*[@id=\"ctl00_MCP_CUW_CreateUserStepContainer_Password\"]')\n password_field.send_keys(valid_password)\n\n # 4. Potwierdź hasło\n # poprawa czytelności - rozbicie jednej linii kodu na dwie, aby długość linii nie przekraczała 80 znaków),\n # dla odmiany bez użycia dodatkowej zmiennej\n\n driver.find_element \\\n (By.XPATH, '// *[ @ id = \"ctl00_MCP_CUW_CreateUserStepContainer_ConfirmPassword\"]').send_keys(valid_password)\n\n # 5. Wprowadź email\n driver.find_element(By.NAME, \"ctl00$MCP$CUW$CreateUserStepContainer$Email\").send_keys(valid_email)\n\n # 6. Powtórz email\n driver.find_element(By.NAME, \"ctl00$MCP$CUW$CreateUserStepContainer$Email2\").send_keys(valid_email)\n\n # 7. Wprowadź datę urodzenia\n driver.find_element(By.NAME, \"ctl00$MCP$CUW$CreateUserStepContainer$BirthYear\").send_keys(invalid_date)\n\n # 8. Wprowadź płeć\n driver.find_element(By.XPATH, '//*[@id=\"ctl00_MCP_CUW_CreateUserStepContainer_Sex_1\"]').click()\n\n # 9. Zaakceptuj regulamin\n \"\"\"\n W sytuacji jeśli komunikat o ciasteczkach nie byłyby wyłączony (lina 52), można wymusić akceptację regulaminu\n przez \"wysłanie\" spacji \n driver.find_element_by_xpath('//*[@id=\"ctl00_MCP_CUW_CreateUserStepContainer_RulesAccepted\"]').send_keys(' ')\n \"\"\"\n driver.find_element(By.XPATH, '//*[@id=\"ctl00_MCP_CUW_CreateUserStepContainer_RulesAccepted\"]').click()\n\n \"\"\"\n Kliknięcie rejestracji - nie używam, ponieważ nie chcę dokonać rzeczywistej rejestacji i generować\n pustych kont Biblionetce\n driver.find_element_by_xpath('// *[ @ id = \"ctl00_MCP_CUW___CustomNav0_StepNextButton\"]').click()\n \"\"\"\n\n # Wizualnie oceniam test\"\n sleep(10)\n\n \"\"\"\n Test: sprawdzam oczekiwany rezultat\n \"\"\"\n\n # Wyszukuję wszystkie błędy\n error_notices = driver.find_elements(By.XPATH,\n '//*[@id=\"ctl00_MCP_CUW_CreateUserStepContainer_RangeValidator1\"]')\n # Zapisuję widoczne błędy do listy visible_error_notices\n # Tworzę pustą listę\n visible_error_notices = []\n for error in error_notices:\n # Jesli błąd jest widoczny, dodaj go do listy\n if error.is_displayed():\n visible_error_notices.append(error)\n # Sprawdzam, czy jest widoczny tylko jeden błąd\n assert len(visible_error_notices) == 1\n # Sprawdzam treść widocznego błędu\n error_text = visible_error_notices[0].get_attribute(\"innerText\")\n assert error_text == \"* Niepoprawny rok urodzenia\"\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n" }, { "alpha_fraction": 0.6460245847702026, "alphanum_fraction": 0.6610665917396545, "avg_line_length": 37.20149230957031, "blob_id": "4939c45ad5879b5c981a239e453af70abef6707a", "content_id": "3cb725401afff84d7d9f8bcf8d5552ba621f9465", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5162, "license_type": "no_license", "max_line_length": 257, "num_lines": 134, "path": "/ingeloan.py", "repo_name": "miketester1/nauka_pythona", "src_encoding": "UTF-8", "text": "import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.keys import Keys\nfrom time import sleep\nfrom faker import Faker\n\n\"\"\" 'pl_PL' jest niezbędne aby skorzystać z generowania danych do testów wykorzystujących np. polski numer nip\"\"\"\nfake = Faker(['en_US', 'pl_PL'])\n\nvalid_first_name = fake.first_name()\nvalid_last_name = fake.last_name()\nvalid_password = fake.password(length=5)\nvalid_email = fake.free_email()\ninvalid_date = str(fake.date_between(start_date='-123y', end_date='-123y'))\n\n\nclass INGLoan(unittest.TestCase):\n \"\"\"\n Scenariusz testowy: Pożyczka dla firm\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Warunki wstępne:\n Przeglądarka otwarta na ing\n \"\"\"\n self.driver = webdriver.Chrome()\n self.driver.maximize_window()\n self.driver.get(\"https://forms.ing.pl/DETeWniosekWormsExt/wizardwfb.aspx?path=T5_E-EndUserWormsExt-S5-CREDIT_SBF&url_channel=vortal&FROM=https%3a%2f%2fwww.ing.pl%2fmale-firmy%2fkredyty-i-pozyczki%2fpozyczka-dla-malych-firm&bankId=6&profileId=4&c=1\")\n self.driver.implicitly_wait(10)\n\n def tearDown(self):\n \"\"\" Sprzątanie po teście \"\"\"\n self.driver.quit()\n\n def test_invalid_date_of_birth(self):\n \"\"\"\n Wnioskowanie o pożyczkę używająć\n używając nieakceptowalnego roku urodzenia - dane niepoprawne\n (data urodzenia wcześniejsza niż rok 1900)\n \"\"\"\n driver = self.driver\n # KROKI:\n\n \"\"\"\n Wyłączam komunikat o ciasteczkach - \"zasłania\" on dolne pola formularza, przez co Selenium ich\n \"nie widzi\"\n\n Sposób bez użycia javascript:\n driver.find_element_by_xpath('//*[@id=\"ctl00_MCP_CUW___CustomNav0_StepNextButton\"]').send_keys(Keys.ENTER)\n \"\"\"\n # sleep(100)\n # Wyłączam komunikat o ciasteczkach z użyciem javascript\n\n # accept_cookies = driver.find_element(By.XPATH, '// *[ @ id = \"qc-cmp2-ui\"] / div[2] / div / button[2] / span')\n # driver.execute_script(\"arguments[0].click();\", accept_cookies)\n\n\n\n # 1. Kliknij Dalej\n\n\n\n\n dwanascie_mies_button = driver.find_element(By.XPATH, '// *[ @ id = \"icheckFullID_ctl00_CPH_Content_companyPeriodOfActivity__RB__0\"]')\n dwanascie_mies_button.click()\n\n szesc_mies_button = driver.find_element(By.XPATH, '//*[@id=\"icheckFullID_ctl00_CPH_Content_companyPeriodOfBusinessBankAccount__RB__0\"]')\n szesc_mies_button.click()\n\n klauzula_button = driver.find_element(By.ID, 'icheckHelperID_ctl00_CPH_UI_KlauzulaBIKVortal')\n klauzula_button.click()\n\n # rodzaj_dzialalnosci = driver.find_element(By.ID, 'ctl00_CPH_SelectedOptionID_DropDown3_companyBusinessActivityType')\n # drop = Select(rodzaj_dzialalnosci)\n # drop.select_by_visible_text('Kancelarie notarialne')\n\n # rodzaj_dzialalnosci = driver.find_element(By.XPATH, '// *[ @ id = \"ctl00_CPH_SelectedOptionID_DropDown3_companyBusinessActivityType\"]')\n # rodzaj_dzialalnosci.click()\n\n # driver.send_keys(Keys.DOWN)\n\n\n # inna = driver.find_element(By.ID, 'ctl00_CPH_SelectedOptionID_DropDown3_companyBusinessActivityType')\n # inna.select_by_visible_text('Inna')\n\n\n # rodzaj_dzialalnosci = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '// *[ @ id = \"ctl00_CPH_SelectedOptionID_DropDown3_companyBusinessActivityType\"]')))\n # rodzaj_dzialalnosci.send_keys(Keys.DOWN)\n #\n # inna = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id=\"ctl00_CPH_SelectedOptionID_DropDown3_companyBusinessActivityType\"]')))\n # inna.click()\n\n # . Kliknij Dalej\n # dalej_button = driver.find_element(By.XPATH, '// *[ @ id = \"ctl00_CPH_nav_START_Button1_Start_goNextAction\"]')\n # dalej_button.click()\n\n # dalej_button = driver.find_element(By.ID, 'ctl00_CPH_nav_START_Button1_Start_goNextAction')\n # dalej_button.click()\n\n\n sleep(5)\n\n\n # Wizualnie oceniam test\"\n sleep(10)\n\n \"\"\"\n Test: sprawdzam oczekiwany rezultat\n \"\"\"\n\n # Wyszukuję wszystkie błędy\n error_notices = driver.find_elements(By.XPATH,\n '//*[@id=\"ctl00_MCP_CUW_CreateUserStepContainer_RangeValidator1\"]')\n # Zapisuję widoczne błędy do listy visible_error_notices\n # Tworzę pustą listę\n visible_error_notices = []\n for error in error_notices:\n # Jesli błąd jest widoczny, dodaj go do listy\n if error.is_displayed():\n visible_error_notices.append(error)\n # Sprawdzam, czy jest widoczny tylko jeden błąd\n assert len(visible_error_notices) == 1\n # Sprawdzam treść widocznego błędu\n error_text = visible_error_notices[0].get_attribute(\"innerText\")\n assert error_text == \"* Niepoprawny rok urodzenia\"\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n" } ]
2
franciscorgodoy/sistema-gastronomico
https://github.com/franciscorgodoy/sistema-gastronomico
de032e9a044962d706afb9bbbbc058ccc238f675
e65813bfda259fa72aec25d23e0bc0ff55577996
8f75f40833de0e96ca95384db4e6e23b4627a8b0
refs/heads/main
2023-04-03T04:58:37.899116
2021-04-13T00:03:55
2021-04-13T00:03:55
357,371,821
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.761904776096344, "alphanum_fraction": 0.761904776096344, "avg_line_length": 23.5, "blob_id": "f00ee89678a740f02d532ddb9d9dbb60fba4882b", "content_id": "8a2ab32bc72947428d84e966786155c3f91047cf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 147, "license_type": "permissive", "max_line_length": 41, "num_lines": 6, "path": "/sis_gastronomico/proveedores/apps.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass ProveedoresConfig(AppConfig):\n name = \"sis_gastronomico.proveedores\"\n verbose_name = \"Proveedores\"\n" }, { "alpha_fraction": 0.6595025062561035, "alphanum_fraction": 0.6604684591293335, "avg_line_length": 32.39516067504883, "blob_id": "801fb1c18675be8074b389a24062e106701bfff9", "content_id": "faaf11fe4afadadb8cb3b479847a0aa1a842cee2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4141, "license_type": "permissive", "max_line_length": 88, "num_lines": 124, "path": "/sis_gastronomico/stocks/views.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse_lazy\nfrom django.utils.decorators import method_decorator\nfrom django.views import generic\n\nfrom sis_gastronomico.insumos.models import Insumo\nfrom sis_gastronomico.productos.models import Producto\nfrom sis_gastronomico.stocks.forms import StockInsumoForm, StockProductoForm\nfrom sis_gastronomico.stocks.models import StockInsumo, StockProducto\n\n# Create your views here.\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass ListStockInsumo(generic.ListView):\n\n model = StockInsumo\n paginate_by = 10\n template_name = \"stocks/list_stockInsumo.html\"\n\n def get_queryset(self):\n return StockInsumo.objects.filter(insumo_id=self.kwargs.get(\"pk\")).order_by(\n \"-fecha_modificacion\"\n )\n\n def get_context_data(self, **kwargs):\n context = super(ListStockInsumo, self).get_context_data(**kwargs)\n # insumo = Insumo.objects.filter(id=self.kwargs.get(\"pk\"))\n insumo = Insumo.objects.get(id=self.kwargs.get(\"pk\"))\n context[\"insumo\"] = insumo\n context[\"stock_actual\"] = StockInsumo.stockactual(insumo)\n return context\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass ListStockProducto(generic.ListView):\n\n model = StockProducto\n paginate_by = 10\n template_name = \"stocks/list_stockProducto.html\"\n\n def get_queryset(self):\n return StockProducto.objects.filter(producto_id=self.kwargs.get(\"pk\")).order_by(\n \"-fecha_modificacion\"\n )\n\n def get_context_data(self, **kwargs):\n context = super(ListStockProducto, self).get_context_data(**kwargs)\n # producto = Producto.objects.filter(id=self.kwargs.get(\"pk\"))\n producto = Producto.objects.get(id=self.kwargs.get(\"pk\"))\n context[\"producto\"] = producto\n context[\"stock_actual\"] = StockProducto.stockactual(producto)\n return context\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UpdateStockInsumo(generic.UpdateView):\n\n model = StockInsumo\n form_class = StockInsumoForm\n template_name = \"stocks/create_stockInsumo.html\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"insumo_ID\"] = self.object.insumo.id\n return context\n\n def post(self, request, *args, **kwargs):\n self.object = None\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n if form.is_valid():\n return self.form_valid(form)\n else:\n return self.form_invalid(form)\n\n def form_valid(self, form):\n self.object = form.save(commit=False)\n self.object.pk = None\n self.object.save()\n return HttpResponseRedirect(\n reverse_lazy(\n \"stocks:list_stockInsumo\", kwargs={\"pk\": self.object.insumo.id}\n )\n )\n\n def form_invalid(self, form):\n return self.render_to_response(self.get_context_data(form=form))\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UpdateStockProducto(generic.UpdateView):\n\n model = StockProducto\n form_class = StockProductoForm\n template_name = \"stocks/create_stockProducto.html\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"producto_ID\"] = self.object.producto.id\n return context\n\n def post(self, request, *args, **kwargs):\n self.object = None\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n if form.is_valid():\n return self.form_valid(form)\n else:\n return self.form_invalid(form)\n\n def form_valid(self, form):\n self.object = form.save(commit=False)\n self.object.pk = None\n self.object.save()\n return HttpResponseRedirect(\n reverse_lazy(\n \"stocks:list_stockProducto\", kwargs={\"pk\": self.object.producto.id}\n )\n )\n\n def form_invalid(self, form):\n return self.render_to_response(self.get_context_data(form=form))\n" }, { "alpha_fraction": 0.6391061544418335, "alphanum_fraction": 0.6435754299163818, "avg_line_length": 38.485294342041016, "blob_id": "df831a522e48dd4c518b34957cc7de9881b70c34", "content_id": "78a19f4277922aa68e6c379e332ada677a0420e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2685, "license_type": "permissive", "max_line_length": 87, "num_lines": 68, "path": "/config/urls.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.contrib.auth.decorators import login_required\nfrom django.urls import include, path\nfrom django.views import defaults as default_views\nfrom django.views.generic import TemplateView\n\nurlpatterns = [\n path(\"gastos/\", include(\"sis_gastronomico.gastos.urls\", namespace=\"gastos\")),\n path(\"turnos/\", include(\"sis_gastronomico.turnos.urls\", namespace=\"turnos\")),\n path(\n \"\",\n login_required(TemplateView.as_view(template_name=\"pages/home.html\")),\n name=\"home\",\n ),\n path(\n \"empleados/\", include(\"sis_gastronomico.empleados.urls\", namespace=\"empleados\")\n ),\n path(\"\", TemplateView.as_view(template_name=\"pages/home.html\"), name=\"home\"),\n path(\n \"about/\", TemplateView.as_view(template_name=\"pages/about.html\"), name=\"about\"\n ),\n # Django Admin, use {% url 'admin:index' %}\n path(settings.ADMIN_URL, admin.site.urls),\n # User management\n path(\"users/\", include(\"sis_gastronomico.users.urls\", namespace=\"users\")),\n path(\"accounts/\", include(\"allauth.urls\")),\n path(\n \"productos/\", include(\"sis_gastronomico.productos.urls\", namespace=\"productos\")\n ),\n # Your stuff: custom urls includes go here\n path(\"insumos/\", include(\"sis_gastronomico.insumos.urls\", namespace=\"insumos\")),\n path(\"compras/\", include(\"sis_gastronomico.compras.urls\", namespace=\"compras\")),\n path(\"stocks/\", include(\"sis_gastronomico.stocks.urls\", namespace=\"stocks\")),\n path(\"pedidos/\", include(\"sis_gastronomico.pedidos.urls\", namespace=\"pedidos\")),\n path(\n \"proveedores/\",\n include(\"sis_gastronomico.proveedores.urls\", namespace=\"proveedores\"),\n ),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n\nif settings.DEBUG:\n # This allows the error pages to be debugged during development, just visit\n # these url in browser to see how these error pages look like.\n urlpatterns += [\n path(\n \"400/\",\n default_views.bad_request,\n kwargs={\"exception\": Exception(\"Bad Request!\")},\n ),\n path(\n \"403/\",\n default_views.permission_denied,\n kwargs={\"exception\": Exception(\"Permission Denied\")},\n ),\n path(\n \"404/\",\n default_views.page_not_found,\n kwargs={\"exception\": Exception(\"Page not Found\")},\n ),\n path(\"500/\", default_views.server_error),\n ]\n if \"debug_toolbar\" in settings.INSTALLED_APPS:\n import debug_toolbar\n\n urlpatterns = [path(\"__debug__/\", include(debug_toolbar.urls))] + urlpatterns\n" }, { "alpha_fraction": 0.6251564621925354, "alphanum_fraction": 0.6251564621925354, "avg_line_length": 28.054546356201172, "blob_id": "e95cef435ff4f32bf470caa298774459ad0cc3cd", "content_id": "f5d905082f39ed343b14880196307b041743d3f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1598, "license_type": "permissive", "max_line_length": 87, "num_lines": 55, "path": "/sis_gastronomico/gastos/urls.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom sis_gastronomico.gastos.views import (\n CreateAdelantoSueldo,\n CreateGasto,\n CreateTipoGasto,\n DeleteAdelantoSueldo,\n DeleteGasto,\n DeleteTipoGasto,\n ListAdelantoSueldo,\n ListGasto,\n ListTipoGasto,\n UpdateAdelantoSueldo,\n UpdateGasto,\n UpdateTipoGasto,\n)\n\napp_name = \"gastos\"\nurlpatterns = [\n # path(\"\", index, name=\"index\"),\n path(\"\", ListGasto.as_view(), name=\"index\"),\n path(\"create_gasto\", CreateGasto.as_view(), name=\"create_gasto\"),\n path(\"create_tipo_gasto\", CreateTipoGasto.as_view(), name=\"create_tipo_gasto\"),\n path(\"delete_gasto/<int:pk>\", DeleteGasto.as_view(), name=\"delete_gasto\"),\n path(\n \"delete_tipo_gasto/<int:pk>\",\n DeleteTipoGasto.as_view(),\n name=\"delete_tipo_gasto\",\n ),\n path(\"list_tipo_gasto\", ListTipoGasto.as_view(), name=\"list_tipo_gasto\"),\n path(\"update_gasto/<int:pk>\", UpdateGasto.as_view(), name=\"update_gasto\"),\n path(\n \"update_tipo_gasto/<int:pk>\",\n UpdateTipoGasto.as_view(),\n name=\"update_tipo_gasto\",\n ),\n path(\n \"create_adelantoSueldo\",\n CreateAdelantoSueldo.as_view(),\n name=\"create_adelantoSueldo\",\n ),\n path(\n \"list_adelantoSueldo\", ListAdelantoSueldo.as_view(), name=\"list_adelantoSueldo\"\n ),\n path(\n \"update_adelantoSueldo/<int:pk>\",\n UpdateAdelantoSueldo.as_view(),\n name=\"update_adelantoSueldo\",\n ),\n path(\n \"delete_adelanto_sueldo/<int:pk>\",\n DeleteAdelantoSueldo.as_view(),\n name=\"delete_adelanto_sueldo\",\n ),\n]\n" }, { "alpha_fraction": 0.7063711881637573, "alphanum_fraction": 0.7077562212944031, "avg_line_length": 24.785715103149414, "blob_id": "673bd1a79407d443b3a45d7ffc55e17c73d3b344", "content_id": "09c181a3276e654d3d308739365719f90e65a453", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 722, "license_type": "permissive", "max_line_length": 59, "num_lines": 28, "path": "/sis_gastronomico/insumos/forms.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.forms import ModelForm\nfrom django.forms.models import inlineformset_factory\n\nfrom sis_gastronomico.insumos.models import Insumo\nfrom sis_gastronomico.stocks.forms import StockInsumoForm\nfrom sis_gastronomico.stocks.models import StockInsumo\n\n\nclass InsumoForm(ModelForm):\n class Meta:\n model = Insumo\n fields = \"__all__\"\n\n def clean_nombre(self, *args, **kwargs):\n return self.cleaned_data.get(\"nombre\").lower()\n\n def clean_descripcion(self, *args, **kwargs):\n return self.cleaned_data.get(\"descripcion\").lower()\n\n\nStockInsumoFormSet = inlineformset_factory(\n Insumo,\n StockInsumo,\n form=StockInsumoForm,\n can_delete=True,\n extra=1,\n fields=\"__all__\",\n)\n" }, { "alpha_fraction": 0.7412587404251099, "alphanum_fraction": 0.7412587404251099, "avg_line_length": 22.83333396911621, "blob_id": "6b7e96aba404dffd14e6681c88af3e0982ea5581", "content_id": "2229658b2439ba5fcde98a35bcb896fba830dc43", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 143, "license_type": "permissive", "max_line_length": 39, "num_lines": 6, "path": "/sis_gastronomico/empleados/apps.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass EmpleadosConfig(AppConfig):\n name = 'sis_gastronomico.empleados'\n verbose_name = (\"Empleados\")\n" }, { "alpha_fraction": 0.5097732543945312, "alphanum_fraction": 0.5250195264816284, "avg_line_length": 29.094118118286133, "blob_id": "e7eb51fba5d59f92948f229d7ce81064e75d6db5", "content_id": "5af4cc2fd3beae59fe4eb4677ea35763cb8fd24d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2561, "license_type": "permissive", "max_line_length": 134, "num_lines": 85, "path": "/sis_gastronomico/templates/empleados/inicio.html", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n\n{% block content %}\n{% load materializecss %}\n\n<h3 class=\"center\">Listado de Empleados</h3>\n<div class=\"divider\"></div>\n\n {% if 'ok' in request.GET %}\n <div class=\"row\">\n <ul class=\"collection green-border-color col s12 xl10 offset-xl1\">\n <li class=\"collection-item s12 xl12 green-text\">\n <span class=\"badge\">\n <i class=\"material-icons green-text\">check_box</i>\n </span>\n Empleado Creado con Éxito!\n </li>\n </ul>\n </div>\n {% elif 'up' in request.GET %}\n <div class=\"row\">\n <ul class=\"collection blue-border-color col s12 xl10 offset-xl1\">\n <li class=\"collection-item s12 xl12 blue-text\">\n <span class=\"badge\">\n <i class=\"material-icons blue-text\">check_box</i>\n </span>\n Empleado Modificado con Éxito!\n </li>\n </ul>\n </div>\n {% elif 'del' in request.GET %}\n <div class=\"row\">\n <ul class=\"collection orange-border-color col s12 xl10 offset-xl1\">\n <li class=\"collection-item s12 xl12 orange-text\">\n <span class=\"badge\">\n <i class=\"material-icons orange-text\">check_box</i>\n </span>\n Empleado Eliminado con Éxito!\n </li>\n </ul>\n </div>\n {% endif %}\n\n\n{% include 'pagination.html' %}\n<div class=\"row\">\n <table class=\"highlight centered\">\n <thead>\n <tr>\n <th>Apellidos</th>\n <th>Nombres</th>\n <th>Fecha Ingreso</th>\n <th>Modificar/Eliminar</th>\n </tr>\n </thead>\n\n <tbody>\n\n\n {% for empleado in page_obj %}\n <tr>\n <td>{{empleado.apellido | truncatechars:15}}</td>\n <td>{{empleado.nombre | truncatechars:15}}</td>\n <td>{{empleado.fecha_ingreso|date:\"d/m/Y\"}}</td>\n <td>\n <a class=\"btn-small\" href=\"{% url 'empleados:update_empleado' empleado.id %}\"><i class=\"material-icons\">edit</i></a>\n <a class=\"btn-small red\" href=\"{% url 'empleados:delete_empleado' empleado.id %}\"><i class=\"material-icons\">cancel</i></a>\n </td>\n {%endfor%}\n </tr>\n </tbody>\n </table>\n</div>\n\n{% include 'pagination.html' %}\n\n<div class=\"row center\">\n <a class=\"col xl12 btn-large green\" href=\"{% url 'empleados:create_empleado' %}\">Cargar Empleado</a>\n</div>\n<div class=\"row center\">\n <a class=\"col s12 xl12 btn-large\" href=\"{% url 'home' %}\">Volver</a>\n</div>\n\n\n{% endblock %}\n" }, { "alpha_fraction": 0.6370044350624084, "alphanum_fraction": 0.6370044350624084, "avg_line_length": 28.102563858032227, "blob_id": "45d0635f92baec759c9a3867fbb0eec4f1f8692e", "content_id": "a82e6ba16d68d5a577f5ebfb5090d860efa4070a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1135, "license_type": "permissive", "max_line_length": 87, "num_lines": 39, "path": "/sis_gastronomico/productos/urls.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom sis_gastronomico.productos.views import (\n BorrarProducto,\n BorrarTipoProducto,\n CrearProducto,\n CrearTipoProducto,\n ListarProductos,\n ListarTipoProducto,\n UpdateProducto,\n UpdateTipoProducto,\n)\n\napp_name = \"productos\"\nurlpatterns = [\n # path(\"\", index, name=\"index\"),\n path(\"\", ListarProductos.as_view(), name=\"index\"),\n path(\"crear_producto/\", CrearProducto.as_view(), name=\"crear_producto\"),\n path(\n \"crear_tipo_producto\", CrearTipoProducto.as_view(), name=\"crear_tipo_producto\"\n ),\n path(\"borrar_producto/<int:pk>\", BorrarProducto.as_view(), name=\"borrar_producto\"),\n path(\n \"borrar_tipo_producto/<int:pk>\",\n BorrarTipoProducto.as_view(),\n name=\"borrar_tipo_producto\",\n ),\n path(\n \"listar_tipo_producto\",\n ListarTipoProducto.as_view(),\n name=\"listar_tipo_producto\",\n ),\n path(\"update_producto/<int:pk>\", UpdateProducto.as_view(), name=\"update_producto\"),\n path(\n \"update_tipo_producto/<int:pk>\",\n UpdateTipoProducto.as_view(),\n name=\"update_tipo_producto\",\n ),\n]\n" }, { "alpha_fraction": 0.7045305371284485, "alphanum_fraction": 0.7062814831733704, "avg_line_length": 28.288461685180664, "blob_id": "d960e7460418ef5955e92c0b700a017c27acf449", "content_id": "e2757e058548cc4f6c080a7b37e37febeebd3b4b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4569, "license_type": "permissive", "max_line_length": 86, "num_lines": 156, "path": "/sis_gastronomico/gastos/views.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import HttpResponseRedirect, render\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic.edit import CreateView, DeleteView, UpdateView\nfrom django.views.generic.list import ListView\n\nfrom sis_gastronomico.gastos.forms import AdelantoSueldoForm, GastoForm, TipoGastoForm\nfrom sis_gastronomico.gastos.models import AdelantoSueldo, Gasto, TipoGasto\n\n# Create your views here.\n\n\n@method_decorator(login_required, name=\"dispatch\")\ndef index(request):\n\n gastos = Gasto.objects.all().order_by(\"-fecha_modificacion\")[:10]\n for gasto in gastos:\n gasto.descripcion = gasto.descripcion.title()\n\n return render(request, \"gastos/index.html\", {\"gastos\": gastos})\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass CreateGasto(CreateView):\n\n model = Gasto\n form_class = GastoForm\n template_name = \"gastos/gasto_form.html\"\n success_url = \"/gastos/?ok\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n gastos = set()\n for gasto in Gasto.objects.values_list(\"descripcion\", flat=True):\n gastos.add(gasto.title())\n context[\"gastos\"] = gastos\n return context\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass CreateTipoGasto(CreateView):\n\n model = TipoGasto\n form_class = TipoGastoForm\n template_name = \"gastos/tipo_gasto_form.html\"\n success_url = \"/gastos/list_tipo_gasto?tgok\"\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass CreateAdelantoSueldo(CreateView):\n model = AdelantoSueldo\n form_class = AdelantoSueldoForm\n template_name = \"gastos/adelantoSueldo_form.html\"\n success_url = \"/gastos/list_adelantoSueldo?ok\"\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass DeleteGasto(DeleteView):\n\n model = Gasto\n template_name = \"gastos/delete_gasto.html\"\n success_url = \"/gastos/?del\"\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n self.object.delete()\n return HttpResponseRedirect(self.get_success_url())\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass DeleteTipoGasto(DeleteView):\n\n model = TipoGasto\n template_name = \"gastos/delete_tipo_gasto.html\"\n success_url = \"/gastos/list_tipo_gasto?tgdel\"\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n self.object.delete()\n return HttpResponseRedirect(self.get_success_url())\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass DeleteAdelantoSueldo(DeleteView):\n\n model = AdelantoSueldo\n template_name = \"gastos/delete_adelanto_sueldo.html\"\n success_url = \"/gastos/list_adelantoSueldo?del\"\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass ListGasto(ListView):\n\n model = Gasto\n paginate_by = 10\n template_name = \"gastos/list_gasto.html\"\n\n def get_queryset(self):\n return Gasto.objects.all().order_by(\"-fecha_modificacion\")\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass ListTipoGasto(ListView):\n\n model = TipoGasto\n paginate_by = 10\n template_name = \"gastos/list_tipo_gasto.html\"\n\n def get_queryset(self):\n return TipoGasto.objects.all().order_by(\"tipo\")\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass ListAdelantoSueldo(ListView):\n\n model = AdelantoSueldo\n paginate_by = 10\n template_name = \"gastos/list_adelanto_sueldo.html\"\n\n def get_queryset(self):\n return AdelantoSueldo.objects.all().order_by(\"-fecha_modificacion\")\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UpdateGasto(UpdateView):\n\n model = Gasto\n form_class = GastoForm\n template_name = \"gastos/gasto_form.html\"\n success_url = \"/gastos/?up\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n gastos = set()\n for gasto in Gasto.objects.values_list(\"descripcion\", flat=True):\n gastos.add(gasto.title())\n context[\"gastos\"] = gastos\n return context\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UpdateTipoGasto(UpdateView):\n\n model = TipoGasto\n form_class = TipoGastoForm\n template_name = \"gastos/tipo_gasto_form.html\"\n success_url = \"/gastos/list_tipo_gasto?tgup\"\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UpdateAdelantoSueldo(UpdateView):\n\n model = AdelantoSueldo\n form_class = AdelantoSueldoForm\n template_name = \"gastos/adelantoSueldo_form.html\"\n success_url = \"/gastos/list_adelantoSueldo?up\"\n" }, { "alpha_fraction": 0.5843302607536316, "alphanum_fraction": 0.5850340127944946, "avg_line_length": 30.34558868408203, "blob_id": "52cb7d8831d02d79f06958c3a60f16b6fdb7d8f6", "content_id": "13ba82e3f6e3959f56d4ca5c1adfe60fbd2d0deb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4263, "license_type": "permissive", "max_line_length": 88, "num_lines": 136, "path": "/sis_gastronomico/pedidos/forms.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.core.exceptions import ValidationError\nfrom django.forms import ModelForm\nfrom django.forms.models import BaseInlineFormSet, inlineformset_factory\n\nfrom sis_gastronomico.pedidos.models import (\n DetallePedido,\n MedioPago,\n MedioPedido,\n Pedido,\n)\nfrom sis_gastronomico.stocks.models import StockProducto\n\n\nclass MedioPagoForm(ModelForm):\n class Meta:\n model = MedioPago\n fields = \"__all__\"\n\n\nclass MedioPedidoForm(ModelForm):\n class Meta:\n model = MedioPedido\n fields = \"__all__\"\n\n\nclass PedidoForm(ModelForm):\n class Meta:\n model = Pedido\n exclude = [\"estado\", \"turno\"]\n\n\nclass DetallePedidoForm(ModelForm):\n def __init__(self, *args, **kwargs):\n super(DetallePedidoForm, self).__init__(*args, **kwargs)\n self.empty_permitted = False\n\n def clean(self):\n cleaned_data = super().clean()\n\n if \"cantidad\" in cleaned_data and \"producto\" in cleaned_data:\n cantidad = cleaned_data[\"cantidad\"]\n producto = cleaned_data[\"producto\"]\n stock = StockProducto.stockactual(producto=producto)\n\n if (stock.cantidad - cantidad) < 0:\n self.add_error(\n \"cantidad\",\n ValidationError(\n \"El stock disponible es de %(cantidad_stock)s\",\n code=\"invalid\",\n params={\"cantidad_stock\": stock.cantidad},\n ),\n )\n return cleaned_data\n\n class Meta:\n model = DetallePedido\n fields = \"__all__\"\n\n\nclass BaseInlineProductoFormSet(BaseInlineFormSet):\n def save_new(self, form, commit):\n # Crear nuevo stock en base al stock actual\n producto = form.cleaned_data[\"producto\"]\n cantidad = form.cleaned_data[\"cantidad\"]\n stock = StockProducto.stockactual(producto=producto)\n stock.pk = None\n stock.cantidad = stock.cantidad - cantidad\n stock.save()\n\n return super().save_new(form, commit=commit)\n\n def save_existing(self, form, instance, commit):\n if \"producto\" in form.changed_data:\n # Sumar a la la cantidad del registro de stock original\n stockoriginal = StockProducto.stockactual(producto=form.initial[\"producto\"])\n stockoriginal.pk = None\n stockoriginal.cantidad = stockoriginal.cantidad + form.initial[\"cantidad\"]\n stockoriginal.save()\n\n # Restar stock en el nuevo producto\n stocknuevo = StockProducto.stockactual(\n producto=form.cleaned_data[\"producto\"]\n )\n stocknuevo.pk = None\n stocknuevo.cantidad = stocknuevo.cantidad - form.cleaned_data[\"cantidad\"]\n stocknuevo.save()\n else:\n # Crear nuevo stock en base al stock actual\n stock = StockProducto.stockactual(producto=form.cleaned_data[\"producto\"])\n stock.pk = None\n stock.cantidad = (\n stock.cantidad\n + form.initial[\"cantidad\"]\n - form.cleaned_data[\"cantidad\"]\n )\n stock.save()\n\n return super().save_existing(form, instance, commit=commit)\n\n def delete_existing(self, obj, commit):\n # Restar la cantidad del registro de stock\n stock = StockProducto.stockactual(producto=obj.producto)\n stock.pk = None\n stock.cantidad = stock.cantidad + obj.cantidad\n stock.save()\n\n return super().delete_existing(obj, commit=commit)\n\n def clean(self):\n\n if any(self.errors):\n return\n productos = dict()\n for form in self.forms:\n if form.cleaned_data:\n if form.cleaned_data[\"DELETE\"]:\n continue\n\n producto = form.cleaned_data[\"producto\"]\n if producto in productos:\n form.add_error(\n \"producto\", \"Este producto ya fue listado en el Pedido\"\n )\n else:\n productos[producto] = 1\n\n\nDetallePedidoFormSet = inlineformset_factory(\n Pedido,\n DetallePedido,\n DetallePedidoForm,\n can_delete=True,\n extra=1,\n formset=BaseInlineProductoFormSet,\n)\n" }, { "alpha_fraction": 0.550000011920929, "alphanum_fraction": 0.5724999904632568, "avg_line_length": 33.78260803222656, "blob_id": "cd948e2916dc5211a366466f60a9b1c10ac517ca", "content_id": "ec1df1c4c9fc5a1abf448e061c462ac68aef0758", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 800, "license_type": "permissive", "max_line_length": 147, "num_lines": 23, "path": "/sis_gastronomico/templates/turnos/turno_form.html", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n\n{% block content %}\n{% load materializecss %}\n\n<h3 class=\"center\">Formulario de Turno</h3>\n<div class=\"divider\"></div>\n\n<div class=\"row center\">\n <form method=\"post\" id=\"form\">{% csrf_token %}\n <div class=\"row\">\n {{form.horario | materializecss:'s12 xl12'}}\n </div>\n <div class=\"row\">\n {{ form.empleados | materializecss:'s12 xl12' }}\n </div>\n <div class=\"row center\">\n <button class=\"btn col s12 xl2\" type=\"submit\"><i class=\"material-icons icon-align\">check</i> Agregar</button><div class=\"col s2\"></div>\n <a class=\"btn red col s12 offset-xl6 xl2\" href=\"{% url 'turnos:index' %}\"><i class=\"material-icons icon-align\">cancel</i> Cancelar</a>\n </div>\n </form>\n</div>\n{% endblock %}\n" }, { "alpha_fraction": 0.6004579067230225, "alphanum_fraction": 0.6250715255737305, "avg_line_length": 47.52777862548828, "blob_id": "c7df0ab634062df6ca86c2647741afb311958d36", "content_id": "3f663307858434d7a493492e1a41abf7826d40d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1747, "license_type": "permissive", "max_line_length": 241, "num_lines": 36, "path": "/sis_gastronomico/empleados/migrations/0001_initial.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.8 on 2020-12-16 17:30\n\nimport django.core.validators\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Empleado',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('nombre', models.CharField(max_length=50, validators=[django.core.validators.MinLengthValidator(3), django.core.validators.MaxLengthValidator(50)])),\n ('apellido', models.CharField(max_length=50, validators=[django.core.validators.MinLengthValidator(3), django.core.validators.MaxLengthValidator(50)])),\n ('dni', models.IntegerField(unique=True, validators=[django.core.validators.MaxValueValidator(99999999, message='Ingrese un DNI valido'), django.core.validators.MinValueValidator(11111111, message='Ingrese un DNI valido')])),\n ('fecha_nacimiento', models.DateField()),\n ('fecha_ingreso', models.DateField(default=django.utils.timezone.now)),\n ('estado', models.BooleanField(default=True)),\n ('genero', models.CharField(choices=[('femenino', 'Femenino'), ('masculino', 'Masculino')], default='femenino', max_length=20)),\n ('fecha_creacion', models.DateTimeField(auto_now_add=True)),\n ('fecha_modificacion', models.DateTimeField(auto_now=True)),\n ],\n options={\n 'verbose_name': 'Empleado',\n 'verbose_name_plural': 'Empleados',\n 'db_table': 'empleados',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.6884307265281677, "alphanum_fraction": 0.6891943216323853, "avg_line_length": 31.33333396911621, "blob_id": "fb971a2211aff76d9ce74a72238e3693de98ea5d", "content_id": "4f19e4254a148523e5c544e42de35b2f1c6e2e49", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2619, "license_type": "permissive", "max_line_length": 81, "num_lines": 81, "path": "/sis_gastronomico/insumos/views.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic.edit import CreateView, DeleteView, UpdateView\nfrom django.views.generic.list import ListView\n\nfrom sis_gastronomico.insumos.forms import InsumoForm, StockInsumoFormSet\nfrom sis_gastronomico.insumos.models import Insumo\n\n\ndef index(request):\n form = InsumoForm()\n return render(request, \"insumos/home.html\", {\"form\": form})\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass ListInsumo(ListView):\n model = Insumo\n form_class = InsumoForm\n paginate_by = 10\n template_name = \"insumos/list_insumo.html\"\n\n def get_queryset(self, **kwargs):\n return Insumo.objects.order_by(\"nombre\")\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass CreateInsumo(CreateView):\n\n model = Insumo\n form_class = InsumoForm\n template_name = \"insumos/insumo_form.html\"\n success_url = \"/insumos/?ok\"\n\n def get(self, request, *args, **kwargs):\n self.object = None\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n stock_insumo_form = StockInsumoFormSet()\n return self.render_to_response(\n self.get_context_data(form=form, stock_insumo_form=stock_insumo_form)\n )\n\n def post(self, request, *args, **kwargs):\n self.object = None\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n stock_insumo_form = StockInsumoFormSet(self.request.POST)\n if form.is_valid() and stock_insumo_form.is_valid():\n return self.form_valid(form, stock_insumo_form)\n else:\n return self.form_invalid(form, stock_insumo_form)\n\n def form_valid(self, form, stock_insumo_form):\n self.object = form.save()\n stock_insumo_form.instance = self.object\n stock_insumo_form.save()\n return HttpResponseRedirect(self.get_success_url())\n\n def form_invalid(self, form, stock_insumo_form):\n return self.render_to_response(\n self.get_context_data(form=form, stock_insumo_form=stock_insumo_form)\n )\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass DeleteInsumo(DeleteView):\n\n model = Insumo\n template_name = \"insumos/delete_insumo.html\"\n success_url = \"/insumos/?del\"\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UpdateInsumo(UpdateView):\n\n model = Insumo\n form_class = InsumoForm\n template_name = \"insumos/insumo_form.html\"\n success_url = \"/insumos/?up\"\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.7865496873855591, "avg_line_length": 33.20000076293945, "blob_id": "a8476e61cc6bb943b0c0627dd57323b4aa518281", "content_id": "42447197a90d49bcdbcf2f717e10a018b2d7d34d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 344, "license_type": "permissive", "max_line_length": 120, "num_lines": 10, "path": "/CHANGELOG.md", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "# [0.0.1] - 23-10-2020\n## Added\n- ABM Gasto\n- ABM Tipo de Gasto\n- Paginación de modelos funcionando\n- Login_required en todas las vistas\n- Diseño general para todas las vistas\n- Archivos necesarios para deploy en Heroku\n\n[0.0.1]: https://bitbucket.org/EstebanSaborido/2020-sistemagastronomico/commits/61c3df99ae458ee1da4207da3f468e1c6ea3883d\n" }, { "alpha_fraction": 0.7348484992980957, "alphanum_fraction": 0.7348484992980957, "avg_line_length": 21, "blob_id": "f1d6e642040447f922c2d81dd1adba12c366019e", "content_id": "579e73fc4b4c569dc3118276b87a17bb5245c41a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 132, "license_type": "permissive", "max_line_length": 36, "num_lines": 6, "path": "/sis_gastronomico/turnos/apps.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass TurnosConfig(AppConfig):\n name = \"sis_gastronomico.turnos\"\n verbose_name = \"Turnos\"\n" }, { "alpha_fraction": 0.6053921580314636, "alphanum_fraction": 0.6225489974021912, "avg_line_length": 21.66666603088379, "blob_id": "6ab664cb08f266dbb7478f7632188d6249c78a2c", "content_id": "62e8947d8a09c3f5b00b0f93155b8cef42f1c616", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 408, "license_type": "permissive", "max_line_length": 98, "num_lines": 18, "path": "/sis_gastronomico/templates/turnos/no_active_turno.html", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n\n{% block content %}\n\n<h3 class=\"center\">NO HAY UN TURNO ACTIVO!</h3>\n<div class=\"divider\"></div>\n\n<div class=\"row center\">\n <blockquote>\n <h5>Por favor, crea un turno nuevo para cargar pedidos!</p>\n </blockquote>\n</div>\n\n<div class=\"row center\">\n <a class=\"col s12 xl12 btn-large green\" href=\"{% url 'turnos:create_turno' %}\">Nuevo Turno</a>\n</div>\n\n{% endblock %}\n" }, { "alpha_fraction": 0.6510319113731384, "alphanum_fraction": 0.6529080867767334, "avg_line_length": 27.810810089111328, "blob_id": "527779dd3190f387103b722c6dc858c8e9ac52fe", "content_id": "b933cd60d8320698bb151a641561e523af2c259d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1066, "license_type": "permissive", "max_line_length": 72, "num_lines": 37, "path": "/sis_gastronomico/turnos/models.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.db import models\n\nfrom sis_gastronomico.empleados.models import Empleado\n\n# Create your models here.\n\n\nclass Horario(models.Model):\n\n horario = models.CharField(max_length=35)\n desde = models.TimeField()\n hasta = models.TimeField()\n fecha_creacion = models.DateTimeField(auto_now=True)\n fecha_modificacion = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n ordering = [\"desde\"]\n\n def __str__(self):\n return \"{:s} - De {:s} a {:s}\".format(\n self.horario.title(),\n self.desde.strftime(\"%H:%M\"),\n self.hasta.strftime(\"%H:%M\"),\n )\n\n\nclass Turno(models.Model):\n\n horario = models.ForeignKey(Horario, models.CASCADE)\n fecha = models.DateField(auto_now=True)\n empleados = models.ManyToManyField(Empleado)\n fecha_creacion = models.DateTimeField(auto_now=True)\n fecha_modificacion = models.DateTimeField(auto_now_add=True)\n activo = models.BooleanField(default=True)\n\n def __str__(self):\n return \"{:s} - {:s} \".format(str(self.fecha), str(self.horario))\n" }, { "alpha_fraction": 0.5889830589294434, "alphanum_fraction": 0.6101694703102112, "avg_line_length": 42.47368240356445, "blob_id": "83c59d2b008178123d9dd2ce46c9d626927a92ec", "content_id": "89dc331949d5a8aec4ec0d6f10a97499b58b2fe1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1652, "license_type": "permissive", "max_line_length": 192, "num_lines": 38, "path": "/sis_gastronomico/productos/migrations/0001_initial.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.8 on 2020-12-16 17:30\n\nimport django.core.validators\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='TipoProducto',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('fecha_creacion', models.DateTimeField(auto_now_add=True)),\n ('fecha_modificacion', models.DateTimeField(auto_now=True)),\n ('tipo', models.CharField(max_length=35, unique=True)),\n ('descripcion', models.CharField(max_length=100)),\n ],\n ),\n migrations.CreateModel(\n name='Producto',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('nombre', models.CharField(max_length=30, unique=True)),\n ('descripcion', models.CharField(max_length=50)),\n ('precio', models.DecimalField(decimal_places=2, max_digits=7, validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(99999.99)])),\n ('fecha_creacion', models.DateTimeField(auto_now=True)),\n ('fecha_modificacion', models.DateTimeField(auto_now=True)),\n ('tipo_producto', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='productos.TipoProducto', verbose_name='Tipo Producto')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.6614673733711243, "alphanum_fraction": 0.6626227498054504, "avg_line_length": 28.3389835357666, "blob_id": "9b97537ee5defbf6c67c9762efb030a8a413c14a", "content_id": "740b728caf7a1eb44c1ceeee6a31f413dbbb8065", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1731, "license_type": "permissive", "max_line_length": 76, "num_lines": 59, "path": "/sis_gastronomico/stocks/models.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.core.validators import MinValueValidator\nfrom django.db import models\n\nfrom sis_gastronomico.insumos.models import Insumo\nfrom sis_gastronomico.productos.models import Producto\n\n# Create your models here.\n\n\nclass StockInsumo(models.Model):\n\n cantidad = models.SmallIntegerField(validators=[MinValueValidator(0)])\n insumo = models.ForeignKey(\n Insumo, on_delete=models.CASCADE, verbose_name=\"stock de insumo\"\n )\n fecha_creacion = models.DateTimeField(auto_now_add=True)\n fecha_modificacion = models.DateTimeField(auto_now=True)\n\n class Meta:\n verbose_name = \"Stock de Insumo\"\n verbose_name_plural = \"Stock de Insumos\"\n db_table = \"stock_Insumo\"\n\n def __str__(self):\n return \"{:d}\".format(self.cantidad)\n\n @staticmethod\n def stockactual(insumo):\n return (\n StockInsumo.objects.filter(insumo=insumo)\n .order_by(\"fecha_modificacion\")\n .last()\n )\n\n\nclass StockProducto(models.Model):\n\n cantidad = models.SmallIntegerField(validators=[MinValueValidator(0)])\n producto = models.ForeignKey(\n Producto, on_delete=models.CASCADE, verbose_name=\"stock de producto\"\n )\n fecha_creacion = models.DateTimeField(auto_now_add=True)\n fecha_modificacion = models.DateTimeField(auto_now=True)\n\n class Meta:\n verbose_name = \"Stock de Producto\"\n verbose_name_plural = \"Stock de Productos\"\n db_table = \"stock_Producto\"\n\n def __str__(self):\n return \"{:d}\".format(self.cantidad)\n\n @staticmethod\n def stockactual(producto):\n return (\n StockProducto.objects.filter(producto=producto)\n .order_by(\"fecha_modificacion\")\n .last()\n )\n" }, { "alpha_fraction": 0.8282828330993652, "alphanum_fraction": 0.8282828330993652, "avg_line_length": 23.75, "blob_id": "925fdf9ff78a6cba828d099b36e5d59842000cd5", "content_id": "ee4b65fab2d57747f43f2356bc71ce323696fc49", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 198, "license_type": "permissive", "max_line_length": 68, "num_lines": 8, "path": "/sis_gastronomico/productos/admin.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom sis_gastronomico.productos.models import Producto, TipoProducto\n\n# Register your models here.\n\nadmin.site.register(Producto)\nadmin.site.register(TipoProducto)\n" }, { "alpha_fraction": 0.7735849022865295, "alphanum_fraction": 0.7735849022865295, "avg_line_length": 20.200000762939453, "blob_id": "5d918733cb2b87223f5ac6a28bef820023db32a6", "content_id": "1016217bd7c7ff142aac78ef1adcc7a2f9505d29", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 106, "license_type": "permissive", "max_line_length": 37, "num_lines": 5, "path": "/sis_gastronomico/pedidos/apps.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass PedidosConfig(AppConfig):\n name = \"sis_gastronomico.pedidos\"\n" }, { "alpha_fraction": 0.6453673839569092, "alphanum_fraction": 0.6453673839569092, "avg_line_length": 18.5625, "blob_id": "0e6b26fa001e14085a7aea7ac7a46b4057de30c2", "content_id": "362e09e40ace52a48c0b81cf29f6399e1583573a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 313, "license_type": "permissive", "max_line_length": 47, "num_lines": 16, "path": "/sis_gastronomico/utils/context_processors.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "import json\n\nfrom django.conf import settings\n\n\ndef settings_context(_request):\n return {\"settings\": settings}\n\n\ndef get_version(request):\n with open(\"./version.json\") as f:\n data = json.load(f)\n version = data[\"version\"]\n fecha = data[\"fecha\"]\n\n return {\"version\": version, \"fecha\": fecha}\n" }, { "alpha_fraction": 0.5976418852806091, "alphanum_fraction": 0.612871527671814, "avg_line_length": 55.54166793823242, "blob_id": "1fa3f35c76fad150b0eef21210293d46f8f05ee6", "content_id": "0813abe87bcb2580128915167bb5a87f048820a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4071, "license_type": "permissive", "max_line_length": 235, "num_lines": 72, "path": "/sis_gastronomico/pedidos/migrations/0001_initial.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.8 on 2020-12-16 17:30\n\nimport datetime\nimport django.core.validators\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport sis_gastronomico.pedidos.models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('productos', '0001_initial'),\n ('turnos', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='MedioPago',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('fecha_creacion', models.DateTimeField(auto_now=True)),\n ('fecha_modificacion', models.DateTimeField(auto_now_add=True)),\n ('medio_pago', models.CharField(max_length=100)),\n ('cuotas', models.IntegerField(validators=[django.core.validators.MinValueValidator(0)])),\n ('comision', models.DecimalField(decimal_places=2, max_digits=7)),\n ],\n ),\n migrations.CreateModel(\n name='MedioPedido',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('fecha_creacion', models.DateTimeField(auto_now=True)),\n ('fecha_modificacion', models.DateTimeField(auto_now_add=True)),\n ('medio_pedido', models.CharField(max_length=100)),\n ('aumento', models.DecimalField(decimal_places=2, max_digits=7)),\n ],\n ),\n migrations.CreateModel(\n name='Pedido',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('fecha', models.DateField(auto_now=True, validators=[django.core.validators.MaxValueValidator(datetime.date.today)])),\n ('fecha_creacion', models.DateTimeField(auto_now=True)),\n ('fecha_modificacion', models.DateTimeField(auto_now_add=True)),\n ('estado', models.IntegerField(choices=[(0, 'No Entregado'), (1, 'En Camino'), (2, 'Entregado'), (3, 'Cancelado')], default=0)),\n ('numero_pedido', models.SmallIntegerField(blank=True, default=sis_gastronomico.pedidos.models.calc_num_pedido, validators=[django.core.validators.MaxValueValidator(9999), django.core.validators.MinValueValidator(0)])),\n ('calle', models.CharField(max_length=100)),\n ('altura', models.SmallIntegerField(validators=[django.core.validators.MaxValueValidator(9999), django.core.validators.MinValueValidator(0)])),\n ('piso', models.CharField(blank=True, max_length=3, null=True)),\n ('departamento', models.CharField(blank=True, max_length=3, null=True)),\n ('comentario', models.CharField(blank=True, max_length=100, null=True)),\n ('precio_total', models.DecimalField(decimal_places=2, default=0.0, max_digits=7)),\n ('medio_pago', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pedidos.MedioPago')),\n ('medio_pedido', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pedidos.MedioPedido')),\n ('turno', models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='turnos.Turno')),\n ],\n ),\n migrations.CreateModel(\n name='DetallePedido',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('fecha_creacion', models.DateTimeField(auto_now=True)),\n ('fecha_modificacion', models.DateTimeField(auto_now_add=True)),\n ('cantidad', models.SmallIntegerField()),\n ('pedido', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pedidos.Pedido')),\n ('producto', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='productos.Producto')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.6311970949172974, "alphanum_fraction": 0.6311970949172974, "avg_line_length": 29.629629135131836, "blob_id": "b7eb4e35b451c779784988789cd4eb725c8897ef", "content_id": "eb2e1b3ea1bed2c043d1b98f41290653af05db68", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 827, "license_type": "permissive", "max_line_length": 69, "num_lines": 27, "path": "/sis_gastronomico/stocks/forms.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.forms import HiddenInput, ModelForm\n\nfrom sis_gastronomico.stocks.models import StockInsumo, StockProducto\n\n\nclass StockInsumoForm(ModelForm):\n class Meta:\n model = StockInsumo\n fields = \"__all__\"\n exclude = (\"fecha_creacion\", \"fecha_modificacion\")\n widgets = {\"insumo\": HiddenInput}\n\n def __init__(self, *args, **kwargs):\n super(StockInsumoForm, self).__init__(*args, **kwargs)\n self.empty_permitted = False\n\n\nclass StockProductoForm(ModelForm):\n class Meta:\n model = StockProducto\n fields = \"__all__\"\n exclude = (\"fecha_creacion\", \"fecha_modificacion\")\n widgets = {\"producto\": HiddenInput}\n\n def __init__(self, *args, **kwargs):\n super(StockProductoForm, self).__init__(*args, **kwargs)\n self.empty_permitted = False\n" }, { "alpha_fraction": 0.6053169965744019, "alphanum_fraction": 0.6053169965744019, "avg_line_length": 24.736841201782227, "blob_id": "de152a3da350e2910ac623024ba9b700f2c37614", "content_id": "6c3beb79171871d9a6f9feadb7f60ec27ff9f3c8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 489, "license_type": "permissive", "max_line_length": 85, "num_lines": 19, "path": "/sis_gastronomico/empleados/urls.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom . import views\n\napp_name = \"empleados\"\nurlpatterns = [\n path(\"\", views.ListEmpleado.as_view(), name=\"inicio\"),\n path(\"create_empleado/\", views.CreateEmpleado.as_view(), name=\"create_empleado\"),\n path(\n \"update_empleado/<int:pk>/\",\n views.UpdateEmpleado.as_view(),\n name=\"update_empleado\",\n ),\n path(\n \"delete_empleado/<int:pk>/\",\n views.DeleteEmpleado.as_view(),\n name=\"delete_empleado\",\n ),\n]\n" }, { "alpha_fraction": 0.6732495427131653, "alphanum_fraction": 0.6732495427131653, "avg_line_length": 26.850000381469727, "blob_id": "570c7e6e00dda9bc93a058ea6d6dfa4995a6189c", "content_id": "250928a7a373f71963bc09d11c560819be3abc89", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 557, "license_type": "permissive", "max_line_length": 87, "num_lines": 20, "path": "/sis_gastronomico/proveedores/urls.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom sis_gastronomico.proveedores.views import (\n BorrarProveedor,\n CrearProveedor,\n ListarProveedores,\n UpdateProveedor,\n)\n\napp_name = \"proveedores\"\nurlpatterns = [\n path(\"\", ListarProveedores.as_view(), name=\"index\"),\n path(\"crear_proveedor/\", CrearProveedor.as_view(), name=\"crear_proveedor\"),\n path(\n \"borrar_proveedor/<int:pk>\", BorrarProveedor.as_view(), name=\"borrar_proveedor\"\n ),\n path(\n \"update_proveedor/<int:pk>\", UpdateProveedor.as_view(), name=\"update_proveedor\"\n ),\n]\n" }, { "alpha_fraction": 0.582413375377655, "alphanum_fraction": 0.600685179233551, "avg_line_length": 47.64814758300781, "blob_id": "083f0e6e35359e694cffd317e09bbbe6305c20a0", "content_id": "37f865417cec5fe0066b1c1a3f13ad3a08e38508", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2627, "license_type": "permissive", "max_line_length": 198, "num_lines": 54, "path": "/sis_gastronomico/gastos/migrations/0001_initial.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.8 on 2020-12-16 17:30\n\nimport django.core.validators\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 ('empleados', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='AdelantoSueldo',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('monto_pagado', models.DecimalField(decimal_places=2, max_digits=7, validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(99999.99)])),\n ('fecha_pago', models.DateField(auto_now=True)),\n ('fecha_modificacion', models.DateTimeField(auto_now_add=True)),\n ('empleado', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='empleados.Empleado')),\n ],\n options={\n 'verbose_name': 'Adelanto de sueldo',\n 'verbose_name_plural': 'Adelanto de sueldos',\n 'db_table': 'Adelanto_Sueldo',\n },\n ),\n migrations.CreateModel(\n name='TipoGasto',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('fecha_creacion', models.DateTimeField(auto_now_add=True)),\n ('fecha_modificacion', models.DateTimeField(auto_now=True)),\n ('tipo', models.CharField(max_length=35)),\n ('descripcion', models.CharField(max_length=100)),\n ],\n ),\n migrations.CreateModel(\n name='Gasto',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('fecha_creacion', models.DateTimeField(auto_now_add=True)),\n ('fecha_modificacion', models.DateTimeField(auto_now=True)),\n ('descripcion', models.CharField(max_length=50)),\n ('monto', models.DecimalField(decimal_places=2, max_digits=7, validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(99999.99)])),\n ('adelanto', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='gastos.AdelantoSueldo')),\n ('tipo_gasto', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='gastos.TipoGasto', verbose_name='Tipo Gasto')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.7060359120368958, "alphanum_fraction": 0.7181076407432556, "avg_line_length": 33.438201904296875, "blob_id": "14702b1911ca6ccf9f6a41d07849438bdf8456aa", "content_id": "0860f870bfa1ca11cdf69c6d849a37bf760a3ab9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3065, "license_type": "permissive", "max_line_length": 75, "num_lines": 89, "path": "/sis_gastronomico/pedidos/models.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from datetime import date\n\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\nfrom django.utils.timezone import now\n\nfrom sis_gastronomico.productos.models import Producto\nfrom sis_gastronomico.turnos.models import Turno\n\n# Create your models here.\n\n\nclass MedioPago(models.Model):\n fecha_creacion = models.DateTimeField(auto_now=True)\n fecha_modificacion = models.DateTimeField(auto_now_add=True)\n medio_pago = models.CharField(max_length=100)\n cuotas = models.IntegerField(validators=[MinValueValidator(0)])\n comision = models.DecimalField(max_digits=7, decimal_places=2)\n\n def __str__(self):\n return self.medio_pago\n\n\nclass MedioPedido(models.Model):\n fecha_creacion = models.DateTimeField(auto_now=True)\n fecha_modificacion = models.DateTimeField(auto_now_add=True)\n medio_pedido = models.CharField(max_length=100)\n aumento = models.DecimalField(max_digits=7, decimal_places=2)\n\n def __str__(self):\n return self.medio_pedido\n\n\ndef calc_num_pedido():\n pedidos_del_dia = Pedido.objects.filter(fecha=now().date()).order_by(\n \"numero_pedido\"\n )\n numero_pedido = 1\n if pedidos_del_dia:\n numero_pedido += pedidos_del_dia.first().numero_pedido\n return numero_pedido\n\n\nclass Pedido(models.Model):\n class EstadoPedido(models.IntegerChoices):\n NO_ENTREGADO = 0\n EN_CAMINO = 1\n ENTREGADO = 2\n CANCELADO = 3\n\n fecha = models.DateField(\n auto_now_add=True, validators=[MaxValueValidator(date.today)]\n )\n fecha_creacion = models.DateTimeField(auto_now_add=True)\n fecha_modificacion = models.DateTimeField(auto_now=True)\n estado = models.IntegerField(\n choices=EstadoPedido.choices, default=EstadoPedido.NO_ENTREGADO\n )\n\n numero_pedido = models.SmallIntegerField(\n default=calc_num_pedido,\n blank=True,\n validators=[MaxValueValidator(9999), MinValueValidator(0)],\n )\n calle = models.CharField(max_length=100)\n altura = models.SmallIntegerField(\n validators=[MaxValueValidator(9999), MinValueValidator(0)]\n )\n piso = models.CharField(max_length=3, blank=True, null=True)\n departamento = models.CharField(max_length=3, blank=True, null=True)\n comentario = models.CharField(max_length=100, blank=True, null=True)\n medio_pago = models.ForeignKey(MedioPago, on_delete=models.CASCADE)\n medio_pedido = models.ForeignKey(MedioPedido, on_delete=models.CASCADE)\n precio_total = models.DecimalField(max_digits=7, decimal_places=2)\n turno = models.ForeignKey(Turno, on_delete=models.CASCADE, default=0)\n\n\nclass DetallePedido(models.Model):\n\n fecha_creacion = models.DateTimeField(auto_now=True)\n fecha_modificacion = models.DateTimeField(auto_now_add=True)\n cantidad = models.SmallIntegerField()\n producto = models.ForeignKey(Producto, on_delete=models.CASCADE)\n\n pedido = models.ForeignKey(Pedido, on_delete=models.CASCADE)\n\n @property\n def precio_total(self):\n return self.cantidad * self.producto.precio\n" }, { "alpha_fraction": 0.6387782096862793, "alphanum_fraction": 0.6394422054290771, "avg_line_length": 33.422855377197266, "blob_id": "2303b5d68e1832a39a13932f57c488eec5a1990e", "content_id": "df0b0d375bd9ca30b2b67e87db32a2578a60ef88", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6024, "license_type": "permissive", "max_line_length": 86, "num_lines": 175, "path": "/sis_gastronomico/compras/views.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic.detail import DetailView\nfrom django.views.generic.edit import CreateView, DeleteView, UpdateView # NOQA\nfrom django.views.generic.list import ListView\n\nfrom sis_gastronomico.compras.forms import (\n CompraForm,\n DetalleInsumoFormSet,\n DetalleProductoFormSet,\n)\nfrom sis_gastronomico.compras.models import Compra\n\n\n# Create your views here.\n@method_decorator(login_required, name=\"dispatch\")\nclass ListCompras(ListView):\n model = Compra\n paginate_by = 10\n template_name = \"compras/list_compras.html\"\n\n def get_queryset(self, **kwargs):\n return Compra.objects.order_by(\"-fecha_modificacion\")\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass CreateCompra(CreateView):\n model = Compra\n form_class = CompraForm\n template_name = \"compras/compra_form.html\"\n success_url = \"/compras/?ok\"\n\n def get(self, request, *args, **kwargs):\n self.object = None\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n detalle_insumo_form = DetalleInsumoFormSet()\n detalle_producto_form = DetalleProductoFormSet()\n return self.render_to_response(\n self.get_context_data(\n form=form,\n detalle_insumo_form=detalle_insumo_form,\n detalle_producto_form=detalle_producto_form,\n )\n )\n\n def post(self, request, *args, **kwargs):\n self.object = None\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n detalle_insumo_form = DetalleInsumoFormSet(self.request.POST)\n detalle_producto_form = DetalleProductoFormSet(self.request.POST)\n if (\n form.is_valid()\n and detalle_insumo_form.is_valid()\n and detalle_producto_form.is_valid()\n ):\n return self.form_valid(form, detalle_insumo_form, detalle_producto_form)\n else:\n return self.form_invalid(form, detalle_insumo_form, detalle_producto_form)\n\n def form_valid(self, form, detalle_insumo_form, detalle_producto_form):\n self.object = form.save()\n detalle_insumo_form.instance = self.object\n detalle_insumo_form.save()\n detalle_producto_form.instance = self.object\n detalle_producto_form.save()\n\n gasto = self.object.gasto\n gasto.monto = self.object.precio_total\n gasto.save()\n\n return HttpResponseRedirect(self.get_success_url())\n\n def form_invalid(self, form, detalle_insumo_form, detalle_producto_form):\n return self.render_to_response(\n self.get_context_data(\n form=form,\n detalle_insumo_form=detalle_insumo_form,\n detalle_producto_form=detalle_producto_form,\n )\n )\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass DetailCompra(DetailView):\n model = Compra\n template_name = \"compras/detail_compra.html\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n\n context[\"precio_total_productos\"] = sum(\n x.precio_total for x in self.object.detalleproducto_set.all()\n )\n context[\"precio_total_insumos\"] = sum(\n x.precio_total for x in self.object.detalleinsumo_set.all()\n )\n\n return context\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UpdateCompra(UpdateView):\n model = Compra\n form_class = CompraForm\n template_name = \"compras/compra_form.html\"\n success_url = \"/compras/?up\"\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n\n detalle_insumo_form = DetalleInsumoFormSet(instance=self.object)\n detalle_insumo_form.extra = 0\n detalle_producto_form = DetalleProductoFormSet(instance=self.object)\n detalle_producto_form.extra = 0\n\n return self.render_to_response(\n self.get_context_data(\n form=form,\n detalle_insumo_form=detalle_insumo_form,\n detalle_producto_form=detalle_producto_form,\n )\n )\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n detalle_insumo_form = DetalleInsumoFormSet(\n self.request.POST, instance=self.object\n )\n detalle_producto_form = DetalleProductoFormSet(\n self.request.POST, instance=self.object\n )\n if (\n form.is_valid()\n and detalle_insumo_form.is_valid()\n and detalle_producto_form.is_valid()\n ):\n return self.form_valid(form, detalle_insumo_form, detalle_producto_form)\n else:\n return self.form_invalid(form, detalle_insumo_form, detalle_producto_form)\n\n def form_valid(self, form, detalle_insumo_form, detalle_producto_form):\n self.object = form.save()\n detalle_insumo_form.instance = self.object\n detalle_insumo_form.save()\n detalle_producto_form.instance = self.object\n detalle_producto_form.save()\n\n gasto = self.object.gasto\n gasto.monto = self.object.precio_total\n gasto.save()\n\n return HttpResponseRedirect(self.get_success_url())\n\n def form_invalid(self, form, detalle_insumo_form, detalle_producto_form):\n return self.render_to_response(\n self.get_context_data(\n form=form,\n detalle_insumo_form=detalle_insumo_form,\n detalle_producto_form=detalle_producto_form,\n )\n )\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass DeleteCompra(DeleteView):\n model = Compra\n template_name = \"compras/delete_compra.html\"\n success_url = \"/compras/?del\"\n" }, { "alpha_fraction": 0.5386648774147034, "alphanum_fraction": 0.5525445938110352, "avg_line_length": 35.90243911743164, "blob_id": "53ad328c0d24536b860659624d9b5a29973812b1", "content_id": "ab3ae6521f41d2fb1f8879046bb8b82ffe571247", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1513, "license_type": "permissive", "max_line_length": 114, "num_lines": 41, "path": "/sis_gastronomico/turnos/migrations/0001_initial.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.8 on 2020-12-16 17:30\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 ('empleados', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Horario',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('horario', models.CharField(max_length=35)),\n ('desde', models.TimeField()),\n ('hasta', models.TimeField()),\n ('fecha_creacion', models.DateTimeField(auto_now=True)),\n ('fecha_modificacion', models.DateTimeField(auto_now_add=True)),\n ],\n options={\n 'ordering': ['desde'],\n },\n ),\n migrations.CreateModel(\n name='Turno',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('fecha', models.DateField(auto_now=True)),\n ('fecha_creacion', models.DateTimeField(auto_now=True)),\n ('fecha_modificacion', models.DateTimeField(auto_now_add=True)),\n ('empleados', models.ManyToManyField(to='empleados.Empleado')),\n ('horario', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='turnos.Horario')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.7720588445663452, "alphanum_fraction": 0.7749999761581421, "avg_line_length": 25.153846740722656, "blob_id": "2ca5434170b10e1208bdc3b747811ada416eed10", "content_id": "0a87139ed790e84ff8fb648a555de6137730ba7b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 682, "license_type": "permissive", "max_line_length": 82, "num_lines": 26, "path": "/sis_gastronomico/compras/admin.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom sis_gastronomico.compras.models import Compra, DetalleInsumo, DetalleProducto\n\n\n# Register your models here.\nclass DetalleInsumoInline(admin.TabularInline):\n model = DetalleInsumo\n # Mostramos dos inlines acíos por defecto\n extra = 1\n\n\nclass DetalleProductoInline(admin.TabularInline):\n model = DetalleProducto\n # Mostramos dos inlines acíos por defecto\n extra = 1\n\n\nclass CompraAdmin(admin.ModelAdmin):\n list_display = (\"fecha\", \"precio_total\")\n inlines = [DetalleInsumoInline, DetalleProductoInline]\n\n\nadmin.site.register(Compra, CompraAdmin)\nadmin.site.register(DetalleInsumo)\nadmin.site.register(DetalleProducto)\n" }, { "alpha_fraction": 0.8142076730728149, "alphanum_fraction": 0.8142076730728149, "avg_line_length": 21.875, "blob_id": "284db7e59e92ffdfd1d37c828984ab4ac7f9c093", "content_id": "c7d1ecdf52f41183628d85ef09191b8519bb7320", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 183, "license_type": "permissive", "max_line_length": 59, "num_lines": 8, "path": "/sis_gastronomico/gastos/admin.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom sis_gastronomico.gastos.models import Gasto, TipoGasto\n\n# Register your models here.\n\nadmin.site.register(Gasto)\nadmin.site.register(TipoGasto)\n" }, { "alpha_fraction": 0.6689860820770264, "alphanum_fraction": 0.6689860820770264, "avg_line_length": 29.484848022460938, "blob_id": "335ee5bff2fb4849bb4d4c85bafeb0cee7fc8dd3", "content_id": "47e1f292647f6397718f1e262296ff88827a5c64", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1006, "license_type": "permissive", "max_line_length": 77, "num_lines": 33, "path": "/sis_gastronomico/gastos/forms.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.forms import ModelForm, TextInput\n\n# from django.forms.models import inlineformset_factory\nfrom sis_gastronomico.gastos.models import AdelantoSueldo, Gasto, TipoGasto\n\n\nclass GastoForm(ModelForm):\n class Meta:\n model = Gasto\n exclude = [\"fecha_creacion\", \"fecha_modificacion\"]\n widgets = {\"descripcion\": TextInput(attrs={\"class\": \"autocomplete\"})}\n\n def clean_descripcion(self, *args, **kwargs):\n return self.cleaned_data.get(\"descripcion\").lower()\n\n\nclass TipoGastoForm(ModelForm):\n class Meta:\n model = TipoGasto\n exclude = [\"fecha_creacion\", \"fecha_modificacion\"]\n\n def clean_tipo(self, *args, **kwargs):\n return self.cleaned_data.get(\"tipo\").lower()\n\n def clean_descripcion(self, *args, **kwargs):\n return self.cleaned_data.get(\"descripcion\").lower()\n\n\nclass AdelantoSueldoForm(ModelForm):\n class Meta:\n model = AdelantoSueldo\n fields = \"__all__\"\n exclude = [\"fecha_pago\", \"fecha_modificacion\"]\n" }, { "alpha_fraction": 0.8300653696060181, "alphanum_fraction": 0.8300653696060181, "avg_line_length": 24.5, "blob_id": "7aabe0720f1386e3b218e56dcbba79c222dd5d8b", "content_id": "c3df77e7ff4ea6d5c832313859bb8ca343caf998", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 153, "license_type": "permissive", "max_line_length": 57, "num_lines": 6, "path": "/sis_gastronomico/proveedores/admin.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom sis_gastronomico.proveedores.models import Proveedor\n\n# Register your models here.\nadmin.site.register(Proveedor)\n" }, { "alpha_fraction": 0.6841263771057129, "alphanum_fraction": 0.6937224864959717, "avg_line_length": 32.797298431396484, "blob_id": "e39c27cfbe37b60306867fda19dcd7411aa02cbf", "content_id": "4b272cde73d293801d379d5942b2512e494d0865", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2501, "license_type": "permissive", "max_line_length": 88, "num_lines": 74, "path": "/sis_gastronomico/compras/models.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from datetime import date\n\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\n\nfrom sis_gastronomico.gastos.models import Gasto, TipoGasto\nfrom sis_gastronomico.insumos.models import Insumo\nfrom sis_gastronomico.productos.models import Producto\nfrom sis_gastronomico.proveedores.models import Proveedor\n\n\n# Create your models here.\nclass Compra(models.Model):\n fecha = models.DateField(\n default=date.today, validators=[MaxValueValidator(date.today)]\n )\n gasto = models.ForeignKey(Gasto, on_delete=models.CASCADE, default=None)\n\n fecha_creacion = models.DateTimeField(auto_now=True)\n fecha_modificacion = models.DateTimeField(auto_now_add=True)\n proveedor = models.ForeignKey(Proveedor, on_delete=models.CASCADE)\n\n @property\n def precio_total(self):\n \"Retorna la suma de los precios totales de todos los detalles de la compra\"\n total = 0\n\n total += sum(d.precio_total for d in self.detalleinsumo_set.all())\n total += sum(d.precio_total for d in self.detalleproducto_set.all())\n\n return total\n\n def save(self, *args, **kwargs):\n\n if self._state.adding:\n tipo_gasto, _ = TipoGasto.objects.get_or_create(\n tipo=\"compra\", defaults={\"descripcion\": \"Descrpicion de la compra\"}\n )\n\n self.gasto = Gasto.objects.create(\n descripcion=\"Compra de insumos/producto\", monto=0, tipo_gasto=tipo_gasto\n )\n\n super(Compra, self).save(*args, **kwargs)\n\n\nclass DetalleInsumo(models.Model):\n precio_unitario = models.DecimalField(\n max_digits=7,\n decimal_places=2,\n validators=[MinValueValidator(0.0), MaxValueValidator(99999.99)],\n )\n cantidad = models.PositiveIntegerField()\n insumo = models.ForeignKey(Insumo, on_delete=models.CASCADE)\n compra = models.ForeignKey(Compra, on_delete=models.CASCADE)\n\n @property\n def precio_total(self):\n return self.precio_unitario * self.cantidad\n\n\nclass DetalleProducto(models.Model):\n precio_unitario = models.DecimalField(\n max_digits=7,\n decimal_places=2,\n validators=[MinValueValidator(0.0), MaxValueValidator(99999.99)],\n )\n cantidad = models.PositiveIntegerField()\n producto = models.ForeignKey(Producto, on_delete=models.CASCADE)\n compra = models.ForeignKey(Compra, on_delete=models.CASCADE)\n\n @property\n def precio_total(self):\n return self.precio_unitario * self.cantidad\n" }, { "alpha_fraction": 0.685071587562561, "alphanum_fraction": 0.685071587562561, "avg_line_length": 27.764705657958984, "blob_id": "2bd7ce9e41991c60cf231459fb3073da37086366", "content_id": "960c8d00b4122f3849a17b69bd7b4c03b1b9497d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 489, "license_type": "permissive", "max_line_length": 68, "num_lines": 17, "path": "/sis_gastronomico/empleados/forms.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.forms import ModelForm\n\n# from django.forms.models import inlineformset_factory\nfrom sis_gastronomico.empleados.models import Empleado\n\n\nclass EmpleadoForm(ModelForm):\n class Meta:\n model = Empleado\n fields = \"__all__\"\n exclude = [\"estado\", \"fecha_creacion\", \"fecha_modificacion\"]\n\n def clean_nombre(self):\n return self.cleaned_data.get(\"nombre\").lower()\n\n def clean_apellido(self):\n return self.cleaned_data.get(\"apellido\").lower()\n" }, { "alpha_fraction": 0.6848780512809753, "alphanum_fraction": 0.7043902277946472, "avg_line_length": 31.03125, "blob_id": "2c2481f5376bf894c07061d82045ce019ba39a47", "content_id": "018eb0dec2da418331cc654121fc3da8ec05f4d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1025, "license_type": "permissive", "max_line_length": 76, "num_lines": 32, "path": "/sis_gastronomico/productos/models.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\n\n\nclass TipoProducto(models.Model):\n\n fecha_creacion = models.DateTimeField(auto_now_add=True)\n fecha_modificacion = models.DateTimeField(auto_now=True)\n tipo = models.CharField(unique=True, max_length=35)\n descripcion = models.CharField(max_length=100)\n\n def __str__(self):\n return \"{:s}\".format(self.tipo)\n\n\nclass Producto(models.Model):\n\n nombre = models.CharField(max_length=30, unique=True)\n descripcion = models.CharField(max_length=50)\n precio = models.DecimalField(\n max_digits=7,\n decimal_places=2,\n validators=[MinValueValidator(0.0), MaxValueValidator(99999.99)],\n )\n fecha_creacion = models.DateTimeField(auto_now=True)\n fecha_modificacion = models.DateTimeField(auto_now=True)\n tipo_producto = models.ForeignKey(\n TipoProducto, on_delete=models.CASCADE, verbose_name=\"Tipo Producto\"\n )\n\n def __str__(self):\n return self.nombre\n" }, { "alpha_fraction": 0.6904425024986267, "alphanum_fraction": 0.6916548609733582, "avg_line_length": 31.5592098236084, "blob_id": "23c1d29ea87e29e415db8dbb7af5b1b085e5d7e0", "content_id": "499f8a58567a2017cb7cfcc01ff49b0d6cd048ad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4949, "license_type": "permissive", "max_line_length": 85, "num_lines": 152, "path": "/sis_gastronomico/productos/views.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import HttpResponseRedirect, render\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic.edit import CreateView, DeleteView, UpdateView\nfrom django.views.generic.list import ListView\n\nfrom sis_gastronomico.productos.forms import (\n ProductoForm,\n StockProductoFormSet,\n TipoProductoForm,\n)\nfrom sis_gastronomico.productos.models import Producto, TipoProducto\n\n# Create your views here.\n\n\n@method_decorator(login_required, name=\"dispatch\")\ndef index(request):\n productos = Producto.objects.all().order_by(\"-fecha_modificacion\")[:10]\n for producto in productos:\n producto.descripcion = producto.descripcion.title()\n\n return render(request, \"productos/index.html\", {\"productos\": productos})\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass ListarProductos(ListView):\n\n model = Producto\n paginate_by = 10\n template_name = \"productos/listar_productos.html\"\n\n def get_queryset(self):\n return Producto.objects.all().order_by(\"nombre\")\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass ListarTipoProducto(ListView):\n\n model = TipoProducto\n paginate_by = 10\n template_name = \"productos/listar_tipo_producto.html\"\n\n def get_queryset(self):\n return TipoProducto.objects.all().order_by(\"-tipo\")\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass CrearProducto(CreateView):\n\n model = Producto\n form_class = ProductoForm\n template_name = \"productos/productos_form.html\"\n success_url = \"/productos/?ok\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n productos = set()\n for producto in Producto.objects.values_list(\"nombre\", flat=True):\n productos.add(producto.title())\n context[\"productos\"] = productos\n return context\n\n def get(self, request, *args, **kwargs):\n self.object = None\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n stock_producto_form = StockProductoFormSet()\n return self.render_to_response(\n self.get_context_data(form=form, stock_producto_form=stock_producto_form)\n )\n\n def post(self, request, *args, **kwargs):\n self.object = None\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n stock_producto_form = StockProductoFormSet(self.request.POST)\n if form.is_valid() and stock_producto_form.is_valid():\n return self.form_valid(form, stock_producto_form)\n else:\n return self.form_invalid(form, stock_producto_form)\n\n def form_valid(self, form, stock_producto_form):\n self.object = form.save()\n stock_producto_form.instance = self.object\n stock_producto_form.save()\n return HttpResponseRedirect(self.get_success_url())\n\n def form_invalid(self, form, stock_producto_form):\n return self.render_to_response(\n self.get_context_data(form=form, stock_producto_form=stock_producto_form)\n )\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass CrearTipoProducto(CreateView):\n\n model = TipoProducto\n form_class = TipoProductoForm\n template_name = \"productos/tipo_producto_form.html\"\n success_url = \"/productos/listar_tipo_producto?tgok\"\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass BorrarProducto(DeleteView):\n\n model = Producto\n template_name = \"productos/borrar_producto.html\"\n success_url = \"/productos/?del\"\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n self.object.delete()\n return HttpResponseRedirect(self.get_success_url())\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass BorrarTipoProducto(DeleteView):\n\n model = TipoProducto\n template_name = \"productos/borrar_tipo_producto.html\"\n success_url = \"/productos/listar_tipo_producto?tgdel\"\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n self.object.delete()\n return HttpResponseRedirect(self.get_success_url())\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UpdateProducto(UpdateView):\n model = Producto\n form_class = ProductoForm\n template_name = \"productos/productos_form.html\"\n success_url = \"/productos/?up\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n productos = set()\n for producto in Producto.objects.values_list(\"descripcion\", flat=True):\n productos.add(producto.title())\n context[\"productos\"] = productos\n return context\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UpdateTipoProducto(UpdateView):\n\n model = TipoProducto\n form_class = TipoProductoForm\n template_name = \"productos/tipo_producto_form.html\"\n success_url = \"/productos/listar_tipo_producto?tgup\"\n" }, { "alpha_fraction": 0.6285878419876099, "alphanum_fraction": 0.6285878419876099, "avg_line_length": 30.10714340209961, "blob_id": "045a280a7b65d82a1bcaa85c3f9be0b27dfd0775", "content_id": "fbb112e9b846965eb487a6fd7f93fe163fb3c23d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1742, "license_type": "permissive", "max_line_length": 86, "num_lines": 56, "path": "/sis_gastronomico/pedidos/urls.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.urls import path # NOQA\n\nfrom sis_gastronomico.pedidos.views import (\n CreateMedioPago,\n CreateMedioPedido,\n CreatePedido,\n DeleteMedioPago,\n DeleteMedioPedido,\n DeletePedido,\n DetailPedido,\n ListMedioPago,\n ListMedioPedido,\n UpdateMedioPago,\n UpdateMedioPedido,\n UpdatePedido,\n informes,\n listPedido,\n)\n\napp_name = \"pedidos\"\nurlpatterns = [\n # path(\"\", index, name=\"index\"),\n path(\"\", listPedido, name=\"index\"),\n path(\"list_medio_pago\", ListMedioPago.as_view(), name=\"list_medio_pago\"),\n path(\"list_medio_pedido\", ListMedioPedido.as_view(), name=\"list_medio_pedido\"),\n path(\n \"create_medio_pedido\", CreateMedioPedido.as_view(), name=\"create_medio_pedido\"\n ),\n path(\"create_medio_pago\", CreateMedioPago.as_view(), name=\"create_medio_pago\"),\n path(\"\", listPedido, name=\"index\"),\n path(\"informes\", informes, name=\"informes\"),\n path(\"create_pedido\", CreatePedido.as_view(), name=\"create_pedido\"),\n path(\n \"delete_medio_pago/<int:pk>\",\n DeleteMedioPago.as_view(),\n name=\"delete_medio_pago\",\n ),\n path(\n \"delete_medio_pedido/<int:pk>\",\n DeleteMedioPedido.as_view(),\n name=\"delete_medio_pedido\",\n ),\n path(\"delete_pedido/<int:pk>\", DeletePedido.as_view(), name=\"delete_pedido\"),\n path(\"detail_pedido/<int:pk>\", DetailPedido.as_view(), name=\"detail_pedido\"),\n path(\n \"update_medio_pago/<int:pk>\",\n UpdateMedioPago.as_view(),\n name=\"update_medio_pago\",\n ),\n path(\n \"update_medio_pedido/<int:pk>\",\n UpdateMedioPedido.as_view(),\n name=\"update_medio_pedido\",\n ),\n path(\"update_pedido/<int:pk>\", UpdatePedido.as_view(), name=\"update_pedido\"),\n]\n" }, { "alpha_fraction": 0.7149999737739563, "alphanum_fraction": 0.7275000214576721, "avg_line_length": 32.33333206176758, "blob_id": "b5811e7e0a4a57b18d72f02343105ef70445a4c4", "content_id": "857101ebd704b6c4e415a826c9244b31177ae1f6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 400, "license_type": "permissive", "max_line_length": 76, "num_lines": 12, "path": "/sis_gastronomico/insumos/models.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\n# Create your models here.\nclass Insumo(models.Model):\n nombre = models.CharField(max_length=30, unique=True)\n descripcion = models.CharField(max_length=100)\n fecha_creacion = models.DateTimeField(auto_now_add=True, editable=False)\n fecha_modificacion = models.DateTimeField(auto_now=True, editable=False)\n\n def __str__(self):\n return self.nombre\n" }, { "alpha_fraction": 0.6335195302963257, "alphanum_fraction": 0.6491619944572449, "avg_line_length": 29.86206817626953, "blob_id": "3507582e8b921dabb24c411243e82049d8824ebd", "content_id": "6f8110c6ffb7c32fe8b30eb7ccea4910448d6589", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1790, "license_type": "permissive", "max_line_length": 73, "num_lines": 58, "path": "/sis_gastronomico/empleados/models.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.core.validators import (\n MaxLengthValidator,\n MaxValueValidator,\n MinLengthValidator,\n MinValueValidator,\n)\nfrom django.db import models\nfrom django.utils.timezone import now\n\n\n# Create your models here.\nclass Empleado(models.Model):\n nombre = models.CharField(\n max_length=50,\n null=False,\n blank=False,\n validators=[MinLengthValidator(3), MaxLengthValidator(50)],\n )\n apellido = models.CharField(\n max_length=50,\n null=False,\n blank=False,\n validators=[MinLengthValidator(3), MaxLengthValidator(50)],\n )\n dni = models.IntegerField(\n unique=True,\n blank=False,\n null=False,\n validators=[\n MaxValueValidator(99999999, message=\"Ingrese un DNI valido\"),\n MinValueValidator(11111111, message=\"Ingrese un DNI valido\"),\n ],\n )\n fecha_nacimiento = models.DateField(null=False, blank=False)\n fecha_ingreso = models.DateField(\n null=False, blank=False, default=now\n ) # Fecha en la que el empleado ingreso a trabajar en la empresa\n estado = models.BooleanField(default=True)\n\n generos = models.TextChoices(\"Genero\", \"femenino masculino\")\n genero = models.CharField(\n max_length=20, choices=generos.choices, default=\"femenino\"\n )\n\n fecha_creacion = models.DateTimeField(\n auto_now_add=True\n ) # Fecha en que se creo el empleado en el sistema\n fecha_modificacion = models.DateTimeField(\n auto_now=True\n ) # Fecha en que se modificp los datos del empleado en el sistema\n\n class Meta:\n verbose_name = \"Empleado\"\n verbose_name_plural = \"Empleados\"\n db_table = \"empleados\"\n\n def __str__(self):\n return \"{:s}, {:s}\".format(self.apellido, self.nombre)\n" }, { "alpha_fraction": 0.5678218007087708, "alphanum_fraction": 0.5801980495452881, "avg_line_length": 41.08333206176758, "blob_id": "f4eb597376e3826cc254e09e673357f352b6ef4d", "content_id": "042eaca9adc5d30e9cd88a878ca392b892f4f7ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2020, "license_type": "permissive", "max_line_length": 152, "num_lines": 48, "path": "/sis_gastronomico/stocks/migrations/0001_initial.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.8 on 2020-12-16 17:30\n\nimport django.core.validators\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 ('productos', '0001_initial'),\n ('insumos', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='StockProducto',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('cantidad', models.SmallIntegerField(validators=[django.core.validators.MinValueValidator(0)])),\n ('fecha_creacion', models.DateTimeField(auto_now_add=True)),\n ('fecha_modificacion', models.DateTimeField(auto_now=True)),\n ('producto', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='productos.Producto', verbose_name='stock de producto')),\n ],\n options={\n 'verbose_name': 'Stock de Producto',\n 'verbose_name_plural': 'Stock de Productos',\n 'db_table': 'stock_Producto',\n },\n ),\n migrations.CreateModel(\n name='StockInsumo',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('cantidad', models.SmallIntegerField(validators=[django.core.validators.MinValueValidator(0)])),\n ('fecha_creacion', models.DateTimeField(auto_now_add=True)),\n ('fecha_modificacion', models.DateTimeField(auto_now=True)),\n ('insumo', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insumos.Insumo', verbose_name='stock de insumo')),\n ],\n options={\n 'verbose_name': 'Stock de Insumo',\n 'verbose_name_plural': 'Stock de Insumos',\n 'db_table': 'stock_Insumo',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.6770833134651184, "alphanum_fraction": 0.6770833134651184, "avg_line_length": 31, "blob_id": "db0ecd5e36f6fbb2db8f09983b0326a837bdbd61", "content_id": "decd4a277da63fcb2a04e9ab7cc448d9f65e3105", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 576, "license_type": "permissive", "max_line_length": 81, "num_lines": 18, "path": "/sis_gastronomico/compras/urls.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom sis_gastronomico.compras.views import (\n CreateCompra,\n DeleteCompra,\n DetailCompra,\n ListCompras,\n UpdateCompra,\n)\n\napp_name = \"compras\"\nurlpatterns = [\n path(\"\", ListCompras.as_view(), name=\"index\"),\n path(\"create_compra\", CreateCompra.as_view(), name=\"create_compra\"),\n path(\"detail_compra/<int:pk>\", DetailCompra.as_view(), name=\"detail_compra\"),\n path(\"update_compra/<int:pk>\", UpdateCompra.as_view(), name=\"update_compra\"),\n path(\"delete_compra/<int:pk>\", DeleteCompra.as_view(), name=\"delete_compra\"),\n]\n" }, { "alpha_fraction": 0.6705632209777832, "alphanum_fraction": 0.6705632209777832, "avg_line_length": 35.19230651855469, "blob_id": "aa74fa7645def343fd2f94d03cb0b6ea45f5bb2a", "content_id": "b2e6066cc18c2834140c36723131958bbc6517b2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 941, "license_type": "permissive", "max_line_length": 85, "num_lines": 26, "path": "/sis_gastronomico/turnos/urls.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom sis_gastronomico.turnos.views import (\n CreateHorario,\n CreateTurno,\n DeleteHorario,\n DeleteTurno,\n ListHorario,\n ListTurno,\n UpdateHorario,\n UpdateTurno,\n no_active_turno,\n)\n\napp_name = \"turnos\"\nurlpatterns = [\n path(\"\", ListTurno.as_view(), name=\"index\"),\n path(\"create_horario\", CreateHorario.as_view(), name=\"create_horario\"),\n path(\"create_turno\", CreateTurno.as_view(), name=\"create_turno\"),\n path(\"delete_turno/<int:pk>\", DeleteTurno.as_view(), name=\"delete_turno\",),\n path(\"delete_horario/<int:pk>\", DeleteHorario.as_view(), name=\"delete_horario\",),\n path(\"list_horario\", ListHorario.as_view(), name=\"list_horario\"),\n path(\"no_active_turno\", no_active_turno, name=\"no_active_turno\"),\n path(\"update_horario/<int:pk>\", UpdateHorario.as_view(), name=\"update_horario\"),\n path(\"update_turno/<int:pk>\", UpdateTurno.as_view(), name=\"update_turno\"),\n]\n" }, { "alpha_fraction": 0.7348484992980957, "alphanum_fraction": 0.7348484992980957, "avg_line_length": 21, "blob_id": "26cb27080d18e93baa64a4f1d9b44e83e53ea3ef", "content_id": "a9866926d2571ba794abd0598a4035ad392c9450", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 132, "license_type": "permissive", "max_line_length": 36, "num_lines": 6, "path": "/sis_gastronomico/stocks/apps.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass StocksConfig(AppConfig):\n name = \"sis_gastronomico.stocks\"\n verbose_name = \"Stocks\"\n" }, { "alpha_fraction": 0.8146067261695862, "alphanum_fraction": 0.8146067261695862, "avg_line_length": 24.428571701049805, "blob_id": "a7810588e44be8e6081889c806d3453b65377e34", "content_id": "b76222ef33e99973d8bcf5c03418b80cea64ee66", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 178, "license_type": "permissive", "max_line_length": 57, "num_lines": 7, "path": "/sis_gastronomico/turnos/admin.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom sis_gastronomico.turnos.models import Horario, Turno\n\n# Register your models here.\nadmin.site.register(Horario)\nadmin.site.register(Turno)\n" }, { "alpha_fraction": 0.6987951993942261, "alphanum_fraction": 0.6987951993942261, "avg_line_length": 19.75, "blob_id": "541874a01f4e15d3f88d8fed0df3e79daf91f554", "content_id": "50b3e7cc242e30356c697781d9e3cb1c36bc858b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 83, "license_type": "permissive", "max_line_length": 32, "num_lines": 4, "path": "/sis_gastronomico/productos/tests.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.test import TestCase\n\n__all__ = [\"TestCase\"]\n# Create your tests here.\n" }, { "alpha_fraction": 0.5411471128463745, "alphanum_fraction": 0.5935162305831909, "avg_line_length": 21.27777862548828, "blob_id": "dec68c5bfe06425a58b4e3c805f0886e406670e6", "content_id": "45d7ecdf2f4ac1fd0c696c52c394e3a4db02868c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 401, "license_type": "permissive", "max_line_length": 70, "num_lines": 18, "path": "/sis_gastronomico/pedidos/migrations/0002_auto_20201228_0858.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.8 on 2020-12-28 08:58\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('pedidos', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='pedido',\n name='precio_total',\n field=models.DecimalField(decimal_places=2, max_digits=7),\n ),\n ]\n" }, { "alpha_fraction": 0.6772152185440063, "alphanum_fraction": 0.6772152185440063, "avg_line_length": 28.625, "blob_id": "465b9fef1fa717ff5009ad346efcb648a1a97de2", "content_id": "fc0529a230f573921a34153868c8ae6a303e3c53", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 474, "license_type": "permissive", "max_line_length": 81, "num_lines": 16, "path": "/sis_gastronomico/insumos/urls.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom sis_gastronomico.insumos.views import (\n CreateInsumo,\n DeleteInsumo,\n ListInsumo,\n UpdateInsumo,\n)\n\napp_name = \"insumos\"\nurlpatterns = [\n path(\"\", ListInsumo.as_view(), name=\"index\"),\n path(\"create_insumo\", CreateInsumo.as_view(), name=\"create_insumo\"),\n path(\"delete_insumo/<int:pk>\", DeleteInsumo.as_view(), name=\"delete_insumo\"),\n path(\"update_insumo/<int:pk>\", UpdateInsumo.as_view(), name=\"update_insumo\"),\n]\n" }, { "alpha_fraction": 0.567726731300354, "alphanum_fraction": 0.6042402982711792, "avg_line_length": 27.299999237060547, "blob_id": "d66ba636400d8d5151d97671e3b54521d7f8fda4", "content_id": "812caed8714cb3efc309c954015e1fe6e18ddf32", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 849, "license_type": "permissive", "max_line_length": 130, "num_lines": 30, "path": "/sis_gastronomico/pedidos/migrations/0003_auto_20201228_1203.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.8 on 2020-12-28 12:03\n\nimport datetime\nimport django.core.validators\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('pedidos', '0002_auto_20201228_0858'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='pedido',\n name='fecha',\n field=models.DateField(auto_now_add=True, validators=[django.core.validators.MaxValueValidator(datetime.date.today)]),\n ),\n migrations.AlterField(\n model_name='pedido',\n name='fecha_creacion',\n field=models.DateTimeField(auto_now_add=True),\n ),\n migrations.AlterField(\n model_name='pedido',\n name='fecha_modificacion',\n field=models.DateTimeField(auto_now=True),\n ),\n ]\n" }, { "alpha_fraction": 0.7407407164573669, "alphanum_fraction": 0.7407407164573669, "avg_line_length": 21.5, "blob_id": "fc8ba69cdf2c6468e24d03905c560e51383e8136", "content_id": "93f331ae27b1be524f0690d0c2a62903e91c23d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 135, "license_type": "permissive", "max_line_length": 37, "num_lines": 6, "path": "/sis_gastronomico/insumos/apps.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass InsumosConfig(AppConfig):\n name = \"sis_gastronomico.insumos\"\n verbose_name = \"Insumos\"\n" }, { "alpha_fraction": 0.6051467657089233, "alphanum_fraction": 0.6248492002487183, "avg_line_length": 48.7400016784668, "blob_id": "8b9309497e287598f057c396a20f402c6ad186dc", "content_id": "4f05e6f0df474d240b17d995526217059ce8711c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2487, "license_type": "permissive", "max_line_length": 201, "num_lines": 50, "path": "/sis_gastronomico/compras/migrations/0001_initial.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.8 on 2020-12-16 17:30\n\nimport datetime\nimport django.core.validators\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 ('productos', '0001_initial'),\n ('insumos', '0001_initial'),\n ('gastos', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Compra',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('fecha', models.DateField(default=datetime.date.today, validators=[django.core.validators.MaxValueValidator(datetime.date.today)])),\n ('fecha_creacion', models.DateTimeField(auto_now=True)),\n ('fecha_modificacion', models.DateTimeField(auto_now_add=True)),\n ('gasto', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='gastos.Gasto')),\n ],\n ),\n migrations.CreateModel(\n name='DetalleProducto',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('precio_unitario', models.DecimalField(decimal_places=2, max_digits=7, validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(99999.99)])),\n ('cantidad', models.PositiveIntegerField()),\n ('compra', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='compras.Compra')),\n ('producto', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='productos.Producto')),\n ],\n ),\n migrations.CreateModel(\n name='DetalleInsumo',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('precio_unitario', models.DecimalField(decimal_places=2, max_digits=7, validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(99999.99)])),\n ('cantidad', models.PositiveIntegerField()),\n ('compra', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='compras.Compra')),\n ('insumo', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insumos.Insumo')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.6087689995765686, "alphanum_fraction": 0.6087689995765686, "avg_line_length": 25.954545974731445, "blob_id": "aec9fcc9a972879a1a0ceb269d6c80b11ca19db9", "content_id": "09e874975b26a149307883f00b80efe8a6c02b62", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 593, "license_type": "permissive", "max_line_length": 62, "num_lines": 22, "path": "/sis_gastronomico/turnos/forms.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.forms import ModelForm, TimeInput\n\nfrom sis_gastronomico.turnos.models import Horario, Turno\n\n\nclass HorarioForm(ModelForm):\n class Meta:\n model = Horario\n fields = [\"horario\", \"desde\", \"hasta\"]\n widgets = {\n \"desde\": TimeInput(attrs={\"class\": \"timepicker\"}),\n \"hasta\": TimeInput(attrs={\"class\": \"timepicker\"}),\n }\n\n def clean_horario(self, *args, **kwargs):\n return self.cleaned_data.get(\"horario\").lower()\n\n\nclass TurnoForm(ModelForm):\n class Meta:\n model = Turno\n fields = [\"horario\", \"empleados\"]\n" }, { "alpha_fraction": 0.6994949579238892, "alphanum_fraction": 0.6994949579238892, "avg_line_length": 27.285715103149414, "blob_id": "ebed449ee5b3c7d0021918ceecb7ef7e04588dc0", "content_id": "bc6e600f743cdd68e310a6b0ec6092488420c1bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 396, "license_type": "permissive", "max_line_length": 58, "num_lines": 14, "path": "/sis_gastronomico/proveedores/forms.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.forms import ModelForm\n\n# from django.forms.models import inlineformset_factory\nfrom sis_gastronomico.proveedores.models import Proveedor\n\n\nclass ProveedorForm(ModelForm):\n class Meta:\n model = Proveedor\n fields = \"__all__\"\n exclude = [\"fecha_creacion\", \"fecha_modificacion\"]\n\n def clean_nombre(self):\n return self.cleaned_data.get(\"nombre\").lower()\n" }, { "alpha_fraction": 0.6392936110496521, "alphanum_fraction": 0.6402586102485657, "avg_line_length": 33.5433349609375, "blob_id": "7587b66c6e05a26cd24a9adcd3906af042f8fe89", "content_id": "f7874c5f757268be6b06a4bd92c2af58f6850a89", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10363, "license_type": "permissive", "max_line_length": 88, "num_lines": 300, "path": "/sis_gastronomico/pedidos/views.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.contrib.auth.decorators import login_required\nfrom django.db.models import Count, F, Sum\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render # NOQA\nfrom django.urls import reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.timezone import datetime, now\nfrom django.views.generic.detail import DetailView\nfrom django.views.generic.edit import CreateView, DeleteView, UpdateView\nfrom django.views.generic.list import ListView\n\nfrom sis_gastronomico.pedidos.forms import (\n DetallePedidoFormSet,\n MedioPagoForm,\n MedioPedidoForm,\n PedidoForm,\n)\nfrom sis_gastronomico.pedidos.models import MedioPago, MedioPedido, Pedido\nfrom sis_gastronomico.turnos.models import Turno\n\n# Create your views here.\n\n\n@login_required\ndef informes(request):\n date = now().date()\n if \"fecha\" in request.GET:\n year, month, day = map(int, request.GET[\"fecha\"].split(\"-\"))\n date = datetime(year, month, day)\n turnos = Turno.objects.filter(fecha=date)\n context = {}\n context[\"turnos\"] = []\n for turno in turnos:\n context[\"turnos\"].append(\n {\n \"turno\": turno,\n # Pedidos por medio de pedido\n \"medios_pedidos\": Pedido.objects.filter(turno=turno)\n .values(tipo=F(\"medio_pedido__medio_pedido\"))\n .annotate(cantidad=Count(\"medio_pedido__medio_pedido\")),\n # Total de Pedidos\n \"total_pedidos\": Pedido.objects.filter(turno=turno).count(),\n # Total de productos por producto\n \"total_tipos_productos\": Pedido.objects.filter(turno=turno)\n .values(tipo=F(\"detallepedido__producto__nombre\"))\n .annotate(cantidad=Sum(\"detallepedido__cantidad\")),\n # Total de productos\n \"total_productos\": Pedido.objects.filter(turno=turno).aggregate(\n total=Sum(\"detallepedido__cantidad\")\n ),\n # Total de pedidos por medio de pago\n \"total_medio_pago\": Pedido.objects.filter(turno=turno)\n .values(tipo=F(\"medio_pago__medio_pago\"))\n .annotate(total=Sum(\"precio_total\")),\n \"total_facturado\": Pedido.objects.filter(turno=turno).aggregate(\n total=Sum(\"precio_total\")\n ),\n }\n )\n return render(request, \"pedidos/informes.html\", context)\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass CreatePedido(CreateView):\n\n model = Pedido\n form_class = PedidoForm\n template_name = \"pedidos/pedido_form.html\"\n success_url = \"/pedidos/?ok\"\n\n def get(self, request, *args, **kwargs):\n last_turno = Turno.objects.filter(fecha=now().date()).last()\n if last_turno is None or last_turno.activo is False:\n return HttpResponseRedirect(reverse(\"turnos:no_active_turno\"))\n self.object = None\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n detalle_pedido_form = DetallePedidoFormSet()\n return self.render_to_response(\n self.get_context_data(form=form, detalle_pedido_form=detalle_pedido_form,)\n )\n\n def post(self, request, *args, **kwargs):\n self.object = None\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n detalle_pedido_form = DetallePedidoFormSet(self.request.POST)\n if form.is_valid() and detalle_pedido_form.is_valid():\n return self.form_valid(form, detalle_pedido_form)\n else:\n return self.form_invalid(form, detalle_pedido_form)\n\n def form_valid(self, form, detalle_pedido_form):\n self.object = pedido = form.save(commit=False)\n pedidos = Pedido.objects.filter(fecha=now().date())\n if pedidos.count() == 0:\n pedido.numero_pedido = 1\n else:\n pedido.numero_pedido = pedidos.last().numero_pedido + 1\n pedido.turno = Turno.objects.last()\n pedido.save()\n detalle_pedido_form.instance = self.object\n detalles_pedido = detalle_pedido_form.save()\n total = sum([detalle_pedido.precio_total for detalle_pedido in detalles_pedido])\n pedido.precio_total = total\n pedido.save()\n return HttpResponseRedirect(self.get_success_url())\n\n def form_invalid(self, form, detalle_pedido_form):\n return self.render_to_response(\n self.get_context_data(form=form, detalle_pedido_form=detalle_pedido_form,)\n )\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass CreateMedioPedido(CreateView):\n model = MedioPedido\n form_class = MedioPedidoForm\n template_name = \"pedidos/medio_pedido_form.html\"\n success_url = \"/pedidos/list_medio_pedido?ok\"\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass CreateMedioPago(CreateView):\n model = MedioPago\n form_class = MedioPagoForm\n template_name = \"pedidos/medio_pago_form.html\"\n success_url = \"/pedidos/list_medio_pago?ok\"\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass DetailPedido(DetailView):\n model = Pedido\n template_name = \"pedidos/detail_pedido.html\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"precio_total\"] = sum(\n dp.precio_total for dp in self.object.detallepedido_set.all()\n )\n return context\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass DeletePedido(DeleteView):\n model = Pedido\n template_name = \"pedidos/delete_pedido.html\"\n success_url = \"/pedidos/?del\"\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass DeleteMedioPedido(DeleteView):\n\n model = MedioPedido\n template_name = \"pedidos/delete_medio_pedido.html\"\n success_url = \"/pedidos/list_medio_pedido?del\"\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass DeleteMedioPago(DeleteView):\n\n model = MedioPago\n template_name = \"pedidos/delete_medio_pago.html\"\n success_url = \"/pedidos/list_medio_pago?del\"\n\n\n@login_required\ndef listPedido(request):\n\n if request.POST.get(\"encamino\"):\n pedido_id = request.POST.get(\"pedido_id\")\n print(pedido_id)\n pedido = Pedido.objects.get(pk=pedido_id)\n pedido.estado = Pedido.EstadoPedido.EN_CAMINO\n pedido.save()\n elif request.POST.get(\"entregado\"):\n pedido_id = request.POST.get(\"pedido_id\")\n pedido = Pedido.objects.get(pk=pedido_id)\n pedido.estado = Pedido.EstadoPedido.ENTREGADO\n pedido.save()\n\n context = {}\n date = now().date()\n if \"fecha\" in request.GET:\n year, month, day = map(int, request.GET[\"fecha\"].split(\"-\"))\n date = datetime(year, month, day)\n context[\"pnentregados\"] = (\n Pedido.objects.filter(fecha=date, estado=0)\n .order_by(\"fecha_creacion\")\n .prefetch_related(\n \"detallepedido_set\",\n \"detallepedido_set__producto\",\n \"detallepedido_set__producto\",\n \"medio_pedido\",\n \"medio_pago\",\n )\n )\n context[\"pencamino\"] = (\n Pedido.objects.filter(fecha=date, estado=1)\n .order_by(\"-fecha_creacion\")\n .prefetch_related(\n \"detallepedido_set\",\n \"detallepedido_set__producto\",\n \"detallepedido_set__producto\",\n \"medio_pedido\",\n \"medio_pago\",\n )\n )\n context[\"pentregados\"] = (\n Pedido.objects.filter(fecha=date, estado=2)\n .order_by(\"-fecha_creacion\")\n .prefetch_related(\n \"detallepedido_set\",\n \"detallepedido_set__producto\",\n \"detallepedido_set__producto\",\n \"medio_pedido\",\n \"medio_pago\",\n )\n )\n return render(request, \"pedidos/list_pedido.html\", context)\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass ListMedioPedido(ListView):\n model = MedioPedido\n paginate_by = 10\n template_name = \"pedidos/list_medio_pedido.html\"\n\n def get_queryset(self, **kwargs):\n return MedioPedido.objects.order_by(\"medio_pedido\")\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass ListMedioPago(ListView):\n model = MedioPago\n paginate_by = 10\n template_name = \"pedidos/list_medio_pago.html\"\n\n def get_queryset(self, **kwargs):\n return MedioPago.objects.order_by(\"medio_pago\")\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UpdatePedido(UpdateView):\n model = Pedido\n form_class = PedidoForm\n template_name = \"pedidos/pedido_form.html\"\n success_url = \"/pedidos/?up\"\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n\n detalle_pedido_form = DetallePedidoFormSet(instance=self.object)\n\n return self.render_to_response(\n self.get_context_data(form=form, detalle_pedido_form=detalle_pedido_form,)\n )\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n detalle_pedido_form = DetallePedidoFormSet(\n self.request.POST, instance=self.object\n )\n if form.is_valid() and detalle_pedido_form.is_valid():\n return self.form_valid(form, detalle_pedido_form)\n else:\n return self.form_invalid(form, detalle_pedido_form)\n\n def form_valid(self, form, detalle_pedido_form):\n self.object = form.save()\n detalle_pedido_form.instance = self.object\n detalle_pedido_form.save()\n return HttpResponseRedirect(self.get_success_url())\n\n def form_invalid(self, form, detalle_pedido_form):\n return self.render_to_response(\n self.get_context_data(form=form, detalle_pedido_form=detalle_pedido_form,)\n )\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UpdateMedioPedido(UpdateView):\n\n model = MedioPedido\n form_class = MedioPedidoForm\n template_name = \"pedidos/medio_pedido_form.html\"\n success_url = \"/pedidos/list_medio_pedido?up\"\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UpdateMedioPago(UpdateView):\n\n model = MedioPago\n form_class = MedioPagoForm\n template_name = \"pedidos/medio_pago_form.html\"\n success_url = \"/pedidos/list_medio_pago?up\"\n" }, { "alpha_fraction": 0.6585264801979065, "alphanum_fraction": 0.6705297827720642, "avg_line_length": 29.9743595123291, "blob_id": "98a1dcb7085fa4a4c8ef458e0b6927fd687387f4", "content_id": "6599d088e72c25f30484defc1a537c78c955244c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2416, "license_type": "permissive", "max_line_length": 73, "num_lines": 78, "path": "/sis_gastronomico/gastos/models.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\nfrom django.db.models.signals import post_save\n\nfrom sis_gastronomico.empleados.models import Empleado\n\n# Create your models here.\n\n\nclass TipoGasto(models.Model):\n\n fecha_creacion = models.DateTimeField(auto_now_add=True)\n fecha_modificacion = models.DateTimeField(auto_now=True)\n tipo = models.CharField(max_length=35)\n descripcion = models.CharField(max_length=100)\n\n def __str__(self):\n return \"{:s}\".format(self.tipo)\n\n\nclass AdelantoSueldo(models.Model):\n monto_pagado = models.DecimalField(\n max_digits=7,\n decimal_places=2,\n validators=[MinValueValidator(0.0), MaxValueValidator(99999.99)],\n )\n empleado = models.ForeignKey(Empleado, on_delete=models.CASCADE)\n fecha_pago = models.DateField(auto_now=True)\n fecha_modificacion = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n verbose_name = \"Adelanto de sueldo\"\n verbose_name_plural = \"Adelanto de sueldos\"\n db_table = \"Adelanto_Sueldo\"\n\n def __str__(self):\n return \"{:d}\".format(self.monto_pagado)\n\n\nclass Gasto(models.Model):\n\n fecha_creacion = models.DateTimeField(auto_now_add=True)\n fecha_modificacion = models.DateTimeField(auto_now=True)\n descripcion = models.CharField(max_length=50)\n monto = models.DecimalField(\n max_digits=7,\n decimal_places=2,\n validators=[MinValueValidator(0.0), MaxValueValidator(99999.99)],\n )\n tipo_gasto = models.ForeignKey(\n TipoGasto, on_delete=models.CASCADE, verbose_name=\"Tipo Gasto\"\n )\n adelanto = models.ForeignKey(\n AdelantoSueldo, on_delete=models.CASCADE, null=True, blank=True\n )\n\n def __str__(self):\n return \"{:s}\".format(self.descripcion)\n\n\ndef save_adelanto(sender, instance, **kwargs):\n if not kwargs[\"created\"]:\n gasto = Gasto.objects.get(adelanto_id=instance.pk)\n gasto.monto = instance.monto_pagado\n gasto.save()\n else:\n gasto = Gasto()\n tipo_gasto, _ = TipoGasto.objects.get_or_create(\n tipo=\"adelanto de sueldo\", defaults={\"descripcion\": \"-\"}\n )\n gasto.tipo_gasto = tipo_gasto\n gasto.monto = instance.monto_pagado\n gasto.adelanto = instance\n gasto.descripcion = \"-\"\n gasto.save()\n\n\npost_save.connect(save_adelanto, sender=AdelantoSueldo)\n" }, { "alpha_fraction": 0.6153846383094788, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 22.399999618530273, "blob_id": "06472478354925345dd0c82cdef38819457e0866", "content_id": "1a931f11c53f03de5b18692e0a46602ee813466a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 702, "license_type": "permissive", "max_line_length": 87, "num_lines": 30, "path": "/sis_gastronomico/stocks/urls.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom sis_gastronomico.stocks.views import (\n ListStockInsumo,\n ListStockProducto,\n UpdateStockInsumo,\n UpdateStockProducto,\n)\n\napp_name = \"stocks\"\nurlpatterns = [\n path(\n \"list_stockInsumo/<int:pk>\", ListStockInsumo.as_view(), name=\"list_stockInsumo\"\n ),\n path(\n \"list_stockProducto/<int:pk>\",\n ListStockProducto.as_view(),\n name=\"list_stockProducto\",\n ),\n path(\n \"update_stockInsumo/<int:pk>\",\n UpdateStockInsumo.as_view(),\n name=\"update_stockInsumo\",\n ),\n path(\n \"update_stockProducto/<int:pk>\",\n UpdateStockProducto.as_view(),\n name=\"update_stockProducto\",\n ),\n]\n" }, { "alpha_fraction": 0.5098039507865906, "alphanum_fraction": 0.5630252361297607, "avg_line_length": 18.83333396911621, "blob_id": "f93be3a51577207cacc80f8d305e992dcf25ff18", "content_id": "d5d2590aab0950d431a6a9de1d60b8c30fe18cb3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 357, "license_type": "permissive", "max_line_length": 47, "num_lines": 18, "path": "/sis_gastronomico/turnos/migrations/0003_auto_20201226_1714.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.8 on 2020-12-26 17:14\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('turnos', '0002_turno_abierto'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='turno',\n old_name='abierto',\n new_name='activo',\n ),\n ]\n" }, { "alpha_fraction": 0.5472972989082336, "alphanum_fraction": 0.5484234094619751, "avg_line_length": 29.47058868408203, "blob_id": "2c2e8a8b8034c7f096f032b088e1a096907b27d3", "content_id": "3861470707ac084108f0a3aa8c2e457635aafa76", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6220, "license_type": "permissive", "max_line_length": 112, "num_lines": 204, "path": "/sis_gastronomico/compras/forms.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.core.exceptions import ValidationError\nfrom django.forms import ModelForm\nfrom django.forms.models import BaseInlineFormSet, inlineformset_factory\n\nfrom sis_gastronomico.compras.models import Compra, DetalleInsumo, DetalleProducto\nfrom sis_gastronomico.stocks.models import StockInsumo, StockProducto\n\n\nclass CompraForm(ModelForm):\n class Meta:\n model = Compra\n fields = \"__all__\"\n exclude = [\"gasto\"]\n\n\nclass DetalleInsumoForm(ModelForm):\n class Meta:\n model = DetalleInsumo\n fields = \"__all__\"\n\n def clean(self):\n\n cantidad = 0\n if \"cantidad\" in self.cleaned_data:\n cantidad = self.cleaned_data[\"cantidad\"]\n\n if self.get_stock_new_value() < 0:\n\n self.add_error(\n \"cantidad\",\n ValidationError(\n \"Cambiar la cantidad a %(new_cantidad)s provocaría que el stock quede en %(new_stock)s\",\n code=\"invalid\",\n params={\n \"new_cantidad\": cantidad,\n \"new_stock\": self.get_stock_new_value(),\n },\n ),\n )\n\n def get_stock_new_value(self):\n insumo = self.cleaned_data[\"insumo\"]\n stock_actual = (\n StockInsumo.objects.filter(insumo=insumo)\n .order_by(\"fecha_modificacion\")\n .last()\n )\n\n cantidad_stock_actual = stock_actual.cantidad\n cantidad_compra_nueva = self.cleaned_data[\"cantidad\"]\n\n if self.initial:\n cantidad_compra_vieja = self.initial[\"cantidad\"]\n cantidad_stock_nuevo = cantidad_stock_actual - (\n cantidad_compra_vieja - cantidad_compra_nueva\n )\n\n else:\n cantidad_compra_nueva = self.cleaned_data[\"cantidad\"]\n cantidad_stock_nuevo = cantidad_stock_actual + cantidad_compra_nueva\n\n return cantidad_stock_nuevo\n\n\nclass DetalleProductoForm(ModelForm):\n class Meta:\n model = DetalleProducto\n fields = \"__all__\"\n\n def clean(self):\n\n cantidad = 0\n if \"cantidad\" in self.cleaned_data:\n cantidad = self.cleaned_data[\"cantidad\"]\n if self.get_stock_new_value() < 0:\n\n self.add_error(\n \"cantidad\",\n ValidationError(\n \"Cambiar la cantidad a %(new_cantidad)s provocaría que el stock quede en %(new_stock)s\",\n code=\"invalid\",\n params={\n \"new_cantidad\": cantidad,\n \"new_stock\": self.get_stock_new_value(),\n },\n ),\n )\n\n def get_stock_new_value(self):\n producto = self.cleaned_data[\"producto\"]\n stock_actual = (\n StockProducto.objects.filter(producto=producto)\n .order_by(\"fecha_modificacion\")\n .last()\n )\n\n cantidad_stock_actual = stock_actual.cantidad\n cantidad_compra_nueva = self.cleaned_data[\"cantidad\"]\n\n if self.initial:\n # En este caso es un UPDATE\n cantidad_compra_vieja = self.initial[\"cantidad\"]\n cantidad_stock_nuevo = max(\n 0,\n cantidad_stock_actual - (cantidad_compra_vieja - cantidad_compra_nueva),\n )\n\n else:\n cantidad_compra_nueva = self.cleaned_data[\"cantidad\"]\n cantidad_stock_nuevo = cantidad_stock_actual + cantidad_compra_nueva\n\n return cantidad_stock_nuevo\n\n\nclass BaseInlineInsumoFormSet(BaseInlineFormSet):\n def save_new(self, form, commit):\n stock = StockInsumo()\n stock.insumo = form.cleaned_data[\"insumo\"]\n stock.cantidad = form.get_stock_new_value()\n\n super().save_new(form, commit)\n stock.save()\n\n def save_existing(self, form, instance, commit):\n stock = StockInsumo()\n stock.insumo = form.cleaned_data[\"insumo\"]\n stock.cantidad = form.get_stock_new_value()\n\n super().save_existing(form, instance, commit)\n stock.save()\n\n def clean(self):\n if any(self.errors):\n return\n insumos = []\n for form in self.forms:\n if form.cleaned_data:\n if form.cleaned_data[\"DELETE\"]:\n continue\n\n insumo = form.cleaned_data[\"insumo\"]\n if insumo in insumos:\n form.add_error(\n \"insumo\", \"No puede haber más de uno del mismo insumo\"\n )\n else:\n insumos.append(insumo)\n\n\nclass BaseInlineProductoFormSet(BaseInlineFormSet):\n def save_new(self, form, commit):\n stock = StockProducto()\n stock.producto = form.cleaned_data[\"producto\"]\n stock.cantidad = form.get_stock_new_value()\n\n super().save_new(form, commit)\n stock.save()\n\n def save_existing(self, form, instance, commit):\n stock = StockProducto()\n stock.producto = form.cleaned_data[\"producto\"]\n stock.cantidad = form.get_stock_new_value()\n\n super().save_existing(form, instance, commit)\n stock.save()\n\n def clean(self):\n\n if any(self.errors):\n return\n productos = []\n for form in self.forms:\n if form.cleaned_data:\n if form.cleaned_data[\"DELETE\"]:\n continue\n\n producto = form.cleaned_data[\"producto\"]\n if producto in productos:\n form.add_error(\n \"producto\", \"No puede haber más de uno del mismo producto\"\n )\n else:\n productos.append(producto)\n\n\nDetalleInsumoFormSet = inlineformset_factory(\n Compra,\n DetalleInsumo,\n can_delete=True,\n extra=1,\n fields=\"__all__\",\n formset=BaseInlineInsumoFormSet,\n form=DetalleInsumoForm,\n)\n\nDetalleProductoFormSet = inlineformset_factory(\n Compra,\n DetalleProducto,\n can_delete=True,\n extra=1,\n fields=\"__all__\",\n formset=BaseInlineProductoFormSet,\n form=DetalleProductoForm,\n)\n" }, { "alpha_fraction": 0.6127694845199585, "alphanum_fraction": 0.6384742856025696, "avg_line_length": 26.409090042114258, "blob_id": "cfd69fa902894f8b31c03ea414a4abbc2fb5eeaa", "content_id": "3c005e6620c05acef840a0b726f1a6b1c2dee708", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1206, "license_type": "permissive", "max_line_length": 80, "num_lines": 44, "path": "/sis_gastronomico/proveedores/models.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.core.validators import (\n MaxLengthValidator,\n MaxValueValidator,\n MinLengthValidator,\n MinValueValidator,\n)\nfrom django.db import models\n\n\n# Create your models here.\nclass Proveedor(models.Model):\n nombre = models.CharField(\n max_length=75,\n null=False,\n blank=False,\n validators=[MinLengthValidator(3), MaxLengthValidator(75)],\n )\n\n direccion = models.CharField(\n max_length=100,\n null=False,\n blank=False,\n validators=[MinLengthValidator(3), MaxLengthValidator(100)],\n )\n\n telefono = models.BigIntegerField(\n unique=True,\n blank=False,\n null=False,\n validators=[\n MaxValueValidator(9999999999, message=\"Ingrese un telefono valido\"),\n MinValueValidator(111111111, message=\"Ingrese un telefono valido\"),\n ],\n )\n fecha_creacion = models.DateTimeField(auto_now_add=True)\n fecha_modificacion = models.DateTimeField(auto_now=True)\n\n class Meta:\n verbose_name = \"Proveedor\"\n verbose_name_plural = \"Proveedores\"\n db_table = \"proveedores\"\n\n def __str__(self):\n return \"{:s}, {:s}\".format(self.nombre, self.direccion)\n" }, { "alpha_fraction": 0.6909547448158264, "alphanum_fraction": 0.6917923092842102, "avg_line_length": 28.121952056884766, "blob_id": "982475766539180bb16ae6a1b92a2f8d3d2e03cf", "content_id": "193040cbc355d4a21c4d1e10d9cf2f8cf5e395e4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1194, "license_type": "permissive", "max_line_length": 77, "num_lines": 41, "path": "/sis_gastronomico/productos/forms.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.forms import ModelForm, TextInput\nfrom django.forms.models import inlineformset_factory\n\nfrom sis_gastronomico.productos.models import Producto, TipoProducto\nfrom sis_gastronomico.stocks.forms import StockProductoForm\nfrom sis_gastronomico.stocks.models import StockProducto\n\n\nclass ProductoForm(ModelForm):\n class Meta:\n model = Producto\n fields = \"__all__\"\n widgets = {\"descripcion\": TextInput(attrs={\"class\": \"autocomplete\"})}\n\n def clean_nombre(self, *args, **kwargs):\n return self.cleaned_data.get(\"nombre\").lower()\n\n def clean_descripcion(self, *args, **kwargs):\n return self.cleaned_data.get(\"descripcion\").lower()\n\n\nclass TipoProductoForm(ModelForm):\n class Meta:\n model = TipoProducto\n exclude = [\"fecha_creacion\", \"fecha_modificacion\"]\n\n def clean_tipo(self, *args, **kwargs):\n return self.cleaned_data.get(\"tipo\").lower()\n\n def clean_descripcion(self, *args, **kwargs):\n return self.cleaned_data.get(\"descripcion\").lower()\n\n\nStockProductoFormSet = inlineformset_factory(\n Producto,\n StockProducto,\n form=StockProductoForm,\n can_delete=True,\n extra=1,\n fields=\"__all__\",\n)\n" }, { "alpha_fraction": 0.6040171980857849, "alphanum_fraction": 0.6370157599449158, "avg_line_length": 43.967742919921875, "blob_id": "fde521164fc9426eaf74c4091687f74cbf2d1c8c", "content_id": "efc9f2da9d17cbf9c0dbb90d3637e4dad53f8407", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1394, "license_type": "permissive", "max_line_length": 262, "num_lines": 31, "path": "/sis_gastronomico/proveedores/migrations/0001_initial.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.8 on 2020-12-16 17:30\n\nimport django.core.validators\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='Proveedor',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('nombre', models.CharField(max_length=75, validators=[django.core.validators.MinLengthValidator(3), django.core.validators.MaxLengthValidator(75)])),\n ('direccion', models.CharField(max_length=100, validators=[django.core.validators.MinLengthValidator(3), django.core.validators.MaxLengthValidator(100)])),\n ('telefono', models.BigIntegerField(unique=True, validators=[django.core.validators.MaxValueValidator(9999999999, message='Ingrese un telefono valido'), django.core.validators.MinValueValidator(111111111, message='Ingrese un telefono valido')])),\n ('fecha_creacion', models.DateTimeField(auto_now_add=True)),\n ('fecha_modificacion', models.DateTimeField(auto_now=True)),\n ],\n options={\n 'verbose_name': 'Proveedor',\n 'verbose_name_plural': 'Proveedores',\n 'db_table': 'proveedores',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.7201834917068481, "alphanum_fraction": 0.7220183610916138, "avg_line_length": 24.34883689880371, "blob_id": "ac9eced8bc083906d37b08b4020131cf73b34497", "content_id": "5025194cdf44d61dcb272c5fc4c9ef919146afe8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2180, "license_type": "permissive", "max_line_length": 72, "num_lines": 86, "path": "/sis_gastronomico/turnos/views.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic.edit import CreateView, DeleteView, UpdateView\nfrom django.views.generic.list import ListView\n\nfrom sis_gastronomico.turnos.forms import HorarioForm, TurnoForm\nfrom sis_gastronomico.turnos.models import Horario, Turno\n\n# Create your views here.\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass CreateHorario(CreateView):\n\n model = Horario\n form_class = HorarioForm\n template_name = \"turnos/horario_form.html\"\n success_url = \"/turnos/list_horario?ok\"\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass CreateTurno(CreateView):\n\n model = Turno\n form_class = TurnoForm\n template_name = \"turnos/turno_form.html\"\n success_url = \"/turnos/?ok\"\n\n\nclass DeleteTurno(DeleteView):\n\n model = Turno\n template_name = \"turnos/delete_turno.html\"\n success_url = \"/turnos/?del\"\n\n\nclass DeleteHorario(DeleteView):\n\n model = Horario\n template_name = \"turnos/delete_horario.html\"\n success_url = \"/turnos/list_horario?del\"\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass ListHorario(ListView):\n\n model = Horario\n paginate_by = 10\n template_name = \"turnos/list_horario.html\"\n\n def get_queryset(self):\n return Horario.objects.all().order_by(\"desde\")\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass ListTurno(ListView):\n\n model = Turno\n paginate_by = 10\n template_name = \"turnos/list_turno.html\"\n\n def get_queryset(self):\n return Turno.objects.all().order_by(\"-fecha\", \"-fecha_creacion\")\n\n\ndef no_active_turno(request):\n return render(request, \"turnos/no_active_turno.html\")\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UpdateHorario(UpdateView):\n\n model = Horario\n form_class = HorarioForm\n template_name = \"turnos/horario_form.html\"\n success_url = \"/turnos/list_horario?up\"\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UpdateTurno(UpdateView):\n\n model = Turno\n form_class = TurnoForm\n template_name = \"turnos/turno_form.html\"\n success_url = \"/turnos/?up\"\n" }, { "alpha_fraction": 0.7348484992980957, "alphanum_fraction": 0.7348484992980957, "avg_line_length": 21, "blob_id": "6ab5ec824e01e79a3006450a708b5b7da9e24c83", "content_id": "e4558003f45fc0d168c9069761ddee6269437a7d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 132, "license_type": "permissive", "max_line_length": 36, "num_lines": 6, "path": "/sis_gastronomico/gastos/apps.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass GastosConfig(AppConfig):\n name = \"sis_gastronomico.gastos\"\n verbose_name = \"Gastos\"\n" }, { "alpha_fraction": 0.7224669456481934, "alphanum_fraction": 0.7239353656768799, "avg_line_length": 25.705883026123047, "blob_id": "c55e8ce9918f86b72cf60715a22d9ca8509a3766", "content_id": "7fb8c84f70fa3c9745ce69d02c7db3a135e29b8d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1362, "license_type": "permissive", "max_line_length": 72, "num_lines": 51, "path": "/sis_gastronomico/empleados/views.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import redirect\nfrom django.utils.decorators import method_decorator\nfrom django.views import generic\n\nfrom .forms import EmpleadoForm\nfrom .models import Empleado\n\n# Create your views here.\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass ListEmpleado(generic.ListView):\n\n model = Empleado\n template_name = \"empleados/inicio.html\"\n paginate_by = 10\n\n def get_queryset(self):\n return Empleado.objects.filter(estado=True).order_by(\"apellido\")\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass CreateEmpleado(generic.CreateView):\n\n model = Empleado\n form_class = EmpleadoForm\n template_name = \"empleados/crear.html\"\n success_url = \"/empleados/?ok\"\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UpdateEmpleado(generic.UpdateView):\n\n model = Empleado\n form_class = EmpleadoForm\n template_name = \"empleados/crear.html\"\n success_url = \"/empleados/?up\"\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass DeleteEmpleado(generic.DeleteView):\n\n model = Empleado\n template_name = \"empleados/delete_empleado.html\"\n\n def post(self, request, *args, **kwars):\n self.object = self.get_object()\n self.object.estado = False\n self.object.save()\n return redirect(\"/empleados/?del\")\n" }, { "alpha_fraction": 0.7124752402305603, "alphanum_fraction": 0.7140594124794006, "avg_line_length": 33.121620178222656, "blob_id": "ca8855382e1d9f5db609992f03b6c86771f8517f", "content_id": "cb9a217a29cd84e362dfd38df76a6088f98b8017", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2525, "license_type": "permissive", "max_line_length": 83, "num_lines": 74, "path": "/sis_gastronomico/proveedores/views.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import HttpResponseRedirect, render\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic.edit import CreateView, DeleteView, UpdateView\nfrom django.views.generic.list import ListView\n\nfrom sis_gastronomico.proveedores.forms import ProveedorForm\nfrom sis_gastronomico.proveedores.models import Proveedor\n\n\n@method_decorator(login_required, name=\"dispatch\")\ndef index(request):\n proveedores = Proveedor.objects.all().order_by(\"-fecha_modificacion\")[:10]\n # for proveedor in proveedores:\n # proveedor.descripcion = proveedor.descripcion.title()\n\n return render(request, \"proveedores/index.html\", {\"proveedores\": proveedores})\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass ListarProveedores(ListView):\n\n model = Proveedor\n paginate_by = 10\n template_name = \"proveedores/listar_proveedores.html\"\n\n def get_queryset(self):\n return Proveedor.objects.all().order_by(\"-fecha_modificacion\")\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass CrearProveedor(CreateView):\n\n model = Proveedor\n form_class = ProveedorForm\n template_name = \"proveedores/proveedores_form.html\"\n success_url = \"/proveedores/?ok\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n proveedores = set()\n for proveedor in Proveedor.objects.values_list(\"nombre\", flat=True):\n proveedores.add(proveedor.title())\n context[\"proveedores\"] = proveedores\n return context\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass BorrarProveedor(DeleteView):\n\n model = Proveedor\n template_name = \"proveedores/borrar_proveedor.html\"\n success_url = \"/proveedores/?del\"\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n self.object.delete()\n return HttpResponseRedirect(self.get_success_url())\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UpdateProveedor(UpdateView):\n model = Proveedor\n form_class = ProveedorForm\n template_name = \"proveedores/proveedores_form.html\"\n success_url = \"/proveedores/?up\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n proveedores = set()\n # for proveedor in Proveedor.objects.values_list(\"descripcion\", flat=True):\n # proveedores.add(proveedor.title())\n context[\"proveedores\"] = proveedores\n return context\n" }, { "alpha_fraction": 0.707317054271698, "alphanum_fraction": 0.707317054271698, "avg_line_length": 22.428571701049805, "blob_id": "130638984918f31ca971d6a0341bed2bad8e0e65", "content_id": "5bae8ff5a10c9bf41c3ea501877ffe3cc8c30326", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 164, "license_type": "permissive", "max_line_length": 39, "num_lines": 7, "path": "/sis_gastronomico/productos/apps.py", "repo_name": "franciscorgodoy/sistema-gastronomico", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass ProductosConfig(AppConfig):\n name = \"sis_gastronomico.productos\"\n # label = 'my.foo'\n verbose_name = \"Productos\"\n" } ]
67
Yauhenija-Umet/LR0
https://github.com/Yauhenija-Umet/LR0
63c2ab0153686b92881ee7bc9992ccf845926ba2
32e2336b140ec9e5963fa01e51566198b83f7d69
fab4e900615126abcc0173ef5a5b026738d4a0fc
refs/heads/main
2023-03-12T08:07:58.171683
2021-02-27T15:48:15
2021-02-27T15:48:15
341,577,333
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5984848737716675, "alphanum_fraction": 0.6482684016227722, "avg_line_length": 22.3157901763916, "blob_id": "6c090098b6890da16038065dc105bb255c23e2d2", "content_id": "d12f1972557337afddce009d8eebb4a2f818df95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 990, "license_type": "no_license", "max_line_length": 55, "num_lines": 38, "path": "/bmi_calculator.py", "repo_name": "Yauhenija-Umet/LR0", "src_encoding": "UTF-8", "text": "name1 = 'Марина'\r\nheight1 = 1.70\r\nweight1 = 61\r\n\r\nname2 = 'Саня'\r\nheight2 = 1.70\r\nweight2 = 70\r\n\r\nname3 = 'Лена'\r\nheight3 = 1.70\r\nweight3 = 75\r\n\r\ndef calculate_bmi(height, weight):\r\n return weight / height**2\r\n\r\ndef show_person_bmi(name, height, weight):\r\n bmi = calculate_bmi(height, weight)\r\n print('%s: индекс массы тела = %.2f' % (name, bmi))\r\n\r\ndef get_advice_on_bmi(bmi):\r\n if bmi <= 25:\r\n return 'может скушать пончик'\r\n else: \r\n return 'пора садиться на диету'\r\n\r\ndef show_advice_on_bmi(name, height, weight):\r\n bmi = calculate_bmi(height, weight)\r\n advice = get_advice_on_bmi(bmi)\r\n print(f\"{name} {advice}\")\r\n\r\nshow_person_bmi(name1, height1, weight1)\r\nshow_advice_on_bmi(name1, height1, weight1)\r\n\r\nshow_person_bmi(name2, height2, weight2)\r\nshow_advice_on_bmi(name2, height2, weight2)\r\n\r\nshow_person_bmi(name3, height3, weight3)\r\nshow_advice_on_bmi(name3, height3, weight3)\r\n" } ]
1
rshen91/CS-Data-Structures-Assessment
https://github.com/rshen91/CS-Data-Structures-Assessment
4acfedecac700ef360a4191c5b96f982f78d5451
8d2c2a4fc81bc95001f8783450303bdfc6856823
dc0552ab7db11fbc3474fc4b63c1b9ff33c08fa4
refs/heads/master
2016-09-21T01:07:03.202956
2016-08-29T00:17:54
2016-08-29T00:17:54
66,797,729
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6658536791801453, "alphanum_fraction": 0.672764241695404, "avg_line_length": 56.20930099487305, "blob_id": "c99221847255a8e1507072b24c9c071e8f5a2a64", "content_id": "31d459c26e5e48de8f69c915d6ca921e10844fa6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2460, "license_type": "no_license", "max_line_length": 83, "num_lines": 43, "path": "/discussion_questions.py", "repo_name": "rshen91/CS-Data-Structures-Assessment", "src_encoding": "UTF-8", "text": "################################################################################\n######################CS DATA STRUCTURES ASSESSMENT#############################\n################################################################################\n# Part 1: Discussion Questions\n# Runtime\n# 1. The workload is the amount of items you have to iterate through in a list. In \n# the case of animal crackers to find the first instance of an elephant, the worst\n# case scenario is O(n) because you would assume that if an elephant were not to \n# exist in the cracker container you'd go through the entire container. \n# 2. O(1) > O(log n) > O(n) > O(n log n) > O(n^2) > O(2^n) \n# \n# Stacks and Queues\n# 1. The process of loading and unloading pallets onto a flatbed trusk: stack\n# 2. Putting bottle caps on bottles of beer as they roll down: queue\n# 3. Calculating the solution to this mathematical expression: stack \n# 2. Queue: I like the idea of the help queue at Hackbright and also the subway \n# line across the street during lunch\n# 3. Stack: I like the undo button example mentioned in lecture and another one \n# could be unloading groceries from a trunk of a car\n#\n#Linked Lists\n# 1. The nodes are \"Apple\", \"Berry\", and \"Cherry\" and the data are the same. \n# Each node has the data and the next that references the next node or references\n# None if it's at the tail. The head is the node \"Apple\" since the head is \n# referencing \"Apple\". The tail is \"Cherry\" since the node references None versus\n# another node.\n# 2. The a singly linked list is like the example above where each node references\n# only one direction. A doubly linked list references the next node and the \n# previous node. \n# 3. Instead of having to find the last node by iterating through each node, you\n# can just see what the tail references and change the reference to a new node. \n#\n# Trees\n# 1. [food] [Italian, Indian, Mexican] [Indian, Mexican, lasagna, pizza] \n# [Mexican, lasagna, pizza, tikka masala, saag] \n# [lasagna, pizza, tikka masala, saag, burrito!] < -- YAY!\n# 2. [food] [Italian, Indian, Mexican] then go through the entire Mexican node,\n# then the Indian node, and finally hit up the Italian node. Since the DFS would \n# work right to left, Chicago-style would be found before exploring the lasagna\n# node. \n# 3. A BST is differen because each node has two nodes and it's sorted in a way \n# that makes sense (eg. alphabetically with the root node being the middle \n# letter).\n" }, { "alpha_fraction": 0.4575757682323456, "alphanum_fraction": 0.46262624859809875, "avg_line_length": 26.303447723388672, "blob_id": "967da319cf202d935472f15a2439a6e20a82d05a", "content_id": "9164b75eb5997272779289b2d29712a32fbe1444", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3960, "license_type": "no_license", "max_line_length": 85, "num_lines": 145, "path": "/tree.py", "repo_name": "rshen91/CS-Data-Structures-Assessment", "src_encoding": "UTF-8", "text": "\"\"\"Tree class and tree node class.\"\"\"\n\n\nclass Node(object): #new class called Node \n \"\"\"Node in a tree.\"\"\"\n\n def __init__(self, data, children=None):\n children = children or []\n assert isinstance(children, list), \\\n \"children must be a list!\"\n self.data = data #data \n self.children = children #it's got kids\n\n def __repr__(self):\n \"\"\"Reader-friendly representation.\"\"\"\n\n return \"<Node %s>\" % self.data\n\n def get_num_children(self):\n \"\"\"Get number of children.\n\n For example::\n\n >>> a = Node(\"A\", [Node(\"B\"), Node(\"C\")])\n >>> a.get_num_children()\n 2\n \"\"\"\n\n to_visit = [self.children] #we can count as it visits the kids\n i = 1 # start the counter at one since it's got a kid \n\n while to_visit: #while there is something to visit\n i += 1 #count it\n node = to_visit.pop() #pop it once it's counted\n\n return i\n\n\nclass Tree(object):\n \"\"\"Tree.\"\"\"\n\n def __init__(self, root):\n self.root = root\n\n def __repr__(self):\n \"\"\"Reader-friendly representation.\"\"\"\n\n return \"<Tree root=%s>\" % self.root\n\n def depth_first_search(self, data):\n \"\"\"Return node object with this data, traversing the tree breadth-first.\n\n Start here (on this node), and return None if not found.\n\n Let's make a tree where we have two \"B\" nodes, but where one is far down an\n earlier branch and the other is higher-up in an earlier branch. Since this is\n a BFS, we should find the b2 node for \"B\"::\n\n A\n / \\\n C E\n / \\\n D B2\n /\n B1\n\n >>> a = Node(\"A\")\n >>> b1 = Node(\"B\")\n >>> b2 = Node(\"B\")\n >>> c = Node(\"C\")\n >>> d = Node(\"D\")\n >>> e = Node(\"E\")\n >>> a.depth_first_search = [c, e]\n >>> c.depth_first_search = [d]\n >>> d.depth_first_search = [b2]\n >>> e.depth_first_search = [b1]\n >>> tree = Tree(a)\n\n >>> tree.breadth_first_search(\"B\") is b2\n False\n\n \"\"\"\n\n to_visit = [self.root]\n\n while to_visit:\n node = to_visit.pop() #pop at the end\n\n if node.data == data:\n return node\n\n to_visit.extend(node.children)\n\n\n def breadth_first_search(self, data):\n \"\"\"Return node object with this data, traversing the tree breadth-first.\n\n Start here (on this node), and return None if not found.\n\n Let's make a tree where we have two \"B\" nodes, but where one is far down an\n earlier branch and the other is higher-up in an earlier branch. Since this is\n a BFS, we should find the b2 node for \"B\"::\n\n A\n / \\\n C E\n / \\\n D B2\n /\n B1\n\n >>> a = Node(\"A\")\n >>> b2 = Node(\"B\")\n >>> b1 = Node(\"B\")\n >>> c = Node(\"C\")\n >>> d = Node(\"D\")\n >>> e = Node(\"E\")\n >>> a.breadth_first_search = [c, e]\n >>> b.breadth_first_search = [d]\n >>> c.breadth_first_search = [b2]\n >>> d.breadth_first_search = [b1]\n >>> tree = Tree(a)\n\n >>> tree.breadth_first_search(\"B\") is b2\n True\n\n \"\"\"\n to_visit = [self.root]\n\n while to_visit:\n node = to_visit.pop(0) #pop at the front versus DFS which pops at the end\n\n if node.data == data:\n return node\n\n to_visit.extend(node.children)\n\nif __name__ == \"__main__\":\n import doctest\n\n print\n result = doctest.testmod()\n if not result.failed:\n print \"ALL TESTS PASSED. GOOD WORK!\"\n print\n\n" }, { "alpha_fraction": 0.5250537991523743, "alphanum_fraction": 0.5275130867958069, "avg_line_length": 26.794872283935547, "blob_id": "fe92cb0028f0bdbca85bc5ad07ac3de42ac5a2c7", "content_id": "327bbc8e796bfe5b410a03033151b576b56f0ed0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3253, "license_type": "no_license", "max_line_length": 115, "num_lines": 117, "path": "/linkedlist.py", "repo_name": "rshen91/CS-Data-Structures-Assessment", "src_encoding": "UTF-8", "text": "# Linked list with Node/LinkedList classes\n\n\nclass Node(object):\n \"\"\"Node in a linked list.\"\"\"\n\n def __init__(self, data):\n self.data = data #initiate \n self.next = None #the tail references None\n\n def __repr__(self):\n return \"<Node %s>\" % self.data\n\n\nclass LinkedList(object):\n \"\"\"Linked List using head and tail.\"\"\"\n\n def __init__(self): # empty LL\n self.head = None \n self.tail = None\n\n def add_node(self, data):\n \"\"\"Add node with data to end of list.\"\"\"\n\n new_node = Node(data) # new instance in Node\n\n if self.head is None:\n self.head = new_node # add the node to the head\n\n if self.tail is not None: # if the tail is not pointing None\n self.tail.next = new_node # the tail now is pointing to new node?\n\n self.tail = new_node # tail is now where we added the new node\n\n def remove_node_by_index(self, index):\n \"\"\"Remove node with given index.\"\"\"\n\n prev = None # making prev and it's None\n node = self.head # node is now the head\n i = 0 # heres a counter\n\n while (node is not None) and (i < index): # the node is not None and the counter is less than the parameter\n prev = node # prev is now node\n node = node.next # node is now the next node\n i += 1 #increment\n\n if prev is None: # the first time through if\n self.head = node.next # now prev becomes next node\n else:\n prev.next = node.next \n\n def find_node(self, data):\n \"\"\"Is a matching node in the list?\"\"\"\n\n current = self.head #current is set at the head of LL\n\n while current is not None: # current is not None \n if current.data == data: \n return True\n\n current = current.next\n\n return False\n\n def print_list(self):\n \"\"\"Print all items in the list::\n\n >>> ll = LinkedList()\n >>> ll.add_node('dog')\n >>> ll.add_node('cat')\n >>> ll.add_node('fish')\n\n >>> ll.print_list()\n dog\n cat\n fish\n \"\"\"\n current = self.head\n while current != None:\n print current.data\n current = current.next\n\n def get_node_by_index(self, idx):\n \"\"\"Return a node with the given index::\n\n >>> ll = LinkedList()\n >>> ll.add_node('dog')\n >>> ll.add_node('cat')\n >>> ll.add_node('fish')\n\n >>> ll.get_node_by_index(0)\n <Node dog>\n\n >>> ll.get_node_by_index(2)\n <Node fish>\n \"\"\"\n prev = None #make prev \n node = self.head # set node to the head\n i = 0 # count at 0\n\n while (node is not None) and (i < idx): #node is not the tail and the counter is not at idx\n prev = node # make the prev the node \n node = node.next #now it's the next one\n i += 1 #increment by 1\n\n if node == idx: #want the node to be the same as idx\n return node.data #return it\n\n\nif __name__ == \"__main__\":\n import doctest\n\n print\n result = doctest.testmod()\n if not result.failed:\n print \"ALL TESTS PASSED. GOOD WORK!\"\n print\n\n" } ]
3
Janki170695/Python_Exercises
https://github.com/Janki170695/Python_Exercises
92f20ce47268e6f986610b5f5c670c5bfc551541
a9a5a74a254367781c18566d88eaf1b8ba8e5a0b
5a54fb2031e8618cc03369f01c99a6c43c662272
refs/heads/master
2022-12-25T09:49:23.344470
2020-09-23T02:20:27
2020-09-23T02:20:27
297,806,030
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6036550402641296, "alphanum_fraction": 0.6507709622383118, "avg_line_length": 14.155843734741211, "blob_id": "e80ccf09d466b01253cf1893a6607d51835f94e9", "content_id": "4a2226ec3b5e970a71ab8b7b8b7f74b0d201c785", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3502, "license_type": "no_license", "max_line_length": 269, "num_lines": 231, "path": "/Exercise 2.1a (Objects) V51.py", "repo_name": "Janki170695/Python_Exercises", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# <div style=\"background-color:black;\">\n# <img src=\"https://static.wixstatic.com/media/e99c3b_bf7763d953434005b731c2137dcad343~mv2.png/v1/fill/w_444,h_80,al_c,q_85,usm_0.66_1.00_0.01/TRADECRAFT-logo65-White.webp\" width=\"300\">\n# </div>\n\n# In[ ]:\n\n\n## Object Types\nAn object's type determines the operations that the object supports (e.g., \"does it have a length?\") and also defines the possible values for objects of that type. Every object in Python has a type. Its type can be discovered by calling the *type()* built-in function. \n\nShow the object type for each of the following:\n- 5\n- 3.27\n- \"True\"\n- True\n\n\n# In[1]:\n\n\ntype(5) # Replace the dash with a value.\n\n\n# In[2]:\n\n\ntype(3.27)\n\n\n# In[3]:\n\n\ntype(\"True\")\n\n\n# In[6]:\n\n\ntype(True)\n\n\n# What is the result of this command? Explain why (in a comment in the code below)\n\n# In[5]:\n\n\nint(5.7)\n\n\n# In[ ]:\n\n\n##The function \"int\" converts the float value 5.7 to 5 .\n\n\n# Change the integer **5** into a string and then show its type:\n\n# In[7]:\n\n\ntype(str(5)) # Replace the dashes with the required function names.\n\n\n# Try running this operation. \n# What is the result and why? (explain in a comment in the code below)\n\n# In[8]:\n\n\n5 + \"5\"\n\n\n# In[ ]:\n\n\n##The above statement throws an error because the datatype of both the arguments are different.\n##Addition or concatenation cannot be performed between a string and an integer.\n\n\n# Modify the two versions below so they will work. Explain the different result (in a comment in the code below)\n\n# In[9]:\n\n\nstr(5) + \"5\"\n\n\n# In[ ]:\n\n\n##Here concatenation is performed between two arguments after converting \"integer\" value to \"string\".\n\n\n# In[10]:\n\n\n5 + int(\"5\")\n\n\n# In[ ]:\n\n\n##Here addition is performed between two arguments after converting \"string\" value to \"integer\".\n\n\n# -----------------\n# <h2>Arithmetic</h2>\n# \n# <p>Like every programming language, Python is a good calculator. Print out one calculation for each of these basic operations:</p> \n# \n# <ul>\n# <li>Addition</li>\n# <li>Subtraction</li>\n# <li>Multiplication</li>\n# <li>Division</li>\n# <li>Exponents</li>\n# </ul> \n\n# In[11]:\n\n\nprint(10+10)\n\n\n# In[12]:\n\n\nprint(10000-1000)\n\n\n# In[13]:\n\n\nprint(456*789)\n\n\n# In[27]:\n\n\nprint(28//7)\n\n\n# In[18]:\n\n\nprint(2**3)\n\n\n# * Calculate **0.1 + 0.2** Is this the answer you would expect? \n\n# In[19]:\n\n\n0.1+0.2\n\n\n# In[ ]:\n\n\n##Generally, everyone would assume the output to be 0.3, but it does not work that way with python interpreter.\n##In binary with base-2, we can cleanly express the fractions that has denominator as 2, while rest would be repeating decimals.\n##When we perform math over such fractions, it will have leftovers when we try to convert base-2 to base-10 representation.\n\n\n# * Calculate **round(0.1 + 0.2, 1)** What does the *round()* function do? \n\n# In[22]:\n\n\nround(0.1+.2,1)\n\n\n# In[ ]:\n\n\n##The function round() is used to round the numbers by desired precision. Here, it rounds off to one digit precision.\n\n\n# ## Order of Operations\n# \n# Perform these calculations and explain the results in each case in a comment following the code.\n\n# In[23]:\n\n\n3 + 7 // 2\n\n\n# In[ ]:\n\n\n##Precedance of Division // is higher than addition +.(Also // performs the floor division)\n\n\n# In[24]:\n\n\n(3 + 7) // 2\n\n\n# In[ ]:\n\n\n##Precedence of () is higher than //\n\n\n# In[25]:\n\n\n3 + 7 % 2\n\n\n# In[ ]:\n\n\n## Precedence of Modulus % is greater than addition +. \n\n\n# In[26]:\n\n\n(3 + 7) % 2\n\n\n# In[ ]:\n\n\n## Precedence of () is higher than %.\n\n" } ]
1
EdenStabbfer/Life_Simulation
https://github.com/EdenStabbfer/Life_Simulation
ec6f6085f7dd3ee2c9b412be1e764491f9fea5ff
1346b1f057778f58372b90ee71fb28042c675c87
0c35ce02dfe91d9e351ddd862bb72acce9a7ed9c
refs/heads/main
2023-02-14T22:49:07.788388
2021-01-07T11:46:46
2021-01-07T11:46:46
325,259,169
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5315315127372742, "alphanum_fraction": 0.545045018196106, "avg_line_length": 31.647058486938477, "blob_id": "92ffb4e4d26e330aa4b772859f5cec4f0cff9b39", "content_id": "0c5d690700cb36e191c38898d1538c1afdcc9475", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1132, "license_type": "no_license", "max_line_length": 97, "num_lines": 34, "path": "/ball.py", "repo_name": "EdenStabbfer/Life_Simulation", "src_encoding": "UTF-8", "text": "import pygame as pg\nfrom game_functions import id_gen\nimport numpy as np\nimport pygame.gfxdraw\n\n\n# Просто клетка (без подвида)\nclass Ball(pg.sprite.Sprite):\n def __init__(self, screen, rect, velocity):\n super().__init__()\n self.screen = screen\n self.rect = rect\n self.x, self.y = rect.centerx, rect.centery\n self.radius = rect.width//2\n self.velocity = velocity\n self.id = id_gen()\n\n def update(self):\n dir_x, dir_y = pg.mouse.get_pos()\n dist = ((dir_x - self.x)**2 + (dir_y - self.y)**2) ** 0.5\n\n if dist <= self.velocity:\n self.x, self.y = dir_x, dir_y\n else:\n dx = dir_x - self.x\n dy = dir_y - self.y\n norm = np.linalg.norm((dx, dy)).item()\n dx, dy = dx / norm, dy / norm\n self.x += dx * self.velocity\n self.y += dy * self.velocity\n\n def draw_me(self):\n pg.gfxdraw.aacircle(self.screen, int(self.x), int(self.y), self.radius, (0, 200, 0))\n pg.gfxdraw.filled_circle(self.screen, int(self.x), int(self.y), self.radius, (0, 200, 0))\n" }, { "alpha_fraction": 0.4680851101875305, "alphanum_fraction": 0.6382978558540344, "avg_line_length": 22.5, "blob_id": "6942d70e4a539545de4396f5475a537a24f96244", "content_id": "8c9fea4f37e851949fc05df1424f1b83ac05da74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 117, "license_type": "no_license", "max_line_length": 35, "num_lines": 4, "path": "/settings.py", "repo_name": "EdenStabbfer/Life_Simulation", "src_encoding": "UTF-8", "text": "\"\"\"\" Насройки игры и постоянные \"\"\"\n\nscreen_size = (1280, 720)\nscreen_color = (255, 255, 255)\n" }, { "alpha_fraction": 0.47668394446372986, "alphanum_fraction": 0.5077720284461975, "avg_line_length": 21.44186019897461, "blob_id": "5caa3d2190f01c335e7668ced925ff38fbefdab6", "content_id": "fbb6568eeb15e6bfb8625b7f171a5accfe25d56a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 965, "license_type": "no_license", "max_line_length": 75, "num_lines": 43, "path": "/game_functions.py", "repo_name": "EdenStabbfer/Life_Simulation", "src_encoding": "UTF-8", "text": "import pygame as pg\nfrom math import atan, cos, sin, pi\n\ncells_numb = 0\n\n\ndef key_down_event(event):\n pass\n\n\ndef key_up_event(event):\n pass\n\n\ndef game_events():\n for e in pg.event.get():\n if e.type == pg.QUIT:\n pg.quit()\n quit()\n if e.type == pg.KEYDOWN:\n key_down_event(e)\n if e.type == pg.KEYUP:\n key_up_event(e)\n\n\ndef id_gen():\n global cells_numb\n cells_numb += 1\n return cells_numb - 1\n\n\ndef collision_detect(group1, group2):\n group1 = group1.copy()\n group2 = group2.copy()\n for spr1 in group1:\n for spr2 in group2:\n dist = ((spr2.x - spr1.x) ** 2 + (spr2.y - spr1.y) ** 2) ** 0.5\n collide_dist = spr1.radius + spr2.radius - dist\n if collide_dist >= 0:\n ix = spr2.x - spr1.x\n jy = spr2.y - spr1.y\n spr1.x -= collide_dist * ix / dist\n spr1.y -= collide_dist * jy / dist\n" }, { "alpha_fraction": 0.5972696542739868, "alphanum_fraction": 0.6160409450531006, "avg_line_length": 31.55555534362793, "blob_id": "728e938eaf0b7f4eed19b8fcd004c2c292d1f339", "content_id": "3388ab1c3cae60ba5534d88aa504321eebeef81c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 608, "license_type": "no_license", "max_line_length": 97, "num_lines": 18, "path": "/let.py", "repo_name": "EdenStabbfer/Life_Simulation", "src_encoding": "UTF-8", "text": "import pygame as pg\nfrom game_functions import id_gen\nimport pygame.gfxdraw\n\n\n# Просто клетка (без подвида)\nclass Let(pg.sprite.Sprite):\n def __init__(self, screen, rect):\n super().__init__()\n self.screen = screen\n self.rect = rect\n self.x, self.y = rect.centerx, rect.centery\n self.radius = rect.width//2\n self.id = id_gen()\n\n def draw_me(self):\n pg.gfxdraw.aacircle(self.screen, int(self.x), int(self.y), self.radius, (0, 200, 0))\n pg.gfxdraw.filled_circle(self.screen, int(self.x), int(self.y), self.radius, (0, 200, 0))\n" }, { "alpha_fraction": 0.585669755935669, "alphanum_fraction": 0.6064382195472717, "avg_line_length": 22.487804412841797, "blob_id": "4baa9a852f9f2e724856ec3a2ef4da36041669e1", "content_id": "f71698391f7edcecf95ad9db5655cc35f1952be2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 974, "license_type": "no_license", "max_line_length": 99, "num_lines": 41, "path": "/main.py", "repo_name": "EdenStabbfer/Life_Simulation", "src_encoding": "UTF-8", "text": "import pygame as pg\nimport settings as st\nimport game_functions as gf\nfrom ball import Ball\nfrom let import Let\n\nclock = pg.time.Clock()\n\n\ndef game_cicle():\n pg.init()\n pg.display.set_caption(\"Bacteria\")\n screen = pg.display.set_mode(st.screen_size)\n\n moving_balls = pg.sprite.Group()\n for i in range(1):\n ball = Ball(screen, pg.rect.Rect(400, 400, 60, 60), 5)\n moving_balls.add(ball)\n\n barriers = pg.sprite.Group()\n let = Let(screen, pg.rect.Rect(screen.get_rect().centerx, screen.get_rect().centery, 100, 100))\n barriers.add(let)\n\n # Главный цикл\n while True:\n screen.fill(st.screen_color)\n\n gf.game_events()\n moving_balls.update()\n gf.collision_detect(moving_balls, barriers)\n for ball in moving_balls:\n ball.draw_me()\n for let in barriers:\n let.draw_me()\n\n pg.display.flip()\n clock.tick(30)\n\n\nif __name__ == \"__main__\":\n game_cicle()\n" } ]
5
Fmancino/dotfiles
https://github.com/Fmancino/dotfiles
694fcdbfcf9b994242a279b49e3d451b3b0c7b2a
5fefecb1226f534ef7efc6c63b94215dc0560b53
5352e8e33c24f47304838b10f7eb47e0b3c57abb
refs/heads/master
2021-12-14T13:16:49.728035
2021-12-07T10:30:56
2021-12-07T10:30:56
115,875,939
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.44789761304855347, "alphanum_fraction": 0.4881170094013214, "avg_line_length": 20.8799991607666, "blob_id": "c8fde96368b67e5dc4309a5018b899e7dec3cdea", "content_id": "90d711139ac7bfd8d6188946985fb38d411fc606", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 547, "license_type": "permissive", "max_line_length": 74, "num_lines": 25, "path": "/bin/insert-at-interesting-point", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#FILENAME: bashEd.sh\n\n#PURPOSE: Learn to use ed and stdin.\n\n#CREATION DATE: 25-02-2018\n\n#LAST MODIFIED: Sun Feb 25 23:57:31 2018\n\n#AUTHOR: Francesco Mancino, [email protected]\n#-------------------------------------------------------------------------\n# read whole content (until delimiter -d '') of STDIN in -r (raw) format\nread -rd '' FILE\n#insert this content after interesting string\ned -s $1 << EOF > /dev/null\n /interesting\n a\n$FILE\n.\nw\nq\nEOF\n# show file\ncat $1\n" }, { "alpha_fraction": 0.37821483612060547, "alphanum_fraction": 0.42208775877952576, "avg_line_length": 22.60714340209961, "blob_id": "c70f79ae9afa0e75dd25920716ec3cbadf7903cf", "content_id": "d339e1dd25dc16473561266fc6887323313edbd5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 661, "license_type": "permissive", "max_line_length": 74, "num_lines": 28, "path": "/source/vimfiles/vimbin/b-cmake", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#FILENAME: b-cmake.sh\n\n#PURPOSE: A wrapper around cmake to make the building process easyer\n\n#CREATION DATE: 15-03-2018\n\n#LAST MODIFIED: Thu Mar 15 21:27:22 2018\n\n#AUTHOR: Francesco Mancino, [email protected]\n#-------------------------------------------------------------------------\ncase $# in\n 0)\n echo 'Call cmake .. in current directory:'\n cmake ..\n ;;\n 1)\n echo \"Executing cd $1 && cmake ..\"\n cd $1 && cmake ..\n ;;\n 2)\n echo \"Executing cd $1 && cmake $2\"\n cd $1 && cmake $2\n ;;\nesac\necho 'Build program:'\nmake\n" }, { "alpha_fraction": 0.5334051847457886, "alphanum_fraction": 0.5625, "avg_line_length": 32.14285659790039, "blob_id": "56dfdf73983f822402044fc35fbd81567005e7e9", "content_id": "99e4230d04b32ad6821a0db35657e40a70ee4b88", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 928, "license_type": "permissive", "max_line_length": 74, "num_lines": 28, "path": "/config/polybar/launch.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#CREATION DATE: 07-04-2019\n#PURPOSE:\n#-------------------------------------------------------------------------\n# Terminate already running bar instances\nkillall -q polybar\n\n# Wait until the processes have been shut down\nwhile pgrep -u $UID -x polybar >/dev/null; do sleep 1; done\n\n# Launch Polybar, using default config location ~/.config/polybar/config\n# Launch bar1 and bar2\npolybar -m\n#!/bin/sh\nif xrandr | grep 'HDMI1 connected'; then\n MONITOR=HDMI1 polybar example &\nelse\n xrandr | grep 'eDP1 connected' && MONITOR=eDP1 polybar example &\nfi\n\n# DISPLAY1=\"$( | grep 'eDP1\\|VGA-1' | cut -d ' ' -f1)\"\n# [[ ! -z \"$DISPLAY1\" ]] && MONITOR=\"$DISPLAY1\" polybar example &\n\n# DISPLAY2=\"$(xrandr -q | grep 'HDMI1\\|DVI-I-1' | cut -d ' ' -f1)\"\n# [[ ! -z $DISPLAY2 ]] && MONITOR=$DISPLAY2 polybar example &\n\necho \"Polybar launched...\"\n" }, { "alpha_fraction": 0.287937730550766, "alphanum_fraction": 0.3190661370754242, "avg_line_length": 41.83333206176758, "blob_id": "3e905fbaa242e52cb5611e441caa0f9a2f0a1b0d", "content_id": "6b6700ba9ad584a566f7f91bd307c52b3ca35554", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 257, "license_type": "permissive", "max_line_length": 74, "num_lines": 6, "path": "/bin/clipboard.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#CREATION DATE: 24-06-2019\n#PURPOSE: Easy pipe to clipboard\n#-------------------------------------------------------------------------\nxclip -selection clipboard\n" }, { "alpha_fraction": 0.5381115078926086, "alphanum_fraction": 0.5642775893211365, "avg_line_length": 40.85714340209961, "blob_id": "148804b671777eebe7498d403e0ba88b2ba23452", "content_id": "9ad08654d287b6ab53b13757fa63ccde3327c447", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 879, "license_type": "permissive", "max_line_length": 113, "num_lines": 21, "path": "/bin/findInclude", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#FILENAME: findIncludes.sh\n\n#PURPOSE: Go truoght files specified in standars input and finds their headers (the files included with #include)\n\n#CREATION DATE: 08-02-2018\n\n#LAST MODIFIED: Thu Feb 8 22:43:39 2018\n\n#AUTHOR: Francesco Mancino, [email protected]\n#-------------------------------------------------------------------------\n# Look for includes in all input arguments, delete copies\ninclude=$(grep '#include' $@ | sed 's/^.* [\"<]\\(.*\\)[\">]/\\1/' | sort | uniq)\n\n# If in git directory change to root.\n# (statement after && executes only if first statement has non zero exit status)\n[[ $(git rev-parse --is-inside-work-tree 2> /dev/null) ]] && cd $(git rev-parse --show-toplevel)\n\n# Print path to includes (-n 1 stays for one argument per line)\necho $include | xargs -n 1 -I % find . -name % | sort\n" }, { "alpha_fraction": 0.44266054034233093, "alphanum_fraction": 0.4655963182449341, "avg_line_length": 30.14285659790039, "blob_id": "6ffe997fd4b7c2f0a6f8ce2aaa1581539740465d", "content_id": "517e69f2ad818263cc99001a577005ac0f6f314a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 436, "license_type": "permissive", "max_line_length": 74, "num_lines": 14, "path": "/bin/prestart.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#CREATION DATE: 17-06-2019\n#PURPOSE: Restart process given full command line used to start it\n#-------------------------------------------------------------------------\nif [ $# -lt 1 ]; then\n echo \"$0 <full command name>\"\n exit\nfi\n\nfullCommandName=\"$@\"\necho \"restarting: $fullCommandName\"\npkill -fx \"$fullCommandName\"\n$fullCommandName\n" }, { "alpha_fraction": 0.45945945382118225, "alphanum_fraction": 0.48948949575424194, "avg_line_length": 30.714284896850586, "blob_id": "634cdfea2e05c256d7223f12f4d449fc12c79586", "content_id": "fca37fb98cd281d6cf64869d7627de015d226b09", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 666, "license_type": "permissive", "max_line_length": 108, "num_lines": 21, "path": "/bin/commit-amend-review", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#FILENAME: commit-amend-review.sh\n\n#PURPOSE:To commit amend and review in a fast automated manner.\n\n#CREATION DATE: 07-03-2018\n\n#LAST MODIFIED: Wed 07 Mar 2018 03:21:48 PM CET\n\n#AUTHOR: Francesco Mancino, [email protected]\n#-------------------------------------------------------------------------\ngit add -u && git diff --cached && read -p 'Adding done, do you want to push with amend? (y/n)' WANTAMEND\n\ncase \"$WANTAMEND\" in\n [yY][eE][sS]|[yY])\n git commit --amend --no-edit && git pull -r && git submodule update --recursive --init && git review\n ;;\n *)\n ;;\nesac\n" }, { "alpha_fraction": 0.7044476270675659, "alphanum_fraction": 0.715925395488739, "avg_line_length": 45.46666717529297, "blob_id": "c8f21eb545b823339649e06a9db7e30d86b09a6f", "content_id": "041e1a4f4e04580f1081b7bd8558f9add7a8cedf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 697, "license_type": "permissive", "max_line_length": 85, "num_lines": 15, "path": "/effortless_ctags/readme.md", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "# Effortless ctags\nFrom: https://tbaggery.com/2011/08/08/effortless-ctags-with-git.html\n\nUtility files to implement ctags effortlessly in vim repositories.\n\n## Install\nJust run `dotfiles/effortless_ctags/setup.sh` to get the files and git setup.\nRun `git init` in the repository you want to have ctags on.\n\n## Useful ctags flags\nDocs: http://ctags.sourceforge.net/ctags.html\n* **--c++-kinds=+p** - puts prototype tags (not only f) f is function implementation\n* **--fields=+iaS** - adds i (inheritance info) a (access or export of class member)\n and S (prototype paramter list - signature)\n* **--extra=+q** - inclode exte class qualified tag (more precise jumping possible)\n" }, { "alpha_fraction": 0.43667545914649963, "alphanum_fraction": 0.47625330090522766, "avg_line_length": 24.266666412353516, "blob_id": "e1608fc8d7cec07dc2eb6e13db34aa0e2532d5ce", "content_id": "507bc08d4c49b5c8a845c5c904f27b72cd1c7976", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 758, "license_type": "permissive", "max_line_length": 74, "num_lines": 30, "path": "/source/os-functions.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#FILENAME:\n\n#PURPOSE:\n\n#CREATION DATE: 31-03-2018\n\n#LAST MODIFIED: Sat 31 Mar 2018 04:47:52 PM CEST\n\n#AUTHOR: Francesco Mancino, [email protected]\n#-------------------------------------------------------------------------\n# OS detection\nfunction is_osx() {\n [[ \"$OSTYPE\" =~ ^darwin ]] || return 1\n}\nfunction is_ubuntu() {\n [[ \"$(cat /etc/issue 2> /dev/null)\" =~ Ubuntu ]] || return 1\n}\nfunction is_debian() {\n [[ \"$(cat /etc/issue 2> /dev/null)\" =~ Debian ]] || return 1\n}\nfunction is_ubuntu_desktop() {\n dpkg -l ubuntu-desktop >/dev/null 2>&1 || return 1\n}\nfunction get_os() {\n for os in osx ubuntu ubuntu_desktop debian; do\n is_$os; [[ $? == ${1:-0} ]] && echo $os\n done\n}\n" }, { "alpha_fraction": 0.7125307321548462, "alphanum_fraction": 0.7174447178840637, "avg_line_length": 21, "blob_id": "6bc59ec377afb773e57a377ed5b13246aaab7e4f", "content_id": "546e0426c0ef80b41da095ef265682a27486fd94", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 814, "license_type": "permissive", "max_line_length": 69, "num_lines": 37, "path": "/init/apt-get.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n# OS detection\nsource $DOTFILES/source/os-functions.sh\nsource $DOTFILES/source/log-functions.sh\n\necho \"os detected: $(get_os)\"\n\nfunction install-program() {\n if [[ ! \"$(type -P $1)\" ]]; then\n e_header \"Installing $1\"\n sudo apt-get -y install $1\n fi\n}\n\n# If Git is not installed, install it\ninstall-program git\n\n# If Git isn't installed by now, something exploded. We gots to quit!\nif [[ ! \"$(type -P git)\" ]]; then\n e_error \"Git should be installed. It isn't. Aborting.\"\n exit 1\nfi\n\ninstall-program curl\ninstall-program ranger\ninstall-program tree\ninstall-program tmux\ninstall-program cmake\ninstall-program exuberant-ctags\ninstall-program build-essential\ninstall-program xclip\ninstall-program apt-file\n\n\ne_header \"updating system\"\nsudo apt-get update\nsudo apt-get upgrade\n" }, { "alpha_fraction": 0.3452685475349426, "alphanum_fraction": 0.39897698163986206, "avg_line_length": 29.076923370361328, "blob_id": "72f0de27479fde23e3368f7fb5daabdb628b03e7", "content_id": "6e82488261c745de96d16d1f6c5e68e3dc58dea0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 391, "license_type": "permissive", "max_line_length": 82, "num_lines": 13, "path": "/bin/get-merge", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#FILENAME: get-merge.sh\n\n#PURPOSE:\n\n#CREATION DATE: 13-03-2018\n\n#LAST MODIFIED: Tue 13 Mar 2018 05:24:25 PM CET\n\n#AUTHOR: Francesco Mancino, [email protected]\n#-------------------------------------------------------------------------\ngit --no-pager log --pretty=format:\"[%ai] %h: %s - parents: %P\" --merges | grep $1\n" }, { "alpha_fraction": 0.47866418957710266, "alphanum_fraction": 0.5157699584960938, "avg_line_length": 27.36842155456543, "blob_id": "5ebbae76225c9ae8df26c1cd2d2b51c6580bac7a", "content_id": "b62e3bb91cf3160e8763536cba4e4bf0001765cc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 539, "license_type": "permissive", "max_line_length": 74, "num_lines": 19, "path": "/bin/set-git-author.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#FILENAME: set-git-author.sh\n\n#PURPOSE: Set myself as author of commits in this repository. \n# Change address if needed!\n\n#CREATION DATE: 23-07-2018\n\n#LAST MODIFIED: Mon Jul 23 07:39:02 2018\n\n#AUTHOR: Francesco Mancino, [email protected]\n#-------------------------------------------------------------------------\ngit config user.name \"Fmancino\"\ngit config user.email \"[email protected]\"\necho \"User name:\"\ngit config user.name\necho \"User email:\"\ngit config user.email\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6899224519729614, "avg_line_length": 20.5, "blob_id": "c80bfd2a2c0a10cead488d1fe446da2c3217ef61", "content_id": "134bb0c71ed85c0cc5754df4fe62033459b656df", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 129, "license_type": "permissive", "max_line_length": 43, "num_lines": 6, "path": "/bin/bmi.py", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport sys\nimport os\n\nheight = float(os.environ['MY_HEIGHT'])\nprint (float(sys.argv[1]) / pow(height, 2))\n" }, { "alpha_fraction": 0.3290734887123108, "alphanum_fraction": 0.35463258624076843, "avg_line_length": 43.71428680419922, "blob_id": "a9312abb0546ad5c93c5dc038794293138b35e3a", "content_id": "ea02d9d1ed8499c108bcc857e2bc81473d0dc391", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 313, "license_type": "permissive", "max_line_length": 74, "num_lines": 7, "path": "/bin/to-qrcode.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#CREATION DATE: 17-12-2020\n#PURPOSE: pipe to this to show big qr-code of text\n# echo 'www.google.com' | to-qrcode.sh\n#-------------------------------------------------------------------------\nqrencode -o - | feh -FZ -\n" }, { "alpha_fraction": 0.32459017634391785, "alphanum_fraction": 0.3508196771144867, "avg_line_length": 37.125, "blob_id": "91d1fedbd106144264024afb930c4761a28e0be8", "content_id": "382b28dda09017eca32b7b5ad4368033cec350a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 305, "license_type": "permissive", "max_line_length": 74, "num_lines": 8, "path": "/source/history-functions.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#CREATION DATE: 12-07-2019\n#PURPOSE: Synch this shell with the history file\n#-------------------------------------------------------------------------\nsync-history () {\nhistory -a && history -c && history -r\n}\n" }, { "alpha_fraction": 0.6692132949829102, "alphanum_fraction": 0.6795374751091003, "avg_line_length": 25.756906509399414, "blob_id": "d5e11b78f1fefdaeca78b9e86b4894a875727456", "content_id": "88260ad4ab128ec2d43624ae12e626736f798c66", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4845, "license_type": "permissive", "max_line_length": 164, "num_lines": 181, "path": "/source/.bashrc", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "# This file should be sourced and DOTFILES variable set before sourcing it\n# Add local directory to path\nPATH=$PATH:$DOTFILES/bin\n\nsource $DOTFILES/source/os-functions.sh\n\n# remove contrl-s\nstty -ixon\n\n# Os specific settings\nVIM=~/.vim\n\nif is_osx; then\n export VISUAL=nvim\n\n # Easy to open things\n alias o='open -a'\n\n # alias vim='nvim'\nelse\n export VISUAL=vim\nfi\nexport EDITOR=vim\n\n# Add language\nexport LC_ALL=en_US.UTF-8\nexport LANG=en_US.UTF-8\nexport LANGUAGE=en_US.UTF-8\n\n# Add coloring\nexport CLICOLOR=1\n\n# Add support for global patterns\nshopt -s extglob\n\n# Problems with my l\nalias òsa='ls -all'\nalias òs='ls'\n\n# Easier navigation: .., ..., -\nalias ..='cd ..'\nalias ...='cd ../..'\n\n# Smarter tumx\nalias tmux='TERM=xterm-256color tmux'\n\n# Make git easyer\nalias s='git status'\nalias gl='git log'\n\n# Find easyer\nalias f='find . -name'\n\n#Promt\nsource $DOTFILES/source/cowboy_promt.sh\n\n# goto see -> https://github.com/iridakos/goto\nsource $DOTFILES/source/goto.sh\nfunction cd(){\n builtin cd \"$@\" >/dev/null 2>&1\n if [ \"$?\" != 0 ]\n then\n echo \"Using goto\"\n goto \"$@\"\n fi\n}\n\n# Autocorrect typos in path names when using `cd`\nshopt -s cdspell;\n\nset -o vi\n# History search:\nbind '\"\\e[A\":history-search-backward'\nbind '\"\\e[B\":history-search-forward'\nbind '\"^P\":history-search-backward'\nbind '\"^N\":history-search-forward'\n\n# Have time formatted history\n#export HISTTIMEFORMAT='%y%m%d_%H:%M:%S '\n\n[ -f ~/.fzf.bash ] && source ~/.fzf.bash\n\n## Settings from ubuntu standard\n# don't put duplicate lines or lines starting with space in the history.\n# See bash(1) for more options\nHISTCONTROL=ignoreboth:erasedups\nHISTIGNORE='??'\n\n# append to the history file, don't overwrite it\nshopt -s histappend\n\n# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)\nHISTSIZE=10000\nHISTFILESIZE=11000\n\n# check the window size after each command and, if necessary,\n# update the values of LINES and COLUMNS.\nshopt -s checkwinsize\n\n\n# make less more friendly for non-text input files, see lesspipe(1)\n[ -x /usr/bin/lesspipe ] && eval \"$(SHELL=/bin/sh lesspipe)\"\n\n# set variable identifying the chroot you work in (used in the prompt below)\nif [ -z \"${debian_chroot:-}\" ] && [ -r /etc/debian_chroot ]; then\n debian_chroot=$(cat /etc/debian_chroot)\nfi\n\n# enable color support of ls and also add handy aliases\nif [ -x /usr/bin/dircolors ]; then\n test -r ~/.dircolors && eval \"$(dircolors -b ~/.dircolors)\" || eval \"$(dircolors -b)\"\n alias ls='ls --color=auto'\n #alias dir='dir --color=auto'\n #alias vdir='vdir --color=auto'\n\n alias grep='grep --color=auto'\n alias fgrep='fgrep --color=auto'\n alias egrep='egrep --color=auto'\nfi\n\n# colored GCC warnings and errors\n#export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'\n\n# some more ls aliases\nalias ll='ls -alF'\nalias la='ls -A'\nalias l='ls -CF'\n\nif is_ubuntu || is_debian; then\n alias ?='apt search'\n alias ?f='apt-file search'\n alias dl='sudo apt install'\n alias upd-system='sudo apt update && time sudo apt dist-upgrade'\nfi\n\n# used to open files ans urls, use xdg-mime to set favorite program\nalias o=xdg-open\n\n# Add an \"alert\" alias for long running commands. Use like so:\n# sleep 10; alert\nalias alert='notify-send --urgency=low -i \"$([ $? = 0 ] && echo terminal || echo error)\" \"$(history|tail -n1|sed -e '\\''s/^\\s*[0-9]\\+\\s*//;s/[;&|]\\s*alert$//'\\'')\"'\n\n# Alias definitions.\n# You may want to put all your additions into a separate file like\n# ~/.bash_aliases, instead of adding them here directly.\n# See /usr/share/doc/bash-doc/examples in the bash-doc package.\n\nif [ -f ~/.bash_aliases ]; then\n . ~/.bash_aliases\nfi\n\n\n# enable programmable completion features (you don't need to enable\n# this, if it's already enabled in /etc/bash.bashrc and /etc/profile\n# sources /etc/bash.bashrc).\nif ! shopt -oq posix; then\n if [ -f /usr/share/bash-completion/bash_completion ]; then\n . /usr/share/bash-completion/bash_completion\n elif [ -f /etc/bash_completion ]; then\n . /etc/bash_completion\n fi\nfi\n\nsource $DOTFILES/source/ros-bash.sh\nsource $DOTFILES/source/e-cmd.sh\nsource $DOTFILES/source/git-completion.bash\nsource $DOTFILES/source/history-functions.sh\n\n# export FZF_DEFAULT_COMMAND='\n # (git ls-tree -r --name-only HEAD ||\n # find . -path \"*/\\.*\" -prune -o -type f -print -o -type l -print |\n # sed s/^..//) 2> /dev/null'\n# --files: List files that would be searched but do not search\n# --no-ignore: Do not respect .gitignore, etc...\n# --hidden: Search hidden files and folders\n# --follow: Follow symlinks\n# --glob: Additional conditions for search (in this case ignore everything in the .git/ folder)\nexport FZF_DEFAULT_COMMAND='rg --files --no-ignore --hidden --follow --glob \\!.git/*'\n\n#conplete man with command names\ncomplete -c man\n" }, { "alpha_fraction": 0.48772504925727844, "alphanum_fraction": 0.5351881980895996, "avg_line_length": 26.772727966308594, "blob_id": "c52a36a165d007f63226f4d953970d18fbb362ed", "content_id": "4df77a5583c57dd3dc04fbcdc35ab314edf76eea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 611, "license_type": "permissive", "max_line_length": 112, "num_lines": 22, "path": "/bin/logOutput", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#FILENAME: logOutput.sh\n\n#PURPOSE: https://stackoverflow.com/questions/692000/how-do-i-write-stderr-to-a-file-while-using-tee-with-a-pipe\n\n#CREATION DATE: 09-02-2018\n\n#LAST MODIFIED: Fri 09 Feb 2018 10:51:26 AM CET\n\n#AUTHOR: Francesco Mancino\n#-------------------------------------------------------------------------\n\nstdout='stdoutFrancesco.log'\nstderr='stderrFrancesco.log'\n\n# Creates empty file, clearing the old one if exists\n> $stdout\n> $stderr\n\n# from lhunath answer:\n$1 > >(tee -a \"$stdout\") 2> >(tee -a \"$stderr\" >&2)\n" }, { "alpha_fraction": 0.6689655184745789, "alphanum_fraction": 0.6793103218078613, "avg_line_length": 25.363636016845703, "blob_id": "002fbddce3b50fa20ca514acd72cc25f2ddc15e6", "content_id": "711fb5db91935a70d278601cc0e8a14f28c0a60a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 290, "license_type": "permissive", "max_line_length": 63, "num_lines": 11, "path": "/bin/map", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport webbrowser, sys, pyperclip\nif len(sys.argv) > 1:\n #get adress from the command line\n address = ' '.join(sys.argv[1:])\nelse:\n # Get adress from clipboard\n address = pyperclip.paste()\n\nwebbrowser.open('https://www.google.com/maps/place/' + address)\n" }, { "alpha_fraction": 0.5948774218559265, "alphanum_fraction": 0.6039658784866333, "avg_line_length": 25.698530197143555, "blob_id": "f767a4a7f0807ee9da495cc4e72b189787bb3ee9", "content_id": "37df0fc31171d2c6b079a1fa41406c6685614e91", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3631, "license_type": "permissive", "max_line_length": 81, "num_lines": 136, "path": "/bin/dotfiles", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n# inspired by https://github.com/cowboy/dotfiles/blob/master/bin/dotfiles \n# basically it is an incomplete copy of the parts i understand.\n\necho 'Dotfiles - Francesco \"frasse\" Mancino - inpired by: http://benalman.com/'\n\n# Where the magic happens.\nexport DOTFILES=~/dotfiles\n\n# logging functions\nsource $DOTFILES/source/log-functions.sh\nsource $DOTFILES/source/os-functions.sh\n\n# Copy, link, init, etc.\nfunction do_stuff() {\n local base dest skip\n local files=($DOTFILES/$1/*)\n [[ $(declare -f \"$1_files\") ]] && files=($($1_files \"${files[@]}\"))\n # No files? abort.\n if (( ${#files[@]} == 0 )); then return; fi\n # Run _header function only if declared.\n [[ $(declare -f \"$1_header\") ]] && \"$1_header\"\n # Iterate over files.\n for file in \"${files[@]}\"; do\n base=\"$(basename $file)\"\n # Get dest path.\n if [[ $(declare -f \"$1_dest\") ]]; then\n dest=\"$(\"$1_dest\" \"$base\")\"\n else\n dest=\"$HOME/$base\"\n fi\n # Run _test function only if declared.\n if [[ $(declare -f \"$1_test\") ]]; then\n # If _test function returns a string, skip file and print that message.\n skip=\"$(\"$1_test\" \"$file\" \"$dest\")\"\n if [[ \"$skip\" ]]; then\n e_error \"Skipping ~/$base, $skip\"\n continue\n fi\n # Destination file already exists in ~/. Back it up!\n if [[ -e \"$dest\" ]]; then\n e_arrow \"Backing up ~/$base.\"\n # Set backup flag, so a nice message can be shown at the end.\n backup=1\n # Create backup dir if it doesn't already exist.\n [[ -e \"$backup_dir\" ]] || mkdir -p \"$backup_dir\"\n # Backup file / link / whatever.\n mv \"$dest\" \"$backup_dir\"\n fi\n fi\n # Do stuff.\n \"$1_do\" \"$base\" \"$file\"\n done\n}\n\n# Link files.\nfunction link_header() { e_header \"Linking files into home directory\"; }\nfunction link_test() {\n [[ \"$1\" -ef \"$2\" ]] && echo \"same file\"\n}\nfunction link_do() {\n e_success \"Linking ~/$1.\"\n # removes prefix $HOME\n ln -sf ${2#$HOME/} ~/\n}\n\n# Link config files.\nfunction config_header() { e_header \"Linking files into ~/.config directory\"; }\nfunction config_dest() {\n echo \"$HOME/.config/$base\"\n}\nfunction config_test() {\n [[ \"$1\" -ef \"$2\" ]] && echo \"same file\"\n}\nfunction config_do() {\n e_success \"Linking ~/.config/$1.\"\n ln -sf ../${2#$HOME/} ~/.config/\n}\n\n# Copy files.\nfunction copy_header() { e_header \"Copying files into home directory\"; }\nfunction copy_test() {\n if [[ -e \"$2\" && ! \"$(cmp \"$1\" \"$2\" 2> /dev/null)\" ]]; then\n echo \"same file\"\n elif [[ \"$1\" -ot \"$2\" ]]; then\n echo \"destination file newer\"\n elif [[ -e \"$2\" ]]; then\n echo \"file exists, possible manual interventions:\"\n echo \"cp -f $1 $2\"\n echo \"cat $1 >> $2\"\n fi\n}\nfunction copy_do() {\n e_success \"Copying ~/$1.\"\n cp \"$2\" ~/\n}\n\n\n# DO STUFF\n\n# Add binaries into the path\n[[ -d $DOTFILES/bin ]] && export PATH=$DOTFILES/bin:$PATH && echo 'added to path'\ncd $DOTFILES\n\n# Tweak file globbing.\nshopt -s dotglob\nshopt -s nullglob\n\n# If backups are needed, this is where they'll go.\nbackup_dir=\"$DOTFILES/backups/$(date \"+%Y_%m_%d-%H_%M_%S\")/\"\nbackup=\n\n# Execute code for each file in these subdirectories.\ndo_stuff copy\ndo_stuff link\ndo_stuff config\n# TODO: configure init\n\n\n# Alert if backups were made.\nif [[ \"$backup\" ]]; then\n echo -e \"\\nBackups were moved to ~/${backup_dir#$HOME/}\"\nfi\n\n# install basic softweare\n# if is_ubuntu || is_debian; then\n # e_header \"Starting the installer\"\n # $DOTFILES/init/apt-get.sh\n # e_header \"Installer done\"\n# fi\n\ne_header 'Source git configurations'\ngit config --global include.path \"$DOTFILES/source/.gitconfig\"\n\n# All done!\ne_header \"All done!\"\n" }, { "alpha_fraction": 0.38235294818878174, "alphanum_fraction": 0.4075630307197571, "avg_line_length": 25.44444465637207, "blob_id": "17268f21210882d9593d87872acbcffae2e2e752", "content_id": "ebd8694ed3be493e0d5c17eeeb7d8bdb9a346dd6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 476, "license_type": "permissive", "max_line_length": 74, "num_lines": 18, "path": "/bin/cp-parent.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#CREATION DATE: 26-06-2019\n#PURPOSE: Copy file to directory creating it if necessary\n#-------------------------------------------------------------------------\nset -e\nif [ $# -lt 2 ]; then\n echo \"$0 <files...> <new-dir>\"\n exit\nfi\nnumber_of_files=$#-1\n\nfiles=${@:1:${number_of_files}}\ndir=${@:$#}\n\n# echo \"files: $files\"\n# echo \"dir: $dir\"\nmkdir -p \"$dir\" && cp $files \"$dir\"\n" }, { "alpha_fraction": 0.7721518874168396, "alphanum_fraction": 0.7721518874168396, "avg_line_length": 30.600000381469727, "blob_id": "5be7478578c885f12846daed56d288121eb668b1", "content_id": "a44f12cd9d7839e15cb455294ac2b3c47153b201", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 158, "license_type": "permissive", "max_line_length": 69, "num_lines": 5, "path": "/copy/.bashrc", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "export DOTFILES=~/dotfiles\nsource $DOTFILES/source/.bashrc\n\n# Set this variable to enable default printer (find with 'lpstat -t')\n# export PRINTER=my_printer\n" }, { "alpha_fraction": 0.3586956560611725, "alphanum_fraction": 0.40869563817977905, "avg_line_length": 31.85714340209961, "blob_id": "959088b89166d67293f1d3a0aff7eb101a67e1c7", "content_id": "01d09ba847cca1d01f66335c70db07144dd2d7e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 460, "license_type": "permissive", "max_line_length": 115, "num_lines": 14, "path": "/bin/git-ls-quickfix", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#FILENAME: git-ls-quickfix.sh\n\n#PURPOSE:\n\n#CREATION DATE: 27-02-2018\n\n#LAST MODIFIED: Tue Feb 27 23:08:35 2018\n\n#AUTHOR: Francesco Mancino, [email protected]\n#-------------------------------------------------------------------------\nDIR=$(git rev-parse --show-toplevel)\ngit ls-tree --full-tree --name-only -r HEAD | grep -i -E $1 | sed -e 's/$/:1:1/' -e \"s|^|\"$DIR\"/|\" -e \"s|$(pwd)/||\"\n" }, { "alpha_fraction": 0.6029298305511475, "alphanum_fraction": 0.6098689436912537, "avg_line_length": 27.822221755981445, "blob_id": "d3b21b96e3070e8e949262a1350eb1811de639ad", "content_id": "55bef4d9f8f8d9cc6cb05ca525a3ad51ac85b143", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1297, "license_type": "permissive", "max_line_length": 74, "num_lines": 45, "path": "/bin/backup.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#CREATION DATE: 07-04-2019\n#PURPOSE:\n#-------------------------------------------------------------------------\n# full system backup\n\n# Backup destination\nbackdest=/home/fma/backup\n\n# Backup source\nbacksource=/mnt/snap/\n\n# Labels for backup name\n#PC=${HOSTNAME}\npc=macbookair\ndistro=arch\ntype=full\ndate=$(date \"+%F\")\nbackupfile=\"$backdest/$distro-$type-$date.tar.gz\"\n\n# Exclude file location\n# prog=${0##*/} # Program name from filename\n# excdir=\"/home/<user>/.bin/root/backup\"\n# exclude_file=\"$excdir/$prog-exc.txt\"\n\n# Check if chrooted prompt.\necho -n \"Are you ready to backup? (y/n): \"\nread executeback\n\n# Check if exclude file exists\n# if [ ! -f $exclude_file ]; then\n # echo -n \"No exclude file exists, continue? (y/n): \"\n # read continue\n # if [ $continue == \"n\" ]; then exit; fi\n# fi\n\nif [ $executeback = \"y\" ]; then\n # -p and --xattrs store all permissions and extended attributes.\n # Without both of these, many programs will stop working!\n # It is safe to remove the verbose (-v) flag. If you are using a\n # slow terminal, this can greatly speed up the backup process.\n # tar --exclude-from=$exclude_file --xattrs -czpvf $backupfile /\n tar --xattrs -czpvf $backupfile $backsource\nfi\n" }, { "alpha_fraction": 0.30337077379226685, "alphanum_fraction": 0.3333333432674408, "avg_line_length": 43.5, "blob_id": "c79fff54518d2f1debe1885ace274cc520deabcd", "content_id": "6d78dcd3e27a896416813a7962b7efde62caa7b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 267, "license_type": "permissive", "max_line_length": 74, "num_lines": 6, "path": "/bin/us.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#CREATION DATE: 13-04-2019\n#PURPOSE:\n#-------------------------------------------------------------------------\nsetxkbmap -layout us -variant altgr-intl -option nodeadkeys\n" }, { "alpha_fraction": 0.3580246865749359, "alphanum_fraction": 0.3858024775981903, "avg_line_length": 39.5, "blob_id": "c1412f74a817c92e541fa81b9854adebad151f68", "content_id": "dd818cb84812ed64195b631a896ab4fcc17f3df0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 324, "license_type": "permissive", "max_line_length": 80, "num_lines": 8, "path": "/bin/s-lib.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#CREATION DATE: 04-08-2020\n#PURPOSE: Search include files for the definition of a statement, present in vim\n#-------------------------------------------------------------------------\ncd /usr/include\n# ctags -R\nvim -c \"Tags ${1}\"\n" }, { "alpha_fraction": 0.782608687877655, "alphanum_fraction": 0.782608687877655, "avg_line_length": 22, "blob_id": "1e029c9f133617ac84e09be6c081651709f43235", "content_id": "00e9476a9174fb5d512762dd5bed6308c56f0f9c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 23, "license_type": "permissive", "max_line_length": 22, "num_lines": 1, "path": "/source/vimfiles/vimundo/readme.txt", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "I am an undo directory\n" }, { "alpha_fraction": 0.6581032276153564, "alphanum_fraction": 0.6804322004318237, "avg_line_length": 16.350000381469727, "blob_id": "54d090b29cb1ad7114029d6c366bfa9ba60639e5", "content_id": "7911550112b08d1f46a84a0dc17c3f07ab97e5fb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4165, "license_type": "permissive", "max_line_length": 80, "num_lines": 240, "path": "/guides/good_commands.md", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "## SSH key pair\n\nCreating and sending to server\n```\nssh-keygen -t rsa -b 4096\n# or newer\nssh-keygen -f ~/.ssh/my_key -t ecdsa -b 521\n\nssh-copy-id -i ~/.ssh/my_key user@host\n```\nExample .ssh/config file:\n```\nHost my_host\n HostName 111.111.111.111\n User you\n IdentityFile /home/$USER/.ssh/my_key\n```\n\n## mount .img file in linux with loop device\n\nFrom: https://fossbytes.com/mounting-isos-image-file-types-in-linux/\n\n```\nsudo losetup -f -P <file.img>\nlosetup -a # see what we mounted\nsudo mount <dev/loopXpX> <media/user/file>\n# take away\nsudo umount <media/user/file>\nlosetup -d <dev/loopX> # or if you have no other devices: losetup -D\n```\n\n## Installed libraries\n\nSearch installed libraries:\n```\ngrep -r something /usr/include\n```\n\nIndex installed libraries:\n```\ncd /usr/include\nsudo ctags -R\n```\n\n## Find USB device:\n\nLook at the output of `dmesg` after device is connected.\n\n## Ipv4-forwarding (allow Linux to be a router/gateway)\n```\n# Check:\nsysctl net.ipv4.ip_forward\n# Activate\nsysctl -w net.ipv4.ip_forward=1\n```\n\n## Setup vlan in namespace\n```\n# Create namespace\nsudo ip netns add <namespace>\n\n# Create vlan\n# <eno1.<id>> is the vlan local interface name (vconfig gives it automatiacally)\nsudo ip link add link <eno1> name <eno1.<id>> type vlan id <id>\n# or\nsudo vconfig add <eno1> <id>\n\n# move vlan to namespace\nsudo ip link set <eno1.<id>> netns <namespace>\n\n# give address and set up\nsudo ip netns exec <namespace> ip addr add <10.0.0.1/24> dev <eno1.<id>>\nsudo ip netns exec <namespace> ip link set <eno1.<id>> up\n\n# delete vlan\nip link set dev <eno1.<id>> down\nip link delete <eno1.<id>>\n\n# change address\nip a del 11.0.0.1/24 dev eno1.4\nip a add 11.0.0.254/24 dev eno1.4\n```\n\n## tun tap veth in namespace\n\n```\nsudo ip -n <router2> link add tap0 type veth peer name tap0 netns <server>\n```\n\n## Select ssh\neval `ssh [email protected] 2>&1 | grep ssh-keygen`\neval `!! 2>&1 | grep ssh-keygen`\n\n## Show kernel .config\n```\ngunzip -c /proc/config.gz\ncat /boot/config\ncat /boot/config-$(uname -r)\n```\n\n## Crash boot partition on sda disk (to force USB boot)\n```\ndd if=/dev/zero of=/dev/sda bs=4k count=10\n```\n\n## Restart network service (after configuring ip):\n```\nip addr flush interface-name && systemctrl restart networking.service\n```\n\n## Simpler traceroute (will tell you the MTU)\n```\nip r\nip route get to 20.0.0.1\n```\n\n## Dump traffic in the network\n```\ntcpdump\n# Dump ethernet, line buffered(l), no DNS resolve (n), print packet ascii (A)\ntcpdump -lnAi eth0\n# List interfaces:\ntcpdump -D\n# Other:\ntcpdump -w my.pcap\ntcpdump -r my.pcap\ntcpdump -vvv\ntcpdump -A\ntcpdump -XX\n```\n\n## Trace system calls and signals\n```\nstrace\n```\n\n## Network namespaces\n```\n# Manual\nman ip-netns\n# list\nip netns\n# Execute command\nip netns exec <name> <command>\nip -all netns exec <command>\n```\n\n## Show open ports?\n```\nnetstat -tulpan\n```\n\n## List Linux modules\n```\nhostname.not.set# lsmod\n```\n\n## List all ARP connected to device\n```\narp\nip n\n```\n\n## Active connetions\n```\nnetstat\nss\n```\n\n## Delete entry from arp table\n```\narp -d\nip n del (this invalidates)\nip n f\n```\n\n## Set MTU\n```\nifconfig <if> mtu <number>\nip link set dev <if> mtu <number>\n```\n\n## Activate/deactivate if\n```\nifconfig <if> up/down\nip link set dev <if> up/down\n```\n\n## Putty from terminal\n```\nplink\nplink mysession < mycommands.txt > mylocalfile.strace\n```\n\n## Traffic control\n```\ntc\n# list queueing disciplines\ntc qdisc\n# md stands for classful multique\n```\n\n## List local ip fancy\n```\nip -br -c addr\nip -br a\n```\n\n## Disable TCP segmentation offload\n\nProblematic settings:\n\n```\ntcp-segmentation-offload: off\n tx-tcp-segmentation: off\n tx-tcp-ecn-segmentation: off [fixed]\n tx-tcp6-segmentation: off\ngeneric-segmentation-offload: off [requested on]\ngeneric-receive-offload: off\n```\n\n```\n# view current nic configuration:\nethtool -k <device>\n# remove settings on the fly:\nethtool -K <device> tso off gso off gro off\n```\n\n## Printing in linux\nIf you want to define a default printer just set the \"PRINTER\" variable\n```\nlpstat -t\nlpr -P printer file\n```\n\n## List hw storage (or other hw)\n```\nsudo lshw -short\nsudo lshw -class disk -class storage -short\n```\n\n" }, { "alpha_fraction": 0.7456140518188477, "alphanum_fraction": 0.7631579041481018, "avg_line_length": 27.5, "blob_id": "9e8f2e1f0c42e3653805e405b319e69da36b4409", "content_id": "e93d137a1886de89f05e222939b67bb361a164ed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 114, "license_type": "permissive", "max_line_length": 47, "num_lines": 4, "path": "/bin/week.py", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport datetime\n# Print todays week number\nprint(datetime.datetime.now().isocalendar()[1])\n" }, { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.5454545617103577, "avg_line_length": 15, "blob_id": "522f4cb1ee138b183b85876f53df44bdfa80b2c5", "content_id": "e83023e8664c5bbfbd2ef888aa3e2ecc23c5d358", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 33, "license_type": "permissive", "max_line_length": 19, "num_lines": 2, "path": "/bin/Rg", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\nrg $@ | fzf\n\n" }, { "alpha_fraction": 0.3201320171356201, "alphanum_fraction": 0.34983497858047485, "avg_line_length": 32.66666793823242, "blob_id": "4548c4e908a85f43c1d73bc99fbe0302455e491f", "content_id": "558519be3b372dd4438b3bf1e9aea610e70a20f6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 303, "license_type": "permissive", "max_line_length": 74, "num_lines": 9, "path": "/source/e-cmd.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#CREATION DATE: 23-05-2019\n#PURPOSE: Edit file that generates a specific command\n#-------------------------------------------------------------------------\ne-cmd () {\n$VISUAL `type -p $1`\n}\ncomplete -c e-cmd\n" }, { "alpha_fraction": 0.5174825191497803, "alphanum_fraction": 0.5356643199920654, "avg_line_length": 36.6315803527832, "blob_id": "1460d46bd65a57d9769095e6153d034a07f3e4cb", "content_id": "0e460a480e45d524f2defaa7964fce3f51e02807", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 715, "license_type": "permissive", "max_line_length": 111, "num_lines": 19, "path": "/bin/checkErrors.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#CREATION DATE: 06-04-2019\n#PURPOSE: Scan for errors in the system, see:\n# https://wiki.archlinux.org/index.php/System_maintenance\n#-------------------------------------------------------------------------\nexecute_verbose () {\n echo\n echo \"SHELL \\$ $1\"\n $1\n local status=$?\n [ $status -eq 0 ] || echo \"FAIL: $1: status: ${status}\"\n}\n\n# Check if any systemd services have entered in a failed state:\nexecute_verbose 'systemctl --failed'\n\n# Look for errors in the log files located at /var/log, as well as high priority errors in the systemd journal:\nexecute_verbose 'journalctl -p 3 -xb --no-pager'\n" }, { "alpha_fraction": 0.45646438002586365, "alphanum_fraction": 0.47229552268981934, "avg_line_length": 22.6875, "blob_id": "dadd160760080ef4bfc9c53a71ac5d237702d369", "content_id": "04291a64d14ab254eb3c37c25a4dd7baa87b97b5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 758, "license_type": "permissive", "max_line_length": 102, "num_lines": 32, "path": "/bin/getopt-example.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#CREATION DATE: 08-08-2019\n#PURPOSE: Exaple for getopt, from https://linuxconfig.org/how-to-use-getopts-to-parse-a-script-options\n#-------------------------------------------------------------------------\n#!/bin/bash\nset -e\nset -u\nset -o pipefail\n\nwhile getopts 'lha:' OPTION; do\n case \"$OPTION\" in\n l)\n echo \"linuxconfig\"\n ;;\n\n h)\n echo \"h stands for h\"\n ;;\n\n a)\n avalue=\"$OPTARG\"\n echo \"The value provided is $OPTARG\"\n ;;\n ?)\n echo \"script usage: $(basename $0) [-l] [-h] [-a somevalue]\" >&2\n exit 1\n ;;\n esac\ndone\n#shift sot that the ordet of parsing variables is correct\nshift \"$(($OPTIND -1))\"\n" }, { "alpha_fraction": 0.7890625, "alphanum_fraction": 0.7890625, "avg_line_length": 24.600000381469727, "blob_id": "867a015b5d1521d2e0bfda0c38e865efdb1bdb76", "content_id": "757ab2fa9b2060307f379cb1b824fe7ebb009270", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 128, "license_type": "permissive", "max_line_length": 56, "num_lines": 5, "path": "/README.md", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "# Francescos dotfiles\n\nMy dotiles.\nLot of inspiration in the organization of the repo from:\nhttps://github.com/cowboy/dotfiles:\n" }, { "alpha_fraction": 0.33747780323028564, "alphanum_fraction": 0.44049733877182007, "avg_line_length": 32.117645263671875, "blob_id": "ddc8f4245b805b99794dcdfb116acc0dddc256d7", "content_id": "238180bff645dc86e5be4046712926d438b4593f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 569, "license_type": "permissive", "max_line_length": 74, "num_lines": 17, "path": "/source/log-functions.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#FILENAME: log-helper.sh\n\n#PURPOSE:\n\n#CREATION DATE: 31-03-2018\n\n#LAST MODIFIED: Sat 31 Mar 2018 05:09:07 PM CEST\n\n#AUTHOR: Francesco Mancino, [email protected]\n#-------------------------------------------------------------------------\n# Logging stuff.\nfunction e_header() { echo -e \"\\n\\033[1m$@\\033[0m\"; }\nfunction e_success() { echo -e \" \\033[1;32m✔\\033[0m $@\"; }\nfunction e_error() { echo -e \" \\033[1;31m✖\\033[0m $@\"; }\nfunction e_arrow() { echo -e \" \\033[1;34m➜\\033[0m $@\"; }\n" }, { "alpha_fraction": 0.47826087474823, "alphanum_fraction": 0.5144927501678467, "avg_line_length": 28.052631378173828, "blob_id": "aa2339f77244c76382b293e35f09d482b51872e6", "content_id": "275521f4c0500a0571f48a8cffd6e4f89d554932", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 552, "license_type": "permissive", "max_line_length": 74, "num_lines": 19, "path": "/source/ros-bash.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#FILENAME: ros-bash.sh\n\n#PURPOSE:\n\n#CREATION DATE: 03-04-2018\n\n#LAST MODIFIED: Tue 03 Apr 2018 08:42:24 PM CEST\n\n#AUTHOR: Francesco Mancino, [email protected]\n#-------------------------------------------------------------------------\nPATH_KINETIC='/opt/ros/kinetic/setup.bash'\n\nif [ -f devel/setup.bash ]; then #if you are in a catkin_make directory\n source devel/setup.bash\nelif [ -f $PATH_KINETIC ]; then #if your computer has kinetic installed\n source $PATH_KINETIC\nfi\n" }, { "alpha_fraction": 0.5562852025032043, "alphanum_fraction": 0.5741088390350342, "avg_line_length": 27.052631378173828, "blob_id": "0a0bee0a5390448e88cf5d707209ee096e02fe0d", "content_id": "6a3cb3cb898c072ededf09dd10c329b68a4bb6e2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1066, "license_type": "permissive", "max_line_length": 98, "num_lines": 38, "path": "/bin/base_to_word.py", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport argparse\n\nBASE_LENGTH = {2:8, # binary has usually 8 digits for a byte\n 8:3, # base 8 has max 3 digits\n 16:2} # base 16 has usually 2 digits\n\ndef split_on_base(number, base):\n data_list = []\n temp = ''\n for c in number:\n temp += c\n if len(temp) == BASE_LENGTH[base]:\n data_list.append(temp)\n temp = ''\n if temp != '':\n data_list.append(temp)\n return data_list\n\ndef main(numbers, base):\n ret = b''\n if len(numbers) == 1:\n in_data = split_on_base(numbers[0], base)\n else:\n in_data = numbers\n\n for c in in_data:\n ret += bytes(chr(int(c, base)), 'utf-8')\n print(ret)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Convert a list of numbers into a word')\n parser.add_argument('numbers', nargs='+', help='A list of numbers encoded in particular base')\n parser.add_argument('-b', dest='base', type=int, default='16')\n\n args = parser.parse_args()\n main(args.numbers, args.base)\n" }, { "alpha_fraction": 0.6870604753494263, "alphanum_fraction": 0.7313642501831055, "avg_line_length": 24.85454559326172, "blob_id": "027892b7573c1f23d813e1d81d143d9a63f54820", "content_id": "7fa6bc930a058b56b734c9240cb692b52171bf6c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1422, "license_type": "permissive", "max_line_length": 97, "num_lines": 55, "path": "/guides/exfatPartitioning.md", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "# Partition external drive with exfat\n\nFind your partittion with:\n```\nsudo fdisk -l\n```\n\nUse the `gdisk` program.\nIt is important to have:\n* Partition Table: GPT\n* Partition Type: Microsoft Basic Data (gdisk type: 0700)\n* Filesystem: exfat (of course)\n\n\nIn gdisk (taken from https://matthew.komputerwiz.net/2015/12/13/formatting-universal-drive.html):\n```\n% sudo gdisk /dev/sdX\nGPT fdisk (gdisk) version 0.8.8\n\nPartition table scan:\n MBR: not present\n BSD: not present\n APM: not present\n GPT: not present\n\nCreating new GPT entries.\n\nCommand (? for help): o\nThis option deletes all partitions and creates a new protective MBR.\nProceed? (Y/N): Y\n\nCommand (? for help): n\nPartition number (1-128, default 1):\nFirst sector (34-16326462, default = 2048) or {+-}size{KMGTP}:\nLast sector (2048-16326462, default = 16326462) or {+-}size{KMGTP}:\nCurrent type is 'Linux filesystem'\nHex code or GUID (L to show codes, Enter = 8300): 0700\nChanged type of partition to 'Microsoft basic data'\n\nCommand (? for help): w\n\nFinal checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING\nPARTITIONS!!\n\nDo you want to proceed? (Y/N): Y\nOK; writing new GUID partition table (GPT) to /dev/sdX.\nWarning: The kernel is still using the old partition table.\nThe new table will be used at the next reboot.\nThe operation has completed successfully.\n```\n\nThen make the filesystem:\n```\nsudo mkfs.exfat -n filesystem-name /dev/sdX1\n```\n" }, { "alpha_fraction": 0.2977099120616913, "alphanum_fraction": 0.32824426889419556, "avg_line_length": 42.66666793823242, "blob_id": "dad07fe8a87df758ed50b75501a0fe2affed1081", "content_id": "cf9e17a914ff9fd439294582a772ab11e8225227", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 262, "license_type": "permissive", "max_line_length": 74, "num_lines": 6, "path": "/bin/se.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#CREATION DATE: 13-04-2019\n#PURPOSE: Chenge keyboard layout to swedish\n#-------------------------------------------------------------------------\nsetxkbmap -layout se\n" }, { "alpha_fraction": 0.657681941986084, "alphanum_fraction": 0.657681941986084, "avg_line_length": 36.099998474121094, "blob_id": "2ffd5edf0d9c03c96efa177ab7201c62da98b933", "content_id": "c1d78c38604111de1df287a0463600ae24aa0dd4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 371, "license_type": "permissive", "max_line_length": 77, "num_lines": 10, "path": "/effortless_ctags/git_template/hooks/universalCtags", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# configuration working for universal ctags that is in git\n# More details: https://github.com/universal-ctags/ctags or https://ctags.io/\nset -e\nPATH=\"/usr/local/bin:$PATH\"\ndir=\"`git rev-parse --git-dir`\"\ntrap 'rm -f \"$dir/$$.tags\"' EXIT\ngit ls-files | \\\n exctags --tag-relative=yes -L - -f\"$dir/$$.tags\" --fields=+iaS --extras=+q\nmv \"$dir/$$.tags\" \"$dir/tags\"\n" }, { "alpha_fraction": 0.4751381278038025, "alphanum_fraction": 0.5267034769058228, "avg_line_length": 32.9375, "blob_id": "bdd91b87e2bcb5224675caff0b72e823012742c6", "content_id": "bf2cf3c00b8fd128d830875c059e651acc40b948", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 543, "license_type": "permissive", "max_line_length": 78, "num_lines": 16, "path": "/effortless_ctags/setup.sh", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#FILENAME: setup.sh\n\n#PURPOSE: Setup effortless ctags as tpope suggest:\n# https://tbaggery.com/2011/08/08/effortless-ctags-with-git.html\n\n#CREATION DATE: 18-07-2018\n\n#LAST MODIFIED: Tue Aug 21 21:38:51 2018\n\n#AUTHOR: Francesco Mancino, [email protected]\n#-------------------------------------------------------------------------\n\ngit config --global init.templatedir \"$DOTFILES/effortless_ctags/git_template\"\ngit config --global alias.ctags '!.git/hooks/ctags'\n" }, { "alpha_fraction": 0.3881453275680542, "alphanum_fraction": 0.4263862371444702, "avg_line_length": 23.904762268066406, "blob_id": "90724c3b4374c723b3ae76a4964635fd7eef74a2", "content_id": "45279ca1883f12e29f634f3532d62b0877c09fe4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 523, "license_type": "permissive", "max_line_length": 115, "num_lines": 21, "path": "/bin/commit-steps", "repo_name": "Fmancino/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------\n#FILENAME: commit-steps.sh\n\n#PURPOSE:\n\n#CREATION DATE: 07-03-2018\n\n#LAST MODIFIED: Wed 07 Mar 2018 04:03:01 PM CET\n\n#AUTHOR: Francesco Mancino, [email protected]\n#-------------------------------------------------------------------------\ngit add -u && git diff --cached && git status && read -p 'Adding done, do you wish to commit? (enter/n)' WANTCOMMIT\n\ncase \"$WANTCOMMIT\" in\n [nN][oO]|[nN])\n ;;\n *)\n git commit;\n ;;\nesac\n" } ]
41
vedangmehta/codeforces-rating-alert
https://github.com/vedangmehta/codeforces-rating-alert
46609d3904edc16506a8364c786ee81839ae37cb
fdf9dd694570f04f62295d66f4ea3bc0838b3811
31087be5da9455b33153dc2eb73a1d22dafa064c
refs/heads/master
2017-12-04T14:19:03.066505
2016-05-19T15:11:52
2016-05-19T15:11:52
52,632,118
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.6305625438690186, "alphanum_fraction": 0.6353204846382141, "avg_line_length": 31.189189910888672, "blob_id": "45ee8f78268144f8dec08d8a769a6bb355596a85", "content_id": "1d862cd4f05ebb7e2e4d111f39032dc0ac2bb88a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3573, "license_type": "permissive", "max_line_length": 124, "num_lines": 111, "path": "/alert.py", "repo_name": "vedangmehta/codeforces-rating-alert", "src_encoding": "UTF-8", "text": "import sys\nimport re\nimport argparse\nimport json\nimport time\nimport smtplib\ntry:\n import requests\n if sys.version_info.major == 2:\n from email.MIMEMultipart import MIMEMultipart\n from email.MIMEText import MIMEText\n if sys.version_info.major == 3:\n from email.mime.multipart import MIMEMultipart\n from email.mime.text import MIMEText\nexcept ImportError:\n print('Email/Requests module not found')\n exit()\n\n\ndef parse_argument():\n \"\"\"To parse the arguments\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--handle', type=str, help='Codeforces handle')\n parser.add_argument('--email', type=str, help='Your Email ID')\n parser.add_argument(\n '-time',\n type=int,\n help='Frequency of refresh in seconds',\n default=60)\n args = parser.parse_args()\n return args\n\n\ndef validate_email(email_addr):\n \"\"\"Returns True if email_addr is valid else False\"\"\"\n expr = r'(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)'\n return re.match(expr, email_addr) is not None\n\n\ndef validate_handle(handle):\n \"\"\"Returns True if handle exists else False\"\"\"\n url = 'http://www.codeforces.com/api/user.info?handles=' + handle\n r = requests.get(url)\n data = r.text\n d = json.loads(data)\n return d['status'] == 'OK'\n\n\ndef fetch_user_history(handle):\n \"\"\"Returns a list of dictionaries containing user's contest history\"\"\"\n url = 'http://www.codeforces.com/api/user.rating?handle=' + handle\n r = requests.get(url)\n data = r.text\n d = json.loads(data)\n if d['status'] == 'FAILED' or r.status_code != 200:\n print('Failed to fetch data for {}'.format(handle))\n exit()\n return d['result']\n\n\ndef is_rating_updated(handle, contest_count):\n \"\"\"Returns True if the rating is updated else returns False\"\"\"\n d = fetch_user_history(handle)\n return len(d) != contest_count\n\n\ndef send_email(toaddr, body):\n \"\"\"Sends an email to 'toaddr' with message 'body'\"\"\"\n fromaddr = '[email protected]'\n msg = MIMEMultipart()\n msg['From'] = fromaddr\n msg['To'] = toaddr\n msg['Subject'] = 'Codeforces Rating'\n msg.attach(MIMEText(body, 'plain'))\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.ehlo()\n server.starttls()\n server.login(fromaddr, 'vedangmehta')\n text = msg.as_string()\n server.sendmail(fromaddr, toaddr, text)\n server.quit()\n\nif __name__ == '__main__':\n arguments = parse_argument()\n if arguments.email is None or arguments.handle is None:\n print('Parse arguments correctly!')\n exit()\n if not validate_handle(arguments.handle):\n print('Invalid handle')\n exit()\n if not validate_email(arguments.email):\n print('Invalid email address!')\n exit()\n print('The program is running... Please wait until your rating is updated')\n contest_count = len(fetch_user_history(arguments.handle))\n while True:\n if is_rating_updated(arguments.handle, contest_count):\n print('Rating updated!')\n break\n print('Please wait...')\n time.sleep(arguments.time)\n updated_user_data = fetch_user_history(arguments.handle)[-1]\n msg = 'Hello, {}!\\n\\nYour rating after {} changed from {} to {}. Your rank in {} was {}.\\n\\nRegards,\\nredviper.'.format(\n updated_user_data['handle'],\n updated_user_data['contestName'],\n updated_user_data['oldRating'],\n updated_user_data['newRating'],\n updated_user_data['contestName'],\n updated_user_data['rank'])\n\n send_email(arguments.email, msg)\n" }, { "alpha_fraction": 0.7623762488365173, "alphanum_fraction": 0.7623762488365173, "avg_line_length": 29.299999237060547, "blob_id": "28d675eb3971015b52270e35c5e4a5f7984d2eee", "content_id": "470cb20dd680e4ec8a559ccc4009e5be113f9857", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 303, "license_type": "permissive", "max_line_length": 98, "num_lines": 10, "path": "/README.md", "repo_name": "vedangmehta/codeforces-rating-alert", "src_encoding": "UTF-8", "text": "# codeforces-rating-alert\n\nThis handy Python script will send an email to the user whenever his CodeForces rating is updated.\n\n###usage:\n```\npython alert.py --handle your_handle --email your_email -time refresh_rate_in_seconds\n```\n\nNote : Please verify that you have all the required modules installed.\n" } ]
2
antuness/Learning_Python
https://github.com/antuness/Learning_Python
2670a922a3ea195877ee625f2e69c95db66668ea
4cffde8e5283ceb3d9f029119c412352b45ba015
545cb76bde3c1ee60758e83c56245bfee8b1d4c9
refs/heads/master
2023-07-20T13:32:15.159425
2021-08-23T11:26:44
2021-08-23T11:26:44
283,361,516
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.578199028968811, "alphanum_fraction": 0.6295418739318848, "avg_line_length": 13.84705924987793, "blob_id": "596867a024b4aff8aa6009f34c171a5c052b3d18", "content_id": "d9be2700be551ff522737e0ea915a18d0b3a98b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1266, "license_type": "no_license", "max_line_length": 110, "num_lines": 85, "path": "/Lesson_01.py", "repo_name": "antuness/Learning_Python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport scipy.stats\nimport pandas as pd\n\n\n# In[2]:\n\n\nimport matplotlib\nimport matplotlib.pyplot as pp\n\nfrom IPython import display\nfrom ipywidgets import interact, widgets\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[3]:\n\n\nimport re\nimport mailbox\nimport csv\n\n\n# In[4]:\n\n\ngapminder = pd.read_csv('C:/Users/99810471/Desktop/dados/gapminder.csv')\n\n\n# In[6]:\n\n\ngapminder.info()\n\n\n# In[7]:\n\n\ngapminder.loc[0:200:20]\n\n\n# In[8]:\n\n\ngapminder[gapminder.year == 1965].plot.scatter('babies_per_woman', 'age5_surviving')\n\n\n# In[15]:\n\n\ndef plotyear(year):\n data = gapminder[gapminder.year == year]\n area = 5e-6 * data.population\n colors = data.region.map({'Africa': 'skyblue', 'Europe': 'gold', 'America': 'palegreen', 'Asia': 'coral'})\n \n data.plot.scatter('babies_per_woman', 'age5_surviving',\n s=area,c=colors,\n linewidths=1,edgecolors='k',\n figsize=(12,9))\n pp.axis(ymin=50, ymax=105, xmin=0, xmax=8)\n pp.xlabel('babies per woman')\n pp.ylabel('% children alive at 5')\n\n\n# In[16]:\n\n\nplotyear(1965)\n\n\n# In[17]:\n\n\ninteract(plotyear,year=widgets.IntSlider(min=1950,max=2015,step=1,value=1965))\n\n\n# In[ ]:\n\n\n\n\n" }, { "alpha_fraction": 0.5555129647254944, "alphanum_fraction": 0.607094943523407, "avg_line_length": 19.8439998626709, "blob_id": "a3ba4950cfde18e4f3e0a93c1a93c815962ec19d", "content_id": "0bb6d7a2af44fcc51ca05e7248eb999498dd16e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5215, "license_type": "no_license", "max_line_length": 113, "num_lines": 250, "path": "/Lesson_02.py", "repo_name": "antuness/Learning_Python", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[42]:\n\n\nimport numpy as np\nimport scipy.stats\nimport pandas as pd\n\n\n# In[2]:\n\n\nimport matplotlib\nimport matplotlib.pyplot as pp\n\nfrom IPython import display\nfrom ipywidgets import interact, widgets\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[3]:\n\n\nimport re\nimport mailbox\nimport csv\n\n\n# In[4]:\n\n\nchina1965 = pd.read_csv('C:/Users/99810471/Desktop/dados/income-1965-china.csv')\nchina2015 = pd.read_csv('C:/Users/99810471/Desktop/dados/income-1965-usa.csv')\nusa1965 = pd.read_csv('C:/Users/99810471/Desktop/dados/income-2015-china.csv')\nusa1965 = pd.read_csv('C:/Users/99810471/Desktop/dados/income-2015-usa.csv')\n\n\n# In[5]:\n\n\nchina1965.income.plot(kind='box')\n\n\n# In[6]:\n\n\ngapminder = pd.read_csv('C:/Users/99810471/Desktop/dados/gapminder.csv')\n\n\n# In[8]:\n\n\ngapminder.info()\n\n\n# In[9]:\n\n\nitaly = gapminder.query('country == \"Italy\"')\n\n\n# In[10]:\n\n\nitaly.head()\n\n\n# In[11]:\n\n\nitaly.plot.scatter(\"year\", \"population\")\n\n\n# In[14]:\n\n\ngapminder.query('country == \"India\"').plot.scatter(\"year\", \"population\")\n\n\n# In[16]:\n\n\nitaly.plot.scatter(\"year\", \"gdp_per_day\", logy=True)\n\n\n# In[17]:\n\n\nitaly.plot.scatter(\"gdp_per_day\", \"life_expectancy\", logx=True)\n\n\n# In[19]:\n\n\nsize = np.where(italy.year % 10 == 0,30,2)\n\nitaly.plot.scatter(\"gdp_per_day\", \"life_expectancy\", logx=True, s=size)\n\n\n# In[23]:\n\n\ndata = gapminder.query('(country == \"Italy\") or (country == \"United States\")')\n \nsize = np.where(data.year % 10 == 0,30,2)\ncolor = np.where(data.country == 'Italy', 'blue', 'orange')\n\ndata.plot.scatter(\"gdp_per_day\", \"life_expectancy\", logx=True, s=size, c=color)\n\n\n# In[25]:\n\n\ndata = gapminder.query('(country == \"China\") or (country == \"United States\")')\n \nsize = np.where(data.year % 10 == 0,30,2)\ncolor = np.where(data.country == 'China', 'red', 'orange')\n\nax = data.plot.scatter(\"gdp_per_day\", \"life_expectancy\", logx=True, s=size, c=color)\n\ndata[data.country == 'China'].plot.line(x=\"gdp_per_day\", y=\"life_expectancy\", ax=ax)\n\n\n# In[26]:\n\n\ngapminder = pd.read_csv('C:/Users/99810471/Desktop/dados/gapminder.csv')\n\n\n# In[27]:\n\n\ndef plotyear(year):\n data = gapminder[gapminder.year == year]\n \n data.plot.scatter(\"gdp_per_day\", \"life_expectancy\", logx=True)\n \nplotyear(1965)\n\n\n# In[31]:\n\n\ndef plotyear(year):\n data = gapminder[gapminder.year == year].sort_values('population', ascending=False)\n area = 5e-6 * data.population\n color = data.age5_surviving\n \n data.plot.scatter(\"gdp_per_day\", \"life_expectancy\", logx=True, \n s=area, c=color,\n colormap=matplotlib.cm.get_cmap('Purples_r'), vmin=55, vmax=100,\n linewidths=1, edgecolors='k')\n \nplotyear(1965)\n\n\n# In[34]:\n\n\ndef plotyear(year):\n data = gapminder[gapminder.year == year].sort_values('population', ascending=False)\n area = 5e-6 * data.population\n color = data.age5_surviving\n edgecolor = data.region.map({'Africa': 'skyblue', 'Europe': 'gold', 'America': 'palegreen', 'Asia': 'coral'})\n \n data.plot.scatter(\"gdp_per_day\", \"life_expectancy\", logx=True, \n s=area, c=color,\n colormap=matplotlib.cm.get_cmap('Purples_r'), vmin=55, vmax=100,\n linewidths=1, edgecolors=edgecolor, sharex=False,\n figsize=(10,6.5))\n \n pp.axis(xmin=1, xmax=500, ymin=30, ymax=100)\n \nplotyear(1965)\n\n\n# In[35]:\n\n\ninteract(plotyear,year=range(1965, 2016,10))\n\n\n# In[36]:\n\n\ngapminder[gapminder.year == 2015].population.sum()\n\n\n# In[37]:\n\n\ngapminder[gapminder.year == 2015].groupby('region').population.sum()\n\n\n# In[38]:\n\n\ndef plotyear(year):\n data = gapminder[gapminder.year == year].sort_values('population', ascending=False)\n area = 5e-6 * data.population\n color = data.age5_surviving\n edgecolor = data.region.map({'Africa': 'skyblue', 'Europe': 'gold', 'America': 'palegreen', 'Asia': 'coral'})\n \n data.plot.scatter(\"gdp_per_day\", \"life_expectancy\", logx=True, \n s=area, c=color,\n colormap=matplotlib.cm.get_cmap('Purples_r'), vmin=55, vmax=100,\n linewidths=1, edgecolors=edgecolor, sharex=False,\n figsize=(10,6.5))\n \n for level in [4, 16,64]:\n pp.axvline(level, linestyle=':', color='k')\n \n pp.axis(xmin=1, xmax=500, ymin=30, ymax=100)\n \nplotyear(1965)\n\n\n# In[44]:\n\n\ndef plotyear(year):\n data = gapminder[gapminder.year == year].sort_values('population', ascending=False)\n area = 5e-6 * data.population\n color = data.age5_surviving\n edgecolor = data.region.map({'Africa': 'skyblue', 'Europe': 'gold', 'America': 'palegreen', 'Asia': 'coral'})\n \n data.plot.scatter(\"gdp_per_day\", \"life_expectancy\", logx=True, \n s=area, c=color,\n colormap=matplotlib.cm.get_cmap('Purples_r'), vmin=55, vmax=100,\n linewidths=1, edgecolors=edgecolor, sharex=False,\n figsize=(10,6.5))\n \n for level in [4, 16,64]:\n pp.axvline(level, linestyle=':', color='k')\n \n pp.axis(xmin=1, xmax=500, ymin=30, ymax=100)\n \nplotyear(2015)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n" } ]
2
nakkaya/emacs
https://github.com/nakkaya/emacs
74a1098b690edc6f3f52a4c154b94c0602c94711
66e5142498cc86a226c5f15eae202804c5fac86c
bbc8a0b5f3c571e798f7ebeb562d020050ce8e5f
refs/heads/master
2023-07-24T23:29:05.624336
2023-07-15T16:19:36
2023-07-15T16:19:36
210,782
20
6
null
2009-05-26T18:34:17
2022-05-12T16:10:58
2022-09-21T12:27:59
Dockerfile
[ { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6793611645698547, "avg_line_length": 22.594202041625977, "blob_id": "40c661ba161aaedfb035708d886397c9209c6433", "content_id": "4d969848562a8a92d3a3c5c22272bca40e3a18fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1628, "license_type": "no_license", "max_line_length": 83, "num_lines": 69, "path": "/readme.md", "repo_name": "nakkaya/emacs", "src_encoding": "UTF-8", "text": "# Emacs \n\n![CI Status](https://github.com/nakkaya/emacs/actions/workflows/main.yml/badge.svg)\n\n### Docker Setup\n\nThere is a Docker image built from this repository that contains Emacs\n28 with all packages AOT compiled. Image runs as user `core` replace\nyour username as required.\n\n docker pull nakkaya/emacs:latest\n\nYou can run it using,\n\n docker run \\\n\t --privileged \\\n\t --security-opt=\"seccomp=unconfined\" \\\n\t --restart=always \\\n\t --name emacsd \\\n\t --detach \\\n\t -p 2222:2222/tcp -p 4242:4242/tcp -p 9090:9090/tcp \\\n\t nakkaya/emacs\n\nIf you have `python` `invoke` installed you can run more complicated\ncommands,\n\n invoke docker # For bares bones version same as above\n\tinvoke docker --with-gpu # Run with GPUs attached\n invoke docker --with-host # Run with host networking\n invoke docker --with-passwd 1234 # Set password for Web & SSH login\n\nSee,\n\n invoke docker --help\n\nFor more options, Either of the following can be used to connect to a\nrunning image.\n\n # Connect using\n xpra attach tcp://127.0.0.1:9090 --window-close=disconnect\n # or\n chrome --app=http://127.0.0.1:9090\n\nService ports used by the image when enabled,\n\n - Xpra: `9090`\n - SSH: `2222`\n - WebDAV: `4242`\n - Jupyter: `8181`\n - PGAdmin: `5050`\n - Airflow: `8888`\n\n### Semi Automated Setup\n\nClone this repository,\n\n\tgit clone [email protected]:nakkaya/emacs.git\n\nNavigate to `devops/<your_os>` and run the provided install script.\n\n### Manual Setup\n\nClone this repository,\n\n\tgit clone [email protected]:nakkaya/emacs.git\n\t\nTell ```.emacs``` to load ```init.el```.\n\n\t(load-file \"~/source/emacs/init.el\")\n" }, { "alpha_fraction": 0.6799628734588623, "alphanum_fraction": 0.6836734414100647, "avg_line_length": 33.774192810058594, "blob_id": "117266e8ca362ae4beb1bc7b61d1dbd938923f4a", "content_id": "447c156b0bf302798e4333bf9f4634ca59e558bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1078, "license_type": "no_license", "max_line_length": 154, "num_lines": 31, "path": "/devops/docker/resources/bin/bootrc", "repo_name": "nakkaya/emacs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nif [[ -v JUPYTER_SERVER_ENB ]]; then\n /usr/bin/supervisorctl start jupyter\nfi\n\nif [[ -v SYNCTHING_ENB ]]; then\n /usr/bin/supervisorctl start syncthing\nfi\n\nif [[ -v PGADMIN_ENB ]]; then\n /usr/bin/supervisorctl start pgadmin\nfi\n\n# AIRFLOW_HOME=~/.airflow /opt/airflow/bin/airflow users create --username nakkaya --firstname Nurullah --lastname Akkaya --role Admin --email [email protected]\nif [[ -v AIRFLOW_ENB ]]; then\n\n if [ -d \"/home/$USER/.airflow\" ]; then\n AIRFLOW_HOME=~/.airflow /opt/airflow/bin/airflow db init\n fi\n\n if [ -f \"/home/$USER/.airflow/airflow-webserver.pid\" ]; then\n rm /home/$USER/.airflow/airflow-webserver.pid\n fi\n\n /usr/bin/supervisorctl start airflow-webserver\n /usr/bin/supervisorctl start airflow-scheduler\n\n # (cd /home/$USER/;AIRFLOW_HOME=~/.airflow /opt/airflow/bin/airflow webserver -p 8888 &> /opt/emacsd/logs/airflow_webserver.log &)\n # (cd /home/$USER/;AIRFLOW_HOME=~/.airflow PATH=/opt/airflow/bin:$PATH /opt/airflow/bin/airflow scheduler &> /opt/emacsd/logs/airflow_scheduler.log &)\nfi\n" }, { "alpha_fraction": 0.7239915132522583, "alphanum_fraction": 0.7303609251976013, "avg_line_length": 32.64285659790039, "blob_id": "854e5f889129d93cc0ad8acdec593e803066bbea", "content_id": "9f40d46d8e652ab4a5d72a51ae47b3cfae30bdf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 471, "license_type": "no_license", "max_line_length": 143, "num_lines": 14, "path": "/devops/darwin/install.sh", "repo_name": "nakkaya/emacs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nrm -f ~/.emacs\necho \"(load-file \\\"`pwd`/../../init.el\\\")\" > ~/.emacs\n\nbrew install automake poppler libtool aspell\nbrew install [email protected]\n# pip3 install jupyterlab\n\nbrew tap railwaycat/emacsmacport\n# --with-natural-title-bar\nbrew install emacs-mac --with-native-comp --with-xwidgets --with-no-title-bars\n\nosascript -e 'tell application \"Finder\" to make alias file to POSIX file \"/opt/homebrew/opt/emacs-mac/Emacs.app\" at POSIX file \"/Applications\"'\n" }, { "alpha_fraction": 0.645404577255249, "alphanum_fraction": 0.6629108786582947, "avg_line_length": 39.988548278808594, "blob_id": "29dcfbd5bbd19abad2e30c75bb98739c0df7251b", "content_id": "c1b560ece8348f54515de297b4c7d3591903cfd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 10739, "license_type": "no_license", "max_line_length": 219, "num_lines": 262, "path": "/devops/docker/Dockerfile", "repo_name": "nakkaya/emacs", "src_encoding": "UTF-8", "text": "FROM ghcr.io/nakkaya/emacsd as build\n\nENV LANG=en_US.UTF-8 \\\n LANGUAGE=en_US.UTF-8 \\\n LC_ALL=C.UTF-8 \\\n DEBIAN_FRONTEND=noninteractive\n\nENV USER=\"core\" \\\n UID=1000 \\\n TZ=UTC\n\nUSER root\n\n# Install Packages\n#\nRUN apt-get update && \\\n apt-get upgrade -y && \\\n apt-get install curl apt-utils -y --no-install-recommends && \\\n curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -\n\nRUN apt-get install \\\n # apt\n gnupg software-properties-common \\\n # Misc\n openssh-server sudo iputils-ping bash-completion \\\n zip unzip wget htop xz-utils nq \\\n graphviz qutebrowser \\\n libpq-dev postgresql-client influxdb-client python3-psycopg2 \\\n redis-tools \\\n offlineimap dovecot-imapd dnsutils nano iproute2 \\\n meshlab rlwrap netcat less jq \\\n python3-venv python3-wheel \\\n # Backup & Storage\n rsync rclone git git-lfs git-annex git-annex-remote-rclone \\\n apt-transport-https apache2-utils \\\n # Java\n openjdk-11-jdk maven visualvm \\\n # C/C++\n build-essential gcc-10 g++-10 clang clangd cmake cppcheck valgrind \\\n protobuf-compiler protobuf-compiler-grpc-java-plugin \\\n # Latex\n texlive-latex-base texlive-xetex texlive-lang-english texlive-lang-european \\\n texlive-luatex texlive-plain-generic texlive-fonts-recommended pandoc latexmk \\\n # PDF Tools\n libpng-dev zlib1g-dev libpoppler-glib-dev \\\n poppler-utils libpoppler-private-dev imagemagick \\\n # for cv2\n libgl1 libglib2.0-0 \\\n # Jupyter\n jupyter jupyter-notebook \\\n # emcas-jupyter\n autoconf automake libtool \\\n # For Teensy\n # libxft2 \\\n tesseract-ocr \\\n -y --no-install-recommends\n\nRUN apt-get install ispell -y\n\n# Node\n#\nRUN apt-get install -y nodejs\n\n# Install Serverless\n#\n\nRUN npm install -g serverless\n\n# Install Terraform\n#\nRUN ARCH=\"$(dpkg --print-architecture)\"; \\\n TERRAFORM_VERSION=0.14.11; \\\n TERRAFORM_LS_VERSION=0.22.0; \\\n TERRAFORM_DIST=\"terraform_${TERRAFORM_VERSION}_linux_${ARCH}.zip\"; \\\n TERRAFORM_LS_DIST=\"terraform-ls_${TERRAFORM_LS_VERSION}_linux_${ARCH}.zip\"; \\\n echo $TERRAFORM_DIST && \\\n echo $TERRAFORM_LS_DIST && \\\n wget -q https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/${TERRAFORM_DIST} && \\\n wget -q https://releases.hashicorp.com/terraform-ls/${TERRAFORM_LS_VERSION}/${TERRAFORM_LS_DIST} && \\\n unzip ${TERRAFORM_DIST} -d /usr/bin && \\\n rm -rf ${TERRAFORM_DIST} && \\\n unzip ${TERRAFORM_LS_DIST} -d /usr/bin && \\\n rm -rf ${TERRAFORM_LS_DIST}\n\n# Install Docker CLI\n#\nRUN ARCH=\"$(dpkg --print-architecture)\"; \\\n curl -fsSL https://download.docker.com/linux/ubuntu/gpg | \\\n gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg && \\\n echo \\\n \"deb [arch=${ARCH} signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \\\n $(lsb_release -cs) stable\" | tee /etc/apt/sources.list.d/docker.list > /dev/null && \\\n apt-get update && \\\n apt-get install docker-ce-cli -y --no-install-recommends && \\\n curl -L \"https://github.com/docker/compose/releases/download/v2.12.2/docker-compose-linux-$(uname -m)\" -o /usr/local/bin/docker-compose && \\\n chmod +x /usr/local/bin/docker-compose && \\\n touch /var/run/docker.sock && \\\n groupadd docker && \\\n chown root:docker /var/run/docker.sock && \\\n usermod -a -G docker $USER\n\n# Install Syncthing\n#\nRUN wget -q https://syncthing.net/release-key.txt -O- | apt-key add - && \\\n add-apt-repository \"deb https://apt.syncthing.net/ syncthing stable\" && \\\n apt-get install syncthing -y --no-install-recommends\n\n# Configure Python\n#\n\nRUN python3 -m venv /opt/python-lsp-server && \\\n /opt/python-lsp-server/bin/python -m pip install python-lsp-server[all] --no-cache-dir\n\nRUN python3 -m venv /opt/ansible && \\\n /opt/ansible/bin/python -m pip install ansible ansible-lint --no-cache-dir && \\\n echo \"export PATH=\\\"\\$PATH:/opt/ansible/bin\\\"\" >> /home/$USER/.bashrc\n\nRUN python3 -m venv /opt/invoke && \\\n /opt/invoke/bin/python -m pip install invoke --no-cache-dir && \\\n echo \"export PATH=\\\"\\$PATH:/opt/invoke/bin\\\"\" >> /home/$USER/.bashrc\n\n# Install Miniconda\n#\nRUN ARCH=\"$(dpkg --print-architecture)\"; \\\n case \"$ARCH\" in \\\n amd64) URL='https://repo.anaconda.com/miniconda/Miniconda3-py310_23.1.0-1-Linux-x86_64.sh' ;; \\\n arm64) URL='https://repo.anaconda.com/miniconda/Miniconda3-py310_23.1.0-1-Linux-aarch64.sh' ;; \\\n esac; \\\n curl -s \"${URL}\" -o \"Miniconda3.sh\" && \\\n bash Miniconda3.sh -b -u -p /opt/conda && \\\n su - $USER -c '/opt/conda/bin/conda init bash' && \\\n su - $USER -c '/opt/conda/bin/conda config --set auto_activate_base false' && \\\n rm -rf Miniconda3.sh\n\n# Install Clojure\n#\nRUN wget https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein -P /usr/bin/ && \\\n chmod 755 /usr/bin/lein && \\\n /bin/bash -c \"$(curl -fsSL https://download.clojure.org/install/linux-install-1.11.1.1113.sh)\" && \\\n /bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/clojure-lsp/clojure-lsp/master/install)\" -- --static && \\\n /bin/bash -c \"$(curl -s https://raw.githubusercontent.com/babashka/babashka/master/install)\" && \\\n /bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/clj-kondo/clj-kondo/master/script/install-clj-kondo)\" && \\\n rm -f /usr/local/bin/clj && \\\n ln -s /usr/local/bin/clojure /usr/local/bin/clj\n\n# Install GraalVM\n#\nRUN ARCH=\"$(dpkg --print-architecture)\"; \\\n case \"$ARCH\" in \\\n amd64) URL='https://github.com/graalvm/graalvm-ce-builds/releases/download/vm-22.3.1/graalvm-ce-java11-linux-amd64-22.3.1.tar.gz' ;; \\\n arm64) URL='https://github.com/graalvm/graalvm-ce-builds/releases/download/vm-22.3.1/graalvm-ce-java11-linux-aarch64-22.3.1.tar.gz' ;; \\\n esac; \\\n curl -L -s \"${URL}\" -o \"graalvm.tar.gz\" && \\\n mkdir graalvm && \\\n tar -xzf graalvm.tar.gz --strip 1 -C graalvm && \\\n mv graalvm /opt/ && \\\n /opt/graalvm/bin/gu install native-image && \\\n rm graalvm.tar.gz\n\n\n# Install AWS CLI\n#\nRUN ARCH=\"$(dpkg --print-architecture)\"; \\\n case \"$ARCH\" in \\\n amd64) URL='https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip' ;; \\\n arm64) URL='https://awscli.amazonaws.com/awscli-exe-linux-aarch64.zip' ;; \\\n esac; \\\n cd /opt/ && \\\n curl -s \"${URL}\" -o \"awscliv2.zip\" && \\\n unzip -q awscliv2.zip && \\\n ./aws/install && \\\n rm awscliv2.zip\n\n# Install Google Cloud CLI\n#\nRUN ARCH=\"$(dpkg --print-architecture)\"; \\\n curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key --keyring /usr/share/keyrings/cloud.google.gpg add - && \\\n echo \\\n \"deb [arch=${ARCH} signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt \\\n cloud-sdk main\" | tee -a /etc/apt/sources.list.d/google-cloud-sdk.list && \\\n apt-get update && \\\n apt-get install google-cloud-sdk -y --no-install-recommends\n\n# Install GitHub Tool\n#\n\n# RUN curl https://cli.github.com/packages/githubcli-archive-keyring.gpg | apt-key --keyring /usr/share/keyrings/githubcli-archive-keyring.gpg add - && \\\n# echo \"deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main\" | tee /etc/apt/sources.list.d/github-cli.list > /dev/null && \\\n# apt-get update && \\\n# apt-get install gh -y --no-install-recommends\n\n# Install pgAdmin\n#\n\nRUN mkdir /var/lib/pgadmin && \\\n mkdir /var/log/pgadmin && \\\n chown $USER /var/lib/pgadmin && \\\n chown $USER /var/log/pgadmin && \\\n python3 -m venv /opt/pgadmin && \\\n /opt/pgadmin/bin/python -m pip install install wheel --no-cache-dir && \\\n /opt/pgadmin/bin/python -m pip install install pgadmin4 --no-cache-dir && \\\n sed -i -e \"s/^DEFAULT_SERVER =.*/DEFAULT_SERVER=\\'0\\.0\\.0\\.0\\'/g\" /opt/pgadmin/lib/python3.10/site-packages/pgadmin4/config.py && \\\n mkdir -p /etc/pgadmin && \\\n echo \"DATA_DIR = '/home/${USER}/.pgadmin/'\" >> /etc/pgadmin/config_system.py && \\\n mkdir -p /home/$USER/.pgadmin\n\nRUN AIRFLOW_VERSION=\"2.5.2\"; \\\n PYTHON_VERSION=\"3.10\"; \\\n AIRFLOW_HOME=/home/$USER/.bashrc; \\\n CONSTRAINT_URL=\"https://raw.githubusercontent.com/apache/airflow/constraints-${AIRFLOW_VERSION}/constraints-${PYTHON_VERSION}.txt\"; \\\n python3 -m venv /opt/airflow && \\\n /opt/airflow/bin/python -m pip install virtualenv --no-cache-dir && \\\n /opt/airflow/bin/python -m pip install \"apache-airflow==${AIRFLOW_VERSION}\" --constraint \"${CONSTRAINT_URL}\" --no-cache-dir && \\\n sed -i -e \"s/^load_examples = .*/load_examples = False/g\" /opt/airflow/lib/python3.10/site-packages/airflow/config_templates/default_airflow.cfg && \\\n /opt/airflow/bin/python -m pip install \"apache-airflow-providers-postgres==5.4.0\" --no-cache-dir\n\nRUN python3 -m venv /opt/skypilot && \\\n /opt/skypilot/bin/python -m pip install \"skypilot[gcp,aws]==0.3.1\" --no-cache-dir && \\\n echo \"export PATH=\\\"\\$PATH:/opt/skypilot/bin\\\"\" >> /home/$USER/.bashrc\n\n# Arduino\n#\n# RUN wget http://downloads.arduino.cc/arduino-1.8.13-linux64.tar.xz && \\\n# tar xf arduino-1.8.13-linux64.tar.xz && \\\n# mv arduino-1.8.13 /usr/local/share/arduino && \\\n# ln -s /usr/local/share/arduino/arduino /usr/local/bin/arduino && \\\n# ln -s /usr/local/share/arduino/arduino-builder /usr/local/bin/arduino-builder && \\\n# rm -rf arduino-1.8.13-linux64.tar.xz && \\\n# arduino --install-boards arduino:sam && \\\n# wget https://www.pjrc.com/teensy/td_153/TeensyduinoInstall.linux64 && \\\n# chmod +x TeensyduinoInstall.linux64 && \\\n# ./TeensyduinoInstall.linux64 --dir=/usr/local/share/arduino && \\\n# rm -rf TeensyduinoInstall.linux64\n\nRUN apt-get autoremove -y && \\\n apt-get clean && \\\n apt-get autoclean\n\n# Setup Emacs\n#\nRUN git clone https://github.com/nakkaya/emacs /opt/emacsd/conf && \\\n echo \"(setq package-native-compile t)\" > /home/$USER/.emacs && \\\n echo \"(load-file \\\"/opt/emacsd/conf/init.el\\\")\" >> /home/$USER/.emacs\n\nCOPY resources/bin/ob-tangle.sh /usr/bin/ob-tangle\nRUN sudo chmod +x /usr/bin/ob-tangle\nCOPY resources/bin/bootrc /usr/bin/bootrc\nRUN sudo chmod +x /usr/bin/bootrc\nCOPY resources/bin/notebook /usr/bin/notebook\nRUN sudo chmod +x /usr/bin/notebook\nCOPY resources/conf/supervisord/bootrc.conf /etc/supervisor/conf.d/\nCOPY resources/conf/supervisord/syncthing.conf /etc/supervisor/conf.d/\nCOPY resources/conf/supervisord/pgadmin.conf /etc/supervisor/conf.d/\nCOPY resources/conf/supervisord/jupyter.conf /etc/supervisor/conf.d/\nCOPY resources/conf/supervisord/airflow.conf /etc/supervisor/conf.d/\n\nRUN mkdir -p /home/$USER/.local/share/ && \\\n chown -R $USER:$USER /opt/emacsd && \\\n chown -R $USER:$USER /home/$USER && \\\n chown -R $USER:$USER /storage\n\nUSER $USER\n" }, { "alpha_fraction": 0.5883590579032898, "alphanum_fraction": 0.5904628038406372, "avg_line_length": 24.01754379272461, "blob_id": "bb46651eeffed3b39896b2b6468f08b6111f6f82", "content_id": "373ccdf28897a6b58ed614ac9ef2ac5856a7a60a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1426, "license_type": "no_license", "max_line_length": 73, "num_lines": 57, "path": "/devops/docker/resources/bin/ob-tangle.sh", "repo_name": "nakkaya/emacs", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/emacs --script\n\n(if (not (string= (car argv) \"--\"))\n (setq argv (cons \"--\" argv)))\n\n(setq package-archives\n '((\"melpa\" . \"http://melpa.org/packages/\")))\n\n(package-initialize)\n\n(setq package-list\n '(use-package\n org\n commander))\n\n(dolist (package package-list)\n (when (not (package-installed-p package))\n (package-install package)))\n\n(require 'commander)\n(require 'org)\n(require 'ob-tangle)\n\n(setq tramp-verbose 0\n org-id-locations-file nil)\n\n(setq tangle-host '())\n(setq tangle-files '())\n\n(defun tangle (&rest files)\n \"List of Files to Tangle.\"\n (setq tangle-files files))\n\n(defun host (&rest hosts)\n \"List of Hosts to Tangle to.\"\n (setq tangle-hosts hosts))\n\n(defun tangle-to-host (host)\n (while (re-search-forward \":tangle\\s-*?\\\\(.*?\\\\)\\\\($\\\\|\\s-*?\\\\)\" nil t)\n (replace-match\n (concat \"/ssh:\" host \":\" (match-string 1)) nil nil nil 1)))\n\n(commander\n (name \"ob-tangle\")\n (option \"--host <*>\" host)\n (option \"--tangle <*>\" tangle)\n (option \"--help\" \"Show usage information\" commander-print-usage))\n\n(dolist (host tangle-hosts)\n (dolist (file tangle-files)\n (let* ((data (with-temp-buffer\n (insert-file-contents file)\n (beginning-of-buffer)\n (tangle-to-host host)\n (buffer-string)))\n (t_file (make-temp-file file nil \".org\" data)))\n (org-babel-tangle-file t_file))))\n" }, { "alpha_fraction": 0.4944286048412323, "alphanum_fraction": 0.5097175240516663, "avg_line_length": 26.564285278320312, "blob_id": "8d4d302fb2b76dff14705cdc864799de58e3f3ad", "content_id": "788f7e21ca3f138d54a7cfe076c671a2089721c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3859, "license_type": "no_license", "max_line_length": 78, "num_lines": 140, "path": "/tasks.py", "repo_name": "nakkaya/emacs", "src_encoding": "UTF-8", "text": "\"\"\"emacs build file.\"\"\"\n\nfrom invoke import task\nimport os\nfrom datetime import datetime\nimport platform\n\n\ndef tag(n):\n \"\"\"Create tag command.\"\"\"\n t_str = datetime.now().strftime(\"%Y_%m_%d_%H_%M_%S\")\n return (\"--tag nakkaya/\" + n + \":latest \" +\n \"--tag ghcr.io/nakkaya/\" + n + \":latest \" +\n \"--tag nakkaya/\" + n + \":\" + t_str + \" \")\n\n\n@task\ndef build(c, march=False):\n \"\"\"Build Multi Arch CPU Image.\"\"\"\n os.chdir(\"devops/docker/\")\n\n def cmd(builder):\n return \"docker \" + builder + \" -f Dockerfile \" + tag(\"emacs\") + \" \"\n\n if march:\n c.run(\"docker build -f Dockerfile \" + tag(\"emacs\") + \" .\")\n else:\n # c.run(\"docker buildx build --push -f Dockerfile \" + tag(\"emacs\") +\n # \" --platform linux/amd64 .\")\n c.run(\"docker buildx build --push -f Dockerfile \" + tag(\"emacs\") +\n \" --platform linux/amd64,linux/arm64 .\")\n\n\n@task(auto_shortflags=False,\n help={'with-host': 'Enable host networking.',\n 'with-passwd': 'Set login password.',\n 'with-gpu': 'Enable GPU in container.',\n 'with-docker': 'Mounts host docker socket into container.',\n 'with-syncthing': 'Enable Syncthing.',\n 'with-jupyter': 'Enable Jupyter.',\n 'with-pgadmin': 'Enable pgAdmin.',\n 'with-airflow': 'Enable Airflow.',\n 'restart': 'Stop/Remove/Start running container.'})\ndef docker(c,\n with_host=False,\n with_passwd=None,\n with_gpu=False,\n with_docker=False,\n with_syncthing=False,\n with_jupyter=False,\n with_pgadmin=False,\n with_airflow=False,\n restart=False):\n \"\"\"Launch emacsd Docker Image.\"\"\"\n if restart:\n try:\n c.run(\"docker stop emacsd\")\n except Exception:\n pass\n\n try:\n c.run(\"docker container rm emacsd\")\n except Exception:\n pass\n\n if with_host:\n host = \"--network host\"\n else:\n host = \"\"\"\n -p 2222:2222/tcp\n -p 4242:4242/tcp\n -p 9090:9090/tcp\n \"\"\"\n\n passwd = \"--env PASSWD=\" + with_passwd if with_passwd else \"\"\n gpu = \"--gpus all\" if with_gpu else \"\"\n\n docker_sock = \"\"\n if with_docker:\n import grp\n group_info = grp.getgrnam('docker')\n group_id = group_info[2]\n\n docker_sock = \\\n \"--group-add \" + str(group_id) + \" \" + \\\n \"-v /var/run/docker.sock:/var/run/docker.sock\"\n\n syncthing = \"--env SYNCTHING_ENB=1\" if with_syncthing else \"\"\n\n jupyter = \"\"\n if with_jupyter:\n jupyter = \"--env JUPYTER_SERVER_ENB=1\"\n if not with_host:\n jupyter = jupyter + \" -p 8181:8181/tcp\"\n\n pgadmin = \"\"\n if with_pgadmin:\n pgadmin = \"--env PGADMIN_ENB=1\"\n if not with_host:\n pgadmin = pgadmin + \" -p 5050:5050/tcp\"\n\n airflow = \"\"\n if with_airflow:\n airflow = \"--env AIRFLOW_ENB=1\"\n if not with_host:\n airflow = airflow + \" -p 8888:8888/tcp\"\n\n volumes = [[\"emacsd-home\", \"/home/core\"],\n [\"emacsd-storage\", \"/storage\"]]\n\n volume_mounts = \"\"\n\n for v in volumes:\n v_host, v_docker = v\n volume_mounts = volume_mounts + \" -v \" + v_host + \":\" + v_docker + \" \"\n\n c.run(\"docker pull nakkaya/emacs:latest\")\n\n cmd = \"\"\"\n docker run\n --privileged\n --security-opt=\\\"seccomp=unconfined\\\"\n --restart=always\n --name emacsd\n --detach\n \"\"\" + host + \"\"\"\n --hostname \"\"\" + platform.node() + \"\"\"\n \"\"\" + passwd + \"\"\"\n \"\"\" + syncthing + \"\"\"\n \"\"\" + jupyter + \"\"\"\n \"\"\" + pgadmin + \"\"\"\n \"\"\" + airflow + \"\"\"\n \"\"\" + volume_mounts + \"\"\"\n \"\"\" + docker_sock + \"\"\"\n \"\"\" + gpu + \"\"\"\n nakkaya/emacs\"\"\"\n\n cmd = cmd.replace('\\n', ' ')\n cmd = ' '.join(cmd.split())\n c.run(cmd)\n" }, { "alpha_fraction": 0.6090534925460815, "alphanum_fraction": 0.6419752836227417, "avg_line_length": 26, "blob_id": "47b6124fa26034dd42c1a815ee11b4d0268a18e4", "content_id": "0db05ddfea6a11ac622e5e38e2200a46b7e2f914", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 243, "license_type": "no_license", "max_line_length": 86, "num_lines": 9, "path": "/devops/docker/resources/bin/notebook", "repo_name": "nakkaya/emacs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nexport SHELL=/bin/bash\n\nif [[ -v PASSWD ]]; then\n jupyter notebook --no-browser --ip='*' --port=8181 --NotebookApp.token=\"${PASSWD}\"\nelse\n jupyter notebook --no-browser --ip='*' --port=8181 --NotebookApp.token=''\nfi\n" }, { "alpha_fraction": 0.6339399218559265, "alphanum_fraction": 0.657215416431427, "avg_line_length": 24.96703338623047, "blob_id": "c0a822a0f75f3010ac20293954807bd836eb640b", "content_id": "0e41978f8be214059484e16d7aa50fddd7d8ed88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2363, "license_type": "no_license", "max_line_length": 107, "num_lines": 91, "path": "/devops/ubuntu/install.sh", "repo_name": "nakkaya/emacs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nset -e\n\nEMACS_BUILD_TOOLS=\"wget \\\n\t\t gnupg \\\n\t\t software-properties-common \\\n\t\t equivs \\\n\t\t devscripts \\\n\t\t autoconf \\\n\t\t make \\\n\t\t pkg-config \\\n\t\t texinfo \\\n\t\t gcc-10 \\\n\t\t g++-10 \\\n\t\t libgtk-3-dev \\\n\t\t libotf-dev \\\n\t\t libharfbuzz-dev \\\n\t\t libjansson-dev \\\n\t\t libwebkit2gtk-4.0-dev \\\n\t\t libgccjit-10-dev \\\n\t\t libgif-dev \\\n\t\t libxpm-dev \\\n\t\t gnutls-dev\"\n\nEMACS_BUILD_DEPS=\"libgtk-3-0 \\\n\t\t libharfbuzz-bin \\\n\t\t libwebkit2gtk-4.0 \\\n\t\t libotf-bin \\\n\t\t libgccjit0 \\\n\t\t libjansson4 \\\n\t\t libm17n-0 \\\n\t\t libgccjit0\"\n\nsudo apt-get update\nsudo apt-get upgrade -y\nsudo apt-get install $EMACS_BUILD_TOOLS $EMACS_BUILD_DEPS -y --no-install-recommends\n\nrm -f ~/.emacs\necho \"(load-file \\\"`pwd`/../../init.el\\\")\" > ~/.emacs\n\nif [ -d ~/.emacs.build ]; then rm -Rf ~/.emacs.build; fi\n\ngit clone --depth 1 --branch emacs-28.2 https://git.savannah.gnu.org/git/emacs.git ~/.emacs.build\n\ncd ~/.emacs.build\n\nexport CC=/usr/bin/gcc-10\nexport CXX=/usr/bin/gcc-10\nexport CFLAGS=\"-O3 -mtune=native -march=native -fomit-frame-pointer\"\n\n./autogen.sh\n./configure \\\n --with-zlib \\\n --with-native-compilation \\\n --with-modules \\\n --with-json \\\n --with-mailutils \\\n --with-xml2 \\\n --with-xft \\\n --with-libotf \\\n --with-gnutls=yes \\\n --with-x=yes \\\n --with-cairo \\\n --with-xwidgets \\\n --with-x-toolkit=gtk3 \\\n --with-harfbuzz \\\n --with-jpeg=yes \\\n --with-png=yes\nmake -j$(nproc)\n\nif [ -f ~/.local/share/applications/emacs28.desktop ];\nthen\n rm ~/.local/share/applications/emacs28.desktop;\nfi\n\necho \"#!/usr/bin/env xdg-open\" > ~/.local/share/applications/emacs28.desktop\necho \"[Desktop Entry]\" >> ~/.local/share/applications/emacs28.desktop\necho \"Name=Emacs 28\" >> ~/.local/share/applications/emacs28.desktop\necho \"Icon=/usr/share/icons/hicolor/scalable/apps/emacs.svg\" >> ~/.local/share/applications/emacs28.desktop\necho \"Exec=$HOME/.emacs.build/src/emacs\" >> ~/.local/share/applications/emacs28.desktop\necho \"Type=Application\" >> ~/.local/share/applications/emacs28.desktop\necho \"Terminal=false\" >> ~/.local/share/applications/emacs28.desktop\necho \"StartupNotify=true\" >> ~/.local/share/applications/emacs28.desktop\n\n#sudo pip3 install jupyterlab\n\nsudo adduser $USER dialout\nsudo adduser $USER dialout\n\ngsettings set org.gnome.desktop.input-sources xkb-options \"['ctrl:nocaps']\"\n" } ]
8
wfp9880/Python
https://github.com/wfp9880/Python
048737ca033c59fc7c2798c22982f21bccc92568
da9c17ff0a83acd4a73f7b8de729ad0e9caf003d
868724a4602c4255cb63d92c9aaa7082acc6b577
refs/heads/master
2021-01-05T18:50:58.964282
2020-03-25T09:27:55
2020-03-25T09:27:55
241,107,234
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3142857253551483, "alphanum_fraction": 0.41428571939468384, "avg_line_length": 9.333333015441895, "blob_id": "c183f687fd4767c9984d457e3946c21c68da0a61", "content_id": "c4317de44c8d3a5f5b96c2a980fd17a56102eaa7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 84, "license_type": "no_license", "max_line_length": 22, "num_lines": 6, "path": "/hello world.py", "repo_name": "wfp9880/Python", "src_encoding": "UTF-8", "text": "\r\n\"\"\"\r\n 测试代码\r\n 2020.2.17\r\n 王丰平\r\n\"\"\"\r\nprint(\"hello world !\")\r\n" }, { "alpha_fraction": 0.41860464215278625, "alphanum_fraction": 0.569767415523529, "avg_line_length": 12.44444465637207, "blob_id": "fb5d2d5b71534c3470aa6e04fc584ef3f95ff39a", "content_id": "f4ca140966362ae88f4530ec8c970b2749e350b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 276, "license_type": "no_license", "max_line_length": 25, "num_lines": 18, "path": "/变量.py", "repo_name": "wfp9880/Python", "src_encoding": "UTF-8", "text": "#数据类型\r\nnum1=1\r\nprint(type(num1))\r\nnum2=1.1\r\nprint(type(num2))\r\nb=True\r\nprint(type(b))\r\nc=[10,20,30,40,50]\r\nprint(type(c))\r\nd=(10,20,30,40,50)\r\nprint(type(d))\r\ne={10,20,30,40,50}\r\nprint(type(e))\r\nf={'name':'Tom','age':18}\r\nprint(type(f))\r\n\"\"\"\r\n 变量名=赋值\r\n\"\"\"" } ]
2
rajunadaf570/My-Blog
https://github.com/rajunadaf570/My-Blog
b79a073d03a74951de090ac7719453567a8e3462
6e795cf28e01fde3f0a4632767791c1fefc26f6a
ba757727af58c1e2340c9fa93967e7b46d2d6c77
refs/heads/master
2021-09-28T14:21:18.979757
2019-12-15T20:06:25
2019-12-15T20:06:25
227,207,070
0
0
null
2019-12-10T20:13:27
2019-12-15T20:06:28
2021-09-22T18:07:59
Python
[ { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 17.33333396911621, "blob_id": "98f3eee81a9a25c3f2057aec79cf3501117086c2", "content_id": "601fc4d333c6675d93d7335fa81cb030dd6b4b03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 110, "license_type": "no_license", "max_line_length": 27, "num_lines": 6, "path": "/requirements.txt", "repo_name": "rajunadaf570/My-Blog", "src_encoding": "UTF-8", "text": "asgiref==3.2.3\nDjango==3.0\ndjango-model-utils==3.1.2\ndjangorestframework==3.10.3\npytz==2019.3\nsqlparse==0.3.0\n" }, { "alpha_fraction": 0.46913954615592957, "alphanum_fraction": 0.5199148654937744, "avg_line_length": 28.899999618530273, "blob_id": "63b9d72b5107f5864e01b288313e28255efa7844", "content_id": "e06d7839ec98a64e52d86bfd79b28eb859f4db56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3289, "license_type": "no_license", "max_line_length": 126, "num_lines": 110, "path": "/README.md", "repo_name": "rajunadaf570/My-Blog", "src_encoding": "UTF-8", "text": "# My Blog\n## Requirements:\n1. Python 3.7\n2. virtualenv\n### Step 1: Create virtualenv and Install requirements.txt file.\n virtualenv -p python3.7 {env_name}\n pip install -r requirements.txt\n Active the virualenv.\n### Step 2: Create Migration file, Execute migrations and Run the Application\n python manage.py makemigrations\n python manage.py migrate\n python manage.py runserver\n\n### Create User \n python manage.py createsuperuser\n \n## Api request and response\n#### Login user\n curl -X POST \\\n http://127.0.0.1:8000/api-token-auth/ \\\n -d '{\n \"username\":\"{enter username}\",\n \"password\":\"{password}\"\n }'\n Response:\n {\n \"token\": \"4bcb0439356a53a577355abe01d42d39428b0e89\"\n }\n#### Post the Blog\n curl -X POST \\\n http://127.0.0.1:8000/api/v1/blog/post/ \\\n -H 'Authorization: token {token}' \\\n -d '{\n \"title\":\"{title name}\",\n \"content\":\"{body}.\",\n \"status\":\"P\"\n }'\n#### My Blogs\n curl -X GET \\\n http://127.0.0.1:8000/api/v1/blog/mybloglist/ \\\n -H 'Authorization: token {token}' \n#### Delete my Blog\n curl -X DELETE \\\n http://127.0.0.1:8000/api/v1/blog/deleteblog/ \\\n -H 'Authorization: token {token}' \\\n -d '{\n \"id\":\"{blog id}\"\n }'\n#### To list the Blogs with total_likes, total_dislike, total_comment and total_views for the perticular blog with Pagination\n curl -X GET \\\n http://127.0.0.1:8000/api/v1/blog/listofblogs/ \\\n -H 'Authorization: token {token}' \\\n#### To like the perticular Blog\n curl -X POST \\\n http://127.0.0.1:8000/api/v1/blog/like/ \\\n -H 'Authorization: token {token}' \\\n -d '{\n \"id\": \"{blog_id}\"\n }\n Response:\n {\n \"status\": \"ok\"\n }\n#### To dislike \n curl -X POST \\\n http://127.0.0.1:8000/api/v1/blog/dislike/ \\\n -H 'Authorization: token {token}' \\\n -d '{\n \"id\": \"{blog_id}\"\n }'\n Response:\n {\n \"status\": \"ok\"\n }\n#### To get the Blog and this api increament the number of views.\n curl -X GET \\\n http://127.0.0.1:8000/api/v1/blog/getblog/ \\\n -H 'Authorization: token {token}' \n \"id\":\"{blog_id}\"\n }'\n#### Comment to the Blog\n curl -X POST \\\n http://127.0.0.1:8000/api/v1/comment/postcomment/ \\\n -H 'Authorization: token {token}' \\\n -d '{\n \"id\":\"{blog_id}\",\n \"comment\":\"{comment}./\"\n }'\n#### List a blog Comments\n curl -X GET \\\n http://127.0.0.1:8000/api/v1/comment/listcomment/ \\\n -H 'Authorization: token {token}' \\\n -d '{\n \"id\":\"{blog_id}\"\n }'\n#### Delete the Comment\n curl -X DELETE \\\n http://127.0.0.1:8000/api/v1/comment/deletecomment/ \\\n -H 'Authorization: token {token}' \\\n -d '{\n \"id\":\"{comment_id}\"\n }'\n Response:\n {\n \"detail\": \"deleted successfully.\"\n }\n#### Blogs Details will display the who all commented liked and disliked the Blogs.\n curl -X GET \\\n http://127.0.0.1:8000/api/v1/blog/blogsdetails/ \\\n -H 'Authorization: token {token}' \\\n" }, { "alpha_fraction": 0.5879675149917603, "alphanum_fraction": 0.5959118008613586, "avg_line_length": 32.050148010253906, "blob_id": "1d4a23930444f7221160caade2f217cc60ca47f2", "content_id": "0974055e06f73a2b3cdad892db437effcb73c61b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11203, "license_type": "no_license", "max_line_length": 123, "num_lines": 339, "path": "/blogger/blog/views.py", "repo_name": "rajunadaf570/My-Blog", "src_encoding": "UTF-8", "text": "#django/rest_framework imports.\nfrom django.shortcuts import render\nfrom django.db.models import Max\nfrom django.http import Http404\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import GenericViewSet\nfrom rest_framework import status\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nimport json\nfrom django.db.models import F\n\n#app level imports.\nfrom .serializer import(\n BlogPostSerializer,\n ListOfBlogsSerializer,\n CommentPostSerializer,\n ListOfCommentsSerializer,\n ListOfBlogsWithDetailsSerializer,\n)\nfrom libs.constants import(\n BAD_ACTION,\n BAD_REQUEST,\n)\nfrom libs.exceptions import(\n ParseException,\n ResourceNotFoundException,\n)\nfrom .models import (\n Blog,\n Comment,\n)\nfrom libs.sort_json_data import sort\n\n\nclass BlogViewSet(GenericViewSet):\n \"\"\"\n \"\"\"\n lookup_field = 'id'\n http_method_names = ['get', 'post', 'put','delete']\n model = Blog\n\n permission_classes=[IsAuthenticated, ]\n\n def get_queryset(self, filterdata=None):\n self.queryset = self.model.objects.all()\n if filterdata:\n self.queryset = self.queryset.filter(**filterdata)\n return self.queryset\n\n def get_object(self, id):\n try:\n return self.model.objects.get(id=id)\n except Exception as key:\n raise Http404('Invalid id')\n # raise ResourceNotFoundException()\n\n serializers_dict = {\n 'post': BlogPostSerializer,\n 'mybloglist': ListOfBlogsSerializer,\n 'listofblogs': ListOfBlogsSerializer,\n 'mostliked': ListOfBlogsSerializer,\n 'mostcommented': ListOfBlogsSerializer,\n 'mostdisliked': ListOfBlogsSerializer,\n 'mostviewd': ListOfBlogsSerializer,\n 'blogsdetails': ListOfBlogsWithDetailsSerializer,\n 'getblog': ListOfBlogsWithDetailsSerializer,\n }\n\n def get_serializer_class(self):\n \"\"\"\n \"\"\"\n try:\n return self.serializers_dict[self.action]\n except KeyError as key:\n raise ParseException(BAD_ACTION, errors=key)\n\n @action(methods=['post'], detail=False)\n def post(self, request):\n '''\n Post your blog.\n '''\n data = request.data\n data[\"author\"] = request.user.id\n\n serializer = self.get_serializer(data=data)\n print(serializer.is_valid())\n print(serializer.errors)\n if serializer.is_valid() is False:\n raise ParseException(BAD_REQUEST, serializer.errors)\n\n user = serializer.save()\n print(user)\n if user:\n return Response(serializer.data, status=status.HTTP_201_CREATED) \n return Response(serializer.data, status=status.HTTP_200_OK)\n\n @action(methods=['get'], detail=False)\n def mybloglist(self, request):\n '''\n To get the perticular user blogs.\n '''\n try:\n data = self.get_serializer(self.get_queryset(\n filterdata={\"author\": request.user}), many=True).data\n\n page = self.paginate_queryset(data)\n if page is not None:\n return self.get_paginated_response(page)\n\n except Exception as e:\n return Response({'error':str(e)},\n status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n @action(methods=['delete'], detail=False)\n def deleteblog(self, request):\n '''\n delete blog.\n '''\n try:\n data = self.get_queryset(filterdata={\"author\": request.user,\"id\": request.data[\"id\"]})\n data.delete()\n return Response(({\"detail\": \"deleted successfully.\"}),\n status=status.HTTP_200_OK)\n except Exception as e:\n return Response({\"error\":str(e)}, status=status.HTTP_400_BAD_REQUEST)\n\n @action(methods=['get'], detail=False)\n def listofblogs(self, request):\n '''\n List of blogs.\n '''\n try:\n data = self.get_serializer(self.get_queryset(filterdata={'status':'P'}), many=True).data\n page = self.paginate_queryset(data)\n if page is not None:\n return self.get_paginated_response(page)\n\n except Exception as e:\n return Response({'error':str(e)}, \n status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n @action(\n methods=['post'], detail=False\n )\n def like(self, request):\n '''\n This function will like the perticular blog, but before liking \n it will remove the dislike.\n '''\n try:\n obj = self.get_object(id=request.data['id'])\n obj.dislikes.remove(request.user) # <-- remove\n obj.likes.add(request.user)\n return Response(({'status':'ok'}), status=status.HTTP_200_OK)\n\n except Exception as e:\n return Response(({'error':str(e)}), status=status.HTTP_400_BAD_REQUEST)\n\n @action(\n methods=['post'], detail=False\n )\n def dislike(self, request):\n '''\n This function will dislike the blog, but before disliking it will remove the \n like.\n '''\n try:\n obj = self.get_object(id=request.data['id'])\n obj.likes.remove(request.user) # <-- remove \n obj.dislikes.add(request.user)\n return Response(({'status':'ok'}), status=status.HTTP_200_OK)\n\n except Exception as e:\n return Response(({'error':str(e)}), status=status.HTTP_400_BAD_REQUEST)\n\n @action(methods=['get'], detail=False)\n def mostcommented(self, request):\n '''\n It returns most commentd blog.\n '''\n try:\n data = self.get_serializer(self.get_queryset(filterdata={'status':'P'}), many=True).data\n most_commented = sort(data, 'total_comments')[-1]\n return Response(most_commented, status=status.HTTP_200_OK) \n\n except Exception as e:\n return Response(({'error':str(e)}), status=status.HTTP_400_BAD_REQUEST)\n\n @action(methods=['get'], detail=False)\n def mostliked(self, request):\n '''\n It returns most liked blog.\n '''\n try: \n data = self.get_serializer(self.get_queryset(filterdata={'status':'P'}), many=True).data\n most_liked = sort(data, 'total_likes')[-1]\n return Response(most_liked, status=status.HTTP_200_OK)\n\n except Exception as e:\n return Response(({'error':str(e)}), status=status.HTTP_400_BAD_REQUEST)\n\n @action(methods=['get'], detail=False)\n def mostdisliked(self, request):\n '''\n It returns most disliked blog.\n '''\n try:\n data = self.get_serializer(self.get_queryset(filterdata={'status':'P'}), many=True).data\n most_disliked = sort(data, 'total_dislikes')[-1]\n return Response(most_disliked, status=status.HTTP_200_OK)\n\n except Exception as e:\n return Response(({'error':str(e)}), status=status.HTTP_400_BAD_REQUEST)\n\n @action(methods=['get'], detail=False)\n def mostviewd(self, request):\n '''\n It returns most viewd blog.\n '''\n try:\n data = self.get_serializer(self.get_queryset(filterdata={'status':'P'}), many=True).data\n most_disliked = sort(data, 'views')[-1]\n return Response(most_disliked, status=status.HTTP_200_OK)\n\n except Exception as e:\n return Response(({'error':str(e)}), status=status.HTTP_400_BAD_REQUEST)\n\n\n @action(methods=['get'], detail=False)\n def getblog(self, request):\n '''\n To get the perticular blog.\n '''\n try:\n self.model.objects.filter(id=request.data['id'], status='P').update(views=F('views')+1) # <-- increament views.\n data = self.get_serializer(self.get_queryset(\n filterdata={\"id\": request.data['id'], 'status':'P'}), many=True).data\n return Response(data, status=status.HTTP_200_OK)\n\n except Exception as e:\n return Response(({'error':str(e)}), status=status.HTTP_400_BAD_REQUEST)\n\n\n @action(methods=['get'], detail=False)\n def blogsdetails(self, request):\n '''\n get all the blogs with total views who commented , who liked, and who disliked.\n '''\n try:\n data = self.get_serializer(self.get_queryset(filterdata={'status':'P'}), many=True).data\n page = self.paginate_queryset(data)\n if page is not None:\n return self.get_paginated_response(page)\n\n except Exception as e:\n return Response({'error':str(e)},\n status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n\nclass BlogsCommentViewSet(GenericViewSet):\n \"\"\"\n \"\"\"\n lookup_field = 'id'\n http_method_names = ['get', 'post', 'put','delete']\n model = Comment\n\n permission_classes = [IsAuthenticated, ]\n\n def get_queryset(self, filterdata=None):\n self.queryset = self.model.objects.all()\n if filterdata:\n self.queryset = self.queryset.filter(**filterdata)\n return self.queryset\n\n\n def get_serializer_class(self):\n \"\"\"\n \"\"\"\n try:\n return self.serializers_dict[self.action]\n except KeyError as key:\n raise ParseException(BAD_ACTION, errors=key)\n\n serializers_dict = {\n 'postcomment': CommentPostSerializer,\n 'listcomment': ListOfCommentsSerializer,\n }\n\n @action(methods=['post'], detail=False)\n def postcomment(self, request):\n '''\n Post your Comment to the Blog.\n '''\n data = request.data\n data[\"blog\"] = request.data['id']\n\n serializer = self.get_serializer(data=data)\n print(serializer.is_valid())\n print(serializer.errors)\n if serializer.is_valid() is False:\n raise ParseException(BAD_REQUEST, serializer.errors)\n\n user = serializer.save()\n print(user)\n if user:\n return Response(serializer.data, status=status.HTTP_201_CREATED) \n return Response(serializer.data, status=status.HTTP_200_OK)\n\n @action(methods=['get'], detail=False)\n def listcomment(self, request):\n '''\n To get the list of Comments for a perticular blog.\n '''\n try:\n data = self.get_serializer(self.get_queryset(\n filterdata={\"blog\": request.data['id']}), many=True).data\n\n page = self.paginate_queryset(data)\n if page is not None:\n return self.get_paginated_response(page)\n\n except Exception as e:\n return Response({'error':str(e)},\n status=status.HTTP_400_BAD_REQUEST)\n\n @action(methods=['delete'], detail=False)\n def deletecomment(self, request):\n '''\n delete comment.\n '''\n try:\n data = self.get_queryset(filterdata={\"id\": request.data[\"id\"]})\n data.delete()\n return Response(({\"detail\": \"deleted successfully.\"}),\n status=status.HTTP_200_OK)\n except Exception as e:\n return Response({\"error\":str(e)}, status=status.HTTP_400_BAD_REQUEST)" }, { "alpha_fraction": 0.7351778745651245, "alphanum_fraction": 0.7378129363059998, "avg_line_length": 32, "blob_id": "864577598438fb90944696ae0ade4889f56f275a", "content_id": "163148a122877ed8bf34fdc5f65915e193530585", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 759, "license_type": "no_license", "max_line_length": 86, "num_lines": 23, "path": "/blogger/blogger/urls.py", "repo_name": "rajunadaf570/My-Blog", "src_encoding": "UTF-8", "text": "#django/rest_framework imports.\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom rest_framework.routers import SimpleRouter\n\n# third part imports.\nfrom rest_framework.authtoken.views import obtain_auth_token # <-- Here\n\n#project level imports.\nfrom blog import views as blog_views\n\n# intialize DefaultRouter.\nrouter = SimpleRouter()\n\n# register blog app urls with router.\nrouter.register(r'blog', blog_views.BlogViewSet, base_name='blog')\nrouter.register(r'comment', blog_views.BlogsCommentViewSet, base_name='comment')\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('api/v1/', include((router.urls, 'api'), namespace='v1')),\n path('api-token-auth/', obtain_auth_token, name='api_token_auth'), # <-- And here\n]\n" }, { "alpha_fraction": 0.5615141987800598, "alphanum_fraction": 0.5709779262542725, "avg_line_length": 42.509803771972656, "blob_id": "ebea00e25ef61fda1e8d42321716f3f12b5cda27", "content_id": "ecf13e3439422e7636d00c51d989acede95275c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2219, "license_type": "no_license", "max_line_length": 141, "num_lines": 51, "path": "/blogger/blog/migrations/0001_initial.py", "repo_name": "rajunadaf570/My-Blog", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0 on 2019-12-15 19:52\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Blog',\n fields=[\n ('is_active', models.BooleanField(default=True)),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('updated_at', models.DateTimeField(auto_now=True)),\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('title', models.CharField(max_length=100, unique=True)),\n ('content', models.TextField()),\n ('status', models.CharField(choices=[('D', 'Draft'), ('P', 'Publish')], default='D', max_length=1)),\n ('views', models.BigIntegerField(default=0)),\n ('author', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='blog', to=settings.AUTH_USER_MODEL)),\n ('dislikes', models.ManyToManyField(blank=True, related_name='dislikes', to=settings.AUTH_USER_MODEL)),\n ('likes', models.ManyToManyField(blank=True, related_name='likes', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'ordering': ['-created_at'],\n },\n ),\n migrations.CreateModel(\n name='Comment',\n fields=[\n ('is_active', models.BooleanField(default=True)),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('updated_at', models.DateTimeField(auto_now=True)),\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('comment', models.TextField()),\n ('blog', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='blog', to='blog.Blog')),\n ],\n options={\n 'ordering': ['-created_at'],\n },\n ),\n ]\n" }, { "alpha_fraction": 0.8028846383094788, "alphanum_fraction": 0.8028846383094788, "avg_line_length": 22.22222137451172, "blob_id": "59deba06fb58e4915528738f9005d8efcaf90858", "content_id": "cb91956421ad44a7fa281da47b227808714cdd7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208, "license_type": "no_license", "max_line_length": 33, "num_lines": 9, "path": "/blogger/blog/admin.py", "repo_name": "rajunadaf570/My-Blog", "src_encoding": "UTF-8", "text": "#django/rest_framework imports.\nfrom django.contrib import admin\n\n#project level imports.\nfrom .models import Blog, Comment\n\n# Register your models here.\nadmin.site.register(Blog)\nadmin.site.register(Comment)" }, { "alpha_fraction": 0.6216216087341309, "alphanum_fraction": 0.6216216087341309, "avg_line_length": 29.33333396911621, "blob_id": "fb013766f96e2e9a21c5db92fc5d1b68957c2a4a", "content_id": "ce09c09e4de7ec664564d5be66c421d1d7d46093", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 185, "license_type": "no_license", "max_line_length": 61, "num_lines": 6, "path": "/blogger/libs/sort_json_data.py", "repo_name": "rajunadaf570/My-Blog", "src_encoding": "UTF-8", "text": "\n\n\n\ndef sort(data, value):\n '''\n Sort the Json data in asscending order using given value.\n '''\n sorted_data = sorted(data, key = lambda i: i[value])\n return sorted_data" }, { "alpha_fraction": 0.6461145281791687, "alphanum_fraction": 0.6472090482711792, "avg_line_length": 27.24742317199707, "blob_id": "6c25fab9873c59e7e509c5a78f70e16137cdc9ba", "content_id": "ec2d85b719b72d6a4e0d07736b7c9f621ed7a72a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2741, "license_type": "no_license", "max_line_length": 103, "num_lines": 97, "path": "/blogger/blog/serializer.py", "repo_name": "rajunadaf570/My-Blog", "src_encoding": "UTF-8", "text": "#django/rest_framework imports.\nfrom rest_framework import serializers\nfrom django.contrib.auth.models import User\n\n\n#app level imports.\nfrom .models import (\n Blog,\n Comment,\n)\n\n\nclass BlogPostSerializer(serializers.ModelSerializer):\n \"\"\"\n BlogPost Serializer.\n \"\"\"\n title = serializers.CharField(required=False, min_length=2)\n content = serializers.CharField(required=False, min_length=2)\n author = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())\n status = serializers.ChoiceField(\n choices = (\n ('D', 'Draft'),\n ('P', 'Publish'),\n )\n ) \n class Meta:\n model = Blog\n fields = ('id', 'title', 'content', 'author', 'status', )\n\n def create(self, validated_data):\n user = Blog.objects.create(**validated_data)\n user.save()\n return user\n\nclass ListOfBlogsSerializer(serializers.ModelSerializer):\n \"\"\"\n List of Blog Serializer.\n \"\"\"\n total_comments = serializers.SerializerMethodField()\n\n class Meta:\n model = Blog\n fields = ('id', 'title', 'content', 'total_likes', 'total_dislikes', 'total_comments','views' )\n\n def get_total_comments(self, obj):\n return Comment.objects.filter(blog=obj).count()\n\n def validate(self, data):\n return data\n\n\nclass CommentPostSerializer(serializers.ModelSerializer):\n \"\"\"\n Post comment serializer.\n \"\"\"\n comment = serializers.CharField(required=False, min_length=2)\n blog = serializers.PrimaryKeyRelatedField(queryset=Blog.objects.all())\n\n class Meta:\n model = Comment\n fields = ('id', 'comment', 'blog')\n\n def create(self, validated_data):\n user = Comment.objects.create(**validated_data)\n user.save()\n return user\n\nclass ListOfCommentsSerializer(serializers.ModelSerializer):\n \"\"\"\n List of comment serializer.\n \"\"\"\n class Meta:\n model = Comment\n fields = ('id', 'blog_id' , 'comment')\n\n\nclass ListOfBlogsWithDetailsSerializer(serializers.ModelSerializer):\n \"\"\"\n List of Blog with details serializer.\n \"\"\"\n\n comments = serializers.SerializerMethodField()\n who_likes = serializers.SerializerMethodField()\n who_dislikes = serializers.SerializerMethodField()\n\n class Meta:\n model = Blog\n fields = ('id', 'title', 'content', 'views', 'comments', 'who_likes', 'who_dislikes', )\n\n def get_comments(self, obj):\n return Comment.objects.filter(blog=obj).values('comment','blog__author__username', )\n\n def get_who_likes(self, obj):\n return Blog.objects.filter(title=obj).values('likes__username')\n\n def get_who_dislikes(self, obj):\n return Blog.objects.filter(title=obj).values('dislikes__username')\n\n" }, { "alpha_fraction": 0.6541943550109863, "alphanum_fraction": 0.6584188342094421, "avg_line_length": 25.30158805847168, "blob_id": "41bd304932caa05031fdf67ae14c2c705c9c3134", "content_id": "aad78ca48a5256a010878c0c765689ce21a42616", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1657, "license_type": "no_license", "max_line_length": 80, "num_lines": 63, "path": "/blogger/blog/models.py", "repo_name": "rajunadaf570/My-Blog", "src_encoding": "UTF-8", "text": "# python imports\nimport uuid\n\n#django/rest_framework imports.\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\n# project level imports\nfrom libs.models import TimeStampedModel\n\n# third party imports\nfrom model_utils import Choices\n\n\nclass Blog(TimeStampedModel):\n \"\"\"\n Blog model represents the number of blogs in the database.\n \"\"\"\n STATUS = Choices(\n ('D', 'Draft'),\n ('P', 'Publish'),\n )\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n title = models.CharField(max_length=100, unique=True)\n content = models.TextField()\n likes = models.ManyToManyField(User, related_name='likes', blank=True)\n dislikes = models.ManyToManyField(User, related_name='dislikes', blank=True)\n status = models.CharField(choices=STATUS, max_length=1, default='D')\n views = models.BigIntegerField(default=0)\n author = models.ForeignKey(\n User,\n on_delete=models.PROTECT,\n related_name='blog'\n )\n\n class Meta:\n ordering = ['-created_at']\n\n def __str__(self):\n return self.title\n\n @property\n def total_likes(self):\n return self.likes.count()\n\n @property\n def total_dislikes(self):\n return self.dislikes.count()\n\n\nclass Comment(TimeStampedModel):\n \"\"\"\n Comment model represent list of comments in perticular Blog.\n \"\"\"\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n comment = models.TextField()\n blog = models.ForeignKey(\n Blog,\n on_delete=models.CASCADE,\n related_name='blog'\n )\n class Meta:\n ordering = ['-created_at']\n" } ]
9
tokjun/VentriculostomyPlanning
https://github.com/tokjun/VentriculostomyPlanning
0b85f6682131eb3cea112f6514dbfdc6faca7718
1276638d2e08285937a8786ffd238609c03e82d7
72c92ecfbad6d4ed568a5d53baf89ef95780bdd4
refs/heads/master
2020-12-04T18:02:00.673355
2018-08-08T03:33:55
2018-08-08T03:33:55
66,381,178
0
3
null
2016-08-23T15:50:22
2016-08-23T15:55:13
2017-05-17T12:05:18
Python
[ { "alpha_fraction": 0.7148798704147339, "alphanum_fraction": 0.7239904999732971, "avg_line_length": 55.1513671875, "blob_id": "db6a69e027cb348b5ed1d5f2031887b2344e552d", "content_id": "409eac7548819c3b72092214f9117376fcd061c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 215902, "license_type": "no_license", "max_line_length": 246, "num_lines": 3845, "path": "/VentriculostomyPlanning/VentriculostomyPlanning.py", "repo_name": "tokjun/VentriculostomyPlanning", "src_encoding": "UTF-8", "text": "import os, inspect\nimport json\nimport unittest\nimport vtk, qt, ctk, slicer\nfrom slicer.ScriptedLoadableModule import *\nfrom slicer.util import VTKObservationMixin\nimport logging\nimport tempfile\nfrom ctk import ctkAxesWidget\nimport numpy\nimport SimpleITK as sitk\nimport sitkUtils\nimport DICOM\nfrom DICOM import DICOMWidget\nimport PercutaneousApproachAnalysis\nfrom PercutaneousApproachAnalysis import *\nfrom numpy import linalg\nfrom code import interact\nfrom VentriculostomyPlanningUtils.SlicerCaseManager import SlicerCaseManagerWidget, beforeRunProcessEvents\nfrom VentriculostomyPlanningUtils.PopUpMessageBox import SerialAssignMessageBox, SagittalCorrectionMessageBox\nfrom VentriculostomyPlanningUtils.UserEvents import VentriculostomyUserEvents\nfrom VentriculostomyPlanningUtils.UsefulFunctions import UsefulFunctions\nfrom VentriculostomyPlanningUtils.WatchDog import WatchDog\nfrom VentriculostomyPlanningUtils.Constants import EndPlacementModes, SagittalCorrectionStatus, CandidatePathStatus\nfrom VentriculostomyPlanningUtils.VentriclostomyButtons import *\nfrom SlicerDevelopmentToolboxUtils.buttons import FourUpLayoutButton\nfrom SlicerDevelopmentToolboxUtils.mixins import ModuleWidgetMixin, ModuleLogicMixin\nfrom shutil import copyfile\nfrom os.path import basename\nfrom os import listdir\nfrom abc import ABCMeta, abstractmethod\nimport datetime\nfrom functools import wraps\n# VentriculostomyPlanning\n\nclass VentriculostomyPlanning(ScriptedLoadableModule):\n \"\"\"Uses ScriptedLoadableModule base class, available at:\n https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py\n \"\"\"\n\n def __init__(self, parent):\n ScriptedLoadableModule.__init__(self, parent)\n self.parent.title = \"VentriculostomyPlanning\" # TODO make this more human readable by adding spaces\n self.parent.categories = [\"IGT\"]\n self.parent.contributors = [\"Junichi Tokuda (BWH)\", \"Longquan Chen(BWH)\"] # replace with \"Firstname Lastname (Organization)\"\n self.parent.helpText = \"\"\"\n This is an scripted module for ventriclostomy planning\n \"\"\"\n self.parent.acknowledgementText = \"\"\"\n This module was developed based on an example code provided by Jean-Christophe Fillion-Robin, Kitware Inc.\n and Steve Pieper, Isomics, Inc. and was partially funded by NIH grant 3P41RR013218-12S1.\n\"\"\" # replace with organization, grant and thanks.\n\n#\n# VentriculostomyPlanningWidget\n#\n\nclass VentriculostomyPlanningWidget(ScriptedLoadableModuleWidget, ModuleWidgetMixin):\n \"\"\"Uses ScriptedLoadableModuleWidget base class, available at:\n https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py\n \"\"\"\n buttonWidth = 45\n buttonHeight = 45\n\n def setup(self):\n ScriptedLoadableModuleWidget.setup(self)\n ModuleWidgetMixin.__init__(self)\n self.scriptDirectory = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"Resources\", \"icons\")\n self.logic = VentriculostomyPlanningLogic()\n self.logic.register(self)\n self.dicomWidget = DICOMWidget()\n self.dicomWidget.parent.close()\n self.SerialAssignBox = SerialAssignMessageBox()\n self.SagittalCorrectionBox = SagittalCorrectionMessageBox()\n self.volumeSelected = False\n self.volumePrepared = False\n self.baseVolumeWindowValue = 974\n self.baseVolumeLevelValue = 270\n self.jsonFile = \"\"\n self.isLoadingCase = False\n self.isInAlgorithmSteps = False\n self.isReverseView = False\n self.progressBar = slicer.util.createProgressDialog()\n self.progressBar.close()\n self.watchDog = WatchDog(5, self.volumeLoadTimeOutHandle)\n self.watchDog.stop()\n self.red_widget = slicer.app.layoutManager().sliceWidget(\"Red\")\n self.red_cn = self.red_widget.mrmlSliceCompositeNode()\n self.red_cn.SetDoPropagateVolumeSelection(False)\n\n self.yellow_widget = slicer.app.layoutManager().sliceWidget(\"Yellow\")\n self.yellow_cn = self.yellow_widget.mrmlSliceCompositeNode()\n self.yellow_cn.SetDoPropagateVolumeSelection(False)\n\n self.green_widget = slicer.app.layoutManager().sliceWidget(\"Green\")\n self.green_cn = self.green_widget.mrmlSliceCompositeNode()\n self.green_cn.SetDoPropagateVolumeSelection(False)\n\n # segmentation widget for 3D export ...\n segmentationWidget = slicer.modules.segmentations.widgetRepresentation()\n self.activeSegmentSelector = segmentationWidget.findChild(\"qMRMLNodeComboBox\", \"MRMLNodeComboBox_Segmentation\")\n self.labelMapSelector = segmentationWidget.findChild(\"qMRMLNodeComboBox\", \"MRMLNodeComboBox_ImportExportNode\")\n self.importRadioButton = segmentationWidget.findChild(\"QRadioButton\", \"radioButton_Import\")\n self.exportRadioButton = segmentationWidget.findChild(\"QRadioButton\", \"radioButton_Export\")\n self.labelMapRadioButton = segmentationWidget.findChild(\"QRadioButton\", \"radioButton_Labelmap\")\n self.modelsRadioButton = segmentationWidget.findChild(\"QRadioButton\", \"radioButton_Model\")\n self.portPushButton = segmentationWidget.findChild(\"ctkPushButton\", \"PushButton_ImportExport\")\n\n # Instantiate and connect widgets ...\n #\n # Lines Area\n #\n\n # Layout within the dummy collapsible button\n\n self.caseManagerBox = qt.QGroupBox()\n CaseManagerInfoLayout = qt.QVBoxLayout()\n self.caseManagerBox.setLayout(CaseManagerInfoLayout)\n slicerCaseWidgetParent = slicer.qMRMLWidget()\n slicerCaseWidgetParent.setLayout(qt.QVBoxLayout())\n slicerCaseWidgetParent.setMRMLScene(slicer.mrmlScene)\n self.slicerCaseWidget = SlicerCaseManagerWidget(slicerCaseWidgetParent)\n self.slicerCaseWidget.logic.register(self)\n CaseManagerInfoLayout.addWidget(self.slicerCaseWidget.patientWatchBox)\n #CaseManagerInfoLayout.addWidget(self.slicerCaseWidget.caseWatchBox)\n CaseManagerInfoLayout.addWidget(self.slicerCaseWidget.mainGUIGroupBox)\n\n self.caseRootConfigLayout = qt.QHBoxLayout()\n self.caseRootConfigLayout.addWidget(self.slicerCaseWidget.rootDirectoryLabel)\n self.caseRootConfigLayout.addWidget(self.slicerCaseWidget.casesRootDirectoryButton)\n #\n # Mid-sagittalReference lineCaseManagerInfoLayout\n #\n \"\"\"\"\"\"\n\n referenceConfigLayout = qt.QHBoxLayout()\n lengthSagittalReferenceLineLabel = self.createLabel('Sagittal Length: ')\n #-- Curve length\n referenceConfigLayout.addWidget(lengthSagittalReferenceLineLabel)\n self.lengthSagittalReferenceLineEdit = self.createLineEdit(title= \"\", text = '100.0', readOnly = False, frame = True,\n styleSheet = \"QLineEdit { background:transparent; }\", cursor = qt.QCursor(qt.Qt.IBeamCursor))\n self.lengthSagittalReferenceLineEdit.setSizePolicy(qt.QSizePolicy.Minimum, qt.QSizePolicy.Expanding)\n self.lengthSagittalReferenceLineEdit.connect('textEdited(QString)', self.onModifyMeasureLength)\n referenceConfigLayout.addWidget(self.lengthSagittalReferenceLineEdit)\n lengthSagittalReferenceLineUnitLabel = self.createLabel('mm ')\n referenceConfigLayout.addWidget(lengthSagittalReferenceLineUnitLabel)\n\n lengthCoronalReferenceLineLabel = self.createLabel('Coronal Length: ')\n referenceConfigLayout.addWidget(lengthCoronalReferenceLineLabel)\n self.lengthCoronalReferenceLineEdit = self.createLineEdit(title= \"\", text = '30.0', readOnly = False, frame = True,\n styleSheet=\"QLineEdit { background:transparent; }\", cursor = qt.QCursor(qt.Qt.IBeamCursor))\n self.lengthCoronalReferenceLineEdit.setSizePolicy(qt.QSizePolicy.Minimum, qt.QSizePolicy.Expanding)\n self.lengthCoronalReferenceLineEdit.connect('textEdited(QString)', self.onModifyMeasureLength)\n referenceConfigLayout.addWidget(self.lengthCoronalReferenceLineEdit)\n lengthCoronalReferenceLineUnitLabel = self.createLabel('mm ')\n referenceConfigLayout.addWidget(lengthCoronalReferenceLineUnitLabel)\n\n self.selectSagittalButton = self.createButton(title=\"\",\n toolTip=\"Add a point in the 3D window to identify the sagittal plane\",\n enabled=True,\n maximumHeight=self.buttonHeight, maximumWidth=self.buttonWidth,\n checkable=True,\n icon=self.createIcon(\"sagittalPoint.png\", self.scriptDirectory),\n iconSize=qt.QSize(self.buttonHeight, self.buttonWidth))\n self.selectSagittalButton.connect('clicked(bool)', self.onSelectSagittalPoint)\n referenceConfigLayout.addWidget(self.selectSagittalButton)\n referenceConfigLayout.addStretch(1)\n\n\n self.layout.addWidget(self.caseManagerBox)\n\n self.reloadButton = self.createButton(title=\"Reload\", toolTip = \"Reload this module.\", name = \"VentriculostomyPlanning Reload\")\n self.reloadButton.connect('clicked()', self.onReload)\n referenceConfigLayout.addWidget(self.reloadButton)\n\n # -- Algorithm setting\n # Surface Model calculation\n surfaceModelConfigLayout = qt.QHBoxLayout()\n surfaceModelThresholdLabel = self.createLabel('Surface Model Intensity Threshold Setting: ')\n surfaceModelConfigLayout.addWidget(surfaceModelThresholdLabel)\n self.surfaceModelThresholdEdit = self.createLineEdit(title= \"\", text = '-500', readOnly = False, frame = True, toolTip = \"set this value to the intensity of the skull, higher value means less segmented skull\",\n maxLength = 6, styleSheet = \"QLineEdit { background:transparent; }\", cursor = qt.QCursor(qt.Qt.IBeamCursor))\n self.surfaceModelThresholdEdit.connect('textEdited(QString)', self.onModifySurfaceModel)\n surfaceModelConfigLayout.addWidget(self.surfaceModelThresholdEdit)\n\n self.createModelButton = self.createButton(title=\"Create Surface\", toolTip=\"Create a surface model.\", enabled=True)\n self.createModelButton.connect('clicked(bool)', self.onCreateModel)\n surfaceModelConfigLayout.addWidget(self.createModelButton)\n\n # Venous model calculation and margin setting\n venousMarginConfigLayout = qt.QHBoxLayout()\n venousMarginLabel = self.createLabel('Venous Safety Margin: ')\n venousMarginConfigLayout.addWidget(venousMarginLabel)\n self.venousMarginEdit = self.createLineEdit(title=\"\", text='10.0', readOnly=False, frame=True, maxLength = 6,\n styleSheet=\"QLineEdit { background:transparent; }\",\n cursor=qt.QCursor(qt.Qt.IBeamCursor))\n self.venousMarginEdit.connect('textEdited(QString)', self.onModifyVenousMargin)\n venousMarginConfigLayout.addWidget(self.venousMarginEdit)\n venousMarginUnitLabel = qt.QLabel('mm ')\n venousMarginConfigLayout.addWidget(venousMarginUnitLabel)\\\n\n self.grayScaleMakerButton = self.createButton(title=\"Segment GrayScale\", enabled=True,\n toolTip=\"Use the GrayScaleMaker module for vessel calculation \")\n self.grayScaleMakerButton.connect('clicked(bool)', self.onVenousGrayScaleCalc)\n venousMarginConfigLayout.addWidget(self.grayScaleMakerButton)\n venousMarginConfigLayout.addStretch(1)\n\n # Posterior margin distance setting\n posteriorMarginConfigLayout = qt.QHBoxLayout()\n posteriorMarginLabel = self.createLabel('Posterior Safety Margin: ')\n posteriorMarginConfigLayout.addWidget(posteriorMarginLabel)\n self.posteriorMarginEdit = self.createLineEdit(title=\"\", text='60.0', readOnly=False, frame=True, maxLength=6,\n styleSheet=\"QLineEdit { background:transparent; }\",\n cursor=qt.QCursor(qt.Qt.IBeamCursor))\n self.posteriorMarginEdit.connect('textEdited(QString)', self.onChangePosteriorMargin)\n posteriorMarginConfigLayout.addWidget(self.posteriorMarginEdit)\n posteriorMarginUnitLabel = qt.QLabel('mm ')\n posteriorMarginConfigLayout.addWidget(posteriorMarginUnitLabel)\n posteriorMarginConfigLayout.addStretch(1)\n\n kocherMarginConfigLayout = qt.QHBoxLayout()\n kocherMarginLabel = self.createLabel('Kocher Distance Limit: ')\n kocherMarginConfigLayout.addWidget(kocherMarginLabel)\n self.kocherMarginEdit = self.createLineEdit(title=\"\", text='20.0', readOnly=False, frame=True, maxLength=6,\n styleSheet=\"QLineEdit { background:transparent; }\",\n cursor=qt.QCursor(qt.Qt.IBeamCursor))\n self.kocherMarginEdit.connect('textEdited(QString)', self.onChangeKocherMargin)\n kocherMarginConfigLayout.addWidget(self.kocherMarginEdit)\n kocherMarginUnitLabel = qt.QLabel('mm ')\n kocherMarginConfigLayout.addWidget(kocherMarginUnitLabel)\n kocherMarginConfigLayout.addStretch(1)\n\n\n self.mainGUIGroupBox = qt.QGroupBox()\n self.mainGUIGroupBoxLayout = qt.QGridLayout()\n self.mainGUIGroupBox.setLayout(self.mainGUIGroupBoxLayout)\n self.layout.addWidget(self.mainGUIGroupBox)\n\n self.inputVolumeBox = qt.QGroupBox()\n inputVolumeLayout = qt.QGridLayout()\n self.inputVolumeBox.setLayout(inputVolumeLayout)\n self.layout.addWidget(self.inputVolumeBox)\n venousVolumeLabel = self.createLabel(title = 'Venous')\n venousVolumeLabel.setAlignment(qt.Qt.AlignLeft | qt.Qt.AlignVCenter)\n\n self.venousVolumeNameLabel = self.createButton(title=\"--\", enabled = True, maximumWidth = 300, styleSheet = \"QPushButton { background:white; border: none;}\", toolTip = \"Show the table of volumes for assignment.\")\n inputVolumeLayout.addWidget(venousVolumeLabel,0,0)\n inputVolumeLayout.addWidget(self.venousVolumeNameLabel,0,1)\n ventricleVolumeLabel = self.createLabel(title='Ventricle')\n ventricleVolumeLabel.setAlignment(qt.Qt.AlignRight | qt.Qt.AlignVCenter)\n self.ventricleVolumeNameLabel = self.createButton(title=\"--\", enabled = True, maximumWidth = 300,\n styleSheet=\"QPushButton { background:white; border: none; }\", toolTip = \"Show the table of volumes for assignment.\")\n self.venousVolumeNameLabel.connect('clicked(bool)', self.onShowVolumeTable)\n self.ventricleVolumeNameLabel.connect('clicked(bool)', self.onShowVolumeTable)\n inputVolumeLayout.addWidget(ventricleVolumeLabel,0,3)\n inputVolumeLayout.addWidget(self.ventricleVolumeNameLabel,0,2)\n self.imageSlider = qt.QSlider(qt.Qt.Horizontal)\n self.imageSlider.setMinimum(0)\n self.imageSlider.setMaximum(100)\n self.imageSlider.connect('valueChanged(int)', self.onChangeSliceViewImage)\n inputVolumeLayout.addWidget(self.imageSlider,1,1,1,2)\n \n self.nodeAddedEventObserverID = slicer.mrmlScene.AddObserver(slicer.mrmlScene.NodeAddedEvent, self.onVolumeAddedNode)\n\n self.LoadCaseButton = self.createButton(title = \"\", toolTip = \"Load a dicom dataset\", enabled = False,\n maximumHeight = self.buttonHeight, maximumWidth = self.buttonWidth,\n icon = self.createIcon(\"load.png\", self.scriptDirectory),\n iconSize = qt.QSize(self.buttonHeight, self.buttonWidth))\n self.LoadCaseButton.connect('clicked(bool)', self.onLoadDicom)\n self.mainGUIGroupBoxLayout.addWidget(self.LoadCaseButton, 2, 0)\n\n self.selectNasionButton = self.createButton(title=\"\", toolTip=\"Add a point in the 3D window\", enabled=False,\n maximumHeight=self.buttonHeight, maximumWidth=self.buttonWidth, checkable = True,\n icon=self.createIcon(\"nasion.png\", self.scriptDirectory),\n iconSize=qt.QSize(self.buttonHeight, self.buttonWidth))\n self.selectNasionButton.connect('clicked(bool)', self.onSelectNasionPoint)\n self.mainGUIGroupBoxLayout.addWidget(self.selectNasionButton, 2, 1)\n\n\n #-- Add Point\n self.defineVentricleButton = self.createButton(title=\"\",\n toolTip=\"Define the ventricle cylinder\",\n enabled=False, checkable = True,\n maximumHeight=self.buttonHeight, maximumWidth=self.buttonWidth,\n icon=self.createIcon(\"cannula.png\", self.scriptDirectory),\n iconSize=qt.QSize(self.buttonHeight, self.buttonWidth))\n self.defineVentricleButton.connect('clicked(bool)', self.onDefineVentricle)\n self.mainGUIGroupBoxLayout.addWidget(self.defineVentricleButton,2,2)\n\n self.addVesselSeedButton = self.createButton(title=\"\",\n toolTip=\"Place the seeds for venous segmentation\",\n enabled=False, checkable = True,\n maximumHeight=self.buttonHeight, maximumWidth=self.buttonWidth,\n icon=self.createIcon(\"vessel.png\", self.scriptDirectory),\n iconSize=qt.QSize(self.buttonHeight, self.buttonWidth))\n self.addVesselSeedButton.connect('clicked(bool)', self.onPlaceVesselSeed)\n self.mainGUIGroupBoxLayout.addWidget(self.addVesselSeedButton, 2, 3)\n\n\n self.relocatePathToKocherButton = self.createButton(title=\"\",\n toolTip=\"Relocate the cannula to be close to Kocher's point\",\n enabled=False,\n maximumHeight=self.buttonHeight, maximumWidth=self.buttonWidth,\n icon=self.createIcon(\"pathPlanning.png\", self.scriptDirectory),\n iconSize=qt.QSize(self.buttonHeight, self.buttonWidth))\n self.relocatePathToKocherButton.connect('clicked(bool)', self.onRelocatePathToKocher)\n self.mainGUIGroupBoxLayout.addWidget(self.relocatePathToKocherButton, 2, 4)\n\n\n self.createPlanningLineButton = self.createButton(title=\"\",\n toolTip=\"Confirm the target and generate the planning line.\",\n enabled=False,\n maximumHeight=self.buttonHeight, maximumWidth=self.buttonWidth,\n icon=self.createIcon(\"confirm.png\", self.scriptDirectory),\n iconSize=qt.QSize(self.buttonHeight, self.buttonWidth))\n self.createPlanningLineButton.connect('clicked(bool)', self.onCreatePlanningLine)\n self.mainGUIGroupBoxLayout.addWidget(self.createPlanningLineButton, 2, 5)\n\n self.saveDataButton = self.createButton(title=\"\",\n toolTip=\"Save the scene and data.\",\n enabled=False,\n maximumHeight=self.buttonHeight, maximumWidth=self.buttonWidth,\n icon=self.createIcon(\"save.png\", self.scriptDirectory),\n iconSize=qt.QSize(self.buttonHeight, self.buttonWidth))\n self.saveDataButton.connect('clicked(bool)', self.onSaveData)\n self.mainGUIGroupBoxLayout.addWidget(self.saveDataButton, 2, 6)\n\n self.viewGroupBox = qt.QGroupBox()\n self.viewGroupBoxLayout = qt.QGridLayout()\n self.viewGroupBox.setLayout(self.viewGroupBoxLayout)\n self.layout.addWidget(self.viewGroupBox)\n\n self.tabWidget = qt.QTabWidget()\n self.layout.addWidget(self.tabWidget)\n self.tabWidget.tabBar().hide()\n # end of GUI section\n #####################################\n self.tabMainGroupBox = qt.QGroupBox()\n self.tabMainGroupBoxLayout = qt.QVBoxLayout()\n self.tabMainGroupBox.setLayout(self.tabMainGroupBoxLayout)\n self.tabMainGroupBoxName = \"tabMainGroup\"\n self.tabMarkupsName = \"markups\"\n self.tabWidgetChildrenName = [self.tabMainGroupBoxName, self.tabMarkupsName]\n self.tabWidget.addTab(self.tabMainGroupBox, self.tabMainGroupBoxName)\n self.tabMainGroupBox.visible = False\n\n self.tabMarkupPlacementGroupBox = qt.QGroupBox()\n self.tabMarkupPlacementGroupBoxLayout = qt.QVBoxLayout()\n self.tabMarkupPlacementGroupBox.setLayout(self.tabMarkupPlacementGroupBoxLayout)\n vesselThresholdLabel = qt.QLabel('Vessel Threshold factor')\n vesselThresholdLayout = qt.QHBoxLayout()\n self.vesselThresholdGroupBox = qt.QGroupBox()\n self.vesselThresholdGroupBox.setLayout(vesselThresholdLayout)\n self.rangeThresholdWidget = slicer.qMRMLRangeWidget()\n self.rangeThresholdWidget.minimum = 0.01\n self.rangeThresholdWidget.maximum = 1\n self.rangeThresholdWidget.singleStep = 0.05\n self.rangeThresholdWidget.setValues(0.75,1)\n self.rangeThresholdWidget.connect('valuesChanged(double, double)', self.onChangeThresholdValues)\n vesselThresholdLayout.addWidget(vesselThresholdLabel)\n vesselThresholdLayout.addWidget(self.rangeThresholdWidget)\n\n\n self.segmentVesselWithSeedsButton = self.createButton(title=\"\",\n toolTip=\"Segment the vessel based on threshold and seeds.\",\n enabled=True,\n maximumHeight=self.buttonHeight*0.8, maximumWidth=self.buttonWidth*0.8,\n icon=self.createIcon(\"startVesselSegment.png\", self.scriptDirectory),\n iconSize=qt.QSize(self.buttonHeight*0.8, self.buttonWidth*0.8))\n self.segmentVesselWithSeedsButton.connect('clicked(bool)', self.onSegmentVesselWithSeeds)\n vesselThresholdLayout.addWidget(self.segmentVesselWithSeedsButton)\n #self.tabMarkupPlacementGroupBoxLayout.addWidget(self.vesselThresholdGroupBox)\n\n self.simpleMarkupsWidget = slicer.qSlicerSimpleMarkupsWidget()\n self.simpleMarkupsWidget.setMRMLScene(slicer.mrmlScene)\n self.tabMarkupPlacementGroupBoxLayout.addWidget(self.simpleMarkupsWidget)\n\n self.tabWidget.addTab(self.tabMarkupPlacementGroupBox, self.tabMarkupsName)\n index = next((i for i, name in enumerate(self.tabWidgetChildrenName) if name == self.tabMainGroupBoxName), None)\n self.tabWidget.setCurrentIndex(index)\n \n #self.setWindowLevelButton = WindowLevelEffectsButton()\n self.greenLayoutButton = GreenSliceLayoutButton()\n self.conventionalLayoutButton = ConventionalSliceLayoutButton()\n self.fourUpLayoutButton = FourUpLayoutButton()\n self.screenShotButton = ScreenShotButton()\n self.setReverseViewButton = ReverseViewOnCannulaButton()\n self.viewGroupBoxLayout.addWidget(self.greenLayoutButton, 0, 0)\n self.viewGroupBoxLayout.addWidget(self.conventionalLayoutButton, 0, 1)\n self.viewGroupBoxLayout.addWidget(self.fourUpLayoutButton, 0, 2)\n self.viewGroupBoxLayout.addWidget(self.setReverseViewButton, 0, 3)\n self.viewGroupBoxLayout.addWidget(self.screenShotButton, 0, 4)\n #self.viewGroupBoxLayout.addWidget(self.setWindowLevelButton, 0, 5)\n #-- Curve length\n self.infoGroupBox = qt.QGroupBox()\n self.infoGroupBoxLayout = qt.QVBoxLayout()\n self.infoGroupBox.setLayout(self.infoGroupBoxLayout)\n\n cannulaLengthInfoLayout = qt.QHBoxLayout()\n lengthCannulaLabel = self.createLabel('Cannula Length: ')\n cannulaLengthInfoLayout.addWidget(lengthCannulaLabel)\n self.lengthCannulaEdit = self.createLineEdit(title=\"\", text='--', readOnly=True, frame=True, maxLength = 5,\n styleSheet=\"QLineEdit { background:transparent; }\",\n cursor=qt.QCursor(qt.Qt.IBeamCursor))\n cannulaLengthInfoLayout.addWidget(self.lengthCannulaEdit)\n lengthCannulaUnitLabel = self.createLabel('mm ')\n cannulaLengthInfoLayout.addWidget(lengthCannulaUnitLabel)\n\n planningSagittalLineLayout = qt.QHBoxLayout()\n lengthSagittalPlanningLineLabel = self.createLabel('Sagittal Length: ')\n planningSagittalLineLayout.addWidget(lengthSagittalPlanningLineLabel)\n self.lengthSagittalPlanningLineEdit = self.createLineEdit(title=\"\", text='--', readOnly=True, frame=True,\n maxLength=5, styleSheet=\"QLineEdit { background:transparent; }\",\n cursor=qt.QCursor(qt.Qt.IBeamCursor))\n planningSagittalLineLayout.addWidget(self.lengthSagittalPlanningLineEdit)\n lengthSagittalPlanningLineUnitLabel = self.createLabel('mm ')\n planningSagittalLineLayout.addWidget(lengthSagittalPlanningLineUnitLabel)\n\n planningCoronalLineLayout = qt.QHBoxLayout()\n lengthCoronalPlanningLineLabel = self.createLabel('Coronal Length: ')\n planningCoronalLineLayout.addWidget(lengthCoronalPlanningLineLabel)\n self.lengthCoronalPlanningLineEdit = self.createLineEdit(title=\"\", text='--', readOnly=True, frame=True,\n maxLength=5,\n styleSheet=\"QLineEdit { background:transparent; }\",\n cursor=qt.QCursor(qt.Qt.IBeamCursor))\n planningCoronalLineLayout.addWidget(self.lengthCoronalPlanningLineEdit)\n lengthCoronalPlanningLineUnitLabel = self.createLabel('mm ')\n planningCoronalLineLayout.addWidget(lengthCoronalPlanningLineUnitLabel)\n\n\n planningDistanceKocherLayout = qt.QHBoxLayout()\n distanceKocherPointLabel = self.createLabel(\"Distance to Kocher's point: \")\n planningDistanceKocherLayout.addWidget(distanceKocherPointLabel)\n self.distanceKocherPointEdit = self.createLineEdit(title=\"\", text='--', readOnly=True, frame=True,\n maxLength=5,\n styleSheet=\"QLineEdit { background:transparent; }\",\n cursor=qt.QCursor(qt.Qt.IBeamCursor))\n planningDistanceKocherLayout.addWidget(self.distanceKocherPointEdit)\n distanceKocherPointUnitLabel = self.createLabel('mm ')\n planningDistanceKocherLayout.addWidget(distanceKocherPointUnitLabel)\n\n planningPitchAngleLayout = qt.QHBoxLayout()\n #-- Curve length\n pitchAngleLabel = self.createLabel('Pitch Angle: ')\n planningPitchAngleLayout.addWidget(pitchAngleLabel)\n self.pitchAngleEdit = self.createLineEdit(title=\"\", text='--', readOnly=True, frame=True,\n maxLength=5,\n styleSheet=\"QLineEdit { background:transparent; }\",\n cursor=qt.QCursor(qt.Qt.IBeamCursor))\n planningPitchAngleLayout.addWidget(self.pitchAngleEdit)\n pitchAngleUnitLabel = self.createLabel('degree ')\n planningPitchAngleLayout.addWidget(pitchAngleUnitLabel)\n\n planningYawAngleLayout = qt.QHBoxLayout()\n yawAngleLabel = self.createLabel('Yaw Angle: ')\n planningYawAngleLayout.addWidget(yawAngleLabel)\n self.yawAngleEdit = self.createLineEdit(title=\"\", text='--', readOnly=True, frame=True,\n maxLength=5,\n styleSheet=\"QLineEdit { background:transparent; }\",\n cursor=qt.QCursor(qt.Qt.IBeamCursor))\n planningYawAngleLayout.addWidget(self.yawAngleEdit)\n yawAngleUnitLabel = self.createLabel('degree ')\n planningYawAngleLayout.addWidget(yawAngleUnitLabel)\n\n planningCannulaToNormAngleLayout = qt.QHBoxLayout()\n cannulaToNormAngleLabel = self.createLabel('Cannula To Norm Angle: ')\n planningCannulaToNormAngleLayout.addWidget(cannulaToNormAngleLabel)\n self.cannulaToNormAngleEdit = self.createLineEdit(title=\"\", text='--', readOnly=True, frame=True,\n maxLength=5,\n styleSheet=\"QLineEdit { background:transparent; }\",\n cursor=qt.QCursor(qt.Qt.IBeamCursor))\n planningCannulaToNormAngleLayout.addWidget(self.cannulaToNormAngleEdit)\n cannulaToNormAngleUnitLabel = self.createLabel('degree ')\n planningCannulaToNormAngleLayout.addWidget(cannulaToNormAngleUnitLabel)\n\n\n planningCannulaToCoronalAngleLayout = qt.QHBoxLayout()\n cannulaToCoronalAngleLabel = self.createLabel('Cannula To Coronal Angle:')\n planningCannulaToCoronalAngleLayout.addWidget(cannulaToCoronalAngleLabel)\n self.cannulaToCoronalAngleEdit = self.createLineEdit(title=\"\", text='--', readOnly=True, frame=True,\n maxLength=5,\n styleSheet=\"QLineEdit { background:transparent; }\",\n cursor=qt.QCursor(qt.Qt.IBeamCursor))\n planningCannulaToCoronalAngleLayout.addWidget(self.cannulaToCoronalAngleEdit)\n cannulaToCoronalAngleUnitLabel = self.createLabel('degree ')\n planningCannulaToCoronalAngleLayout.addWidget(cannulaToCoronalAngleUnitLabel)\n\n planningSkullNormToSagittalAngleLayout = qt.QHBoxLayout()\n skullNormToSagittalAngleLabel = self.createLabel('Skull Norm To Sagital Angle:')\n planningSkullNormToSagittalAngleLayout.addWidget(skullNormToSagittalAngleLabel)\n self.skullNormToSagittalAngleEdit = self.createLineEdit(title=\"\", text='--', readOnly=True, frame=True,\n maxLength=5,\n styleSheet=\"QLineEdit { background:transparent; }\",\n cursor=qt.QCursor(qt.Qt.IBeamCursor))\n planningSkullNormToSagittalAngleLayout.addWidget(self.skullNormToSagittalAngleEdit)\n skullNormToSagittalAngleUnitLabel = self.createLabel('degree ')\n planningSkullNormToSagittalAngleLayout.addWidget(skullNormToSagittalAngleUnitLabel)\n\n planningSkullNormToCoronalAngleLayout = qt.QHBoxLayout()\n skullNormToCoronalAngleLabel = self.createLabel('Skull Norm To Coronal Angle:')\n planningSkullNormToCoronalAngleLayout.addWidget(skullNormToCoronalAngleLabel)\n self.skullNormToCoronalAngleEdit = self.createLineEdit(title=\"\", text='--', readOnly=True, frame=True,\n maxLength=5,\n styleSheet=\"QLineEdit { background:transparent; }\",\n cursor=qt.QCursor(qt.Qt.IBeamCursor))\n planningSkullNormToCoronalAngleLayout.addWidget(self.skullNormToCoronalAngleEdit)\n skullNormToCoronalAngleUnitLabel = self.createLabel('degree ')\n planningSkullNormToCoronalAngleLayout.addWidget(skullNormToCoronalAngleUnitLabel)\n\n self.infoGroupBoxLayout.addLayout(cannulaLengthInfoLayout)\n self.infoGroupBoxLayout.addLayout(planningSagittalLineLayout)\n self.infoGroupBoxLayout.addLayout(planningCoronalLineLayout)\n self.infoGroupBoxLayout.addLayout(planningDistanceKocherLayout)\n self.infoGroupBoxLayout.addLayout(planningPitchAngleLayout)\n self.infoGroupBoxLayout.addLayout(planningYawAngleLayout)\n self.infoGroupBoxLayout.addLayout(planningSkullNormToSagittalAngleLayout)\n self.infoGroupBoxLayout.addLayout(planningSkullNormToCoronalAngleLayout)\n self.infoGroupBoxLayout.addLayout(planningCannulaToNormAngleLayout)\n self.infoGroupBoxLayout.addLayout(planningCannulaToCoronalAngleLayout)\n self.tabMainGroupBoxLayout.addWidget(self.infoGroupBox)\n self.tabMainGroupBoxLayout.addStretch(1)\n # Add vertical spacer\n self.layout.addStretch(1)\n\n appSettingLayout = qt.QFormLayout()\n appSettingLayout.addRow(self.caseRootConfigLayout)\n appSettingLayout.addRow(referenceConfigLayout)\n appSettingLayout.addRow(surfaceModelConfigLayout)\n appSettingLayout.addRow(venousMarginConfigLayout)\n appSettingLayout.addRow(posteriorMarginConfigLayout)\n appSettingLayout.addRow(kocherMarginConfigLayout)\n appSettingLayout.addRow(self.vesselThresholdGroupBox)\n\n self.setAlgorithmButton = AlgorithmSettingsButton(appSettingLayout)\n self.viewGroupBoxLayout.addWidget(self.setAlgorithmButton, 0, 6)\n\n self.setBackgroundAndForegroundIDs(foregroundVolumeID=None,\n backgroundVolumeID=None)\n self.initialNodesIDList = []\n allNodes = slicer.mrmlScene.GetNodes()\n for nodeIndex in range(allNodes.GetNumberOfItems()):\n node = allNodes.GetItemAsObject(nodeIndex)\n self.initialNodesIDList.append(node.GetID())\n\n\n def updateFromCaseManager(self, EventID):\n if EventID == self.slicerCaseWidget.CloseCaseEvent:\n self.logic.clear()\n self.initialFieldsValue()\n self.volumeSelected = False\n self.venousVolumeNameLabel.text = \"--\"\n self.ventricleVolumeNameLabel.text = \"--\"\n self.isLoadingCase = False\n self.screenShotButton.caseResultDir = \"\"\n self.setReverseViewButton.checked = False\n #self.setWindowLevelButton.checked = False\n elif EventID == self.slicerCaseWidget.LoadCaseCompletedEvent:\n self.screenShotButton.caseResultDir = self.slicerCaseWidget.currentCaseDirectory\n allNodes = slicer.mrmlScene.GetNodes()\n for nodeIndex in range(allNodes.GetNumberOfItems()):\n node = allNodes.GetItemAsObject(nodeIndex)\n if node.IsA(\"vtkMRMLVolumeNode\") and node.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_ventricleVolume\"):\n self.logic.baseVolumeNode = node\n self.logic.ventricleVolume = slicer.mrmlScene.GetNodeByID(node.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_ventricleVolume\"))\n if self.logic.baseVolumeNode and self.logic.ventricleVolume:\n self.logic.baseVolumeNode.SetAttribute(\"vtkMRMLScalarVolumeNode.rel_ventricleVolume\",\n self.logic.ventricleVolume.GetID())\n self.venousVolumeNameLabel.text = self.logic.baseVolumeNode.GetName()\n self.ventricleVolumeNameLabel.text = self.logic.ventricleVolume.GetName()\n self.SerialAssignBox.Clear()\n self.SerialAssignBox.volumesCheckedDict = { \"Venous\" : self.logic.baseVolumeNode,\n \"Ventricle\": self.logic.ventricleVolume,\n }\n self.SerialAssignBox.AppendVolumeNode(self.logic.baseVolumeNode)\n self.SerialAssignBox.AppendVolumeNode(self.logic.ventricleVolume)\n self.onSelect(self.logic.baseVolumeNode)\n else:\n slicer.util.warningDisplay(\"Case is not valid, no venous volume found\")\n self.nodeAddedEventObserverID = slicer.mrmlScene.AddObserver(slicer.mrmlScene.NodeAddedEvent,\n self.onVolumeAddedNode)\n self.isLoadingCase = False\n elif EventID == self.slicerCaseWidget.StartCaseImportEvent:\n self.red_cn.SetDoPropagateVolumeSelection(False) # make sure the compositenode doesn't get updated,\n self.green_cn.SetDoPropagateVolumeSelection(False) # so that the background and foreground volumes are not messed up\n self.yellow_cn.SetDoPropagateVolumeSelection(False)\n self.isLoadingCase = True\n slicer.mrmlScene.RemoveObserver(self.nodeAddedEventObserverID)\n elif EventID == self.slicerCaseWidget.CreatedNewCaseEvent:\n self.screenShotButton.caseResultDir = self.slicerCaseWidget.currentCaseDirectory\n self.SerialAssignBox.Clear()\n self.selectNasionButton.setEnabled(False)\n self.defineVentricleButton.setEnabled(False)\n self.addVesselSeedButton.setEnabled(False)\n self.relocatePathToKocherButton.setEnabled(False)\n self.createPlanningLineButton.setEnabled(False)\n self.saveDataButton.setEnabled(False)\n self.setReverseViewButton.checked = False\n self.checkCurrentProgress()\n pass\n\n def volumeLoadTimeOutHandle(self):\n self.watchDog.stop()\n self.onShowVolumeTable()\n\n def responseToReverseView(self, node, eventID):\n if self.isReverseView == False:\n self.isReverseView = True\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_nasion\", \"nasion\", visibility=False)\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_kocher\", \"kocher\", visibility=False)\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_sagittalPoint\", \"sagittalPoint\", visibility=False)\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_target\", \"target\", visibility=False)\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_distal\", \"distal\", visibility=False)\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_vesselSeeds\", \"vesselSeeds\", visibility=False)\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_cannula\", \"cannula\", visibility=False)\n if self.logic.pathCandidatesModel:\n self.logic.pathCandidatesModel.SetDisplayVisibility(0)\n else:\n self.isReverseView = False\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_nasion\", \"nasion\", visibility=True)\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_kocher\", \"kocher\", visibility=True)\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_sagittalPoint\", \"sagittalPoint\", visibility=True)\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_target\", \"target\", visibility=True)\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_distal\", \"distal\", visibility=True)\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_vesselSeeds\", \"vesselSeeds\", visibility=True)\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_cannula\", \"cannula\", visibility=True)\n if self.logic.pathCandidatesModel:\n self.logic.pathCandidatesModel.SetDisplayVisibility(1)\n pass\n\n def updateFromLogic(self, EventID):\n if EventID == VentriculostomyUserEvents.ResetButtonEvent:\n self.onResetButtons()\n if EventID == VentriculostomyUserEvents.SetSliceViewerEvent:\n volumeID=self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_quarterVolume\")\n self.setBackgroundAndForegroundIDs(foregroundVolumeID=self.logic.ventricleVolume.GetID(),\n backgroundVolumeID= volumeID)\n if EventID == VentriculostomyUserEvents.SaveModifiedFiducialEvent:\n self.onSaveData()\n if EventID == VentriculostomyUserEvents.VentricleCylinderModified:\n self.volumePrepared = False # As the cylinder has been modified, the cropped, clipped and quartervolume is not valid, needs to be recalculated.\n normalVec = numpy.array(self.logic.trueSagittalPlane.GetNormal()) # the kocher's point might need to be relocated if the cylinder is pointing to another hemisphere of the brain\n targetPos = numpy.array([0.0, 0.0, 0.0])\n targetNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_target\")\n targetNode = slicer.mrmlScene.GetNodeByID(targetNodeID)\n targetNode.GetNthFiducialPosition(0, targetPos)\n distalPos = numpy.array([0.0, 0.0, 0.0])\n distalNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_distal\")\n distalNode = slicer.mrmlScene.GetNodeByID(distalNodeID)\n distalNode.GetNthFiducialPosition(0, distalPos)\n ventriclePointLeft = -numpy.sign(numpy.dot(distalPos - targetPos,\n normalVec)) # here left hemisphere means from the patient's perspective\n if ventriclePointLeft >= 0 and self.logic.useLeftHemisphere == False:\n self.logic.useLeftHemisphere = True\n self.logic.createEntryPoint()\n if ventriclePointLeft < 0 and self.logic.useLeftHemisphere == True:\n self.logic.useLeftHemisphere = False\n self.logic.createEntryPoint()\n if EventID == VentriculostomyUserEvents.CheckCurrentProgressEvent: \n self.checkCurrentProgress()\n if EventID == VentriculostomyUserEvents.SegmentVesselWithSeedsEvent:\n self.onSegmentVesselWithSeeds()\n if EventID == VentriculostomyUserEvents.SagittalCorrectionFinishedEvent:\n self.onResetButtons()\n self.fourUpLayoutButton.click()\n self.setSliceForCylinder()\n\n def initialFieldsValue(self):\n self.lengthSagittalPlanningLineEdit.text = '--'\n self.lengthCoronalPlanningLineEdit.text = '--'\n self.distanceKocherPointEdit.text = '--'\n self.lengthCannulaEdit.text = '--'\n self.pitchAngleEdit.text = '--'\n self.yawAngleEdit.text = '--'\n self.skullNormToSagittalAngleEdit.text = '--'\n self.skullNormToCoronalAngleEdit.text = '--'\n self.cannulaToNormAngleEdit.text = '--'\n self.cannulaToCoronalAngleEdit.text = '--'\n\n def onLoadDicom(self):\n self.dicomWidget.detailsPopup.open() \n pass\n\n @vtk.calldata_type(vtk.VTK_OBJECT)\n def onVolumeAddedNode(self, caller, eventId, callData):\n # When we are loading the cases, though the slicer.mrmlScene.NodeAddedEvent is removed, sometimes this function is still triggered.\n # We use the flag isLoadingCase to make sure it is not called.\n slicer.app.processEvents()\n if callData.IsA(\"vtkMRMLScalarVolumeDisplayNode\"):\n callData.SetAutoWindowLevel(False)\n callData.SetWindow(self.baseVolumeWindowValue)\n callData.SetLevel(self.baseVolumeLevelValue)\n if callData.IsA(\"vtkMRMLVolumeNode\") and (not self.isLoadingCase) and (not self.isInAlgorithmSteps):\n if self.onSaveDicomFiles():\n self.watchDog.reset()\n #self.showVolumeTable.setEnabled(True)\n #self.showVolumeTable.setStyleSheet(\"QPushButton { background:red; }\")\n self.SerialAssignBox.AppendVolumeNode(callData)\n self.initialNodesIDList.append(callData.GetID())\n\n #the setForegroundVolume will not work, because the slicerapp triggers the SetBackgroundVolume after the volume is loaded\n def onShowVolumeTable(self):\n userAction = self.SerialAssignBox.ShowVolumeTable()\n if userAction == 0:\n if (not self.logic.baseVolumeNode == self.SerialAssignBox.volumesCheckedDict.get(\"Venous\")) or (not self.logic.ventricleVolume == self.SerialAssignBox.volumesCheckedDict.get(\"Ventricle\")):\n userSelectValid = False\n if self.logic.baseVolumeNode == None or self.logic.ventricleVolume == None:\n userSelectValid = True\n else: \n if slicer.util.confirmYesNoDisplay(\"Are you sure you want set the base image?\",\n windowTitle=\"\"):\n userSelectValid = True\n if userSelectValid:\n self.SerialAssignBox.ConfirmUserChanges()\n if (self.SerialAssignBox.volumesCheckedDict.get(\"Venous\")):\n self.logic.baseVolumeNode = self.SerialAssignBox.volumesCheckedDict.get(\"Venous\")\n if (self.SerialAssignBox.volumesCheckedDict.get(\"Ventricle\")):\n self.logic.ventricleVolume = self.SerialAssignBox.volumesCheckedDict.get(\"Ventricle\")\n if self.logic.baseVolumeNode:\n self.venousVolumeNameLabel.text = self.logic.baseVolumeNode.GetName()\n if self.logic.ventricleVolume:\n self.ventricleVolumeNameLabel.text = self.logic.ventricleVolume.GetName()\n if self.logic.baseVolumeNode and self.logic.ventricleVolume:\n self.logic.baseVolumeNode.SetAttribute(\"vtkMRMLScalarVolumeNode.rel_ventricleVolume\",\n self.logic.ventricleVolume.GetID())\n self.initialNodesIDList.append(self.logic.baseVolumeNode.GetDisplayNodeID()) \n self.initialNodesIDList.append(self.logic.baseVolumeNode.GetStorageNodeID()) \n self.initialNodesIDList.append(self.logic.ventricleVolume.GetDisplayNodeID()) \n self.initialNodesIDList.append(self.logic.ventricleVolume.GetStorageNodeID())\n # To start the whole planning procedure, the MRMLScene needs to be clean up, but the nodes such as cameraNode, sliceNodes, baseVolumeNode and ventricleVolumeNode should not be deleted.\n # The following lines deletes the nodes generated from the previous planning case.\n allNodes = slicer.mrmlScene.GetNodes()\n for nodeIndex in range(allNodes.GetNumberOfItems()):\n node = allNodes.GetItemAsObject(nodeIndex)\n if node and (not (node.GetID() in self.initialNodesIDList)):\n if (not (node.GetClassName() == \"vtkMRMLScriptedModuleNode\")) \\\n and (not node.IsA(\"vtkMRMLDisplayNode\")) and (not node.IsA(\"vtkMRMLStorageNode\"))\\\n and (not (node.GetClassName() == \"vtkMRMLCommandLineModuleNode\")) \\\n and (not (node.GetClassName() == \"vtkMRMLCameraNode\")) \\\n and (not (node.GetClassName() == \"vtkMRMLSceneViewNode\")) \\\n and node.GetDisplayNode():\n slicer.mrmlScene.RemoveNode(node.GetDisplayNode())\n slicer.mrmlScene.RemoveNode(node)\n slicer.app.processEvents() \n self.onSelect(self.logic.baseVolumeNode)\n else:\n self.SerialAssignBox.CancelUserChanges()\n else:\n self.SerialAssignBox.CancelUserChanges()\n else:\n self.SerialAssignBox.CancelUserChanges()\n\n def onSaveDicomFiles(self):\n # use decoration to improve the method\n if not os.path.exists(self.slicerCaseWidget.planningDICOMDataDirectory):\n slicer.util.warningDisplay(\"No case is created, create a case first. The current serial is not saved.\")\n return False\n checkedFiles = self.dicomWidget.detailsPopup.fileLists\n for dicomseries in checkedFiles:\n for dicom in dicomseries:\n copyfile(dicom,os.path.join(self.slicerCaseWidget.planningDICOMDataDirectory,basename(dicom)))\n return True\n \n @beforeRunProcessEvents\n def onSelect(self, selectedNode=None):\n slicer.mrmlScene.RemoveObserver(self.nodeAddedEventObserverID)\n if selectedNode:\n qt.QApplication.setOverrideCursor(qt.Qt.WaitCursor)\n self.red_cn.SetDoPropagateVolumeSelection(False) # make sure the compositenode doesn't get updated,\n self.green_cn.SetDoPropagateVolumeSelection(False) # so that the background and foreground volumes are not messed up\n self.yellow_cn.SetDoPropagateVolumeSelection(False)\n self.initialFieldsValue()\n self.logic.clear()\n self.logic = VentriculostomyPlanningLogic()\n self.logic.register(self)\n if self.slicerCaseWidget.planningDICOMDataDirectory and listdir(self.slicerCaseWidget.planningDICOMDataDirectory):\n self.slicerCaseWidget.patientWatchBox.sourceFile = os.path.join(self.slicerCaseWidget.planningDICOMDataDirectory,listdir(self.slicerCaseWidget.planningDICOMDataDirectory)[0])\n self.slicerCaseWidget.currentCaseDirectory\n self.logic.baseVolumeNode = selectedNode\n if self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_ventricleVolume\"):\n self.logic.ventricleVolume = slicer.mrmlScene.GetNodeByID(self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_ventricleVolume\"))\n if self.logic.ventricleVolume and self.logic.baseVolumeNode:\n self.volumePrepared = False\n outputDir = os.path.join(self.slicerCaseWidget.currentCaseDirectory, \"Results\")\n self.logic.savePlanningDataToDirectory(self.logic.baseVolumeNode, outputDir)\n self.logic.savePlanningDataToDirectory(self.logic.ventricleVolume, outputDir)\n outputDir = os.path.join(self.slicerCaseWidget.currentCaseDirectory, \"Results\")\n self.jsonFile = os.path.join(outputDir, \"PlanningTimeStamp.json\")\n self.logic.appendPlanningTimeStampToJson(self.jsonFile, \"StartPreProcessing\",\n datetime.datetime.now().time().isoformat())\n self.logic.enableRelatedModel(\"vtkMRMLScalarVolumeNode.rel_model\", \"surfaceModel\", intersectionVis=False)\n self.logic.enableRelatedModel(\"vtkMRMLScalarVolumeNode.rel_clipModel\", \"clipModel\", visibility=False, intersectionVis=False)\n self.logic.enableRelatedModel(\"vtkMRMLScalarVolumeNode.rel_cannulaModel\", \"cannulaModel\", color = [0.5, 1.0, 0.0])\n self.logic.enableRelatedModel(\"vtkMRMLScalarVolumeNode.rel_sagittalReferenceModel\", \"sagittalReferenceModel\",color=[1.0, 1.0, 0.5], intersectionVis=False)\n self.logic.enableRelatedModel(\"vtkMRMLScalarVolumeNode.rel_coronalReferenceModel\", \"coronalReferenceModel\", color =[0.5, 1.0, 0.5], intersectionVis=False)\n self.logic.enableRelatedModel(\"vtkMRMLScalarVolumeNode.rel_sagittalPlanningModel\", \"sagittalPlanningModel\", color=[1.0,1.0,0.0])\n self.logic.enableRelatedModel(\"vtkMRMLScalarVolumeNode.rel_cylinderModel\", \"cylinderModel\",\n color=[0.0, 1.0, 1.0])\n self.logic.enableRelatedModel(\"vtkMRMLScalarVolumeNode.rel_pathCandidateModel\", \"pathCandidateModel\",\n color=[1.0, 1.0, 0.0], visibility= False)\n self.logic.enableRelatedModel(\"vtkMRMLScalarVolumeNode.rel_pathNavigationModel\", \"pathNavigationModel\",\n color=[1.0, 1.0, 0.0], visibility= False)\n self.logic.enableRelatedModel(\"vtkMRMLScalarVolumeNode.rel_coronalPlanningModel\", \"coronalPlanningModel\", color=[0.0,1.0,0.0])\n self.logic.enableRelatedModel(\"vtkMRMLScalarVolumeNode.rel_vesselnessModel\", \"vesselnessModel\", color=[1.0, 0.0, 0.0])\n self.logic.enableRelatedModel(\"vtkMRMLScalarVolumeNode.rel_vesselnessWithMarginModel\", \"vesselnessWithMarginModel\", visibility=False)\n self.logic.enableRelatedModel(\"vtkMRMLScalarVolumeNode.rel_grayScaleModel\", \"grayScaleModel\",\n color=[0.8, 0.2, 0.0])\n self.logic.enableRelatedModel(\"vtkMRMLScalarVolumeNode.rel_grayScaleWithMarginModel\",\n \"grayScaleWithMarginModel\", visibility=False)\n self.logic.enableRelatedModel(\"vtkMRMLScalarVolumeNode.rel_rightPrintPart\", \"rightPrintPart\")\n self.logic.enableRelatedModel(\"vtkMRMLScalarVolumeNode.rel_leftPrintPart\", \"leftPrintPart\")\n self.logic.enableRelatedModel(\"vtkMRMLScalarVolumeNode.rel_printModel\", \"printModel\")\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_nasion\", \"nasion\")\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_kocher\",\"kocher\")\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_sagittalPoint\", \"sagittalPoint\")\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_target\", \"target\")\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_distal\", \"distal\")\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_vesselSeeds\", \"vesselSeeds\")\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_cannula\", \"cannula\")\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_cylinderMarker\", \"cylinderMarker\")\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_sagittalReferenceMarker\", \"sagittalReferenceMarker\",visibility=False)\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_coronalReferenceMarker\", \"coronalReferenceMarker\", visibility=False)\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_sagittalPlanningMarker\", \"sagittalPlanningMarker\", visibility=False)\n self.logic.enableRelatedMarkups(\"vtkMRMLScalarVolumeNode.rel_coronalPlanningMarker\", \"coronalPlanningMarker\", visibility=False)\n self.logic.enableRelatedVolume(\"vtkMRMLScalarVolumeNode.rel_croppedVolume\",\"croppedVolume\")\n self.logic.enableRelatedVolume(\"vtkMRMLScalarVolumeNode.rel_clippedVolume\", \"clippedVolume\")\n self.logic.enableRelatedVolume(\"vtkMRMLScalarVolumeNode.rel_quarterVolume\", \"quarterVolume\")\n self.logic.enableRelatedVolume(\"vtkMRMLScalarVolumeNode.rel_vesselnessVolume\", \"vesselnessVolume\")\n self.logic.enableRelatedVariables(\"vtkMRMLScalarVolumeNode.rel_kocherMargin\", \"kocherMargin\")\n self.logic.enableRelatedVariables(\"vtkMRMLScalarVolumeNode.rel_venousMargin\", \"venousMargin\")\n self.logic.enableRelatedVariables(\"vtkMRMLScalarVolumeNode.rel_surfaceModelThreshold\", \"surfaceModelThreshold\")\n self.logic.enableRelatedVariables(\"vtkMRMLScalarVolumeNode.rel_cylinderRadius\", \"cylinderRadius\")\n self.logic.enableRelatedVariables(\"vtkMRMLScalarVolumeNode.rel_thresholdProgressiveFactor\", \"thresholdProgressiveFactor\")\n self.logic.enableRelatedVariables(\"vtkMRMLScalarVolumeNode.rel_posteriorMargin\", \"posteriorMargin\")\n self.logic.enableRelatedVariables(\"vtkMRMLScalarVolumeNode.rel_needSagittalCorrection\", \"needSagittalCorrection\")\n self.logic.enableRelatedVariables(\"vtkMRMLScalarVolumeNode.rel_venousMedianValue\",\n \"venousMedianValue\")\n self.logic.enableRelatedVariables(\"vtkMRMLScalarVolumeNode.rel_venousMaxValue\",\n \"venousMaxValue\")\n if self.rangeThresholdWidget.minimum >= self.logic.thresholdProgressiveFactor:\n self.rangeThresholdWidget.minimum = self.logic.thresholdProgressiveFactor*0.9\n self.rangeThresholdWidget.setValues(self.logic.thresholdProgressiveFactor, 1.0)\n vesselSeedsNodelID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselSeeds\")\n self.simpleMarkupsWidget.setCurrentNode(slicer.mrmlScene.GetNodeByID(vesselSeedsNodelID))\n self.kocherMarginEdit.setText(self.logic.kocherMargin)\n self.posteriorMarginEdit.setText(self.logic.posteriorMargin)\n self.surfaceModelThresholdEdit.setText(self.logic.surfaceModelThreshold)\n self.venousMarginEdit.setText(self.logic.venousMargin)\n self.enableEventObserver()\n self.setReverseViewButton.cannulaNode = slicer.mrmlScene.GetNodeByID(self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_cannula\"))\n self.logic.updateMeasureLength(float(self.lengthSagittalReferenceLineEdit.text), float(self.lengthCoronalReferenceLineEdit.text))\n self.lengthSagittalReferenceLineEdit.text = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_sagittalLength\")\n self.lengthCoronalReferenceLineEdit.text = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_coronalLength\")\n\n cylinderModelID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_cylinderModel\")\n self.logic.cylinderManager.connectModelNode(slicer.mrmlScene.GetNodeByID(cylinderModelID))\n cylinderMarkerID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_cylinderMarker\")\n self.logic.cylinderManager.connectMarkerNode(slicer.mrmlScene.GetNodeByID(cylinderMarkerID))\n \n pathCandidateModelID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_pathCandidateModel\")\n self.logic.pathCandidatesModel = slicer.mrmlScene.GetNodeByID(pathCandidateModelID)\n pathNavigationModelID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_pathNavigationModel\")\n self.logic.pathNavigationModel = slicer.mrmlScene.GetNodeByID(pathNavigationModelID)\n\n ReferenceModelID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_sagittalReferenceModel\")\n self.logic.sagittalReferenceCurveManager.connectModelNode(slicer.mrmlScene.GetNodeByID(ReferenceModelID))\n ReferenceModelID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_coronalReferenceModel\")\n self.logic.coronalReferenceCurveManager.connectModelNode(slicer.mrmlScene.GetNodeByID(ReferenceModelID))\n PlanningModelID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_sagittalPlanningModel\")\n self.logic.sagittalPlanningCurveManager.connectModelNode(slicer.mrmlScene.GetNodeByID(PlanningModelID))\n PlanningModelID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_coronalPlanningModel\")\n self.logic.coronalPlanningCurveManager.connectModelNode(slicer.mrmlScene.GetNodeByID(PlanningModelID))\n\n ReferenceMarkerID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_sagittalReferenceMarker\")\n self.logic.sagittalReferenceCurveManager.connectMarkerNode(slicer.mrmlScene.GetNodeByID(ReferenceMarkerID))\n ReferenceMarkerID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_coronalReferenceMarker\")\n self.logic.coronalReferenceCurveManager.connectMarkerNode(slicer.mrmlScene.GetNodeByID(ReferenceMarkerID))\n PlanningMarkerID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_sagittalPlanningMarker\")\n self.logic.sagittalPlanningCurveManager.connectMarkerNode(slicer.mrmlScene.GetNodeByID(PlanningMarkerID))\n PlanningMarkerID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_coronalPlanningMarker\")\n self.logic.coronalPlanningCurveManager.connectMarkerNode(slicer.mrmlScene.GetNodeByID(PlanningMarkerID))\n self.logic.createTrueSagittalPlane()\n self.logic.createEntryPoint()\n cannulaModelID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_cannulaModel\")\n cannulaFiducialsID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_cannula\")\n self.logic.pathNavigationModel.SetDisplayVisibility(0)\n self.logic.cannulaManager.connectModelNode(slicer.mrmlScene.GetNodeByID(cannulaModelID))\n self.logic.cannulaManager.curveFiducials = slicer.mrmlScene.GetNodeByID(cannulaFiducialsID)\n self.logic.cannulaManager.curveFiducials.AddObserver(slicer.vtkMRMLMarkupsNode().PointStartInteractionEvent, self.logic.updateSelectedMarker)\n self.logic.cannulaManager.curveFiducials.AddObserver(slicer.vtkMRMLMarkupsNode().PointModifiedEvent, self.logic.updateCannulaPosition)\n self.logic.cannulaManager.curveFiducials.AddObserver(slicer.vtkMRMLMarkupsNode().PointEndInteractionEvent, self.logic.endCannulaInteraction)\n self.logic.cannulaManager.setModifiedEventHandler(self.onCannulaModified)\n self.logic.cannulaManager.startEditLine()\n self.logic.createVentricleCylinder()\n self.onCreatePlanningLine()\n self.isReverseView = False\n self.progressBar.show()\n self.progressBar.labelText = 'Calculating Skull Surface'\n slicer.app.processEvents()\n self.createModel()\n self.progressBar.value = 25\n self.progressBar.labelText = 'Calculating Vessel'\n slicer.app.processEvents()\n vesselSeedsID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselSeeds\")\n vesselSeedsNode = slicer.mrmlScene.GetNodeByID(vesselSeedsID)\n self.prepareVolumes()\n if vesselSeedsNode and vesselSeedsNode.GetNumberOfFiducials():\n self.onConnectedComponentCalc()\n self.prepareCandidatePath()\n self.progressBar.value = 75\n self.logic.calculateCylinderTransform()\n self.setBackgroundAndForegroundIDs(foregroundVolumeID=self.logic.ventricleVolume.GetID(),\n backgroundVolumeID=self.logic.baseVolumeNode.GetID())\n self.onSet3DViewer()\n self.progressBar.labelText = 'Saving Preprocessed Data'\n slicer.app.processEvents()\n self.onSaveData()\n self.progressBar.close()\n self.logic.appendPlanningTimeStampToJson(self.jsonFile, \"EndPreprocessing\",\n datetime.datetime.now().time().isoformat())\n self.imageSlider.setValue(100.0)\n qt.QApplication.restoreOverrideCursor()\n self.selectNasionButton.setEnabled(True)\n self.saveDataButton.setEnabled(True)\n self.checkCurrentProgress()\n self.logic.placeWidget.setPlaceModeEnabled(False)\n self.nodeAddedEventObserverID = slicer.mrmlScene.AddObserver(slicer.mrmlScene.NodeAddedEvent,\n self.onVolumeAddedNode)\n pass\n\n def onResetButtons(self, caller=None, event=None):\n self.defineVentricleButton.setChecked(False)\n self.selectNasionButton.setChecked(False)\n self.selectSagittalButton.setChecked(False)\n pass\n\n def checkCurrentProgress(self):\n self.LoadCaseButton.setEnabled(False)\n self.saveDataButton.setEnabled(False)\n self.selectNasionButton.setEnabled(False)\n self.defineVentricleButton.setEnabled(False)\n self.addVesselSeedButton.setEnabled(False)\n self.relocatePathToKocherButton.setEnabled(False)\n self.createPlanningLineButton.setEnabled(False)\n self.tabMainGroupBox.visible = False\n if self.slicerCaseWidget.currentCaseDirectory:\n self.LoadCaseButton.setEnabled(True)\n self.saveDataButton.setEnabled(True)\n if self.logic.baseVolumeNode:\n skullModelNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_model\")\n if skullModelNodeID:\n skullModelNode = slicer.mrmlScene.GetNodeByID(skullModelNodeID)\n if skullModelNode.GetPolyData():\n if skullModelNode.GetPolyData().GetNumberOfPoints() > 0:\n self.selectNasionButton.setEnabled(True)\n nasionNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_nasion\")\n if nasionNodeID:\n nasionNode = slicer.mrmlScene.GetNodeByID(nasionNodeID)\n if nasionNode.GetNumberOfFiducials()>0:\n self.defineVentricleButton.setEnabled(True)\n targetNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_target\")\n distalNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_distal\")\n if targetNodeID and distalNodeID:\n targetNode = slicer.mrmlScene.GetNodeByID(targetNodeID)\n distalNode = slicer.mrmlScene.GetNodeByID(distalNodeID)\n if targetNode.GetNumberOfFiducials() and distalNode.GetNumberOfFiducials():\n self.addVesselSeedButton.setEnabled(True)\n self.relocatePathToKocherButton.setEnabled(True)\n cannulaFiducialsID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_cannula\")\n if cannulaFiducialsID:\n cannulaFiducials = slicer.mrmlScene.GetNodeByID(cannulaFiducialsID)\n if cannulaFiducials.GetNumberOfFiducials()>1:\n self.createPlanningLineButton.setEnabled(True)\n self.tabMainGroupBox.visible = True if self.addVesselSeedButton.checked == False else False\n pass\n\n def enableEventObserver(self):\n nasionNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_nasion\")\n nasionNode = slicer.mrmlScene.GetNodeByID(nasionNodeID)\n sagittalID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_sagittalPoint\")\n sagittalPointNode = slicer.mrmlScene.GetNodeByID(sagittalID)\n targetNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_target\")\n targetNode = slicer.mrmlScene.GetNodeByID(targetNodeID)\n distalNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_distal\")\n distalNode = slicer.mrmlScene.GetNodeByID(distalNodeID)\n vesselSeedsNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselSeeds\")\n vesselSeedsNode = slicer.mrmlScene.GetNodeByID(vesselSeedsNodeID)\n if nasionNode:\n nasionNode.AddObserver(slicer.vtkMRMLMarkupsNode.MarkupAddedEvent, self.logic.endPlacement)\n if sagittalPointNode:\n sagittalPointNode.AddObserver(slicer.vtkMRMLMarkupsNode.MarkupAddedEvent, self.logic.endPlacement)\n if targetNode:\n targetNode.AddObserver(slicer.vtkMRMLMarkupsNode.MarkupAddedEvent, self.logic.endPlacement)\n targetNode.AddObserver(slicer.vtkMRMLMarkupsNode().PointModifiedEvent, self.logic.createVentricleCylinder)\n targetNode.AddObserver(slicer.vtkMRMLMarkupsNode().PointEndInteractionEvent, self.logic.endModifiyCylinder)\n if distalNode:\n distalNode.AddObserver(slicer.vtkMRMLMarkupsNode.MarkupAddedEvent, self.logic.endPlacement)\n distalNode.AddObserver(slicer.vtkMRMLMarkupsNode().PointModifiedEvent, self.logic.createVentricleCylinder)\n distalNode.AddObserver(slicer.vtkMRMLMarkupsNode().PointEndInteractionEvent, self.logic.endModifiyCylinder)\n if vesselSeedsNode:\n vesselSeedsNode.AddObserver(slicer.vtkMRMLMarkupsNode.MarkupAddedEvent, self.logic.endPlacement)\n # The TriggerDistalSelectionEvent and CheckSagittalCorrectionEvent are custum events\n slicer.mrmlScene.AddObserver(VentriculostomyUserEvents.TriggerDistalSelectionEvent,\n self.logic.startEditPlanningDistal)\n slicer.mrmlScene.AddObserver(VentriculostomyUserEvents.CheckSagittalCorrectionEvent,\n self.checkIfSagittalCorrectionNeeded)\n\n @beforeRunProcessEvents\n def checkIfSagittalCorrectionNeeded(self, caller, eventId):\n if self.logic.needSagittalCorrection == SagittalCorrectionStatus.NotYetChecked:\n userAction = self.SagittalCorrectionBox.exec_()\n if userAction == 0:\n self.logic.needSagittalCorrection = SagittalCorrectionStatus.NeedCorrection\n else:\n self.logic.needSagittalCorrection = SagittalCorrectionStatus.NoNeedForCorrection\n self.logic.placeWidget.setPlaceModeEnabled(False)\n self.logic.baseVolumeNode.SetAttribute(\"vtkMRMLScalarVolumeNode.rel_needSagittalCorrection\", str(self.logic.needSagittalCorrection))\n if userAction == 0:\n self.selectSagittalButton.click()\n elif self.logic.needSagittalCorrection == SagittalCorrectionStatus.NoNeedForCorrection:\n self.logic.placeWidget.setPlaceModeEnabled(False)\n self.fourUpLayoutButton.click()\n self.setSliceForCylinder()\n elif self.logic.needSagittalCorrection == SagittalCorrectionStatus.NeedCorrection:\n self.selectSagittalButton.click()\n\n @vtk.calldata_type(vtk.VTK_INT)\n def onResetPlanningOutput(self, node, eventID, callData):\n self.lengthCannulaEdit.text = '--'\n self.lengthSagittalPlanningLineEdit.text = '--'\n self.lengthCoronalPlanningLineEdit.text = '--'\n self.distanceKocherPointEdit.text = '--'\n self.pitchAngleEdit.text = '--'\n self.yawAngleEdit.text = '--'\n self.cannulaToCoronalAngleEdit.text = '--'\n self.cannulaToNormAngleEdit.text = '--'\n self.skullNormToSagittalAngleEdit.text = '--'\n self.skullNormToCoronalAngleEdit.text = '--'\n\n\n def onChangeThresholdValues(self, sliderLowerValue, sliderUpperValue):\n if self.logic.baseVolumeNode:\n self.logic.thresholdProgressiveFactor = sliderLowerValue\n self.logic.baseVolumeNode.SetAttribute(\"vtkMRMLScalarVolumeNode.rel_thresholdProgressiveFactor\", str(sliderLowerValue))\n\n def onChangePosteriorMargin(self, value):\n if self.logic.baseVolumeNode:\n self.logic.posteriorMargin = value\n self.posteriorMarginEdit.setText(str(value))\n self.logic.baseVolumeNode.SetAttribute(\"vtkMRMLScalarVolumeNode.rel_posteriorMargin\", str(value))\n\n def onChangeKocherMargin(self, value):\n if self.logic.baseVolumeNode:\n self.logic.kocherMargin = value\n self.kocherMarginEdit.setText(str(value))\n self.logic.baseVolumeNode.SetAttribute(\"vtkMRMLScalarVolumeNode.rel_kocherMargin\", str(value))\n\n def onChangeSliceViewImage(self, sliderValue):\n red_widget = slicer.app.layoutManager().sliceWidget(\"Red\")\n red_logic = red_widget.sliceLogic()\n red_cn = red_logic.GetSliceCompositeNode()\n yellow_widget = slicer.app.layoutManager().sliceWidget(\"Yellow\")\n yellow_logic = yellow_widget.sliceLogic()\n yellow_cn = yellow_logic.GetSliceCompositeNode()\n green_widget = slicer.app.layoutManager().sliceWidget(\"Green\")\n green_logic = green_widget.sliceLogic()\n green_cn = green_logic.GetSliceCompositeNode()\n red_cn.SetForegroundOpacity(sliderValue / 100.0)\n yellow_cn.SetForegroundOpacity(sliderValue / 100.0)\n green_cn.SetForegroundOpacity(sliderValue / 100.0)\n\n def prepareVolumes(self):\n slicer.mrmlScene.RemoveObserver(self.nodeAddedEventObserverID)\n quarterVolumeNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_quarterVolume\")\n quarterVolume = slicer.mrmlScene.GetNodeByID(quarterVolumeNodeID)\n if quarterVolumeNodeID:\n targetNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_target\")\n distalNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_distal\")\n clipModelNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_clipModel\")\n croppedVolumeNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_croppedVolume\")\n clippedVolumeNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_clippedVolume\")\n if targetNodeID and distalNodeID and clippedVolumeNodeID and croppedVolumeNodeID and clipModelNodeID:\n targetNode = slicer.mrmlScene.GetNodeByID(targetNodeID)\n distalNode = slicer.mrmlScene.GetNodeByID(distalNodeID)\n targetNode.SetLocked(True)\n distalNode.SetLocked(True)\n self.logic.cylinderInteractor.SetLocked(True)\n croppedVolumeNode = slicer.mrmlScene.GetNodeByID(croppedVolumeNodeID)\n clippedVolumeNode = slicer.mrmlScene.GetNodeByID(clippedVolumeNodeID)\n clipModelNode = slicer.mrmlScene.GetNodeByID(clipModelNodeID)\n if targetNode.GetNumberOfFiducials() and distalNode.GetNumberOfFiducials() and clipModelNode:\n posTarget = numpy.array([0.0, 0.0, 0.0])\n targetNode.GetNthFiducialPosition(0, posTarget)\n posDistal = numpy.array([0.0, 0.0, 0.0])\n distalNode.GetNthFiducialPosition(0, posDistal)\n if self.volumePrepared == False:\n coneHeight = 100.0 # in millimeter\n coneForVolumeClip = self.logic.functions.generateConeModel(posTarget, posDistal, self.logic.cylinderRadius,coneHeight)\n clipModelNode.SetAndObservePolyData(coneForVolumeClip)\n # -----------\n ventricleDirect = (posDistal - posTarget) / numpy.linalg.norm(\n posTarget - posDistal)\n coneTipPoint = posTarget - numpy.linalg.norm(posDistal - posTarget) / 2.0 * ventricleDirect\n ROICenterPoint = coneTipPoint + ventricleDirect * numpy.array([0, 1, 1])* coneHeight\n self.logic.ROINode.SetXYZ(ROICenterPoint)\n angle = 180.0 / math.pi * math.atan(2 * self.logic.cylinderRadius / numpy.linalg.norm(\n posTarget - posDistal))\n ROIRadiusXYZ = [150, coneHeight * ventricleDirect[1],\n max(coneHeight * math.tan(angle * math.pi / 180.0), coneHeight * ventricleDirect[2])]\n self.logic.ROINode.SetRadiusXYZ(ROIRadiusXYZ)\n cropVolumeLogic = slicer.modules.cropvolume.logic()\n\n cropVolumeLogic.CropVoxelBased(self.logic.ROINode, self.logic.baseVolumeNode, quarterVolume)\n slicer.app.processEvents()\n ROICenterPoint = coneTipPoint + ventricleDirect * coneHeight\n self.logic.ROINode.SetXYZ(ROICenterPoint)\n ROIRadiusXYZ = [max(coneHeight * math.tan(angle * math.pi / 180.0), coneHeight * ventricleDirect[0]),\n coneHeight * ventricleDirect[1],\n max(coneHeight * math.tan(angle * math.pi / 180.0), coneHeight * ventricleDirect[2])]\n self.logic.ROINode.SetRadiusXYZ(ROIRadiusXYZ)\n cropVolumeLogic = slicer.modules.cropvolume.logic()\n cropVolumeLogic.CropVoxelBased(self.logic.ROINode, self.logic.baseVolumeNode, croppedVolumeNode)\n slicer.app.processEvents()\n self.logic.createClippedVolume(croppedVolumeNode, clipModelNode, clippedVolumeNode)\n self.volumePrepared = True\n self.setBackgroundAndForegroundIDs(foregroundVolumeID=self.logic.ventricleVolume.GetID(),\n backgroundVolumeID=quarterVolume.GetID(), fitToSlice=True)\n self.logic.updateSliceViewBasedOnPoints(posTarget, posDistal)\n greenSliceNode = slicer.mrmlScene.GetNodeByID(\"vtkMRMLSliceNodeGreen\")\n greenSliceNode.SetFieldOfView(self.green_widget.width/2, self.green_widget.height/2, 0.5)\n slicer.app.processEvents()\n if quarterVolume.GetDisplayNode():\n quarterVolume.GetDisplayNode().SetAutoWindowLevel(False)\n quarterVolume.GetDisplayNode().SetWindow(self.baseVolumeWindowValue)\n quarterVolume.GetDisplayNode().SetLevel(self.baseVolumeLevelValue)\n slicer.app.processEvents()\n self.nodeAddedEventObserverID = slicer.mrmlScene.AddObserver(slicer.mrmlScene.NodeAddedEvent,\n self.onVolumeAddedNode)\n return True\n\n def prepareCandidatePath(self):\n #oriInteractionMode = self.logic.interactionMode\n #self.logic.interactionMode = EndPlacementModes.NotSpecifiedMode\n targetNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_target\")\n distalNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_distal\")\n nasionNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_nasion\")\n if targetNodeID and distalNodeID and nasionNodeID:\n targetNode = slicer.mrmlScene.GetNodeByID(targetNodeID)\n distalNode = slicer.mrmlScene.GetNodeByID(distalNodeID)\n nasionNode = slicer.mrmlScene.GetNodeByID(nasionNodeID)\n if targetNode.GetNumberOfFiducials() and distalNode.GetNumberOfFiducials() and nasionNode.GetNumberOfFiducials():\n posTarget = numpy.array([0.0, 0.0, 0.0])\n targetNode.GetNthFiducialPosition(0, posTarget)\n posDistal = numpy.array([0.0, 0.0, 0.0])\n distalNode.GetNthFiducialPosition(0, posDistal)\n posNasion = numpy.array([0.0, 0.0, 0.0])\n nasionNode.GetNthFiducialPosition(0, posNasion)\n direction = (numpy.array(posDistal) - numpy.array(posTarget))/numpy.linalg.norm(numpy.array(posDistal) - numpy.array(posTarget))\n if self.logic.trajectoryProjectedMarker.GetNumberOfFiducials() == 0:\n self.logic.trajectoryProjectedMarker.AddFiducial(0,0,0)\n vesselModelWithMarginNodeID = self.logic.baseVolumeNode.GetAttribute(\n \"vtkMRMLScalarVolumeNode.rel_vesselnessWithMarginModel\")\n vesselModelWithMarginNode = slicer.mrmlScene.GetNodeByID(vesselModelWithMarginNodeID)\n modelID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_model\")\n inputModelNode = slicer.mrmlScene.GetNodeByID(modelID)\n surfacePolyData = inputModelNode.GetPolyData()\n FiducialPointAlongVentricle = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLMarkupsFiducialNode\")\n self.logic.functions.calculateLineModelIntersect(surfacePolyData, posDistal+1e6*direction, posTarget-1e6*direction, FiducialPointAlongVentricle)\n posEntry = numpy.array([0.0, 0.0, 0.0])\n FiducialPointAlongVentricle.GetNthFiducialPosition(0,posEntry)\n self.logic.cylinderMiddlePointNode.RemoveAllMarkups()\n posCenter = numpy.array([(posTarget[0]+posDistal[0])/2.0, (posTarget[1]+posDistal[1])/2.0, (posTarget[2]+posDistal[2])/2.0])\n self.logic.cylinderMiddlePointNode.AddFiducial(posCenter[0], posCenter[1], posCenter[2])\n pathPlanningBasePoint = numpy.array(posTarget) + (numpy.array(posEntry) - numpy.array(posTarget)) * 1.2\n self.logic.calculateCylinderTransform()\n matrix = self.logic.transform.GetMatrix()\n points = vtk.vtkPoints()\n phiResolution = 1*numpy.pi/180.0\n radiusResolution = 1.0\n points.InsertNextPoint(posEntry)\n distance2 = numpy.linalg.norm(numpy.array(posTarget) - numpy.array(posEntry))\n distance1 = numpy.linalg.norm(numpy.array(posTarget) - numpy.array(posDistal))/2 # Divided by 2 is because, all the cylinder bottom are possible target points\n self.logic.entryRadius = self.logic.cylinderRadius * distance2 / distance1\n for radius in numpy.arange(radiusResolution, self.logic.entryRadius+radiusResolution, radiusResolution):\n for angle in numpy.arange(0, numpy.pi, phiResolution):\n point = matrix.MultiplyPoint(numpy.array([radius*math.cos(angle), radius*math.sin(angle),0,1]))\n pointTranslated = [point[0]+pathPlanningBasePoint[0],point[1]+pathPlanningBasePoint[1],point[2]+pathPlanningBasePoint[2]]\n points.InsertNextPoint(pointTranslated)\n for angle in numpy.arange(numpy.pi, 2*numpy.pi, phiResolution):\n point = matrix.MultiplyPoint(numpy.array([-radius * math.cos(angle), radius * math.sin(angle), 0, 1]))\n pointTranslated = [point[0] + pathPlanningBasePoint[0], point[1] + pathPlanningBasePoint[1], point[2] + pathPlanningBasePoint[2]]\n points.InsertNextPoint(pointTranslated)\n self.logic.synthesizedData.SetPoints(points)\n tempModel = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLModelNode\")\n tempModel.SetName(\"candicateCannula\")\n tempModel.SetAndObservePolyData(self.logic.synthesizedData)\n numOfRef = self.logic.coronalReferenceCurveManager.curveFiducials.GetNumberOfFiducials()\n if self.logic.synthesizedData.GetNumberOfPoints() and numOfRef >= 1:\n # display all paths model\n posKocher = [0.0,0.0,0.0]\n self.logic.coronalReferenceCurveManager.curveFiducials.GetNthFiducialPosition(numOfRef-1,posKocher)\n if not self.logic.pathCandidatesModel.GetPolyData():\n polyData = vtk.vtkPolyData()\n self.logic.pathCandidatesModel.SetAndObservePolyData(polyData)\n self.logic.pathReceived, self.logic.nPathReceived, self.logic.apReceived, self.logic.minimumPoint, self.logic.minimumDistance, self.logic.maximumPoint, self.logic.maximumDistance = self.logic.PercutaneousApproachAnalysisLogic.makePaths(\n self.logic.cylinderMiddlePointNode, None, 0, vesselModelWithMarginNode, tempModel)\n if self.logic.nPathReceived <= 0:\n slicer.util.warningDisplay(\n \"No any cannula candidate is venous-collision free, considering redefine the ventricle area.\")\n self.disableVentricleModification(False)\n return False\n else:\n status = self.logic.makePathMeetAllConditions(self.logic.pathReceived, self.logic.nPathReceived,\n self.logic.pathCandidatesModel.GetPolyData(), posKocher,\n posNasion, surfacePolyData)\n self.logic.pathCandidatesModel.GetDisplayNode().SetVisibility(1)\n self.logic.pathCandidatesModel.GetDisplayNode().SetSliceIntersectionOpacity(0.2)\n self.disableVentricleModification(False)\n if status == CandidatePathStatus.NoPosteriorAndNoWithinKocherPoint:\n slicer.util.warningDisplay(\n \"Cannula candidates are both too close to the forehead and too far from the kocher's point, considering redefine the ventricle area.\")\n elif status == CandidatePathStatus.NoPosteriorPoint:\n slicer.util.warningDisplay(\n \"Cannula candidates are too close to the forehead, considering redefine the ventricle area.\")\n elif status == CandidatePathStatus.NoWithinKocherPoint:\n slicer.util.warningDisplay(\n \"Cannula candidates are too far from the kocher's point, considering redefine the ventricle area.\")\n else:\n self.disableVentricleModification(True)\n return True\n else:\n return False\n return False\n\n def disableVentricleModification(self, status):\n targetNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_target\")\n distalNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_distal\")\n if targetNodeID and distalNodeID:\n targetNode = slicer.mrmlScene.GetNodeByID(targetNodeID)\n distalNode = slicer.mrmlScene.GetNodeByID(distalNodeID)\n distalNode.SetLocked(status)\n targetNode.SetLocked(status)\n self.logic.cylinderInteractor.SetLocked(status)\n\n def deactivateOtherButtonsAndModel(self, currentButton=None):\n if currentButton:\n self.isInAlgorithmSteps = True\n for childWidget in self.mainGUIGroupBox.children():\n if childWidget.className() == \"QPushButton\" and (not childWidget == currentButton):\n if childWidget.checked:\n childWidget.click()\n slicer.app.processEvents()\n self.setPrintModelVisibility(True if currentButton == self.createPlanningLineButton else False)\n pass\n\n def onCreatePlanningLine(self):\n self.logic.pitchAngle=\"--\"\n self.logic.yawAngle = \"--\"\n self.logic.skullNormToSaggitalAngle = \"--\"\n self.logic.skullNormToCoronalAngle = \"--\"\n self.logic.cannulaToNormAngle = \"--\"\n self.logic.cannulaToCoronalAngle = \"--\"\n self.deactivateOtherButtonsAndModel(currentButton=self.createPlanningLineButton)\n if not self.logic.baseVolumeNode:\n slicer.util.warningDisplay(\"No case is selected, please select the case in the combox\", windowTitle=\"\")\n self.deactivateOtherButtonsAndModel()\n else:\n if self.logic.createPlanningLine():\n self.logic.pathCandidatesModel.SetDisplayVisibility(0)\n self.logic.calcPitchYawAngles()\n self.logic.calculateDistanceToKocher()\n self.lengthSagittalPlanningLineEdit.text = '%.1f' % self.logic.sagittalPlanningCurveManager.getLength()\n self.lengthCoronalPlanningLineEdit.text = '%.1f' % self.logic.coronalPlanningCurveManager.getLength()\n self.distanceKocherPointEdit.text = '%.1f' % self.logic.kocherDistance\n self.pitchAngleEdit.text = '%.1f' % self.logic.pitchAngle\n self.yawAngleEdit.text = '%.1f' % (-self.logic.yawAngle)\n if self.logic.calcCannulaAngles():\n self.cannulaToNormAngleEdit.text = '%.1f' % self.logic.cannulaToNormAngle\n self.cannulaToCoronalAngleEdit.text = '%.1f' % self.logic.cannulaToCoronalAngle\n self.skullNormToSagittalAngleEdit.text = '%.1f' % self.logic.skullNormToSaggitalAngle\n self.skullNormToCoronalAngleEdit.text = '%.1f' % self.logic.skullNormToCoronalAngle\n cannulaNode = slicer.mrmlScene.GetNodeByID(self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_cannula\"))\n cannulaNode.AddObserver(cannulaNode.PointStartInteractionEvent, self.onResetPlanningOutput)\n self.logic.generateLabelMapFor3DModel()\n slicer.app.processEvents()\n # Export the label image to vtkMRMLModelNode\n modelName = self.logic.guideVolumeNode.GetName()\n guidanceModelCollect = slicer.mrmlScene.GetNodesByClassByName(\"vtkMRMLModelNode\", modelName)\n for modelIndex in range(guidanceModelCollect.GetNumberOfItems()):\n modelNode = guidanceModelCollect.GetItemAsObject(modelIndex)\n slicer.mrmlScene.RemoveNode(modelNode.GetDisplayNode())\n slicer.mrmlScene.RemoveNode(modelNode)\n self.activeSegmentSelector.setCurrentNode(self.logic.segmentationNode)\n self.logic.segmentationNode.GetSegmentation().RemoveAllSegments()\n self.importRadioButton.click()\n self.labelMapRadioButton.click()\n slicer.app.processEvents()\n self.labelMapSelector.setCurrentNode(self.logic.guideVolumeNode)\n self.portPushButton.click()\n slicer.app.processEvents()\n self.exportRadioButton.click()\n self.modelsRadioButton.click()\n slicer.app.processEvents()\n self.portPushButton.click()\n slicer.app.processEvents()\n if self.logic.segmentationNode.GetSegmentation().GetNthSegment(0) is not None:\n printModel = slicer.mrmlScene.GetNodeByID(self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_printModel\"))\n if printModel:\n slicer.mrmlScene.RemoveNode(printModel)\n printModel = slicer.mrmlScene.GetNodesByClassByName(\"vtkMRMLModelNode\", modelName).GetItemAsObject(0)\n printModel.SetDisplayVisibility(False)\n self.logic.baseVolumeNode.SetAttribute(\"vtkMRMLScalarVolumeNode.rel_printModel\", printModel.GetID())\n #---------------------\n leftPrintPartNode = slicer.mrmlScene.GetNodeByID(\n self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_leftPrintPart\"))\n rightPrintPartNode = slicer.mrmlScene.GetNodeByID(\n self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_rightPrintPart\"))\n self.logic.cutModel(printModel, leftPrintPartNode, rightPrintPartNode)\n self.onSaveData()\n pass\n\n\n def onPlaceVesselSeed(self):\n slicer.mrmlScene.RemoveObserver(self.nodeAddedEventObserverID)\n self.imageSlider.setValue(0.0)\n if self.addVesselSeedButton.isChecked():\n self.deactivateOtherButtonsAndModel(currentButton=self.addVesselSeedButton)\n index = next((i for i, name in enumerate(self.tabWidgetChildrenName) if name == self.tabMarkupsName), None)\n self.tabWidget.setCurrentIndex(index)\n self.isInAlgorithmSteps = True\n if not self.logic.baseVolumeNode:\n slicer.util.warningDisplay(\"No case is selected, please select the case in the combox\", windowTitle=\"\")\n self.deactivateOtherButtonsAndModel()\n else:\n self.greenLayoutButton.click()\n if self.prepareVolumes() and self.prepareCandidatePath():\n #self.green_widget.sliceOrientation = 'Coronal' #provide coronal view at green widget\n if self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselSeeds\"):\n vesselSeedsNode = slicer.mrmlScene.GetNodeByID(\n self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselSeeds\"))\n self.logic.interactionMode = EndPlacementModes.VesselSeeds\n self.simpleMarkupsWidget.setCurrentNode(vesselSeedsNode)\n else:\n self.logic.interactionMode = EndPlacementModes.NotSpecifiedMode\n self.simpleMarkupsWidget.markupsPlaceWidget().setPlaceModeEnabled(False)\n index = next((i for i, name in enumerate(self.tabWidgetChildrenName) if name == self.tabMainGroupBoxName), None)\n self.tabWidget.setCurrentIndex(index)\n self.checkCurrentProgress()\n self.setBackgroundAndForegroundIDs(foregroundVolumeID=self.logic.ventricleVolume.GetID(),\n backgroundVolumeID=self.logic.baseVolumeNode.GetID()) ## the slice widgets are set to none after the cli module calculation. reason unclear...\n self.isInAlgorithmSteps = False\n self.conventionalLayoutButton.click()\n self.nodeAddedEventObserverID = slicer.mrmlScene.AddObserver(slicer.mrmlScene.NodeAddedEvent,\n self.onVolumeAddedNode)\n pass\n\n def onSegmentVesselWithSeeds(self):\n slicer.mrmlScene.RemoveObserver(self.nodeAddedEventObserverID)\n self.onConnectedComponentCalc()\n self.prepareCandidatePath()\n self.isInAlgorithmSteps = False\n self.nodeAddedEventObserverID = slicer.mrmlScene.AddObserver(slicer.mrmlScene.NodeAddedEvent,\n self.onVolumeAddedNode)\n pass\n\n def onCreateModel(self):\n if self.logic.baseVolumeNode:\n outputModelNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_model\")\n if outputModelNodeID:\n outputModelNode = slicer.mrmlScene.GetNodeByID(outputModelNodeID)\n outputModelNode.SetAttribute(\"vtkMRMLModelNode.modelCreated\", \"False\")\n self.createModel()\n self.setBackgroundAndForegroundIDs(foregroundVolumeID=self.logic.ventricleVolume.GetID(),\n backgroundVolumeID=self.logic.baseVolumeNode.GetID())\n\n def createModel(self):\n self.isInAlgorithmSteps = True\n if self.logic.baseVolumeNode:\n outputModelNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_model\")\n if outputModelNodeID:\n outputModelNode = slicer.mrmlScene.GetNodeByID(outputModelNodeID)\n slicer.mrmlScene.RemoveObserver(self.nodeAddedEventObserverID)\n try:\n self.logic.holeFilledImageNode, self.logic.subtractedImageNode = self.logic.getOrCreateHoleSkullVolumeNode()\n self.logic.functions.createModelBaseOnVolume(self.logic.holeFilledImageNode, outputModelNode)\n self.logic.calculateVenousStat(self.logic.baseVolumeNode, self.logic.surfaceModelThreshold)\n except ValueError:\n slicer.util.warningDisplay(\n \"Skull surface calculation error, volumes might not be suitable for calculation\")\n finally:\n slicer.app.processEvents()\n self.nodeAddedEventObserverID = slicer.mrmlScene.AddObserver(slicer.mrmlScene.NodeAddedEvent,\n self.onVolumeAddedNode)\n self.onSet3DViewer()\n self.onSaveData()\n self.isInAlgorithmSteps = False\n\n def onSelectNasionPoint(self):\n if self.selectNasionButton.isChecked():\n self.conventionalLayoutButton.click()\n self.deactivateOtherButtonsAndModel(currentButton=self.selectNasionButton)\n if not self.logic.baseVolumeNode:\n slicer.util.warningDisplay(\"No case is selected, please select the case in the combox\", windowTitle=\"\")\n self.deactivateOtherButtonsAndModel()\n else:\n outputModelNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_model\")\n if outputModelNodeID:\n outputModelNode = slicer.mrmlScene.GetNodeByID(outputModelNodeID)\n if (not outputModelNode) or outputModelNode.GetAttribute(\"vtkMRMLModelNode.modelCreated\") == \"False\":\n self.logic.holeFilledImageNode, self.logic.subtractedImageNode = self.logic.createHoleFilledAndSubtractVolumeNode()\n self.logic.functions.createModelBaseOnVolume(self.logic.holeFilledImageNode, outputModelNode)\n self.logic.calculateVenousStat(self.logic.baseVolumeNode, self.logic.surfaceModelThreshold)\n self.onSet3DViewer()\n self.logic.selectNasionPointNode(outputModelNode) # when the model is not available, the model will be created, so nodeAdded signal should be disconnected\n self.setBackgroundAndForegroundIDs(foregroundVolumeID=self.logic.ventricleVolume.GetID(),\n backgroundVolumeID=self.logic.baseVolumeNode.GetID())\n else:\n self.logic.placeWidget.setPlaceModeEnabled(False)\n nasionNode = slicer.mrmlScene.GetNodeByID(self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_nasion\"))\n dnode = nasionNode.GetMarkupsDisplayNode()\n if dnode:\n dnode.SetVisibility(1)\n \n def setPrintModelVisibility(self, value):\n leftPrintPartNode = slicer.mrmlScene.GetNodeByID(\n self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_leftPrintPart\"))\n rightPrintPartNode = slicer.mrmlScene.GetNodeByID(\n self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_rightPrintPart\"))\n leftPrintPartNode.SetDisplayVisibility(value)\n rightPrintPartNode.SetDisplayVisibility(value)\n \n def onSelectSagittalPoint(self):\n if self.selectSagittalButton.isChecked():\n self.deactivateOtherButtonsAndModel(currentButton=self.selectSagittalButton)\n self.setAlgorithmButton.settings.okButton.click()\n if not self.logic.baseVolumeNode:\n slicer.util.warningDisplay(\"No case is selected, please select the case in the combox\", windowTitle=\"\")\n self.deactivateOtherButtonsAndModel()\n else:\n outputModelNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_model\")\n if outputModelNodeID:\n outputModelNode = slicer.mrmlScene.GetNodeByID(outputModelNodeID)\n if (not outputModelNode) or outputModelNode.GetAttribute(\"vtkMRMLModelNode.modelCreated\") == \"False\":\n self.logic.holeFilledImageNode, self.logic.subtractedImageNode = self.logic.createHoleFilledAndSubtractVolumeNode(self.logic.ventricleVolume,\n self.logic.surfaceModelThreshold, self.logic.samplingFactor, self.logic.morphologyParameters)\n self.logic.functions.createModelBaseOnVolume(self.logic.holeFilledImageNode, outputModelNode)\n self.logic.calculateVenousStat(self.logic.baseVolumeNode, self.logic.surfaceModelThreshold)\n self.onSet3DViewer()\n self.logic.selectSagittalPointNode(outputModelNode) # when the model is not available, the model will be created, so nodeAdded signal should be disconnected\n self.setBackgroundAndForegroundIDs(foregroundVolumeID=self.logic.ventricleVolume.GetID(),\n backgroundVolumeID=self.logic.baseVolumeNode.GetID())\n else:\n self.logic.placeWidget.setPlaceModeEnabled(False)\n\n def onSaveData(self):\n if not self.isLoadingCase:\n outputDir = os.path.join(self.slicerCaseWidget.currentCaseDirectory, \"Results\")\n if self.logic.baseVolumeNode:\n if self.logic.baseVolumeNode.GetModifiedSinceRead():\n self.logic.savePlanningDataToDirectory(self.logic.baseVolumeNode, outputDir)\n\n nodeAttributes=[\"rel_ventricleVolume\", \"rel_model\",\"rel_nasion\", \"rel_kocher\", \"rel_sagittalPoint\",\"rel_target\",\"rel_distal\", \"rel_vesselSeeds\", \\\n \"rel_cannula\",\"rel_skullNorm\",\"rel_cannulaModel\",\"rel_sagittalReferenceModel\",\"rel_sagittalReferenceMarker\",\"rel_coronalReferenceModel\",\"rel_coronalReferenceMarker\",\\\n \"rel_sagittalPlanningModel\",\"rel_sagittalPlanningMarker\",\"rel_coronalPlanningModel\",\"rel_coronalPlanningMarker\",\"rel_cylinderMarker\",\"rel_vesselnessModel\",\\\n \"rel_vesselnessWithMarginModel\",\"rel_vesselnessVolume\"]\n for attribute in nodeAttributes:\n nodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.\"+attribute)\n if nodeID and slicer.mrmlScene.GetNodeByID(nodeID):\n node = slicer.mrmlScene.GetNodeByID(nodeID)\n if node and node.GetModifiedSinceRead():\n self.logic.savePlanningDataToDirectory(node, outputDir)\n printModelAttributes = [\"rel_printModel\", \"rel_rightPrintPart\", \"rel_leftPrintPart\"]\n for attribute in printModelAttributes:\n nodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.\"+attribute)\n if nodeID and slicer.mrmlScene.GetNodeByID(nodeID):\n node = slicer.mrmlScene.GetNodeByID(nodeID)\n if node and node.GetModifiedSinceRead():\n self.logic.savePlanningDataToDirectory(node, outputDir, extension = \"stl\")\n slicer.util.saveScene(os.path.join(outputDir, \"Results.mrml\"))\n self.logic.appendPlanningTimeStampToJson(self.jsonFile, \"CaseSavedTime\", datetime.datetime.now().time().isoformat())\n pass\n\n def onModifyVenousMargin(self):\n self.logic.venousMargin = float(self.venousMarginEdit.text)\n self.logic.distanceMapThreshold = float(self.distanceMapThresholdEdit.text)\n vesselnessModelNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselnessModel\")\n vesselnessModelNode = slicer.mrmlScene.GetNodeByID(vesselnessModelNodeID)\n grayScaleModelNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_grayScaleModel\")\n grayScaleModelNode = slicer.mrmlScene.GetNodeByID(grayScaleModelNodeID)\n if vesselnessModelNode:\n vesselnessModelNode.SetAttribute(\"vtkMRMLModelNode.modelCreated\",\"False\")\n if grayScaleModelNode:\n grayScaleModelNode.SetAttribute(\"vtkMRMLModelNode.modelCreated\",\"False\")\n nodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselnessWithMarginModel\")\n node = slicer.mrmlScene.GetNodeByID(nodeID)\n if node:\n node.SetAttribute(\"vtkMRMLModelNode.modelCreated\",\"False\")\n nodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_grayScaleWithMarginModel\")\n node = slicer.mrmlScene.GetNodeByID(nodeID)\n if node:\n node.SetAttribute(\"vtkMRMLModelNode.modelCreated\", \"False\")\n pass\n\n def onModifySurfaceModel(self):\n self.logic.surfaceModelThreshold = float(self.surfaceModelThresholdEdit.text)\n outputModelNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_model\")\n if outputModelNodeID:\n outputModelNode = slicer.mrmlScene.GetNodeByID(outputModelNodeID)\n if outputModelNode:\n outputModelNode.SetAttribute(\"vtkMRMLModelNode.modelCreated\",\"False\")\n pass\n\n def onModifyMeasureLength(self):\n sagittalReferenceLength = float(self.lengthSagittalReferenceLineEdit.text)\n coronalReferenceLength = float(self.lengthCoronalReferenceLineEdit.text)\n if self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_sagittalLength\"):\n self.logic.baseVolumeNode.SetAttribute(\"vtkMRMLScalarVolumeNode.rel_sagittalLength\", '%.1f' % sagittalReferenceLength) \n if self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_coronalLength\"):\n self.logic.baseVolumeNode.SetAttribute(\"vtkMRMLScalarVolumeNode.rel_coronalLength\", '%.1f' % coronalReferenceLength)\n\n \n def onVenousGrayScaleCalc(self):\n self.isInAlgorithmSteps = True\n if self.logic.baseVolumeNode and self.prepareVolumes():\n quarterVolumeNode = self.logic.baseVolumeNode\n quarterVolumeNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_quarterVolume\")\n if quarterVolumeNodeID:\n quarterVolumeNode = slicer.mrmlScene.GetNodeByID(quarterVolumeNodeID)\n grayScaleModelNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_grayScaleModel\")\n grayScaleModelNode = slicer.mrmlScene.GetNodeByID(grayScaleModelNodeID)\n if grayScaleModelNode and (grayScaleModelNode.GetAttribute(\"vtkMRMLModelNode.modelCreated\") == \"False\"):\n self.grayScaleMakerButton.setEnabled(0)\n slicer.mrmlScene.RemoveObserver(self.nodeAddedEventObserverID)\n try:\n self.logic.calculateVenousGrayScale(quarterVolumeNode, grayScaleModelNode)\n except ValueError:\n slicer.util.warningDisplay(\n \"Venouse Calculation error, volumes might not be suitable for calculation\")\n finally:\n slicer.app.processEvents()\n self.nodeAddedEventObserverID = slicer.mrmlScene.AddObserver(slicer.mrmlScene.NodeAddedEvent,\n self.onVolumeAddedNode)\n self.onCalculateVenousCompletion(self.logic.cliNode)\n self.onSaveData()\n self.isInAlgorithmSteps = False \n pass\n\n def onConnectedComponentCalc(self):\n self.isInAlgorithmSteps = True\n vesselSeedsNode = None\n #self.logic.pathCandidatesModel.SetDisplayVisibility(0)\n if self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselSeeds\"):\n vesselSeedsNode = slicer.mrmlScene.GetNodeByID(\n self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselSeeds\"))\n vesselSeedsNode.SetLocked(True)\n if self.logic.baseVolumeNode and vesselSeedsNode and self.prepareVolumes():\n quarterVolumeNode = self.logic.baseVolumeNode\n quarterVolumeNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_quarterVolume\")\n if quarterVolumeNodeID:\n quarterVolumeNode = slicer.mrmlScene.GetNodeByID(quarterVolumeNodeID)\n vesselnessModelNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselnessModel\")\n if vesselnessModelNodeID:\n vesselnessModelNode = slicer.mrmlScene.GetNodeByID(vesselnessModelNodeID)\n slicer.mrmlScene.RemoveObserver(self.nodeAddedEventObserverID)\n try:\n self.logic.calculateConnectedComponent(quarterVolumeNode, vesselSeedsNode, vesselnessModelNode)\n except ValueError or TypeError:\n slicer.util.warningDisplay(\n \"Vessel Margin Calculation error, volumes might not be suitable for calculation\")\n finally:\n slicer.app.processEvents()\n self.nodeAddedEventObserverID = slicer.mrmlScene.AddObserver(slicer.mrmlScene.NodeAddedEvent,\n self.onVolumeAddedNode)\n marginNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselnessWithMarginModel\")\n marginNode = slicer.mrmlScene.GetNodeByID(marginNodeID)\n marginNode.SetAttribute(\"vtkMRMLModelNode.modelCreated\", \"False\")\n self.onCalculateVenousCompletion()\n self.onSaveData()\n self.isInAlgorithmSteps = False\n pass\n\n def onVenousVesselnessCalc(self):\n self.isInAlgorithmSteps = True\n vesselSeedsNode = None\n if self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselSeeds\"):\n vesselSeedsNode = slicer.mrmlScene.GetNodeByID(self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselSeeds\"))\n if self.logic.baseVolumeNode and vesselSeedsNode:\n quarterVolumeNode = self.logic.baseVolumeNode\n quarterVolumeNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_quarterVolume\")\n if quarterVolumeNodeID:\n quarterVolumeNode = slicer.mrmlScene.GetNodeByID(quarterVolumeNodeID)\n vesselnessVolumeNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselnessVolume\")\n vesselnessModelNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselnessModel\")\n if vesselnessVolumeNodeID and vesselnessModelNodeID:\n vesselnessVolumeNode = slicer.mrmlScene.GetNodeByID(vesselnessVolumeNodeID)\n vesselnessModelNode = slicer.mrmlScene.GetNodeByID(vesselnessModelNodeID)\n slicer.mrmlScene.RemoveObserver(self.nodeAddedEventObserverID)\n outputTubeFile = os.path.join(self.slicerCaseWidget.outputDir, \"OutputTubeTree\")\n try:\n self.logic.calculateVenousVesselness(quarterVolumeNode, vesselnessVolumeNode, vesselSeedsNode, outputTubeFile, vesselnessModelNode)\n except ValueError or TypeError:\n slicer.util.warningDisplay(\n \"Vessel Margin Calculation error, volumes might not be suitable for calculation\")\n finally:\n slicer.app.processEvents()\n self.nodeAddedEventObserverID = slicer.mrmlScene.AddObserver(slicer.mrmlScene.NodeAddedEvent,\n self.onVolumeAddedNode)\n self.onCalculateVenousCompletion(self.logic.cliNode)\n self.onSaveData()\n self.isInAlgorithmSteps = False \n pass\n\n #@beforeRunProcessEvents\n def onCalculateVenousCompletion(self,node=None,event=None):\n status = 'Completed'\n if node:\n status = node.GetStatusString()\n self.venousCalcStatus.setText(node.GetName() +' '+status)\n if status == 'Completed':\n self.progressBar.value = 50\n self.progressBar.labelText = 'Calculating Vessel margin'\n slicer.app.processEvents()\n slicer.mrmlScene.RemoveObserver(self.nodeAddedEventObserverID)\n try:\n self.logic.calculateConnectedCompWithMargin()\n except ValueError or TypeError:\n slicer.util.warningDisplay(\n \"Vessel Margin Calculation error, volumes might not be suitable for calculation\")\n finally:\n slicer.app.processEvents()\n self.nodeAddedEventObserverID = slicer.mrmlScene.AddObserver(slicer.mrmlScene.NodeAddedEvent,\n self.onVolumeAddedNode)\n self.progressBar.value = 100\n self.progressBar.close()\n self.onSaveData()\n else:\n slicer.util.warningDisplay(\"Vessel segmentation failed.\")\n self.grayScaleMakerButton.enabled = True\n pass\n\n def onSet3DViewer(self):\n layoutManager = slicer.app.layoutManager()\n threeDWidget = layoutManager.threeDWidget(0)\n threeDView = threeDWidget.threeDView()\n threeDView.lookFromViewAxis(ctkAxesWidget.Anterior)\n threeDView.resetFocalPoint()\n\n def setBackgroundAndForegroundIDs(self, foregroundVolumeID, backgroundVolumeID, fitToSlice = True):\n if foregroundVolumeID:\n self.red_cn.SetForegroundVolumeID(foregroundVolumeID)\n self.yellow_cn.SetForegroundVolumeID(foregroundVolumeID)\n self.green_cn.SetForegroundVolumeID(foregroundVolumeID)\n if backgroundVolumeID:\n self.red_cn.SetBackgroundVolumeID(backgroundVolumeID)\n self.yellow_cn.SetBackgroundVolumeID(backgroundVolumeID)\n self.green_cn.SetBackgroundVolumeID(backgroundVolumeID)\n if fitToSlice:\n self.red_widget.fitSliceToBackground()\n self.yellow_widget.fitSliceToBackground()\n self.green_widget.fitSliceToBackground()\n pass\n \n def setSliceForCylinder(self):\n shiftX = 20\n shiftY = -40\n shiftZ = 50\n nasionNode = slicer.mrmlScene.GetNodeByID(self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_nasion\"))\n targetNode = slicer.mrmlScene.GetNodeByID(self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_target\"))\n distalNode = slicer.mrmlScene.GetNodeByID(\n self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_distal\"))\n if (nasionNode.GetNumberOfFiducials() == 1):\n self.setBackgroundAndForegroundIDs(foregroundVolumeID=self.logic.ventricleVolume.GetID(), backgroundVolumeID=self.logic.baseVolumeNode.GetID(), fitToSlice=True\n )\n posNasion = numpy.array([0.0, 0.0, 0.0])\n nasionNode.GetNthFiducialPosition(0, posNasion)\n # posDistal = numpy.array([posTarget[0]-40, posTarget[1]-40, posTarget[2]])\n redSliceNode = slicer.mrmlScene.GetNodeByID(\"vtkMRMLSliceNodeRed\")\n redSliceNode.SetOrientation(\"Axial\")\n yellowSliceNode = slicer.mrmlScene.GetNodeByID(\"vtkMRMLSliceNodeYellow\")\n yellowSliceNode.SetOrientation(\"Sagittal\")\n greenSliceNode = slicer.mrmlScene.GetNodeByID(\"vtkMRMLSliceNodeGreen\")\n greenSliceNode.SetOrientation(\"Coronal\")\n if (distalNode.GetNumberOfFiducials() == 0) :\n direction = numpy.array([1, 1, 0])\n posTarget = numpy.array([posNasion[0] + shiftX, posNasion[1] + shiftY, posNasion[2] + shiftZ])\n self.logic.updateSliceViewBasedOnPoints(posTarget, posTarget + direction)\n else:\n posTarget = [0,0,0]\n posDistal = [0, 0, 0]\n targetNode.GetNthFiducialPosition(0, posTarget)\n distalNode.GetNthFiducialPosition(0, posDistal)\n self.logic.updateSliceViewBasedOnPoints(posTarget, posDistal)\n lm = slicer.app.layoutManager()\n sliceLogics = lm.mrmlSliceLogics()\n for n in range(sliceLogics.GetNumberOfItems()):\n sliceLogic = sliceLogics.GetItemAsObject(n)\n sliceWidget = lm.sliceWidget(sliceLogic.GetName())\n if (sliceWidget.objectName == 'qMRMLSliceWidgetRed'):\n redSliceNode.SetFieldOfView(sliceWidget.width / 3, sliceWidget.height / 3, 0.5)\n if (sliceWidget.objectName == 'qMRMLSliceWidgetYellow'):\n yellowSliceNode.SetFieldOfView(sliceWidget.width / 3, sliceWidget.height / 3, 0.5)\n if (sliceWidget.objectName == 'qMRMLSliceWidgetGreen'):\n greenSliceNode.SetFieldOfView(sliceWidget.width / 3, sliceWidget.height / 3, 0.5)\n pass\n\n # Event handlers for trajectory\n def onDefineVentricle(self):\n targetNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_target\")\n distalNodeID = self.logic.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_distal\")\n if targetNodeID and distalNodeID:\n targetNode = slicer.mrmlScene.GetNodeByID(targetNodeID)\n distalNode = slicer.mrmlScene.GetNodeByID(distalNodeID)\n if self.defineVentricleButton.isChecked():\n self.deactivateOtherButtonsAndModel(currentButton=self.defineVentricleButton)\n if not self.logic.baseVolumeNode:\n slicer.util.warningDisplay(\"No case is selected, please select the case in the combox\", windowTitle=\"\")\n self.deactivateOtherButtonsAndModel()\n else:\n self.imageSlider.setValue(100.0)\n self.initialFieldsValue()\n targetNode.SetLocked(False)\n distalNode.SetLocked(False)\n self.logic.cylinderInteractor.SetLocked(False)\n self.fourUpLayoutButton.click()\n self.logic.pathCandidatesModel.SetDisplayVisibility(0)\n self.logic.startEditPlanningTarget()\n else:\n self.logic.placeWidget.setPlaceModeEnabled(False)\n targetNode.SetLocked(True)\n distalNode.SetLocked(True)\n self.logic.cylinderInteractor.SetLocked(True)\n\n # Event handlers for trajectory\n def onEditPlanningDistal(self):\n self.imageSlider.setValue(100.0)\n self.initialFieldsValue()\n self.logic.startEditPlanningDistal()\n\n def onRelocatePathToKocher(self):\n if not self.logic.baseVolumeNode:\n slicer.util.warningDisplay(\"No case is selected, please select the case in the combox\", windowTitle=\"\")\n self.deactivateOtherButtonsAndModel()\n else:\n self.logic.relocateCannula(1)\n self.logic.pathCandidatesModel.SetDisplayVisibility(1)\n self.checkCurrentProgress()\n\n def onCannulaModified(self, caller, event):\n self.lengthCannulaEdit.text = '%.2f' % self.logic.getCannulaLength()\n\n def onLock(self):\n if self.lockTrajectoryCheckBox.checked == 1:\n self.defineVentricleButton.enabled = False\n self.logic.lockTrajectoryLine()\n else:\n self.defineVentricleButton.enabled = True\n self.logic.unlockTrajectoryLine()\n\n def onReload(self,moduleName=\"VentriculostomyPlanning\"):\n \"\"\"Generic reload method for any scripted module.\n ModuleWizard will subsitute correct default moduleName.\n \"\"\"\n self.logic.clear()\n slicer.mrmlScene.Clear(0)\n globals()[moduleName] = slicer.util.reloadScriptedModule(moduleName)\n\n self.logic = VentriculostomyPlanningLogic()\n self.logic.register(self)\n \nclass CurveManager():\n\n def __init__(self):\n try:\n import CurveMaker\n except ImportError:\n return slicer.util.warningDisplay(\n \"Error: Could not find extension CurveMaker. Open Slicer Extension Manager and install \"\n \"CurveMaker.\", \"Missing Extension\")\n self.cmLogic = CurveMaker.CurveMakerLogic()\n self.curveFiducials = None\n self._curveModel = None\n self.opacity = 1\n self.tubeRadius = 1.0\n self.curveName = \"\"\n self.curveModelName = \"\"\n self.step = 1\n self.tagEventExternal = None\n self.externalHandler = None\n\n self.sliceID = \"vtkMRMLSliceNodeRed\"\n\n # Slice is aligned to the first point (0) or last point (1)\n self.slicePosition = 0\n \n def clear(self):\n if self._curveModel:\n slicer.mrmlScene.RemoveNode(self._curveModel.GetDisplayNode())\n slicer.mrmlScene.RemoveNode(self._curveModel)\n if self.curveFiducials:\n slicer.mrmlScene.RemoveNode(self.curveFiducials.GetDisplayNode())\n slicer.mrmlScene.RemoveNode(self.curveFiducials)\n self.curveFiducials = None\n self._curveModel = None\n\n def connectModelNode(self, mrmlModelNode):\n if self._curveModel:\n slicer.mrmlScene.RemoveNode(self._curveModel.GetDisplayNode())\n slicer.mrmlScene.RemoveNode(self._curveModel)\n self._curveModel = mrmlModelNode\n\n def connectMarkerNode(self, mrmlMarkerNode):\n if self.curveFiducials:\n slicer.mrmlScene.RemoveNode(self.curveFiducials.GetDisplayNode())\n slicer.mrmlScene.RemoveNode(self.curveFiducials)\n self.curveFiducials = mrmlMarkerNode\n\n def setName(self, name):\n self.curveName = name\n self.curveModelName = \"%s-Model\" % (name)\n\n def setSliceID(self, name):\n # ID is either \"vtkMRMLSliceNodeRed\", \"vtkMRMLSliceNodeYellow\", or \"vtkMRMLSliceNodeGreen\"\n self.sliceID = name\n\n def setDefaultSlicePositionToFirstPoint(self):\n self.slicePosition = 0\n\n def setDefaultSlicePositionToLastPoint(self):\n self.slicePosition = 1\n \n def setModelColor(self, r, g, b):\n\n self.cmLogic.ModelColor = [r, g, b]\n \n # Make slice intersetion visible\n if self._curveModel:\n dnode = self._curveModel.GetDisplayNode()\n if dnode:\n dnode.SetColor([r, g, b])\n\n if self.curveFiducials:\n dnode = self.curveFiducials.GetMarkupsDisplayNode()\n if dnode:\n dnode.SetSelectedColor([r, g, b])\n\n def setModelOpacity(self, opacity):\n # Make slice intersetion visible\n self.opacity = opacity\n if self._curveModel:\n dnode = self._curveModel.GetDisplayNode()\n if dnode:\n dnode.SetOpacity(opacity)\n\n def setManagerTubeRadius(self,radius):\n self.tubeRadius = radius\n\n def setModifiedEventHandler(self, handler = None):\n\n self.externalHandler = handler\n \n if self._curveModel:\n self.tagEventExternal = self._curveModel.AddObserver(vtk.vtkCommand.ModifiedEvent, self.externalHandler)\n return self.tagEventExternal\n else:\n return None\n\n def resetModifiedEventHandle(self):\n \n if self._curveModel and self.tagEventExternal:\n self._curveModel.RemoveObserver(self.tagEventExternal)\n\n self.externalHandler = None\n self.tagEventExternal = None\n\n def onLineSourceUpdated(self,caller=None,event=None):\n \n self.cmLogic.updateCurve()\n\n # Make slice intersetion visible\n if self._curveModel:\n dnode = self._curveModel.GetDisplayNode()\n if dnode:\n dnode.SetSliceIntersectionVisibility(1)\n \n def startEditLine(self, initPoint=None):\n\n if self.curveFiducials == None:\n self.curveFiducials = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLMarkupsFiducialNode\")\n self.curveFiducials.SetName(self.curveName)\n slicer.mrmlScene.AddNode(self.curveFiducials)\n dnode = self.curveFiducials.GetMarkupsDisplayNode()\n if dnode:\n dnode.SetSelectedColor(self.cmLogic.ModelColor)\n if initPoint != None:\n self.curveFiducials.AddFiducial(initPoint[0],initPoint[1],initPoint[2])\n self.moveSliceToLine()\n \n if self._curveModel == None:\n self._curveModel = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLModelNode\")\n self._curveModel.SetName(self.curveModelName)\n self.setModelOpacity(self.opacity)\n slicer.mrmlScene.AddNode(self._curveModel)\n modelDisplayNode = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLModelDisplayNode\")\n modelDisplayNode.SetColor(self.cmLogic.ModelColor)\n modelDisplayNode.SetOpacity(self.opacity)\n slicer.mrmlScene.AddNode(modelDisplayNode)\n self._curveModel.SetAndObserveDisplayNodeID(modelDisplayNode.GetID())\n\n # Set exetrnal handler, if it has not been.\n if self.tagEventExternal == None and self.externalHandler:\n self.tagEventExternal = self._curveModel.AddObserver(vtk.vtkCommand.ModifiedEvent, self.externalHandler)\n \n self.cmLogic.DestinationNode = self._curveModel\n self.cmLogic.SourceNode = self.curveFiducials\n self.cmLogic.SourceNode.SetAttribute('CurveMaker.CurveModel', self.cmLogic.DestinationNode.GetID())\n self.cmLogic.updateCurve()\n\n self.cmLogic.CurvePoly = vtk.vtkPolyData() ## For CurveMaker bug\n self.cmLogic.enableAutomaticUpdate(1)\n self.cmLogic.setInterpolationMethod(1)\n self.cmLogic.setTubeRadius(self.tubeRadius)\n\n self.tagSourceNode = self.cmLogic.SourceNode.AddObserver('ModifiedEvent', self.onLineSourceUpdated)\n\n def endEditLine(self):\n\n interactionNode = slicer.mrmlScene.GetNodeByID(\"vtkMRMLInteractionNodeSingleton\")\n interactionNode.SetCurrentInteractionMode(slicer.vtkMRMLInteractionNode.ViewTransform) ## Turn off\n \n def clearLine(self):\n\n if self.curveFiducials:\n self.curveFiducials.RemoveAllMarkups()\n #To trigger the initializaton, when the user clear the trajectory and restart the planning, \n #the last point of the coronal reference line should be added to the trajectory\n\n self.cmLogic.updateCurve()\n\n if self._curveModel:\n pdata = self._curveModel.GetPolyData()\n if pdata:\n pdata.Initialize()\n\n def getLength(self):\n\n return self.cmLogic.CurveLength\n\n def getFirstPoint(self, position):\n\n if self.curveFiducials == None:\n return False\n elif self.curveFiducials.GetNumberOfFiducials() == 0:\n return False\n else:\n self.curveFiducials.GetNthFiducialPosition(0,position)\n return True\n\n def getLastPoint(self, position):\n if self.curveFiducials == None:\n return False\n else:\n nFiducials = self.curveFiducials.GetNumberOfFiducials()\n if nFiducials == 0:\n return False\n else:\n self.curveFiducials.GetNthFiducialPosition(nFiducials-1,position)\n return True\n\n def moveSliceToLine(self):\n\n viewer = slicer.mrmlScene.GetNodeByID(self.sliceID)\n\n if viewer == None:\n return\n\n if self.curveFiducials.GetNumberOfFiducials() == 0:\n return\n\n if self.slicePosition == 0:\n index = 0\n else:\n index = self.curveFiducials.GetNumberOfFiducials()-1\n\n pos = [0.0] * 3\n self.curveFiducials.GetNthFiducialPosition(index,pos)\n\n if self.sliceID == \"vtkMRMLSliceNodeRed\":\n viewer.SetOrientationToAxial()\n viewer.SetSliceOffset(pos[2])\n elif self.sliceID == \"vtkMRMLSliceNodeYellow\":\n viewer.SetOrientationToSagittal()\n viewer.SetSliceOffset(pos[0])\n elif self.sliceID == \"vtkMRMLSliceNodeGreen\":\n viewer.SetOrientationToCoronal()\n viewer.SetSliceOffset(pos[1])\n\n def lockLine(self):\n \n if (self.curveFiducials):\n self.curveFiducials.SetDisplayVisibility(0)\n\n def unlockLine(self):\n \n if (self.curveFiducials):\n self.curveFiducials.SetDisplayVisibility(1)\n \n\n#\n# VentriculostomyPlanningLogic\n#\n\nclass VentriculostomyPlanningLogic(ScriptedLoadableModuleLogic, ModuleLogicMixin):\n \"\"\"This class should implement all the actual\n computation done by your module. The interface\n should be such that other python code can import\n this class and make use of the functionality without\n requiring an instance of the Widget.\n Uses ScriptedLoadableModuleLogic base class, available at:\n https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py\n \"\"\"\n def register(self, observer):\n if not observer in self.observers:\n self.observers.append(observer)\n\n\n def unregister(self, observer):\n if observer in self.observers:\n self.observers.remove(observer)\n\n def unregister_all(self):\n if self.observers:\n del self.observers[:]\n\n @beforeRunProcessEvents\n def update_observers(self, *args, **kwargs):\n for observer in self.observers:\n observer.updateFromLogic(*args, **kwargs)\n\n def __init__(self):\n self.observers = []\n self.unregister_all()\n self.sagittalReferenceCurveManager = CurveManager()\n self.sagittalReferenceCurveManager.setName(\"SR1\")\n self.sagittalReferenceCurveManager.setSliceID(\"vtkMRMLSliceNodeYellow\")\n self.sagittalReferenceCurveManager.setDefaultSlicePositionToFirstPoint()\n self.sagittalReferenceCurveManager.setModelColor(1.0, 1.0, 0.5)\n \n self.coronalReferenceCurveManager = CurveManager()\n self.coronalReferenceCurveManager.setName(\"CR1\")\n self.coronalReferenceCurveManager.setSliceID(\"vtkMRMLSliceNodeGreen\")\n self.coronalReferenceCurveManager.setDefaultSlicePositionToLastPoint()\n self.coronalReferenceCurveManager.setModelColor(0.5, 1.0, 0.5)\n \n self.cylinderManager = CurveManager()\n self.cylinderManager.setName(\"Cylinder\")\n self.cylinderManager.setModelColor(0.0, 1.0, 1.0)\n self.cylinderManager.setDefaultSlicePositionToFirstPoint()\n self.cylinderManager.setModelOpacity(0.5)\n\n self.cannulaManager = CurveManager()\n self.cannulaManager.setName(\"Cannula\")\n self.cannulaManager.setDefaultSlicePositionToLastPoint()\n self.cannulaManager.setModelColor(0.5, 1.0, 0.0)\n self.cannulaManager.setDefaultSlicePositionToFirstPoint()\n\n self.coronalPlanningCurveManager = CurveManager()\n self.coronalPlanningCurveManager.setName(\"CP1\")\n self.coronalPlanningCurveManager.setSliceID(\"vtkMRMLSliceNodeGreen\")\n self.coronalPlanningCurveManager.setDefaultSlicePositionToLastPoint()\n self.coronalPlanningCurveManager.setModelColor(0.0, 1.0, 0.0)\n\n self.sagittalPlanningCurveManager = CurveManager()\n self.sagittalPlanningCurveManager.setName(\"SP1\")\n self.sagittalPlanningCurveManager.setSliceID(\"vtkMRMLSliceNodeYellow\")\n self.sagittalPlanningCurveManager.setDefaultSlicePositionToFirstPoint()\n self.sagittalPlanningCurveManager.setModelColor(1.0, 1.0, 0.0)\n\n self.ROINode = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLAnnotationROINode\")\n self.ROINode.SetName(\"ROINodeForCropping\")\n self.ROINode.HideFromEditorsOff()\n #slicer.mrmlScene.AddNode(self.ROINode)\n\n\n ##Path Planning variables\n self.PercutaneousApproachAnalysisLogic = PercutaneousApproachAnalysisLogic()\n self.cylinderMiddlePointNode = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLMarkupsFiducialNode\")\n self.synthesizedData = vtk.vtkPolyData()\n ##\n self.pathReceived = None\n self.pathCandidatesModel = None\n self.pathNavigationModel = None\n self.cylinderInteractor = None\n self.trajectoryProjectedMarker = None\n self.guideVolumeNode = None\n self.segmentationNode = None\n self.enableAuxilaryNodes()\n\n self.distanceMapFilter = sitk.SignedMaurerDistanceMapImageFilter()\n self.distanceMapFilter.SquaredDistanceOff()\n self.connectedComponentFilter = sitk.ConnectedThresholdImageFilter()\n self.connectedComponentFilter.SetConnectivity(self.connectedComponentFilter.FullConnectivity)\n self.thresholdProgressiveFactor = 0.2\n self.addImageFilter = sitk.AddImageFilter()\n self.statsFilter = sitk.LabelStatisticsImageFilter()\n self.venousMedianValue = -10000\n self.venousMaxValue = -10000\n self.baseVolumeNode = None\n self.ventricleVolume = None\n self.holeFilledImageNode = None\n self.subtractedImageNode = None\n self.functions = UsefulFunctions()\n self.useLeftHemisphere = False\n self.cliNode = None\n self.samplingFactor = 2\n self.topPoint = []\n self.surfaceModelThreshold = -500.0\n # kernel size in pixel: first vector is the hole filling kernel size, second vector is related with the mask thickness\n #self.morphologyParameters = [[10,10,6], [3,3,1]]\n self.morphologyParameters = [[1,1,1], [1,1,1]]\n self.distanceMapThreshold = 100\n self.venousMargin = 10.0 #in mm\n self.minimalVentricleLen = 10.0 # in mm\n self.yawAngle = 0.0\n self.pitchAngle = 0.0\n self.kocherDistance = 0.0\n self.cannulaToNormAngle = 0.0\n self.cannulaToCoronalAngle = 0.0\n self.skullNormToCoronalAngle = 0.0\n self.skullNormToSagittalAngle = 0.0\n self.sagittalYawAngle = 0\n self.trueSagittalPlane = None\n self.needSagittalCorrection = SagittalCorrectionStatus.NotYetChecked\n self.activeTrajectoryMarkup = 0\n self.cylinderRadius = 2.5 # unit mm\n self.posteriorMargin = 60.0 #unit mm\n self.kocherMargin = 20.0 #unit mm\n self.entryRadius = 25.0\n self.transform = vtk.vtkTransform()\n self.placeWidget = slicer.qSlicerMarkupsPlaceWidget()\n self.interactionMode = EndPlacementModes.NotSpecifiedMode\n\n def enableAuxilaryNodes(self):\n # Create display node\n self.cylinderInteractor = None\n self.trajectoryProjectedMarker = None\n modelDisplay = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLModelDisplayNode\")\n red = [1, 0, 0]\n displayNode = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLMarkupsDisplayNode\")\n displayNode.SetColor(red[0], red[1], red[2])\n displayNode.SetScene(slicer.mrmlScene)\n displayNode.SetVisibility(0)\n slicer.mrmlScene.AddNode(displayNode)\n self.cylinderInteractor = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLMarkupsFiducialNode\")\n self.cylinderInteractor.SetName(\"\")\n self.cylinderInteractor.AddObserver(slicer.vtkMRMLMarkupsNode().PointModifiedEvent, self.updateCylinderRadius)\n slicer.mrmlScene.AddNode(self.cylinderInteractor)\n self.cylinderInteractor.SetAndObserveDisplayNodeID(displayNode.GetID())\n markupDisplay = slicer.vtkMRMLMarkupsDisplayNode()\n markupDisplay.SetColor(red[0], red[1], red[2])\n markupDisplay.SetScene(slicer.mrmlScene)\n markupDisplay.SetVisibility(0)\n slicer.mrmlScene.AddNode(markupDisplay)\n self.trajectoryProjectedMarker = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLMarkupsFiducialNode\")\n self.trajectoryProjectedMarker.SetName(\"trajectoryProject\")\n slicer.mrmlScene.AddNode(self.trajectoryProjectedMarker)\n self.trajectoryProjectedMarker.SetAndObserveDisplayNodeID(markupDisplay.GetID())\n self.guideVolumeNode = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLLabelMapVolumeNode\")\n self.guideVolumeNode.SetName(\"GuideForVentriclostomy\")\n slicer.mrmlScene.AddNode(self.guideVolumeNode)\n self.segmentationNode = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLSegmentationNode\")\n self.segmentationNode.SetName(\"segmentation\")\n slicer.mrmlScene.AddNode(self.segmentationNode)\n self.segmentationNode.CreateDefaultDisplayNodes()\n self.segmentationNode.SetDisplayVisibility(False)\n\n def clear(self):\n if self.trajectoryProjectedMarker and self.trajectoryProjectedMarker.GetID():\n slicer.mrmlScene.RemoveNode(self.trajectoryProjectedMarker.GetDisplayNode())\n slicer.mrmlScene.RemoveNode(self.trajectoryProjectedMarker)\n self.trajectoryProjectedMarker = None\n if self.pathCandidatesModel and self.pathCandidatesModel.GetID():\n slicer.mrmlScene.RemoveNode(self.pathCandidatesModel.GetDisplayNode())\n slicer.mrmlScene.RemoveNode(self.pathCandidatesModel)\n self.pathCandidatesModel = None\n if self.pathNavigationModel and self.pathNavigationModel.GetID():\n slicer.mrmlScene.RemoveNode(self.pathNavigationModel.GetDisplayNode())\n slicer.mrmlScene.RemoveNode(self.pathNavigationModel)\n self.pathNavigationModel = None\n if self.cylinderManager:\n self.cylinderManager.clear()\n self.cylinderManager = None\n if self.cannulaManager:\n self.cannulaManager.clear()\n self.cannulaManager = None\n if self.coronalPlanningCurveManager:\n self.coronalPlanningCurveManager.clear()\n self.coronalPlanningCurveManager = None\n if self.coronalReferenceCurveManager:\n self.coronalReferenceCurveManager.clear()\n self.coronalReferenceCurveManager = None\n if self.sagittalReferenceCurveManager:\n self.sagittalReferenceCurveManager.clear()\n self.sagittalReferenceCurveManager = None\n if self.sagittalPlanningCurveManager:\n self.sagittalPlanningCurveManager.clear()\n self.sagittalPlanningCurveManager = None\n if self.holeFilledImageNode:\n slicer.mrmlScene.RemoveNode(self.holeFilledImageNode.GetDisplayNode())\n slicer.mrmlScene.RemoveNode(self.holeFilledImageNode)\n self.holeFilledImageNode = None\n if self.subtractedImageNode:\n slicer.mrmlScene.RemoveNode(self.subtractedImageNode.GetDisplayNode())\n slicer.mrmlScene.RemoveNode(self.subtractedImageNode)\n self.subtractedImageNode = None\n if self.guideVolumeNode:\n slicer.mrmlScene.RemoveNode(self.guideVolumeNode.GetDisplayNode())\n slicer.mrmlScene.RemoveNode(self.guideVolumeNode)\n self.guideVolumeNode = None\n if self.segmentationNode:\n slicer.mrmlScene.RemoveNode(self.segmentationNode.GetDisplayNode())\n slicer.mrmlScene.RemoveNode(self.segmentationNode)\n self.segmentationNode = None \n if self.ROINode:\n self.ROINode = None\n self.baseVolumeNode = None\n self.ventricleVolume = None\n self.venousMedianValue = -10000\n self.venousMaxValue = -10000\n\n def appendPlanningTimeStampToJson(self, JSONFile, parameterName, value):\n data = {}\n if not os.path.isfile(JSONFile):\n data[parameterName] = value\n with open(JSONFile, \"w\") as jsonFile:\n json.dump(data, jsonFile)\n jsonFile.close()\n else:\n with open(JSONFile, \"r\") as jsonFile:\n data = json.load(jsonFile)\n jsonFile.close()\n data[parameterName] = value \n with open(JSONFile, \"w\") as jsonFile:\n json.dump(data, jsonFile)\n jsonFile.close()\n pass\n\n def savePlanningDataToDirectory(self, node, outputDir, extension = None):\n nodeName = node.GetName()\n characters = [\": \", \" \", \":\", \"/\"]\n for character in characters:\n nodeName = nodeName.replace(character, \"-\")\n storageNodeAvailable = node.GetStorageNode()\n if not storageNodeAvailable:\n storageNodeAvailable = node.AddDefaultStorageNode()\n slicer.app.processEvents()\n if storageNodeAvailable:\n storageNode = node.GetStorageNode()\n if extension is None:\n extension = storageNode.GetDefaultWriteFileExtension()\n baseNodeName = self.baseVolumeNode.GetName()\n for character in characters:\n baseNodeName = baseNodeName.replace(character, \"-\")\n filename = os.path.join(outputDir, nodeName +'.'+ extension)\n if slicer.util.saveNode(node, filename):\n return True\n return False\n #warningMSG = \"Error in saving the %s\" %(nodeName)\n #slicer.util.warningDisplay(warningMSG)\n\n def hasImageData(self,volumeNode):\n \"\"\"This is an example logic method that\n returns true if the passed in volume\n node has valid image data\n \"\"\"\n if not volumeNode:\n logging.debug('hasImageData failed: no volume node')\n return False\n if volumeNode.GetImageData() is None:\n logging.debug('hasImageData failed: no image data in volume node')\n return False\n return True\n\n def lockReferenceLine(self):\n self.sagittalReferenceCurveManager.lockLine()\n self.coronalReferenceCurveManager.lockLine()\n\n def unlockReferenceLine(self):\n self.sagittalReferenceCurveManager.unlockLine()\n self.coronalReferenceCurveManager.unlockLine()\n\n def getOrCreateHoleSkullVolumeNode(self):\n if (self.holeFilledImageNode is None) or (self.subtractedImageNode is None):\n self.holeFilledImageNode, self.subtractedImageNode = self.functions.createHoleFilledVolumeNode2(self.ventricleVolume, self.surfaceModelThreshold, self.samplingFactor, self.morphologyParameters)\n return self.holeFilledImageNode, self.subtractedImageNode\n\n def startEditPlanningTarget(self):\n if self.baseVolumeNode:\n if self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_target\"):\n targetNode = slicer.mrmlScene.GetNodeByID(\n self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_target\"))\n self.interactionMode = EndPlacementModes.VentricleTarget\n self.placeWidget.setPlaceMultipleMarkups(self.placeWidget.ForcePlaceMultipleMarkups)\n self.placeWidget.setMRMLScene(slicer.mrmlScene)\n self.placeWidget.setCurrentNode(targetNode)\n self.placeWidget.setPlaceModeEnabled(True)\n\n def startEditPlanningDistal(self, caller = None, event = None):\n if self.baseVolumeNode:\n if self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_distal\"):\n distalNode = slicer.mrmlScene.GetNodeByID(\n self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_distal\"))\n self.interactionMode = EndPlacementModes.VentricleDistal\n self.placeWidget.setMRMLScene(slicer.mrmlScene)\n self.placeWidget.setCurrentNode(distalNode)\n self.placeWidget.setPlaceModeEnabled(True)\n\n def endVentricleCylinderDefinition(self):\n if self.baseVolumeNode:\n distalID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_distal\")\n distalNode = slicer.mrmlScene.GetNodeByID(distalID)\n if distalNode:\n posDistal = numpy.array([0.0, 0.0, 0.0])\n distalNode.GetNthFiducialPosition(distalNode.GetNumberOfMarkups() - 1, posDistal)\n if distalNode.GetNumberOfMarkups() > 1:\n distalNode.RemoveAllMarkups()\n distalNode.AddFiducial(posDistal[0], posDistal[1], posDistal[2])\n targetID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_target\")\n targetNode = slicer.mrmlScene.GetNodeByID(targetID)\n if targetNode:\n posTarget = numpy.array([0.0, 0.0, 0.0])\n targetNode.GetNthFiducialPosition(targetNode.GetNumberOfMarkups() - 1, posTarget)\n if targetNode.GetNumberOfMarkups() > 1:\n targetNode.RemoveAllMarkups()\n targetNode.AddFiducial(posTarget[0], posTarget[1], posTarget[2])\n self.placeWidget.setPlaceModeEnabled(False)\n pass\n \n def endEditTrajectory(self):\n self.cylinderManager.endEditLine()\n \n def calculateVesselWithMargin(self):\n marginNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselnessWithMarginModel\")\n marginNode = slicer.mrmlScene.GetNodeByID(marginNodeID)\n vesselnessNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselnessVolume\")\n vesselnessNode = slicer.mrmlScene.GetNodeByID(vesselnessNodeID)\n if not vesselnessNode.GetImageData():\n slicer.util.warningDisplay(\"Venous was not segmented yet, abort current procedure\")\n return None\n if marginNode and (marginNode.GetAttribute(\"vtkMRMLModelNode.modelCreated\") == \"False\"):\n vesselImage = sitk.Cast(sitkUtils.PullFromSlicer(vesselnessNodeID), sitk.sitkInt32)\n try:\n distanceMap = sitk.Multiply(self.distanceMapFilter.Execute(vesselImage),-1)\n except ValueError:\n slicer.util.warningDisplay(\n \"distance map calucation failed, try use different settings\")\n return None\n sitkUtils.PushToSlicer(distanceMap, \"distanceMap\", 0, True)\n imageCollection = slicer.mrmlScene.GetNodesByClassByName(\"vtkMRMLScalarVolumeNode\", \"distanceMap\")\n if imageCollection:\n distanceMapNode = imageCollection.GetItemAsObject(0)\n parameters = {}\n parameters[\"InputVolume\"] = distanceMapNode.GetID()\n parameters[\"OutputGeometry\"] = marginNode.GetID()\n parameters[\"Threshold\"] = -self.venousMargin\n grayMaker = slicer.modules.grayscalemodelmaker\n self.cliNode = slicer.cli.run(grayMaker, None, parameters, wait_for_completion=True)\n self.baseVolumeNode.SetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselnessWithMarginModel\", marginNode.GetID())\n marginNode.SetAttribute(\"vtkMRMLModelNode.modelCreated\", \"True\")\n self.update_observers(VentriculostomyUserEvents.SetSliceViewerEvent)\n return marginNode\n\n\n def calculateConnectedCompWithMargin(self):\n marginNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselnessWithMarginModel\")\n marginNode = slicer.mrmlScene.GetNodeByID(marginNodeID)\n imageCollection = slicer.mrmlScene.GetNodesByClassByName(\"vtkMRMLScalarVolumeNode\", \"connectedImage\")\n if imageCollection:\n connectedImageNode = imageCollection.GetItemAsObject(0)\n if connectedImageNode == None:\n return None\n if not connectedImageNode.GetImageData():\n slicer.util.warningDisplay(\"vessel was not segmented yet, abort current procedure\")\n return None\n if marginNode and (marginNode.GetAttribute(\"vtkMRMLModelNode.modelCreated\") == \"False\"):\n connectedImage = sitk.Cast(sitkUtils.PullFromSlicer(connectedImageNode.GetID()), sitk.sitkInt8)\n # padding is necessary, because some venous could be very close to the volume boundary. Which causes distance map to be incomplete at the coundary.\n # In the end, the incomplete distance map will create holes in the venous margin model\n padFilter = sitk.ConstantPadImageFilter()\n padFilter.SetPadLowerBound([int(self.venousMargin), int(self.venousMargin), int(self.venousMargin)])\n padFilter.SetPadUpperBound([int(self.venousMargin), int(self.venousMargin), int(self.venousMargin)])\n paddedImage = padFilter.Execute(connectedImage)\n try:\n distanceMap = sitk.Multiply(self.distanceMapFilter.Execute(paddedImage),-1)\n except ValueError:\n slicer.util.warningDisplay(\n \"distance map calucation failed, try use different settings\")\n return None\n sitkUtils.PushToSlicer(distanceMap, \"distanceMap\", 0, True)\n imageCollection = slicer.mrmlScene.GetNodesByClassByName(\"vtkMRMLScalarVolumeNode\", \"distanceMap\")\n if imageCollection:\n distanceMapNode = imageCollection.GetItemAsObject(0)\n parameters = {}\n parameters[\"InputVolume\"] = distanceMapNode.GetID()\n parameters[\"OutputGeometry\"] = marginNode.GetID()\n parameters[\"Threshold\"] = -self.venousMargin\n grayMaker = slicer.modules.grayscalemodelmaker\n self.cliNode = slicer.cli.run(grayMaker, None, parameters, wait_for_completion=True)\n self.baseVolumeNode.SetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselnessWithMarginModel\", marginNode.GetID())\n marginNode.SetAttribute(\"vtkMRMLModelNode.modelCreated\", \"True\")\n self.update_observers(VentriculostomyUserEvents.SetSliceViewerEvent) \n return marginNode\n \n def calculateGrayScaleWithMargin(self):\n nodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_grayScaleWithMarginModel\")\n node = slicer.mrmlScene.GetNodeByID(nodeID)\n if not node:\n node = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLModelNode\")\n slicer.mrmlScene.AddNode(node)\n if node and (node.GetAttribute(\"vtkMRMLModelNode.modelCreated\") == \"False\"):\n quarterVolumeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_quarterVolume\")\n quarterVolume = slicer.mrmlScene.GetNodeByID(quarterVolumeID)\n originImage = sitk.Cast(sitkUtils.PullFromSlicer(self.baseVolumeNode.GetID()), sitk.sitkInt32)\n try:\n distanceMap = self.distanceMapFilter.Execute(quarterVolume, self.distanceMapThreshold - 10, self.distanceMapThreshold )\n except ValueError:\n slicer.util.warningDisplay(\n \"distance map calucation failed, try use different settings\")\n return None\n sitkUtils.PushToSlicer(distanceMap, \"distanceMap\", 0, True)\n imageCollection = slicer.mrmlScene.GetNodesByClassByName(\"vtkMRMLScalarVolumeNode\", \"distanceMap\")\n if imageCollection:\n distanceMapNode = imageCollection.GetItemAsObject(0)\n parameters = {}\n parameters[\"InputVolume\"] = distanceMapNode.GetID()\n parameters[\"OutputGeometry\"] = node.GetID()\n parameters[\"Threshold\"] = -self.venousMargin\n grayMaker = slicer.modules.grayscalemodelmaker\n self.cliNode = slicer.cli.run(grayMaker, None, parameters, wait_for_completion=True)\n self.baseVolumeNode.SetAttribute(\"vtkMRMLScalarVolumeNode.rel_grayScaleWithMarginModel\", node.GetID())\n node.SetAttribute(\"vtkMRMLModelNode.modelCreated\", \"True\")\n self.update_observers(VentriculostomyUserEvents.SetSliceViewerEvent)\n node.SetDisplayVisibility(0) \n return node\n\n def calculateCylinderTransform(self):\n targetNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_target\")\n distalNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_distal\")\n if targetNodeID and distalNodeID:\n targetNode = slicer.mrmlScene.GetNodeByID(targetNodeID)\n distalNode = slicer.mrmlScene.GetNodeByID(distalNodeID)\n if targetNode.GetNumberOfFiducials() and distalNode.GetNumberOfFiducials():\n posTarget = numpy.array([0.0, 0.0, 0.0])\n targetNode.GetNthFiducialPosition(0, posTarget)\n posDistal = numpy.array([0.0, 0.0, 0.0])\n distalNode.GetNthFiducialPosition(0, posDistal)\n cylinderDirection = (numpy.array(posDistal) - numpy.array(posTarget)) / numpy.linalg.norm(\n numpy.array(posTarget) - numpy.array(posDistal))\n angle = math.acos(numpy.dot(numpy.array([0, 0, 1.0]), cylinderDirection))\n rotationAxis = numpy.cross(numpy.array([0, 0, 1.0]), cylinderDirection)\n self.transform.Identity()\n self.transform.RotateWXYZ(angle * 180.0 / numpy.pi, rotationAxis[0], rotationAxis[1], rotationAxis[2])\n return self.transform\n return None\n\n def calculateCannulaTransform(self):\n cannulaNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_cannula\")\n if cannulaNodeID:\n cannulaNode = slicer.mrmlScene.GetNodeByID(cannulaNodeID)\n if cannulaNode.GetNumberOfFiducials() == 2:\n posTarget = numpy.array([0.0, 0.0, 0.0])\n cannulaNode.GetNthFiducialPosition(0, posTarget)\n posEntry = numpy.array([0.0, 0.0, 0.0])\n cannulaNode.GetNthFiducialPosition(1, posEntry)\n cannulaDirection = (numpy.array(posEntry) - numpy.array(posTarget)) / numpy.linalg.norm(\n numpy.array(posTarget) - numpy.array(posEntry))\n angle = math.acos(numpy.dot(numpy.array([0, 0, 1.0]), cannulaDirection))\n rotationAxis = numpy.cross(numpy.array([0, 0, 1.0]), cannulaDirection)\n transform = vtk.vtkTransform()\n transform.Identity()\n transform.RotateWXYZ(angle * 180.0 / numpy.pi, rotationAxis[0], rotationAxis[1], rotationAxis[2])\n return transform\n return None\n\n def makeNavigationLines(self, path, approachablePoints, polyData):\n points = vtk.vtkPoints()\n polyData.SetPoints(points)\n\n lines = vtk.vtkCellArray()\n polyData.SetLines(lines)\n linesIDArray = lines.GetData()\n linesIDArray.Reset()\n linesIDArray.InsertNextTuple1(0)\n\n polygons = vtk.vtkCellArray()\n polyData.SetPolys(polygons)\n idArray = polygons.GetData()\n idArray.Reset()\n idArray.InsertNextTuple1(0)\n\n if approachablePoints != 0:\n for point in path:\n pointIndex = points.InsertNextPoint(*point)\n linesIDArray.InsertNextTuple1(pointIndex)\n linesIDArray.SetTuple1(0, linesIDArray.GetNumberOfTuples() - 1)\n lines.SetNumberOfCells(1)\n # Create model node\n pass\n \n def createCandidatesWithinKocherPoint(self, entryPoints, posCenter, polyData, posKocher, surfacePolyData):\n\n points = vtk.vtkPoints()\n polyData.SetPoints(points)\n\n lines = vtk.vtkCellArray()\n polyData.SetLines(lines)\n linesIDArray = lines.GetData()\n linesIDArray.Reset()\n linesIDArray.InsertNextTuple1(0)\n\n polygons = vtk.vtkCellArray()\n polyData.SetPolys(polygons)\n idArray = polygons.GetData()\n idArray.Reset()\n idArray.InsertNextTuple1(0)\n\n locator = vtk.vtkCellLocator()\n locator.SetDataSet(surfacePolyData)\n locator.BuildLocator()\n t = vtk.mutable(0)\n x = [0.0, 0.0, 0.0]\n pcoords = [0.0, 0.0, 0.0]\n subId = vtk.mutable(0)\n for pointIndex in range(entryPoints.GetNumberOfPoints()):\n hasIntersection = locator.IntersectWithLine(entryPoints.GetPoint(pointIndex), posCenter, 1e-2, t, x,\n pcoords, subId)\n if (hasIntersection > 0) and numpy.linalg.norm(numpy.array(x)-numpy.array(posKocher)) < self.kocherMargin:\n index = points.InsertNextPoint(*posCenter)\n linesIDArray.InsertNextTuple1(index)\n linesIDArray.SetTuple1(0, linesIDArray.GetNumberOfTuples() - 1)\n lines.SetNumberOfCells(1)\n point = entryPoints.GetPoint(pointIndex)\n index = points.InsertNextPoint(*point)\n linesIDArray.InsertNextTuple1(index)\n linesIDArray.SetTuple1(0, linesIDArray.GetNumberOfTuples() - 1)\n lines.SetNumberOfCells(1)\n # Create model node\n pass\n\n def makePathMeetAllConditions(self, path, approachablePoints, polyData, posKocher, posNasion, surfacePolyData):\n\n trimmedPath = []\n points = vtk.vtkPoints()\n polyData.SetPoints(points)\n\n lines = vtk.vtkCellArray()\n polyData.SetLines(lines)\n linesIDArray = lines.GetData()\n linesIDArray.Reset()\n linesIDArray.InsertNextTuple1(0)\n\n polygons = vtk.vtkCellArray()\n polyData.SetPolys(polygons)\n idArray = polygons.GetData()\n idArray.Reset()\n idArray.InsertNextTuple1(0)\n\n locator = vtk.vtkCellLocator()\n locator.SetDataSet(surfacePolyData)\n locator.BuildLocator()\n t = vtk.mutable(0)\n x = [0.0, 0.0, 0.0]\n pcoords = [0.0, 0.0, 0.0]\n subId = vtk.mutable(0)\n numOfRef = self.coronalReferenceCurveManager.curveFiducials.GetNumberOfFiducials()\n hasPosteriorPoints = False\n hasWithinKocherPoints = False\n if approachablePoints != 0 and numOfRef >=1:\n for pointIndex in range(1, len(path), 2):\n hasIntersection = locator.IntersectWithLine(path[pointIndex], path[pointIndex - 1], 1e-2, t, x,\n pcoords, subId)\n isPosteriorEnough = (abs(x[2] - posNasion[2]) > self.posteriorMargin)\n isWithinKocherMargin = (numpy.linalg.norm(numpy.array(x) - numpy.array(posKocher)) < self.kocherMargin)\n if (hasIntersection > 0) and isPosteriorEnough and isWithinKocherMargin:\n pointPre = path[pointIndex - 1]\n index = points.InsertNextPoint(*pointPre)\n linesIDArray.InsertNextTuple1(index)\n linesIDArray.SetTuple1(0, linesIDArray.GetNumberOfTuples() - 1)\n lines.SetNumberOfCells(1)\n point = path[pointIndex]\n index = points.InsertNextPoint(*point)\n linesIDArray.InsertNextTuple1(index)\n linesIDArray.SetTuple1(0, linesIDArray.GetNumberOfTuples() - 1)\n lines.SetNumberOfCells(1)\n trimmedPath.append(path[pointIndex - 1])\n trimmedPath.append(path[pointIndex])\n hasPosteriorPoints = isPosteriorEnough if hasPosteriorPoints == False else hasPosteriorPoints\n hasWithinKocherPoints = isWithinKocherMargin if hasWithinKocherPoints == False else hasWithinKocherPoints\n self.pathReceived = trimmedPath\n self.nPathReceived = int(len(trimmedPath)/2)\n if hasPosteriorPoints == False and hasWithinKocherPoints == False:\n return CandidatePathStatus.NoPosteriorAndNoWithinKocherPoint\n elif hasPosteriorPoints == False:\n return CandidatePathStatus.NoPosteriorPoint\n elif hasWithinKocherPoints == False:\n return CandidatePathStatus.NoWithinKocherPoint\n\n def relocateCannula(self, optimizationMethod=1):\n if self.pathReceived:\n #self.cannulaManager.curveFiducials.RemoveAllMarkups()\n posTarget = numpy.array([0.0] * 3)\n self.cylinderManager.getFirstPoint(posTarget)\n posDistal = numpy.array([0.0] * 3)\n self.cylinderManager.getLastPoint(posDistal)\n direction1Norm = (posDistal - posTarget)/numpy.linalg.norm(posTarget - posDistal)\n angleCalc =numpy.pi\n if optimizationMethod == 0: # the cannula is relocated so that its direction is closer to the ventricle center\n optimizedEntry = numpy.array([])\n for pointIndex in range(1, len(self.pathReceived),2):\n direction2 = numpy.array(self.pathReceived[pointIndex]) - numpy.array(self.pathReceived[pointIndex-1])\n direction2Norm = direction2/numpy.linalg.norm(direction2)\n angle = math.acos(numpy.dot(direction1Norm, direction2Norm))\n if angle < angleCalc:\n angleCalc = angle\n optimizedEntry = numpy.array(self.pathReceived[pointIndex])\n if optimizedEntry.any():\n posEntry = numpy.array([0.0] * 3)\n self.trajectoryProjectedMarker.GetNthFiducialPosition(0, posEntry)\n distance2 = numpy.linalg.norm(numpy.array(posTarget) - numpy.array(posEntry))\n distance1 = numpy.linalg.norm(numpy.array(posTarget) - numpy.array(posDistal))\n posDistalModified = numpy.array(posTarget) + (numpy.array(optimizedEntry) - numpy.array(posTarget))/distance2*distance1\n #self.cylinderManager.curveFiducials.SetNthFiducialPositionFromArray(1,optimizedEntry)\n self.cannulaManager.curveFiducials.SetNthFiducialPositionFromArray(0, posTarget)\n self.cannulaManager.curveFiducials.SetNthFiducialPositionFromArray(1, posDistalModified)\n elif optimizationMethod == 1: # relocate the cannula so that it is close to the reference entry point\n inputModelNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_model\")\n if inputModelNodeID:\n inputModelNode = slicer.mrmlScene.GetNodeByID(inputModelNodeID) \n if (inputModelNode.GetAttribute(\"vtkMRMLModelNode.modelCreated\") == \"True\"):\n polyData = inputModelNode.GetPolyData()\n locator = vtk.vtkCellLocator()\n locator.SetDataSet(polyData)\n locator.BuildLocator()\n t = vtk.mutable(0)\n x = [0.0,0.0,0.0]\n pcoords = [0.0,0.0,0.0]\n subId = vtk.mutable(0)\n numOfRef = self.coronalReferenceCurveManager.curveFiducials.GetNumberOfFiducials()\n distanceMin = 1e20\n minIndex = 1\n if numOfRef >= 1:\n posKocher = [0.0,0.0,0.0]\n self.coronalReferenceCurveManager.curveFiducials.GetNthFiducialPosition(numOfRef-1,posKocher)\n for pointIndex in range(1, len(self.pathReceived),2):\n hasIntersection = locator.IntersectWithLine(self.pathReceived[pointIndex], self.pathReceived[pointIndex-1], 1e-2, t, x, pcoords, subId)\n if hasIntersection>0:\n if distanceMin > numpy.linalg.norm(numpy.array(posKocher)-numpy.array(x)):\n distanceMin = numpy.linalg.norm(numpy.array(posKocher)-numpy.array(x))\n minIndex = pointIndex\n self.cannulaManager.curveFiducials.RemoveAllMarkups()\n self.cannulaManager.curveFiducials.AddFiducial(0, 0, 0)\n self.cannulaManager.curveFiducials.AddFiducial(0, 0, 0)\n self.cannulaManager.curveFiducials.SetNthFiducialPositionFromArray(0, self.pathReceived[minIndex-1])\n self.cannulaManager.curveFiducials.SetNthFiducialPositionFromArray(1, self.pathReceived[minIndex])\n direction2 = numpy.array(self.pathReceived[minIndex]) - numpy.array(self.pathReceived[minIndex-1])\n direction2Norm = direction2/numpy.linalg.norm(direction2)\n angleCalc = math.acos(numpy.dot(direction1Norm, direction2Norm))\n self.activeTrajectoryMarkup = 1\n self.updateCannulaPosition(self.cannulaManager.curveFiducials)\n posProject = numpy.array([0.0] * 3)\n self.trajectoryProjectedMarker.GetNthFiducialPosition(0,posProject)\n posMiddle = (posTarget+posDistal)/2\n posBottom = posMiddle+numpy.linalg.norm(posMiddle - posDistal)/math.cos(angleCalc)*(posMiddle-posProject)/numpy.linalg.norm(posMiddle - posProject)\n self.cannulaManager.curveFiducials.SetNthFiducialPositionFromArray(0, posBottom)\n self.cannulaManager.curveFiducials.SetNthMarkupLocked(0,True)\n self.cannulaManager.curveFiducials.SetNthFiducialPositionFromArray(1, posProject)\n self.trajectoryProjectedMarker.RemoveAllMarkups()\n pass\n\n def getCannulaLength(self):\n return self.cannulaManager.getLength()\n\n def lockTrajectoryLine(self):\n self.cylinderManager.lockLine()\n self.cylinderManager.lockLine()\n\n def unlockTrajectoryLine(self):\n self.cylinderManager.unlockLine()\n self.cylinderManager.unlockLine()\n\n def calculateVenousStat(self, venousVolume, thresholdValue):\n if float(venousVolume.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_venousMedianValue\")) < self.surfaceModelThreshold \\\n or float(venousVolume.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_venousMaxValue\")) < self.surfaceModelThreshold:\n venousImage = sitk.Cast(sitkUtils.PullFromSlicer(venousVolume.GetID()), sitk.sitkInt16)\n resampleFilter = sitk.ResampleImageFilter()\n resampleFilter.SetSize(numpy.array(venousImage.GetSize()) / self.samplingFactor)\n resampleFilter.SetOutputSpacing(numpy.array(venousImage.GetSpacing()) * self.samplingFactor)\n resampleFilter.SetOutputDirection(venousImage.GetDirection())\n resampleFilter.SetOutputOrigin(numpy.array(venousImage.GetOrigin()))\n resampledVenousImage = resampleFilter.Execute(venousImage)\n thresholdFilter = sitk.BinaryThresholdImageFilter()\n thresholdImage = thresholdFilter.Execute(resampledVenousImage, thresholdValue, 10000, 1, 0)\n self.statsFilter.Execute(resampledVenousImage, thresholdImage)\n self.venousMaxValue = self.statsFilter.GetMaximum(1)\n self.venousMedianValue = self.statsFilter.GetMedian(1)\n venousVolume.SetAttribute(\"vtkMRMLScalarVolumeNode.rel_venousMedianValue\", str(self.venousMedianValue))\n venousVolume.SetAttribute(\"vtkMRMLScalarVolumeNode.rel_venousMaxValue\", str(self.venousMaxValue))\n\n def createClippedVolume(self, inputVolumeNode, clippingModel, outputVolume):\n outputImageData = self.functions.clipVolumeWithModelNode(inputVolumeNode, clippingModel, True, 0)\n outputVolume.SetAndObserveImageData(outputImageData)\n ijkToRas = vtk.vtkMatrix4x4()\n inputVolumeNode.GetIJKToRASMatrix(ijkToRas)\n outputVolume.SetIJKToRASMatrix(ijkToRas)\n # Add a default display node to output volume node if it does not exist yet\n if not outputVolume.GetDisplayNode():\n displayNode = slicer.vtkMRMLScalarVolumeDisplayNode()\n displayNode.SetAndObserveColorNodeID(\"vtkMRMLColorTableNodeGrey\")\n slicer.mrmlScene.AddNode(displayNode)\n outputVolume.SetAndObserveDisplayNodeID(displayNode.GetID())\n\n def calculateVenousGrayScale(self, inputVolumeNode, grayScaleModelNode): \n parameters = {}\n parameters[\"InputVolume\"] = inputVolumeNode.GetID()\n parameters[\"Threshold\"] = self.distanceMapThreshold\n parameters[\"OutputGeometry\"] = grayScaleModelNode.GetID()\n grayMaker = slicer.modules.grayscalemodelmaker\n self.cliNode = slicer.cli.run(grayMaker, None, parameters, wait_for_completion=True)\n\n def adjustSeed(self, oriImage, posSeed):\n posIJKAdjusted = [posSeed[0],posSeed[1],posSeed[2]]\n voxelValueMax = oriImage.GetPixel(int(posIJKAdjusted[0]), int(posIJKAdjusted[1]), int(posIJKAdjusted[2]))\n xLength = 3\n yLength = 3\n zLength = 3\n for x in range(-xLength, xLength):\n for y in range(-yLength, yLength):\n for z in range(-zLength, zLength):\n if (posSeed[0] + x)>=0 and (posSeed[1] +y) >=0 and (posSeed[2]+z)>=0 \\\n and (posSeed[0] + x)<oriImage.GetWidth() and (posSeed[1] +y) <oriImage.GetHeight() and (posSeed[2]+z)<oriImage.GetDepth():\n voxelValue = oriImage.GetPixel(int(posSeed[0] + x), int(posSeed[1] +y), int(posSeed[2]+z))\n if voxelValue > voxelValueMax:\n voxelValueMax = voxelValue\n posIJKAdjusted = [posSeed[0] + x, posSeed[1] + y, posSeed[2] + z]\n return posIJKAdjusted, voxelValueMax\n\n def calculateConnectedComponent(self,inputVolumeNode, vesselSeedsNode, vesselnessModelNode):\n if inputVolumeNode:\n oriImage = sitk.Cast(sitkUtils.PullFromSlicer(inputVolumeNode.GetID()), sitk.sitkInt16)\n matrix = vtk.vtkMatrix4x4()\n inputVolumeNode.GetRASToIJKMatrix(matrix)\n self.connectedComponentFilter.ClearSeeds()\n connectedImageTotal = sitk.Image(oriImage.GetWidth(), oriImage.GetHeight(), oriImage.GetDepth(),oriImage.GetPixelID())\n connectedImageTotal.SetOrigin(oriImage.GetOrigin())\n connectedImageTotal.SetSpacing(oriImage.GetSpacing())\n connectedImageTotal.SetDirection(oriImage.GetDirection())\n for iSeed in range(vesselSeedsNode.GetNumberOfFiducials()):\n posRAS = [0.0,0.0,0.0]\n vesselSeedsNode.GetNthFiducialPosition(iSeed, posRAS)\n posIJK = matrix.MultiplyFloatPoint([posRAS[0], posRAS[1], posRAS[2], 1.0])\n self.connectedComponentFilter.ClearSeeds()\n if int(posIJK[0])>=0 and int(posIJK[1]) >=0 and int(posIJK[2])>=0:\n posIJKAdjusted, voxelValue = self.adjustSeed(oriImage, posIJK)\n self.connectedComponentFilter.AddSeed([int(posIJKAdjusted[0]), int(posIJKAdjusted[1]), int(posIJKAdjusted[2])])\n venousMaxValueAdjusted = self.venousMaxValue\n if self.venousMaxValue > 800:\n venousMaxValueAdjusted = 800\n voxelValuefactor = math.pow(\n 1 - (voxelValue - self.venousMedianValue) / (venousMaxValueAdjusted - self.venousMedianValue), 3) * (\n 1 - self.thresholdProgressiveFactor) + self.thresholdProgressiveFactor\n print voxelValue, voxelValuefactor\n self.connectedComponentFilter.SetLower(voxelValue * voxelValuefactor)\n self.connectedComponentFilter.SetUpper(voxelValue / voxelValuefactor)\n connectedImage = sitk.Cast(self.connectedComponentFilter.Execute(oriImage), sitk.sitkInt16)\n connectedImageTotal = self.addImageFilter.Execute(connectedImage, connectedImageTotal)\n else:\n slicer.util.warningDisplay(\"Current seed\"+ str(vesselSeedsNode.GetNthFiducialLabel(iSeed)) + \" is out of the image\")\n sitkUtils.PushToSlicer(connectedImageTotal, \"connectedImage\", 0, True)\n imageCollection = slicer.mrmlScene.GetNodesByClassByName(\"vtkMRMLScalarVolumeNode\", \"connectedImage\")\n if imageCollection:\n connectedImageNode = imageCollection.GetItemAsObject(0)\n parameters = {}\n parameters[\"InputVolume\"] = connectedImageNode.GetID()\n parameters[\"Threshold\"] = 0.5\n parameters[\"OutputGeometry\"] = vesselnessModelNode.GetID()\n grayMaker = slicer.modules.grayscalemodelmaker\n slicer.cli.run(grayMaker, None, parameters, wait_for_completion=True)\n \n def calculateVenousVesselness(self,inputVolumeNode, vesselnessVolumeNode, vesselSeedsNode, outputTubeFile, vesselnessModelNode):\n parameters = {}\n parameters[\"inputVolume\"] = inputVolumeNode.GetID()\n parameters[\"outputTubeFile\"] = outputTubeFile\n parameters[\"outputTubeImage\"] = vesselnessVolumeNode.GetID()\n parameters[\"seedP\"] = vesselSeedsNode.GetID()\n parameters[\"scale\"] = 1.0\n parameters[\"border\"] = 6.00\n self.cliNode = slicer.cli.run(slicer.modules.segmenttubes, None, parameters, wait_for_completion=True)\n parameters = {}\n parameters[\"InputVolume\"] = vesselnessVolumeNode.GetID()\n parameters[\"Threshold\"] = 0.5\n parameters[\"OutputGeometry\"] = vesselnessModelNode.GetID()\n grayMaker = slicer.modules.grayscalemodelmaker\n slicer.cli.run(grayMaker, None, parameters, wait_for_completion=True)\n\n def enableRelatedVolume(self, attributeName, volumeName, visibility = True):\n volumeNode = None\n if self.baseVolumeNode:\n enabledAttributeID = self.baseVolumeNode.GetAttribute(attributeName)\n if enabledAttributeID and slicer.mrmlScene.GetNodeByID(enabledAttributeID):\n volumeNode = slicer.mrmlScene.GetNodeByID(enabledAttributeID)\n if volumeNode and volumeNode.GetDisplayNode() and visibility:\n volumeNode.GetDisplayNode().SetVisibility(1)\n else:\n volumeNode = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLScalarVolumeNode\")\n volumeNode.SetName(volumeName)\n slicer.mrmlScene.AddNode(volumeNode)\n self.baseVolumeNode.SetAttribute(attributeName, volumeNode.GetID())\n return volumeNode\n\n def enableRelatedModel(self, attributeName, modelName, color = [0.0, 0.0, 1.0], visibility = True, intersectionVis=True):\n modelNode = None\n if self.baseVolumeNode:\n enabledAttributeID = self.baseVolumeNode.GetAttribute(attributeName)\n if enabledAttributeID and slicer.mrmlScene.GetNodeByID(enabledAttributeID):\n modelNode = slicer.mrmlScene.GetNodeByID(enabledAttributeID)\n modelNode.SetAttribute(\"vtkMRMLModelNode.modelCreated\", \"True\")\n else:\n modelNode = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLModelNode\")\n modelNode.SetAttribute(\"vtkMRMLModelNode.modelCreated\", \"False\")\n modelNode.SetName(modelName)\n slicer.mrmlScene.AddNode(modelNode)\n modelDisplayNode = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLModelDisplayNode\")\n modelDisplayNode.SetColor(color)\n modelDisplayNode.SetOpacity(0.5)\n slicer.mrmlScene.AddNode(modelDisplayNode)\n modelNode.SetAndObserveDisplayNodeID(modelDisplayNode.GetID())\n self.baseVolumeNode.SetAttribute(attributeName, modelNode.GetID())\n if modelNode and modelNode.GetDisplayNode():\n modelNode.GetDisplayNode().SetVisibility(visibility)\n modelNode.GetDisplayNode().SetSliceIntersectionVisibility(intersectionVis)\n return modelNode\n\n def enableRelatedMarkups(self, attributeName, markupsName, color = [1.0, 0.0, 0.0], visibility = True):\n markupsNode = None\n if self.baseVolumeNode:\n enabledAttributeID = self.baseVolumeNode.GetAttribute(attributeName)\n if enabledAttributeID and slicer.mrmlScene.GetNodeByID(enabledAttributeID):\n markupsNode = slicer.mrmlScene.GetNodeByID(enabledAttributeID)\n else:\n markupsNode = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLMarkupsFiducialNode\")\n markupsNode.SetName(markupsName)\n slicer.mrmlScene.AddNode(markupsNode)\n markupsDisplayNode = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLMarkupsDisplayNode\")\n markupsDisplayNode.SetColor(color)\n slicer.mrmlScene.AddNode(markupsDisplayNode)\n markupsNode.SetAndObserveDisplayNodeID(markupsDisplayNode.GetID())\n self.baseVolumeNode.SetAttribute(attributeName, markupsNode.GetID())\n if markupsNode and markupsNode.GetDisplayNode():\n markupsNode.GetDisplayNode().SetVisibility(visibility)\n return markupsNode\n\n def enableRelatedVariables(self, attributeName, fieldName):\n fieldvalue = -1\n if self.baseVolumeNode:\n enabledAttributeID = self.baseVolumeNode.GetAttribute(attributeName)\n if enabledAttributeID:\n fieldvalue = float(self.baseVolumeNode.GetAttribute(attributeName))\n setattr(self, fieldName, fieldvalue)\n else:\n fieldvalue = getattr(self, fieldName)\n self.baseVolumeNode.SetAttribute(attributeName, str(fieldvalue))\n return fieldvalue\n\n \n def updateMeasureLength(self, sagittalReferenceLength=None, coronalReferenceLength=None):\n if self.baseVolumeNode:\n if not self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_sagittalLength\"):\n if sagittalReferenceLength:\n self.baseVolumeNode.SetAttribute(\"vtkMRMLScalarVolumeNode.rel_sagittalLength\", '%.1f' % sagittalReferenceLength)\n if not self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_coronalLength\"):\n if coronalReferenceLength:\n self.baseVolumeNode.SetAttribute(\"vtkMRMLScalarVolumeNode.rel_coronalLength\", '%.1f' % coronalReferenceLength)\n\n\n @vtk.calldata_type(vtk.VTK_INT)\n def updateSelectedMarker(self,node, eventID, callData):\n self.activeTrajectoryMarkup = callData\n pass\n \n def updateCannulaPosition(self, fiducicalMarkerNode, eventID = None):\n inputModelNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_model\")\n if inputModelNodeID and self.activeTrajectoryMarkup == 1:\n inputModelNode = slicer.mrmlScene.GetNodeByID(inputModelNodeID)\n if (inputModelNode.GetAttribute(\"vtkMRMLModelNode.modelCreated\") == \"True\"):\n self.trajectoryProjectedMarker.RemoveAllMarkups()\n self.trajectoryProjectedMarker.AddFiducial(0,0,0)\n self.trajectoryProjectedMarker.GetMarkupsDisplayNode().SetVisibility(1)\n polyData = inputModelNode.GetPolyData()\n posFirst = [0.0,0.0,0.0]\n fiducicalMarkerNode.GetNthFiducialPosition(0,posFirst)\n posSecond = [0.0,0.0,0.0]\n fiducicalMarkerNode.GetNthFiducialPosition(1,posSecond)\n if fiducicalMarkerNode.GetNumberOfFiducials()>=2: # self.activeTrajectoryMarkup == 0 means the target fiducial, 1 is the fiducial closer to the surface\n direction = numpy.array(posSecond)- numpy.array(posFirst)\n locator = vtk.vtkCellLocator()\n locator.SetDataSet(polyData)\n locator.BuildLocator()\n t = vtk.mutable(0)\n x = [0.0,0.0,0.0]\n pcoords = [0.0,0.0,0.0]\n subId = vtk.mutable(0)\n hasIntersection = locator.IntersectWithLine( posSecond + 1e6*direction, posFirst - 1e6*direction, 1e-2, t, x, pcoords, subId)\n if hasIntersection>0:\n self.trajectoryProjectedMarker.SetNthFiducialPositionFromArray(0,x)\n self.trajectoryProjectedMarker.SetNthFiducialLabel(0,\"\")\n self.updateCannulaTargetPoint(fiducicalMarkerNode)\n #fiducicalMarkerNode.InvokeEvent(VentriculostomyUserEvents.UpdateCannulaTargetPoint)\n else:\n self.trajectoryProjectedMarker.SetNthFiducialLabel(0,\"invalid\")\n else:\n self.trajectoryProjectedMarker.SetNthFiducialPositionFromArray(0,posSecond)\n self.trajectoryProjectedMarker.SetNthFiducialLabel(0,\"\")\n #self.trajectoryProjectedMarker.SetNthFiducialVisibility(0,False)\n self.activeTrajectoryMarkup = 1\n self.cannulaManager.onLineSourceUpdated()\n self.updateSlicePosition(fiducicalMarkerNode,self.activeTrajectoryMarkup)\n\n def updateCannulaTargetPoint(self, fiducialNode, eventID = None):\n posTarget = numpy.array([0.0] * 3)\n self.cylinderManager.getFirstPoint(posTarget)\n posDistal = numpy.array([0.0] * 3)\n self.cylinderManager.getLastPoint(posDistal)\n posProjected = [0.0,0.0,0.0]\n self.trajectoryProjectedMarker.GetNthFiducialPosition(0, posProjected)\n posMiddle = (posTarget + posDistal) / 2\n direction1Norm = (posDistal - posTarget) / numpy.linalg.norm(posTarget - posDistal)\n direction2 = numpy.array(posProjected) - numpy.array(posMiddle)\n direction2Norm = direction2 / numpy.linalg.norm(direction2)\n angleCalc = math.acos(numpy.dot(direction1Norm, direction2Norm))\n posCannulaTarget = [0.0,0.0,0.0]\n fiducialNode.GetNthFiducialPosition(0, posCannulaTarget)\n posCannulaTarget = numpy.array(posCannulaTarget)\n projectedLength = -numpy.dot(posMiddle - posCannulaTarget, posMiddle - posDistal)/numpy.linalg.norm(posMiddle - posDistal)\n #if numpy.dot(posMiddle - posCannulaTarget, posMiddle - posDistal)>0:\n # shortenFactor = -1*projectedLength\n posBottom = posMiddle + projectedLength / math.cos(angleCalc) * (\n posMiddle - posProjected) / numpy.linalg.norm(posMiddle - posProjected)\n self.activeTrajectoryMarkup = 0\n self.cannulaManager.curveFiducials.SetNthFiducialPositionFromArray(0, posBottom)\n pass\n \n def endCannulaInteraction(self, fiducialNode, event=None):\n posEntry = [0.0, 0.0, 0.0]\n if (not self.trajectoryProjectedMarker.GetNthFiducialLabel(0) == \"invalid\") and self.trajectoryProjectedMarker.GetNumberOfFiducials():\n self.trajectoryProjectedMarker.GetNthFiducialPosition(0, posEntry)\n posEntry[1] = posEntry[1] + 0.005\n fiducialNode.SetNthFiducialPositionFromArray(1, posEntry)\n self.trajectoryProjectedMarker.SetNthFiducialVisibility(0, False)\n self.trajectoryProjectedMarker.SetLocked(True)\n # update the intersection of trajectory with venous\n posTarget = [0.0,0.0,0.0]\n fiducialNode.GetNthFiducialPosition(0,posTarget)\n posEntry = [0.0,0.0,0.0]\n fiducialNode.GetNthFiducialPosition(1,posEntry)\n inputVesselMarginModelNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_vesselnessWithMarginModel\")\n nasionNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_nasion\")\n if inputVesselMarginModelNodeID and nasionNodeID:\n inputModelNode = slicer.mrmlScene.GetNodeByID(inputVesselMarginModelNodeID)\n polyData = inputModelNode.GetPolyData()\n nasionNode = slicer.mrmlScene.GetNodeByID(nasionNodeID)\n posNasion = numpy.array([0.0, 0.0, 0.0])\n nasionNode.GetNthFiducialPosition(0, posNasion)\n for index in range(1, self.trajectoryProjectedMarker.GetNumberOfFiducials()):\n self.trajectoryProjectedMarker.RemoveMarkup(index)\n self.functions.calculateLineModelIntersect(polyData, posEntry, posTarget, self.trajectoryProjectedMarker)\n if self.trajectoryProjectedMarker.GetNumberOfFiducials()>1: # The intersection is not only the projected skull point\n slicer.util.warningDisplay(\"Within the margin area of the vessel\")\n if abs(posEntry[2] - posNasion[2]) < self.posteriorMargin:\n slicer.util.warningDisplay(\"Entry point is too close to nasion point\")\n distalNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_distal\")\n distalNode = slicer.mrmlScene.GetNodeByID(distalNodeID)\n posDistal = numpy.array([0.0, 0.0, 0.0])\n distalNode.GetNthFiducialPosition(0, posDistal)\n transform = self.calculateCylinderTransform()\n transformWithTranslate = vtk.vtkTransform()\n transformWithTranslate.SetMatrix(transform.GetMatrix())\n transformWithTranslate.RotateX(-90.0)\n transformWithTranslate.PostMultiply()\n transformWithTranslate.Translate(posDistal)\n cylinderModel = self.functions.generateCylinderModelWithTransform(self.cylinderRadius, 0.05, transformWithTranslate)\n \"\"\"\n modelNode = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLModelNode\")\n modelNode.SetName(\"ForTesting\")\n slicer.mrmlScene.AddNode(modelNode)\n modelDisplayNode = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLModelDisplayNode\")\n ModelColor = [0.0, 1.0, 1.0]\n modelDisplayNode.SetColor(ModelColor)\n modelDisplayNode.SetOpacity(0.5)\n slicer.mrmlScene.AddNode(modelDisplayNode)\n modelNode.SetAndObserveDisplayNodeID(modelDisplayNode.GetID())\n modelNode.SetAndObservePolyData(transformFilter.GetOutput())\n \"\"\"\n ventriculCylinder = self.cylinderManager._curveModel.GetPolyData()\n posTargetBoundary = list(posTarget+(numpy.array(posEntry)-numpy.array(posTarget))/2000.0)\n intersectNumber2 = self.functions.calculateLineModelIntersect(ventriculCylinder, posEntry,posTargetBoundary, self.trajectoryProjectedMarker)\n intersectNumber1 = self.functions.calculateLineModelIntersect(cylinderModel, posEntry, posTargetBoundary, self.trajectoryProjectedMarker)\n if (intersectNumber2 == 2 or intersectNumber2 == 0) and intersectNumber1 == 0:\n slicer.util.warningDisplay(\"Both entry and target points are out of the ventricle cylinder\") \n elif intersectNumber2 == 2 and intersectNumber1 == 2:\n slicer.util.warningDisplay(\"target point is out of the ventricle cylinder\") \n elif intersectNumber2 == 1 and intersectNumber1 == 0:\n slicer.util.warningDisplay(\"Entry point is out of the ventricle cylinder\")\n pass\n \n def updateSlicePosition(self, fiducicalMarkerNode, markupIndex):\n pos = [0.0]*4\n fiducicalMarkerNode.GetNthFiducialWorldCoordinates(markupIndex,pos)\n viewerRed = slicer.mrmlScene.GetNodeByID(\"vtkMRMLSliceNodeRed\")\n viewerRed.SetOrientationToAxial()\n viewerRed.SetSliceOffset(pos[2])\n viewerYellow = slicer.mrmlScene.GetNodeByID(\"vtkMRMLSliceNodeYellow\")\n viewerYellow.SetOrientationToSagittal()\n viewerYellow.SetSliceOffset(pos[0])\n viewerBlue = slicer.mrmlScene.GetNodeByID(\"vtkMRMLSliceNodeGreen\")\n viewerBlue.SetOrientationToCoronal()\n viewerBlue.SetSliceOffset(pos[1]) \n pass\n\n def endPlacement(self, interactionNode = None, event = None):\n ## when place a new trajectory point, the UpdatePosition is called, the projectedMarker will be visiable.\n ## set the projected marker to invisiable here\n if self.interactionMode == EndPlacementModes.Nasion:\n self.createTrueSagittalPlane()\n self.createEntryPoint()\n self.update_observers(VentriculostomyUserEvents.ResetButtonEvent)\n slicer.mrmlScene.InvokeEvent(VentriculostomyUserEvents.CheckSagittalCorrectionEvent)\n elif self.interactionMode == EndPlacementModes.SagittalPoint:\n self.createTrueSagittalPlane()\n self.createEntryPoint()\n self.placeWidget.setPlaceModeEnabled(False)\n self.update_observers(VentriculostomyUserEvents.SagittalCorrectionFinishedEvent)\n elif self.interactionMode == EndPlacementModes.VentricleTarget:\n if self.trajectoryProjectedMarker and self.trajectoryProjectedMarker.GetMarkupsDisplayNode():\n self.trajectoryProjectedMarker.GetMarkupsDisplayNode().SetVisibility(0)\n self.endVentricleCylinderDefinition()\n self.createVentricleCylinder()\n self.endModifiyCylinder()\n slicer.mrmlScene.InvokeEvent(VentriculostomyUserEvents.TriggerDistalSelectionEvent)\n elif self.interactionMode == EndPlacementModes.VentricleDistal:\n if self.trajectoryProjectedMarker and self.trajectoryProjectedMarker.GetMarkupsDisplayNode():\n self.trajectoryProjectedMarker.GetMarkupsDisplayNode().SetVisibility(1)\n self.createVentricleCylinder()\n self.endVentricleCylinderDefinition()\n self.endModifiyCylinder()\n self.update_observers(VentriculostomyUserEvents.ResetButtonEvent)\n elif self.interactionMode == EndPlacementModes.VesselSeeds:\n self.update_observers(VentriculostomyUserEvents.SegmentVesselWithSeedsEvent)\n if not self.interactionMode == EndPlacementModes.NotSpecifiedMode:\n self.update_observers(VentriculostomyUserEvents.SaveModifiedFiducialEvent)\n self.update_observers(VentriculostomyUserEvents.CheckCurrentProgressEvent)\n pass\n\n def selectNasionPointNode(self, modelNode, initPoint = None):\n if self.baseVolumeNode:\n nasionNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_nasion\")\n kocherNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_kocher\")\n if nasionNodeID and kocherNodeID:\n nasionNode = slicer.mrmlScene.GetNodeByID(nasionNodeID)\n self.interactionMode = EndPlacementModes.Nasion\n self.placeWidget.setPlaceMultipleMarkups(self.placeWidget.ForcePlaceMultipleMarkups)\n self.placeWidget.setMRMLScene(slicer.mrmlScene)\n self.placeWidget.setCurrentNode(nasionNode)\n self.placeWidget.setPlaceModeEnabled(True)\n\n def selectSagittalPointNode(self, modelNode):\n if self.baseVolumeNode:\n if self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_sagittalPoint\"):\n sagittalPointNode = slicer.mrmlScene.GetNodeByID(\n self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_sagittalPoint\"))\n dnode = sagittalPointNode.GetMarkupsDisplayNode()\n if dnode :\n dnode.SetVisibility(1)\n sagittalPointNode.SetLocked(True)\n self.interactionMode = EndPlacementModes.SagittalPoint\n self.placeWidget.setPlaceMultipleMarkups(self.placeWidget.ForcePlaceMultipleMarkups)\n self.placeWidget.setMRMLScene(slicer.mrmlScene)\n self.placeWidget.setCurrentNode(sagittalPointNode)\n self.placeWidget.setPlaceModeEnabled(True)\n \n def endModifiyCylinder(self, caller = None, eventID = None):\n targetNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_target\")\n distalNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_distal\")\n if targetNodeID and distalNodeID:\n targetNode = slicer.mrmlScene.GetNodeByID(targetNodeID)\n distalNode = slicer.mrmlScene.GetNodeByID(distalNodeID)\n if targetNode.GetNumberOfFiducials() and distalNode.GetNumberOfFiducials():\n posTarget = numpy.array([0.0, 0.0, 0.0])\n targetNode.GetNthFiducialPosition(0, posTarget)\n posDistal = numpy.array([0.0, 0.0, 0.0])\n distalNode.GetNthFiducialPosition(0, posDistal)\n redSliceNode = slicer.mrmlScene.GetNodeByID(\"vtkMRMLSliceNodeRed\")\n matrixRed = redSliceNode.GetSliceToRAS()\n matrixRedInv = vtk.vtkMatrix4x4()\n matrixRedInv.DeepCopy(matrixRed)\n matrixRedInv.Invert()\n posTarget = [posTarget[0],posTarget[1],posTarget[2],1]\n posTargetInRAS = matrixRedInv.MultiplyPoint(posTarget)\n posDistal = [posDistal[0],posDistal[1],posDistal[2],1]\n posDistalInRAS = matrixRedInv.MultiplyPoint(posDistal)\n verticalDirect = numpy.array([-(posDistalInRAS[1]-posTargetInRAS[1]), posDistalInRAS[0]-posTargetInRAS[0], 0, 0])\n verticalDirect = self.cylinderRadius*verticalDirect/numpy.linalg.norm(verticalDirect)\n cylinderInteractorPosInRAS = numpy.array(posTargetInRAS)/2.0 + verticalDirect\n cylinderInteractorPosInRAS[3] = 1.0\n cylinderInteractorPos = matrixRed.MultiplyPoint(cylinderInteractorPosInRAS)\n self.cylinderInteractor.RemoveAllMarkups()\n self.cylinderInteractor.AddFiducial(cylinderInteractorPos[0],cylinderInteractorPos[1],cylinderInteractorPos[2])\n self.cylinderInteractor.SetNthFiducialLabel(0,\"\")\n self.cylinderInteractor.SetDisplayVisibility(1)\n self.update_observers(VentriculostomyUserEvents.VentricleCylinderModified)\n if numpy.linalg.norm(numpy.array(posDistal)-numpy.array(posTarget)) < (self.minimalVentricleLen * 0.999):\n slicer.util.warningDisplay(\n \"The define ventricle horn is too short, distal point is automatically modified to make length longer than 10.0 mm\")\n pass\n \n def createVentricleCylinder(self, caller = None, eventID = None):\n targetNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_target\")\n distalNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_distal\")\n radius= self.cylinderRadius\n if self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_cylinderRadius\"):\n radius = float(self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_cylinderRadius\"))\n self.cylinderInteractor.SetDisplayVisibility(0)\n if targetNodeID and distalNodeID:\n targetNode = slicer.mrmlScene.GetNodeByID(targetNodeID)\n distalNode = slicer.mrmlScene.GetNodeByID(distalNodeID)\n if targetNode and distalNode:\n if targetNode.GetNumberOfFiducials() and distalNode.GetNumberOfFiducials():\n posTarget = numpy.array([0.0, 0.0, 0.0])\n targetNode.GetNthFiducialPosition(0, posTarget)\n posDistal = numpy.array([0.0, 0.0, 0.0])\n distalNode.GetNthFiducialPosition(0, posDistal)\n if self.cylinderManager.curveFiducials.GetNumberOfFiducials():\n self.cylinderManager.curveFiducials.RemoveAllMarkups()\n self.cylinderManager.curveFiducials.AddFiducial(posTarget[0], posTarget[1], posTarget[2])\n self.cylinderManager.curveFiducials.AddFiducial(posDistal[0], posDistal[1], posDistal[2])\n self.cylinderManager.curveFiducials.SetDisplayVisibility(0)\n self.cylinderManager.setManagerTubeRadius(radius)\n self.cylinderManager.startEditLine()\n self.cylinderManager.onLineSourceUpdated()\n self.updateSliceViewBasedOnPoints(posTarget, posDistal)\n else:\n self.cylinderManager.clearLine()\n else:\n self.cylinderManager.clearLine()\n\n def updateCylinderRadius(self, fiducicalMarkerNode = None, eventID = None):\n posInteractor = [0.0,0.0,0.0]\n fiducicalMarkerNode.GetNthFiducialPosition(0,posInteractor)\n targetNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_target\")\n distalNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_distal\")\n if targetNodeID and distalNodeID:\n targetNode = slicer.mrmlScene.GetNodeByID(targetNodeID)\n distalNode = slicer.mrmlScene.GetNodeByID(distalNodeID)\n if targetNode.GetNumberOfFiducials() and distalNode.GetNumberOfFiducials():\n posTarget = numpy.array([0.0, 0.0, 0.0])\n targetNode.GetNthFiducialPosition(0, posTarget)\n posDistal = numpy.array([0.0, 0.0, 0.0])\n distalNode.GetNthFiducialPosition(0, posDistal)\n a = (posDistal- posTarget)/numpy.linalg.norm(posDistal-posTarget)\n radius = numpy.linalg.norm(numpy.cross(posInteractor-posTarget,a))\n self.baseVolumeNode.SetAttribute(\"vtkMRMLScalarVolumeNode.rel_cylinderRadius\", str(radius))\n self.cylinderRadius = radius\n self.cylinderManager.setManagerTubeRadius(radius)\n self.cylinderManager.startEditLine()\n self.cylinderManager.onLineSourceUpdated()\n pass\n \n def constructCurveReference(self, CurveManager,points, distance):\n step = int(0.02*points.GetNumberOfPoints()) if int(0.02*points.GetNumberOfPoints()) > 0 else 1\n CurveManager.step = step\n ApproximityPos = distance * 0.85\n DestiationPos = distance\n \n if CurveManager.curveFiducials == None:\n CurveManager.curveFiducials = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLMarkupsFiducialNode\")\n CurveManager.curveFiducials.SetName(CurveManager.curveName)\n slicer.mrmlScene.AddNode(CurveManager.curveFiducials) \n else:\n CurveManager.curveFiducials.RemoveAllMarkups()\n CurveManager.cmLogic.updateCurve()\n \n iPos = 0\n iPosValid = iPos\n posModel = numpy.array(points.GetPoint(iPos))\n CurveManager.cmLogic.DestinationNode = CurveManager._curveModel\n CurveManager.curveFiducials.AddFiducial(posModel[0],posModel[1],posModel[2]) \n CurveManager.cmLogic.CurvePoly = vtk.vtkPolyData() ## For CurveMaker bug\n for iPos in range(step,points.GetNumberOfPoints(),step):\n posModel = numpy.array(points.GetPoint(iPos))\n posModelValid = numpy.array(points.GetPoint(iPosValid))\n if numpy.linalg.norm(posModel-posModelValid)> 50.0:\n continue\n iPosValid = iPos\n CurveManager.curveFiducials.AddFiducial(posModel[0],posModel[1],posModel[2]) #adding fiducials takes too long, check the event triggered by this operation\n CurveManager.cmLogic.SourceNode = CurveManager.curveFiducials\n CurveManager.cmLogic.updateCurve()\n if CurveManager.cmLogic.CurveLength>ApproximityPos:\n break\n jPos = iPosValid \n jPosValid = jPos\n posApprox = numpy.array(points.GetPoint(iPos))\n for jPos in range(iPosValid,points.GetNumberOfPoints(), 1):\n posModel = numpy.array(points.GetPoint(jPos))\n posModelValid = numpy.array(points.GetPoint(jPosValid))\n if numpy.linalg.norm(posModel-posModelValid)> 50.0:\n continue\n distance = numpy.linalg.norm(posModel-posApprox)+ CurveManager.cmLogic.CurveLength\n if (distance>DestiationPos) or (jPos==points.GetNumberOfPoints()-1):\n CurveManager.curveFiducials.AddFiducial(posModel[0],posModel[1],posModel[2]) \n jPosValid = jPos \n break\n \n #CurveManager.cmLogic.SourceNode.SetAttribute('CurveMaker.CurveModel', CurveManager.cmLogic.DestinationNode.GetID())\n CurveManager.cmLogic.updateCurve()\n CurveManager.cmLogic.CurvePoly = vtk.vtkPolyData() ## For CurveMaker bug\n CurveManager.cmLogic.enableAutomaticUpdate(1)\n CurveManager.cmLogic.setInterpolationMethod(1)\n CurveManager.cmLogic.setTubeRadius(0.5) \n self.topPoint = points.GetPoint(jPos)\n \n def constructCurvePlanning(self, CurveManager,CurveManagerReference, points, axis):\n posNasion = numpy.array([0.0,0.0,0.0])\n if self.sagittalReferenceCurveManager.curveFiducials:\n self.sagittalReferenceCurveManager.curveFiducials.GetNthFiducialPosition(0,posNasion)\n if CurveManager.curveFiducials == None:\n CurveManager.curveFiducials = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLMarkupsFiducialNode\")\n CurveManager.curveFiducials.SetName(CurveManager.curveName)\n slicer.mrmlScene.AddNode(CurveManager.curveFiducials) \n else:\n CurveManager.curveFiducials.RemoveAllMarkups()\n CurveManager.cmLogic.updateCurve()\n \n iPos = 0\n iPosValid = iPos\n posModel = numpy.array(points.GetPoint(iPos))\n step = CurveManagerReference.step\n CurveManager.cmLogic.DestinationNode = CurveManager._curveModel\n CurveManager.curveFiducials.AddFiducial(posModel[0],posModel[1],posModel[2]) \n \n numOfRef = CurveManagerReference.curveFiducials.GetNumberOfFiducials()\n \n eps = 1e-2\n if axis == 1:\n lastRefPos = [0.0]*3\n CurveManagerReference.curveFiducials.GetNthFiducialPosition(numOfRef-1, lastRefPos)\n if numpy.linalg.norm(numpy.array(lastRefPos)-numpy.array(points.GetPoint(0)))<eps: #if the planning and reference entry points are identical\n pos = [0.0]*3 \n for iPos in range(1,numOfRef): \n CurveManagerReference.curveFiducials.GetNthFiducialPosition(numOfRef-iPos-1, pos)\n CurveManager.curveFiducials.AddFiducial(pos[0],pos[1],pos[2])\n CurveManagerReference.curveFiducials.GetNthFiducialPosition(0, pos) \n self.topPoint = pos \n else:\n posIntersect = [0.0]*3\n posSearch = [0.0]*3\n minDistance = 1e10\n for iSearch in range(points.GetNumberOfPoints()):\n posSearch = points.GetPoint(iSearch)\n if posSearch[2] > posNasion[2]: #Only the upper part of the cutted sagittal plan is considered\n distance = self.trueSagittalPlane.DistanceToPlane(posSearch)\n if distance < minDistance:\n minDistance = distance\n posIntersect = posSearch\n\n shift = step\n \"\"\"\n for iPos in range(1,numOfRef):\n pos = [0.0]*3\n CurveManagerReference.curveFiducials.GetNthFiducialPosition(numOfRef-iPos-1, pos)\n #check if the points is aligned with the reference coronal line, if yes, take the point into the planning curvemanager\n if abs(pos[0]-posIntersect[0])< abs(points.GetPoint(0)[0]-posIntersect[0])and abs(pos[1]-points.GetPoint(0)[1])<eps and abs(pos[2]-points.GetPoint(0)[2])<eps:\n CurveManager.curveFiducials.AddFiducial(pos[0],pos[1],pos[2])\n shift = iPos\n break\n \"\"\"\n for iPos in range(shift,points.GetNumberOfPoints(),step):\n posModel = numpy.array(points.GetPoint(iPos))\n posModelValid = numpy.array(points.GetPoint(iPosValid))\n if numpy.linalg.norm(posModel-posModelValid)> 50.0:\n continue\n if (not self.useLeftHemisphere) and (abs(posModel[0]-posIntersect[0])<eps or (posModel[0]<posIntersect[0])):\n break\n elif self.useLeftHemisphere and (abs(posModel[0]-posIntersect[0])<eps or (posModel[0]>posIntersect[0])):\n break\n iPosValid = iPos\n CurveManager.curveFiducials.AddFiducial(posModel[0],posModel[1],posModel[2]) #adding fiducials takes too long, check the event triggered by this operation\n jPos = iPosValid\n jPosValid = jPos\n for jPos in range(iPosValid, points.GetNumberOfPoints(), 1):\n posModel = numpy.array(points.GetPoint(jPos))\n posModelValid = numpy.array(points.GetPoint(jPosValid))\n if numpy.linalg.norm(posModel-posModelValid)> 50.0:\n continue\n if (not self.useLeftHemisphere) and (abs(posModel[0]-posIntersect[0])<eps or (posModel[0]<posIntersect[0])):\n break\n elif self.useLeftHemisphere and (abs(posModel[0]-posIntersect[0])<eps or (posModel[0]>posIntersect[0])):\n break\n jPosValid = jPos\n self.topPoint = points.GetPoint(jPosValid)\n posModel = numpy.array(points.GetPoint(jPosValid))\n CurveManager.curveFiducials.AddFiducial(posModel[0],posModel[1],posModel[2])\n\n if axis ==0:\n for iPos in range(1,numOfRef): \n pos = [0.0]*3\n CurveManagerReference.curveFiducials.GetNthFiducialPosition(numOfRef-iPos-1, pos) \n if float(pos[2])<self.topPoint[2]:\n CurveManager.curveFiducials.AddFiducial(pos[0],pos[1],pos[2]) \n \n for i in range(CurveManager.curveFiducials.GetNumberOfFiducials()/2):\n pos = [0.0]*3 \n CurveManager.curveFiducials.GetNthFiducialPosition(i,pos)\n posReverse = [0.0]*3 \n CurveManager.curveFiducials.GetNthFiducialPosition(CurveManager.curveFiducials.GetNumberOfFiducials()-i-1,posReverse)\n CurveManager.curveFiducials.SetNthFiducialPositionFromArray(i,posReverse)\n CurveManager.curveFiducials.SetNthFiducialPositionFromArray(CurveManager.curveFiducials.GetNumberOfFiducials()-i-1,pos)\n \"\"\" \n for i in range(CurveManager.curveFiducials.GetNumberOfFiducials()):\n pos = [0.0]*3 \n CurveManager.curveFiducials.GetNthFiducialPosition(i,pos)\n print \"Planning Pos: \", pos\n CurveManagerReference.curveFiducials.GetNthFiducialPosition(i,pos)\n print \"Reference Pos: \", pos\n \"\"\" \n CurveManager.cmLogic.SourceNode = CurveManager.curveFiducials\n CurveManager.cmLogic.updateCurve()\n CurveManager.cmLogic.CurvePoly = vtk.vtkPolyData() ## For CurveMaker bug \n CurveManager.cmLogic.SourceNode.SetAttribute('CurveMaker.CurveModel', CurveManager.cmLogic.DestinationNode.GetID()) \n CurveManager.cmLogic.enableAutomaticUpdate(1)\n CurveManager.cmLogic.setInterpolationMethod(1)\n CurveManager.cmLogic.setTubeRadius(0.5)\n\n def getIntersectPoints(self, polyData, plane, referencePoint, targetDistance, axis, intersectPoints):\n cutter = vtk.vtkCutter()\n cutter.SetCutFunction(plane)\n cutter.SetInputData(polyData)\n cutter.Update()\n cuttedPolyData = cutter.GetOutput()\n points = cuttedPolyData.GetPoints()\n for iPos in range(points.GetNumberOfPoints()):\n posModel = numpy.array(points.GetPoint(iPos))\n ## distance calculation could be simplified if the patient is well aligned in the scanner\n distanceModelNasion = numpy.linalg.norm(posModel - referencePoint)\n valid = False\n if axis == 0:\n valid = posModel[2] >= referencePoint[2]\n elif axis == 1:\n if self.useLeftHemisphere:\n valid = posModel[0] <= referencePoint[0]\n else:\n valid = posModel[0] >= referencePoint[0]\n if (distanceModelNasion < targetDistance) and valid:\n intersectPoints.InsertNextPoint(posModel)\n \n def getIntersectPointsPlanning(self, polyData, plane, referencePoint, axis, intersectPoints):\n cutter = vtk.vtkCutter()\n cutter.SetCutFunction(plane)\n cutter.SetInputData(polyData)\n cutter.Update()\n cuttedPolyData = cutter.GetOutput()\n points = cuttedPolyData.GetPoints() \n for iPos in range(points.GetNumberOfPoints()):\n posModel = numpy.array(points.GetPoint(iPos))\n ## distance calculation could be simplified if the patient is well aligned in the scanner\n distanceModelNasion = numpy.linalg.norm(posModel-referencePoint)\n valid = False\n if axis == 0:\n valid = (posModel[2]<=referencePoint[2] or abs(posModel[2]-referencePoint[2])<1e-3 )\n elif axis == 1:\n if self.useLeftHemisphere:\n valid = (posModel[0]>=referencePoint[0] or abs(posModel[0]-referencePoint[0])<1e-3 )\n else:\n valid = (posModel[0]<=referencePoint[0] or abs(posModel[0]-referencePoint[0])<1e-3 )\n if valid: \n intersectPoints.InsertNextPoint(posModel) \n\n def createTrueSagittalPlane(self):\n nasionNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_nasion\")\n sagittalPointNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_sagittalPoint\")\n if nasionNodeID and sagittalPointNodeID:\n nasionNode = slicer.mrmlScene.GetNodeByID(nasionNodeID)\n sagittalPointNode = slicer.mrmlScene.GetNodeByID(sagittalPointNodeID)\n posNasion = numpy.array([0.0, 0.0, 0.0])\n if nasionNode and sagittalPointNode:\n # create a sagital plane when nasion point is exist, if sagittal doesn't exist, use [0,0,0] As default sagittal point, which might not be correct\n if nasionNode.GetNumberOfFiducials():\n nasionNode.GetNthFiducialPosition(nasionNode.GetNumberOfMarkups()-1, posNasion)\n posSagittal = numpy.array([0.0, 0.0, 0.0])\n sagittalPointNode.GetNthFiducialPosition(sagittalPointNode.GetNumberOfMarkups() - 1, posSagittal)\n if sagittalPointNode.GetNumberOfMarkups() > 1:\n sagittalPointNode.RemoveObservers(slicer.vtkMRMLMarkupsNode.MarkupAddedEvent)\n sagittalPointNode.RemoveAllMarkups()\n sagittalPointNode.AddFiducial(posSagittal[0], posSagittal[1], posSagittal[2])\n sagittalPointNode.AddObserver(slicer.vtkMRMLMarkupsNode.MarkupAddedEvent, self.endPlacement)\n self.sagittalYawAngle = -numpy.arctan2(posNasion[0] - posSagittal[0], posNasion[1] - posSagittal[1])\n self.trueSagittalPlane = vtk.vtkPlane()\n self.trueSagittalPlane.SetOrigin(posNasion[0], posNasion[1], posNasion[2])\n self.trueSagittalPlane.SetNormal(math.cos(self.sagittalYawAngle), math.sin(self.sagittalYawAngle), 0)\n sagittalPointNode.SetLocked(True)\n\n def createEntryPoint(self) :\n ###All calculation is based on the RAS coordinates system\n inputModelNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_model\")\n inputModelNode = slicer.mrmlScene.GetNodeByID(inputModelNodeID)\n nasionNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_nasion\")\n nasionNode = slicer.mrmlScene.GetNodeByID(nasionNodeID)\n kocherNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_kocher\")\n kocherNode = slicer.mrmlScene.GetNodeByID(kocherNodeID)\n kocherNode.RemoveAllMarkups()\n if self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_sagittalLength\"):\n sagittalReferenceLength = float(self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_sagittalLength\")) \n if self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_coronalLength\") :\n coronalReferenceLength = float(self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_coronalLength\") ) \n if inputModelNode and (inputModelNode.GetAttribute(\"vtkMRMLModelNode.modelCreated\") == \"True\") and (nasionNode.GetNumberOfMarkups()) and sagittalReferenceLength and coronalReferenceLength:\n polyData = inputModelNode.GetPolyData()\n if polyData and self.trueSagittalPlane and nasionNode.GetNumberOfMarkups()> 0:\n posNasion = numpy.array([0.0,0.0,0.0])\n nasionNode.GetNthFiducialPosition(nasionNode.GetNumberOfMarkups()-1,posNasion)\n if nasionNode.GetNumberOfMarkups()>1:\n nasionNode.RemoveObservers(slicer.vtkMRMLMarkupsNode.MarkupAddedEvent)\n nasionNode.RemoveAllMarkups()\n nasionNode.AddFiducial(posNasion[0],posNasion[1],posNasion[2])\n nasionNode.AddObserver(slicer.vtkMRMLMarkupsNode.MarkupAddedEvent, self.endPlacement)\n sagittalPoints = vtk.vtkPoints()\n self.getIntersectPoints(polyData, self.trueSagittalPlane, posNasion, sagittalReferenceLength, 0, sagittalPoints)\n\n if sagittalPoints.GetNumberOfPoints() <= 0:\n return\n ## Sorting \n self.functions.sortVTKPoints(sagittalPoints, posNasion)\n self.constructCurveReference(self.sagittalReferenceCurveManager, sagittalPoints, sagittalReferenceLength)\n ##To do, calculate the curvature value points by point might be necessary to exclude the outliers\n if not (self.topPoint == []):\n posNasionBack100 = self.topPoint\n coronalPoints = vtk.vtkPoints()\n coronalPlane = vtk.vtkPlane()\n coronalPlane.SetOrigin(posNasionBack100[0],posNasionBack100[1],posNasionBack100[2])\n coronalPlane.SetNormal(math.sin(self.sagittalYawAngle),-math.cos(self.sagittalYawAngle),0)\n self.getIntersectPoints(polyData, coronalPlane, posNasionBack100, coronalReferenceLength, 1, coronalPoints)\n if coronalPoints.GetNumberOfPoints() <= 0:\n return\n ## Sorting\n self.functions.sortVTKPoints(coronalPoints, posNasionBack100)\n self.constructCurveReference(self.coronalReferenceCurveManager, coronalPoints, coronalReferenceLength)\n posEntry = [0.0, 0.0, 0.0]\n self.coronalReferenceCurveManager.getLastPoint(posEntry)\n kocherNode.AddFiducial(posEntry[0], posEntry[1], posEntry[2])\n self.lockReferenceLine()\n nasionNode.SetLocked(True)\n kocherNode.SetLocked(True)\n pass\n\n def calculateDistanceToKocher(self):\n numOfRef = self.coronalReferenceCurveManager.curveFiducials.GetNumberOfFiducials()\n numOfCannulaPoints = self.cannulaManager.curveFiducials.GetNumberOfFiducials()\n if numOfRef >= 1 and numOfCannulaPoints>=2:\n posRef = [0.0, 0.0, 0.0]\n posEntry = [0.0, 0.0, 0.0]\n self.coronalReferenceCurveManager.getLastPoint(posRef)\n self.cannulaManager.getLastPoint(posEntry)\n self.kocherDistance = numpy.linalg.norm(numpy.array(posRef)-numpy.array(posEntry))\n pass\n\n def createPlanningLine(self):\n ###All calculation is based on the RAS coordinates system\n inputModelNode = None\n nasionNode = None\n inputModelNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_model\")\n if inputModelNodeID:\n inputModelNode = slicer.mrmlScene.GetNodeByID(inputModelNodeID) \n nasionNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_nasion\") \n if nasionNodeID:\n nasionNode = slicer.mrmlScene.GetNodeByID(nasionNodeID) \n if inputModelNode and (inputModelNode.GetAttribute(\"vtkMRMLModelNode.modelCreated\") == \"True\") and (nasionNode.GetNumberOfMarkups()):\n polyData = inputModelNode.GetPolyData()\n if polyData and self.trueSagittalPlane:\n posNasion = numpy.array([0.0,0.0,0.0])\n nasionNode.GetNthFiducialPosition(0,posNasion)\n posEntry = numpy.array([0.0,0.0,0.0])\n if self.cannulaManager.getLastPoint(posEntry):\n normalVec = numpy.array(self.trueSagittalPlane.GetNormal())\n originPos = numpy.array(self.trueSagittalPlane.GetOrigin())\n entryPointAtLeft = -numpy.sign(numpy.dot(numpy.array(posEntry)-originPos, normalVec)) # here left hemisphere means from the patient's perspective\n if entryPointAtLeft >= 0 and self.useLeftHemisphere ==False:\n self.useLeftHemisphere = True\n self.createEntryPoint()\n if entryPointAtLeft < 0 and self.useLeftHemisphere == True:\n self.useLeftHemisphere = False\n self.createEntryPoint()\n coronalPlane = vtk.vtkPlane()\n coronalPlane.SetOrigin(posEntry[0], posEntry[1], posEntry[2])\n coronalPlane.SetNormal(-math.sin(self.sagittalYawAngle), math.cos(self.sagittalYawAngle), 0)\n coronalPoints = vtk.vtkPoints()\n self.getIntersectPointsPlanning(polyData, coronalPlane, posEntry, 1 , coronalPoints)\n\n if coronalPoints.GetNumberOfPoints() <= 0:\n return False\n ## Sorting \n self.functions.sortVTKPoints(coronalPoints, posEntry)\n self.constructCurvePlanning(self.coronalPlanningCurveManager, self.coronalReferenceCurveManager, coronalPoints, 1)\n \n ##To do, calculate the curvature value points by point might be necessary to exclude the outliers \n if self.topPoint:\n posTractoryBack = self.topPoint\n sagittalPoints = vtk.vtkPoints()\n sagittalPlane = vtk.vtkPlane()\n sagittalPlane.SetOrigin(posTractoryBack[0],posTractoryBack[1],posTractoryBack[2])\n sagittalPlane.SetNormal(math.cos(self.sagittalYawAngle), math.sin(self.sagittalYawAngle), 0)\n self.getIntersectPointsPlanning(polyData, sagittalPlane, posTractoryBack, 0, sagittalPoints)\n if sagittalPoints.GetNumberOfPoints() <= 0:\n return False\n ## Sorting \n self.functions.sortVTKPoints(sagittalPoints, posTractoryBack)\n self.constructCurvePlanning(self.sagittalPlanningCurveManager, self.sagittalReferenceCurveManager, sagittalPoints, 0)\n self.sagittalPlanningCurveManager.lockLine()\n self.coronalPlanningCurveManager.lockLine()\n return True\n return False\n\n def generateLabelMapFor3DModel(self):\n self.holeFilledImageNode, self.subtractedImageNode = self.getOrCreateHoleSkullVolumeNode()\n baseDimension = [130, 50, 50]\n posNasion = [0.0, 0.0, 0.0]\n self.sagittalReferenceCurveManager.getFirstPoint(posNasion)\n basePolyData = self.functions.generateCubeModelWithYawAngle(posNasion, self.sagittalYawAngle, baseDimension)\n clippedImage = self.functions.clipVolumeWithPolyData(self.holeFilledImageNode, basePolyData, True, 1)\n clippedImageDataBase = self.functions.inverseVTKImage(clippedImage)\n matrix = vtk.vtkMatrix4x4()\n self.holeFilledImageNode.GetIJKToRASMatrix(matrix)\n centerPos, guidanceDimension = self.getGuidanceCubeBoundary()\n guidancePolyData = self.functions.generateCubeModelWithYawAngle(centerPos, self.sagittalYawAngle, guidanceDimension)\n clippedImageDataGuide = self.functions.clipVolumeWithPolyData(self.subtractedImageNode, guidancePolyData, True, 0)\n # Generate Donut like structure at the entry\n targetPos = numpy.array([0.0, 0.0, 0.0])\n self.cannulaManager.getFirstPoint(targetPos)\n entryPos = numpy.array([0.0, 0.0, 0.0])\n self.cannulaManager.getLastPoint(entryPos)\n xThickness = (self.samplingFactor * self.morphologyParameters[1][0]) * self.baseVolumeNode.GetSpacing()[0]\n yThickness = (self.samplingFactor * self.morphologyParameters[1][1]) * self.baseVolumeNode.GetSpacing()[1]\n totalThickness = numpy.linalg.norm([xThickness, yThickness, 0])\n transform = self.calculateCannulaTransform()\n transformWithTranslate = vtk.vtkTransform()\n transformWithTranslate.SetMatrix(transform.GetMatrix())\n transformWithTranslate.RotateX(-90.0)\n transformWithTranslate.PostMultiply()\n transformWithTranslate.Translate(entryPos)\n cylinderOutside = self.functions.generateCylinderModelWithTransform(4.0, totalThickness * 2, transformWithTranslate)\n clippedImage = self.functions.clipVolumeWithPolyData(self.holeFilledImageNode, cylinderOutside, True, 1)\n clippedImageOutside = self.functions.inverseVTKImage(clippedImage)\n cylinderInside = self.functions.generateCylinderModelWithTransform(2.0, totalThickness * 2, transformWithTranslate)\n clippedImage = self.functions.clipVolumeWithPolyData(self.holeFilledImageNode, cylinderInside, True, 1)\n clippedImageInside = self.functions.inverseVTKImage(clippedImage)\n imageFilterSubtract = vtk.vtkImageMathematics()\n imageFilterSubtract.SetInput1Data(clippedImageOutside)\n imageFilterSubtract.SetInput2Data(clippedImageInside)\n imageFilterSubtract.SetOperationToSubtract() # performed subtraction operation on the two volume\n imageFilterSubtract.Update()\n #------------------------------------\n\n imageFilterMax = vtk.vtkImageMathematics()\n imageFilterMax.SetInput1Data(clippedImageDataGuide)\n imageFilterMax.SetInput2Data(clippedImageDataBase)\n imageFilterMax.SetOperationToMax() # performed union operation on the two volume\n imageFilterMax.Update()\n imageFilterMax2 = vtk.vtkImageMathematics()\n imageFilterMax2.SetInput1Data(imageFilterMax.GetOutput())\n imageFilterMax2.SetInput2Data(imageFilterSubtract.GetOutput())\n imageFilterMax2.SetOperationToMax() # performed union operation on the two volume\n imageFilterMax2.Update()\n\n self.guideVolumeNode.SetIJKToRASMatrix(matrix)\n self.guideVolumeNode.SetAndObserveImageData(imageFilterMax2.GetOutput())\n pass\n\n def cutModel(self, printModel, leftPrintPartNode, rightPrintPartNode):\n entryPos = [0.0] * 3\n markerNum = self.coronalPlanningCurveManager.curveFiducials.GetNumberOfFiducials()\n self.coronalPlanningCurveManager.curveFiducials.GetNthFiducialPosition(markerNum - 1, entryPos)\n nasionPos = [0.0] * 3\n self.sagittalPlanningCurveManager.curveFiducials.GetNthFiducialPosition(0, nasionPos)\n trueSagittalPlane = vtk.vtkPlane()\n shift = -1.0 if self.useLeftHemisphere else 1.0 # add some shift to the cutting plane to avoid cutting the edge of the model\n trueSagittalPlane.SetOrigin(nasionPos[0] - shift, nasionPos[1],\n nasionPos[2])\n trueSagittalPlane.SetNormal(math.cos(self.sagittalYawAngle), math.sin(self.sagittalYawAngle), 0)\n planes = vtk.vtkPlaneCollection()\n planes.AddItem(trueSagittalPlane)\n cuttedPolyData = self.functions.getClosedCuttedModel(planes, printModel.GetPolyData())\n rightPrintPartNode.SetAndObservePolyData(cuttedPolyData)\n\n planes = vtk.vtkPlaneCollection()\n sagittalPlane = vtk.vtkPlane()\n sagittalPlane.SetOrigin(nasionPos[0] - shift, nasionPos[1], nasionPos[2])\n sagittalPlane.SetNormal(-math.cos(self.sagittalYawAngle), -math.sin(self.sagittalYawAngle), 0)\n planes.AddItem(sagittalPlane)\n cuttedPolyData = self.functions.getClosedCuttedModel(planes, printModel.GetPolyData())\n leftPrintPartNode.SetAndObservePolyData(cuttedPolyData)\n\n def getGuidanceCubeBoundary(self):\n posNasion = [0.0]*3\n self.sagittalPlanningCurveManager.getFirstPoint(posNasion)\n posEntry = [0.0, 0.0, 0.0]\n self.coronalPlanningCurveManager.getLastPoint(posEntry)\n posTop = [0.0, 0.0, 0.0]\n self.coronalPlanningCurveManager.getFirstPoint(posTop)\n posCoronal = [0.0]*3\n posSagittal = [0.0] * 3\n maxDistY = 0.0\n maxDistX = 0.0\n for i in range(self.sagittalPlanningCurveManager.curveFiducials.GetNumberOfFiducials()):\n pos = [0.0]*3\n self.sagittalPlanningCurveManager.curveFiducials.GetNthFiducialPosition(i, pos)\n # To calculate the dimension of the cube, coordinate system needs to be rotated also to calculate the correct maximum dimension.\n yDistance = abs((pos[0]* numpy.sin(-self.sagittalYawAngle) + numpy.cos(self.sagittalYawAngle) * pos[1]) - \\\n (posEntry[0] * numpy.sin(-self.sagittalYawAngle) + numpy.cos(self.sagittalYawAngle) * posEntry[1]))\n if yDistance > maxDistY:\n maxDistY = yDistance\n posCoronal = list(pos)\n xDistance = abs((pos[0]* numpy.cos(self.sagittalYawAngle) + numpy.sin(self.sagittalYawAngle)*pos[1]) - \\\n (posEntry[0] * numpy.cos(self.sagittalYawAngle) + numpy.sin(self.sagittalYawAngle) * posEntry[1]))\n if xDistance > maxDistX:\n maxDistX = xDistance\n posSagittal = list(pos)\n\n xThickness = (self.samplingFactor * self.morphologyParameters[1][0]) * self.baseVolumeNode.GetSpacing()[0]\n yThickness = (self.samplingFactor * self.morphologyParameters[1][1]) * self.baseVolumeNode.GetSpacing()[1]\n posCoronal[0] = posCoronal[0] + math.sin(self.sagittalYawAngle)*xThickness # shift in the x axis to cover the dilated skull\n posCoronal[1] = posCoronal[1] + math.cos(self.sagittalYawAngle)*yThickness # shift in the y axis to cover the dilated skull\n centerPos = [0.5*(posEntry[0]+posSagittal[0]), 0.5*(posEntry[1]+posCoronal[1]), 0.5*(posTop[2]+posNasion[2])]\n guidanceDimension = [maxDistX, maxDistY + yThickness, abs(posTop[2]-posNasion[2])]\n return centerPos, guidanceDimension\n\n def calcPitchYawAngles(self):\n firstPos = numpy.array([0.0,0.0,0.0])\n self.cannulaManager.getFirstPoint(firstPos)\n lastPos = numpy.array([0.0,0.0,0.0])\n self.cannulaManager.getLastPoint(lastPos)\n self.updateSliceViewBasedOnPoints(firstPos, lastPos)\n pass\n\n def calcCannulaAngles(self):\n inputModelNodeID = self.baseVolumeNode.GetAttribute(\"vtkMRMLScalarVolumeNode.rel_model\")\n if inputModelNodeID:\n inputModelNode = slicer.mrmlScene.GetNodeByID(inputModelNodeID)\n if self.cannulaManager.curveFiducials and inputModelNode:\n if self.cannulaManager.curveFiducials.GetNumberOfFiducials():\n posTarget = [0.0,0.0,0.0]\n self.cannulaManager.curveFiducials.GetNthFiducialPosition(0,posTarget)\n posEntry = [0.0,0.0,0.0]\n self.cannulaManager.curveFiducials.GetNthFiducialPosition(1,posEntry)\n p_ES = numpy.array([math.cos(self.sagittalYawAngle), math.sin(self.sagittalYawAngle), 0])\n p_EC = numpy.array([-math.sin(self.sagittalYawAngle), math.cos(self.sagittalYawAngle), 0])\n p_EN = self.calculateModelNorm(inputModelNode, posEntry, self.entryRadius)#numpy.array([-0.5,math.sqrt(0.5),0.5]) #this vector we need to get from the skull Norm calculation\n\n self.skullNormToCoronalAngle = 90.0 - math.acos(abs(numpy.dot(p_EC, p_EN))) * 180.0 / numpy.pi\n self.skullNormToSaggitalAngle = 90.0 - math.acos(abs(numpy.dot(p_ES, p_EN))) * 180.0 / numpy.pi\n p_EC = p_EC/numpy.linalg.norm(p_EC)\n p_EN = p_EN/numpy.linalg.norm(p_EN)\n p_ET = numpy.array(posEntry) - numpy.array(posTarget)\n p_ET = p_ET / numpy.linalg.norm(p_ET)\n cosCalc = numpy.dot(p_EN, p_ET)\n sinCalc = math.sqrt(1 - cosCalc*cosCalc)\n p_EM = numpy.array([])\n if cosCalc>1e-6: # make sure the p_EN and p_ET are not perpenticular.\n sinTheta1 = numpy.dot(p_EC, p_EN)\n cosTheta1 = math.sqrt(1-sinTheta1*sinTheta1)\n if cosTheta1 < cosCalc: # here means no intesection between the coronal plan and the cone composed by p_EN and p_ET\n p_EN2 = p_EN - p_EC * sinTheta1\n p_EM = p_EN2 + p_EC * cosTheta1*(sinTheta1 * cosCalc - cosTheta1 * sinCalc) / (cosTheta1 * cosCalc + sinTheta1 * sinCalc) # sin(theta1 - Calc) = sin(theta1)*cos(Calc) - cos(theta1)*sin(Calc)\n p_EM = p_EM / numpy.linalg.norm(p_EM)\n else:\n p_EN2 = p_EN - p_EC * (sinTheta1)\n cosTheta2 = cosCalc/cosTheta1\n tanTheta2 = math.sqrt(1/(cosTheta2*cosTheta2) - 1)\n p_EM = p_EN2 + numpy.cross(p_EC, p_EN2)*tanTheta2\n p_EM = p_EM / numpy.linalg.norm(p_EM)\n cosMT = numpy.dot(p_EM, p_ET)\n cosMN = numpy.dot(p_EN, p_EM)\n if p_EM.any():\n self.cannulaToCoronalAngle = math.acos(cosMT) * 180.0 / numpy.pi\n self.cannulaToNormAngle = math.acos(cosCalc) * 180.0 / numpy.pi\n pathNavigationPoints = [numpy.array(posEntry), numpy.array(posEntry) + p_EN * 80,\n #numpy.array(posEntry), numpy.array(posEntry) + p_EM * 50,\n numpy.array(posEntry), numpy.array(posEntry) + p_ET * 20]\n if not self.pathNavigationModel.GetPolyData():\n polyData = vtk.vtkPolyData()\n self.pathNavigationModel.SetAndObservePolyData(polyData)\n self.makeNavigationLines(pathNavigationPoints, 3, self.pathNavigationModel.GetPolyData())\n self.pathNavigationModel.GetDisplayNode().SetVisibility(1)\n return 1\n else:\n return 0\n else:\n self.cannulaToCoronalAngle = 0.0\n self.cannulaToNormAngle = 0.0\n return 1\n \n return 0\n\n def calculateModelNorm(self, inputModel, spherePos, sphereRadius):\n sphere = vtk.vtkSphere()\n sphere.SetCenter(spherePos)\n sphere.SetRadius(sphereRadius)\n\n triangle = vtk.vtkTriangleFilter()\n triangle.SetInputData(inputModel.GetPolyData())\n triangle.Update()\n\n clip = vtk.vtkClipPolyData()\n clip.SetInputData(triangle.GetOutput())\n clip.SetClipFunction(sphere)\n clip.InsideOutOn()\n clip.Update()\n\n clean = vtk.vtkCleanPolyData()\n clean.SetInputConnection(clip.GetOutputPort())\n clean.Update()\n\n clippedModel = clip.GetOutput()\n cellsNormal = clippedModel.GetPointData().GetNormals()\n\n averageNormal = numpy.array([0.0, 0.0, 0.0])\n\n for cellIndex in range(0, cellsNormal.GetNumberOfTuples()):\n cellNormal = [0.0, 0.0, 0.0]\n cellsNormal.GetTuple(cellIndex, cellNormal)\n\n if not (math.isnan(cellNormal[0]) or math.isnan(cellNormal[1]) or math.isnan(cellNormal[2])):\n averageNormal[0] = averageNormal[0] + cellNormal[0]\n averageNormal[1] = averageNormal[1] + cellNormal[1]\n averageNormal[2] = averageNormal[2] + cellNormal[2]\n averageNormal = averageNormal/numpy.linalg.norm(averageNormal)\n\n return averageNormal\n\n def updateSliceViewBasedOnPoints(self, firstPos, lastPos):\n ## due to the RAS and vtk space difference, the X axis is flipped, So the standard rotation matrix is multiplied by -1 in the X axis\n self.pitchAngle = numpy.arctan2(lastPos[2]-firstPos[2], abs(lastPos[1]-firstPos[1]))*180.0/numpy.pi\n self.yawAngle = -numpy.arctan2(lastPos[0]-firstPos[0], abs(lastPos[1]-firstPos[1]))*180.0/numpy.pi\n redSliceNode = slicer.mrmlScene.GetNodeByID(\"vtkMRMLSliceNodeRed\")\n \n matrixRedOri = redSliceNode.GetSliceToRAS()\n matrixRedNew = vtk.vtkMatrix4x4()\n matrixRedNew.Identity()\n matrixRedNew.SetElement(0, 3, lastPos[0])\n matrixRedNew.SetElement(1, 3, lastPos[1])\n matrixRedNew.SetElement(2, 3, lastPos[2])\n matrixRedNew.SetElement(0, 0, -1) # The X axis is flipped\n matrixRedNew.SetElement(1, 1, numpy.cos(self.pitchAngle / 180.0 * numpy.pi))\n matrixRedNew.SetElement(1, 2, -numpy.sin(self.pitchAngle / 180.0 * numpy.pi))\n matrixRedNew.SetElement(2, 1, numpy.sin(self.pitchAngle / 180.0 * numpy.pi))\n matrixRedNew.SetElement(2, 2, numpy.cos(self.pitchAngle / 180.0 * numpy.pi))\n matrixRedOri.DeepCopy(matrixRedNew)\n redSliceNode.UpdateMatrices()\n\n\n matrixMultiplier = vtk.vtkMatrix4x4()\n yellowSliceNode = slicer.mrmlScene.GetNodeByID(\"vtkMRMLSliceNodeYellow\")\n matrixYellowOri = yellowSliceNode.GetSliceToRAS()\n matrixYaw = vtk.vtkMatrix4x4()\n matrixYaw.Identity()\n matrixYaw.SetElement(0, 3, lastPos[0])\n matrixYaw.SetElement(1, 3, lastPos[1])\n matrixYaw.SetElement(2, 3, lastPos[2])\n matrixYaw.SetElement(0, 0, -1) # The X axis is flipped\n matrixYaw.SetElement(0, 0, numpy.cos(self.yawAngle / 180.0 * numpy.pi)) # definition of\n matrixYaw.SetElement(0, 1, -numpy.sin(self.yawAngle / 180.0 * numpy.pi))\n matrixYaw.SetElement(1, 0, numpy.sin(self.yawAngle / 180.0 * numpy.pi))\n matrixYaw.SetElement(1, 1, numpy.cos(self.yawAngle / 180.0 * numpy.pi))\n matrixYellowNew = vtk.vtkMatrix4x4()\n matrixYellowNew.Zero()\n matrixYellowNew.SetElement(0, 2, 1)\n matrixYellowNew.SetElement(1, 0, -1)\n matrixYellowNew.SetElement(2, 1, 1)\n matrixYellowNew.SetElement(3, 3, 1)\n matrixMultiplier.Multiply4x4(matrixYaw, matrixYellowNew, matrixYellowOri)\n yellowSliceNode.UpdateMatrices()\n\n greenSliceNode = slicer.mrmlScene.GetNodeByID(\"vtkMRMLSliceNodeGreen\")\n matrixGreenOri = greenSliceNode.GetSliceToRAS()\n matrixGreenOri.DeepCopy(matrixRedOri)\n greenSliceNode.UpdateMatrices()\n\n pass\n\nclass VentriculostomyPlanningTest(ScriptedLoadableModuleTest):\n \"\"\"\n This is the test case for your scripted module.\n Uses ScriptedLoadableModuleTest base class, available at:\n https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py\n \"\"\"\n\n def setUp(self):\n \"\"\" Do whatever is needed to reset the state - typically a scene clear will be enough.\n \"\"\"\n slicer.mrmlScene.Clear(0)\n\n def runTest(self):\n \"\"\"Run as few or as many tests as needed here.\n \"\"\"\n self.setUp()\n self.test_VentriculostomyPlanning1()\n\n def test_VentriculostomyPlanning1(self):\n \"\"\" Ideally you should have several levels of tests. At the lowest level\n tests should exercise the functionality of the logic with different inputs\n (both valid and invalid). At higher levels your tests should emulate the\n way the user would interact with your code and confirm that it still works\n the way you intended.\n One of the most important features of the tests is that it should alert other\n developers when their changes will have an impact on the behavior of your\n module. For example, if a developer removes a feature that you depend on,\n your test should break so they know that the feature is needed.\n \"\"\"\n\n self.delayDisplay(\"Starting the test\")\n #\n # first, get some data\n #\n import urllib\n downloads = (\n ('http://slicer.kitware.com/midas3/download?items=5767', 'FA.nrrd', slicer.util.loadVolume),\n )\n\n for url,name,loader in downloads:\n filePath = slicer.app.temporaryPath + '/' + name\n if not os.path.exists(filePath) or os.stat(filePath).st_size == 0:\n logging.info('Requesting download %s from %s...\\n' % (name, url))\n urllib.urlretrieve(url, filePath)\n if loader:\n logging.info('Loading %s...' % (name,))\n loader(filePath)\n self.delayDisplay('Finished with download and loading')\n\n volumeNode = slicer.util.getNode(pattern=\"FA\")\n logic = VentriculostomyPlanningLogic()\n self.assertIsNotNone( logic.hasImageData(volumeNode) )\n self.delayDisplay('Test passed!')\n" }, { "alpha_fraction": 0.7326322197914124, "alphanum_fraction": 0.7400141358375549, "avg_line_length": 47.71921157836914, "blob_id": "bf4d455f5e9d86fc8e20f5d76c010840c84d71bd", "content_id": "1f9b14a92533f35151c0bb9a72208c6175084747", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9889, "license_type": "no_license", "max_line_length": 159, "num_lines": 203, "path": "/VentriculostomyPlanning/VentriculostomyPlanningUtils/PopUpMessageBox.py", "repo_name": "tokjun/VentriculostomyPlanning", "src_encoding": "UTF-8", "text": "import vtk, qt, ctk, slicer\n\nclass SerialAssignMessageBox(qt.QMessageBox):\n def __init__(self):\n qt.QMessageBox.__init__(self)\n #self.setSizeGripEnabled(True)\n self.setWindowTitle ('SerialAssignTable')\n self.volumesCheckedDict = dict()\n self.volumesCheckedDictPre = dict() # Store the previous selected item. if the user click the cancel button. all value should be reset.\n self.serialCheckboxVenous = []\n self.serialCheckboxVentricle = []\n self.volumeNames = []\n self.importedVolumeIDs = []\n self.volumes = []\n self.mainGUILayout = self.layout()\n self.mainGUILayout.setAlignment(qt.Qt.AlignCenter)\n \n self.addTableWidget ()\n #Create QPushButton in QMessageBox\n self.confirmButton = qt.QPushButton('Confirm')\n self.cancelButton = qt.QPushButton('Cancel')\n self.addButton(self.confirmButton, qt.QMessageBox.YesRole)\n self.addButton(self.cancelButton, qt.QMessageBox.RejectRole)\n self.confirmButton.setEnabled(False)\n \n self.buttonBox = qt.QGroupBox()\n buttonLayout = qt.QHBoxLayout()\n buttonLayout.setSizeConstraint(buttonLayout.SetMinAndMaxSize)\n self.buttonBox.setLayout(buttonLayout)\n self.buttonBox.setStyleSheet('QGroupBox{border:0;}')\n buttonLayout.addWidget(self.confirmButton)\n buttonLayout.addWidget(self.cancelButton)\n self.mainGUILayout.addWidget(self.buttonBox,1,0,1,1)\n self.tableHeight = 0\n self.tableWidth = 0\n #Create TableWidget\n def addTableWidget (self) :\n self.tableWidgetBox = qt.QGroupBox()\n layout = qt.QHBoxLayout()\n self.tableWidgetBox.setLayout(layout)\n self.tableWidgetBox.setStyleSheet('QGroupBox{border:0;}')\n self.tableWidget = qt.QTableWidget()\n self.tableWidget.setStyleSheet('QGroupBox{border:0;}')\n self.tableWidget.horizontalScrollBar().setEnabled(True)\n self.tableWidget.setHorizontalScrollBarPolicy(1)\n self.tableWidget.setVerticalScrollBarPolicy(1)\n #layout.setColumnMinimumWidth(0,340)\n #layout.setRowMinimumHeight(0,100)\n #layout.setGeometry (qt.QRect(0, 0, 340, 100))\n layout.addWidget(self.tableWidget)\n #self.tableWidget.setGeometry (qt.QRect(0, 0, 400, 200))\n #self.tableWidget.setMinimumHeight(200)\n #self.tableWidget.setMinimumWidth(300)\n self.tableWidget.setObjectName ('tableWidget')\n self.tableWidget.setColumnCount(2)\n self.tableWidget.setRowCount(2)\n #self.tableWidget.resizeRowsToContents()\n #self.tableWidget.resizeColumnsToContents()\n self.tableWidget.setHorizontalHeaderLabels(\"Venous;Ventricle\".split(\";\"))\n self.tableWidget.setVerticalHeaderLabels(\"Serial1;Serial2\".split(\";\"))\n #self.tableWidget.horizontalHeader().setStretchLastSection(True)\n #self.tableWidget.verticalHeader().setStretchLastSection(True)\n def AppendVolumeNode(self, addedVolumeNode):\n if addedVolumeNode not in self.volumes:\n self.volumes.append(addedVolumeNode)\n self.SetAssignTableWithVolumes(self.volumes)\n\n def Clear(self):\n self.volumesCheckedDict = dict()\n self.volumesCheckedDictPre = dict() # Store the previous selected item. if the user click the cancel button. all value should be reset.\n self.serialCheckboxVenous = []\n self.serialCheckboxVentricle = []\n self.volumeNames = []\n self.importedVolumeIDs = []\n self.volumes = []\n self.tableWidget.setRowCount(0)\n\n def SetAssignTableWithVolumes(self, addedVolumeNodes):\n self.volumes = addedVolumeNodes\n if self.volumes:\n self.tableWidget.setColumnCount(2)\n self.tableWidget.setRowCount(len(self.volumes))\n self.tableHeight = 0\n for counter, volume in enumerate(self.volumes):\n if not volume.GetID() in self.importedVolumeIDs:\n self.importedVolumeIDs.append(volume.GetID())\n self.volumeNames.append(volume.GetName())\n tableItemVenous = qt.QCheckBox()\n tableItemVenous.setCheckState(False)\n tableItemVenous.setCheckable(True)\n itemWidgetVenous = qt.QWidget()\n itemLayoutVenous = qt.QVBoxLayout()\n itemLayoutVenous.setAlignment(qt.Qt.AlignCenter)\n itemWidgetVenous.setLayout(itemLayoutVenous)\n itemLayoutVenous.addWidget(tableItemVenous)\n self.tableWidget.setCellWidget(counter,0,itemWidgetVenous)\n tableItemVentricle = qt.QCheckBox()\n tableItemVentricle.setCheckState(False)\n tableItemVentricle.setCheckable(True)\n itemWidgetVentricle = qt.QWidget()\n itemLayoutVentricle = qt.QVBoxLayout()\n itemLayoutVentricle.setAlignment(qt.Qt.AlignCenter)\n itemWidgetVentricle.setLayout(itemLayoutVentricle)\n itemLayoutVentricle.addWidget(tableItemVentricle)\n self.serialCheckboxVenous.append(tableItemVenous)\n self.serialCheckboxVentricle.append(tableItemVentricle)\n if self.volumesCheckedDict.get(\"Venous\") and volume.GetID() == self.volumesCheckedDict.get(\"Venous\").GetID():\n tableItemVenous.setCheckState(True)\n if self.volumesCheckedDict.get(\"Ventricle\") and volume.GetID() == self.volumesCheckedDict.get(\"Ventricle\").GetID():\n tableItemVentricle.setCheckState(True)\n tableItemVenous.stateChanged.connect(lambda checked, i=counter: self.VenousStateChanged(checked, self.serialCheckboxVenous[i]))\n tableItemVentricle.stateChanged.connect(lambda checked, i=counter: self.VentricleStateChanged(checked, self.serialCheckboxVentricle[i]))\n self.tableWidget.setCellWidget(counter, 1, itemWidgetVentricle)\n self.tableHeight = self.tableHeight + self.tableWidget.cellWidget(counter, 1).geometry.height()\n self.tableWidget.setVerticalHeaderLabels(self.volumeNames)\n #self.tableWidget.setFixedSize(self.tableWidget.verticalHeader().width + self.tableWidth, self.tableWidget.horizontalHeader().height + self.tableHeight)\n self.mainGUILayout.addWidget(self.tableWidgetBox, 0, 0, 1, 3)\n self.ConfirmButtonValid()\n def ConfirmButtonValid(self):\n checkedNum = 0\n for count, box in enumerate(self.serialCheckboxVenous):\n if box.checkState():\n checkedNum = checkedNum + 1\n self.volumesCheckedDict[\"Venous\"] = self.volumes[count]\n for count, box in enumerate(self.serialCheckboxVentricle):\n if box.checkState():\n checkedNum = checkedNum + 1\n self.volumesCheckedDict[\"Ventricle\"] = self.volumes[count]\n if checkedNum == 2:\n self.confirmButton.setEnabled(True)\n elif checkedNum == 1 and len(self.volumes) == 1:\n self.confirmButton.setEnabled(True)\n else:\n self.confirmButton.setEnabled(False)\n def ShowVolumeTable(self):\n self.volumesCheckedDictPre = self.volumesCheckedDict.copy()\n self.show()\n self.close() # show and close to get the width of the header\n if self.tableWidget.cellWidget(0,0) and self.tableWidget.cellWidget(0,1):\n self.tableWidth = self.tableWidget.cellWidget(0,0).geometry.width() + self.tableWidget.cellWidget(0,1).geometry.width()\n self.tableWidget.setFixedSize(self.tableWidget.verticalHeader().width + self.tableWidth+6, self.tableWidget.horizontalHeader().height + self.tableHeight+6)\n return self.exec_()\n def CancelUserChanges(self):\n self.volumesCheckedDict = self.volumesCheckedDictPre.copy()\n self.SetCheckBoxAccordingToAssignment()\n def ConfirmUserChanges(self):\n self.volumesCheckedDictPre = self.volumesCheckedDict.copy()\n def BlockCheckboxSignal(self):\n for box in self.serialCheckboxVenous:\n box.blockSignals(True)\n for box in self.serialCheckboxVentricle:\n box.blockSignals(True)\n def UnblockCheckboxSignal(self):\n for box in self.serialCheckboxVenous:\n box.blockSignals(False)\n for box in self.serialCheckboxVentricle:\n box.blockSignals(False)\n def SetCheckBoxAccordingToAssignment(self):\n self.BlockCheckboxSignal()\n ventricleVolume = self.volumesCheckedDict.get(\"Ventricle\")\n venousVolume = self.volumesCheckedDict.get(\"Venous\")\n for count, checkbox in enumerate(self.serialCheckboxVentricle):\n checkbox.setCheckState(False)\n if ventricleVolume and self.volumes[count].GetID() == ventricleVolume.GetID():\n checkbox.setCheckState(True)\n for count, checkbox in enumerate(self.serialCheckboxVenous):\n checkbox.setCheckState(False)\n if venousVolume and self.volumes[count].GetID() == venousVolume.GetID():\n checkbox.setCheckState(True)\n self.UnblockCheckboxSignal()\n def CheckBoxStatusChanged(self, checked, checkBox, workingSerialCheckbox, otherSerialCheckbox):\n self.BlockCheckboxSignal()\n if checkBox in workingSerialCheckbox:\n for count, box in enumerate(workingSerialCheckbox):\n if not box == checkBox:\n box.setCheckState(False)\n else:\n box.setCheckState(checked)\n otherSerialCheckbox[count].setCheckState(False)\n self.ConfirmButtonValid()\n self.UnblockCheckboxSignal()\n def VenousStateChanged(self, checked, checkBox):\n self.CheckBoxStatusChanged(checked, checkBox, self.serialCheckboxVenous, self.serialCheckboxVentricle)\n def VentricleStateChanged(self,checked, checkBox):\n self.CheckBoxStatusChanged(checked, checkBox, self.serialCheckboxVentricle,self.serialCheckboxVenous)\n\n#volumes = [slicer.mrmlScene.GetNodeByID(\"vtkMRMLScalarVolumeNode1\"), slicer.mrmlScene.GetNodeByID(\"vtkMRMLScalarVolumeNode2\")]\n#a = SerialAssignMessageBox()\n#a.SetAssignTableWithVolumes(volumes)\n#a.ShowVolumeTable()\n\n\nclass SagittalCorrectionMessageBox(qt.QMessageBox):\n def __init__(self):\n qt.QMessageBox.__init__(self)\n self.setWindowTitle('SagittalCorrectionBox')\n self.setText(\"Do you need sagittal plane correction?\")\n self.confirmButton = qt.QPushButton('Yes')\n self.cancelButton = qt.QPushButton('No')\n self.addButton(self.confirmButton, qt.QMessageBox.YesRole)\n self.addButton(self.cancelButton, qt.QMessageBox.RejectRole)\n self.confirmButton.setEnabled(True)\n self.cancelButton.setEnabled(True)" }, { "alpha_fraction": 0.7545871734619141, "alphanum_fraction": 0.7683486342430115, "avg_line_length": 24.647058486938477, "blob_id": "1bac38dfaa4b545f0b42a4ef929b13d500f1218a", "content_id": "0ed5d54422669ad6b2560a54a4719cdc947b5dfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "no_license", "max_line_length": 39, "num_lines": 17, "path": "/VentriculostomyPlanning/VentriculostomyPlanningUtils/Constants.py", "repo_name": "tokjun/VentriculostomyPlanning", "src_encoding": "UTF-8", "text": "class EndPlacementModes(object):\n NotSpecifiedMode = \"None\"\n VesselSeeds = \"vesselSeeds\"\n VentricleTarget = \"target\"\n VentricleDistal = \"distal\"\n Nasion = \"nasion\"\n SagittalPoint = \"sagittalPoint\"\n\nclass SagittalCorrectionStatus(object):\n NotYetChecked = 1\n NeedCorrection = 2\n NoNeedForCorrection = 3\n\nclass CandidatePathStatus(object):\n NoPosteriorAndNoWithinKocherPoint = 1\n NoPosteriorPoint = 2\n NoWithinKocherPoint = 3\n" }, { "alpha_fraction": 0.7724936008453369, "alphanum_fraction": 0.8187660574913025, "avg_line_length": 50.93333435058594, "blob_id": "31bac9e1ad697bdf902a4796b4e1d9926901da72", "content_id": "c352f33a72d425bde77baa03f1ba498dc9807686", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 778, "license_type": "no_license", "max_line_length": 66, "num_lines": 15, "path": "/VentriculostomyPlanning/VentriculostomyPlanningUtils/UserEvents.py", "repo_name": "tokjun/VentriculostomyPlanning", "src_encoding": "UTF-8", "text": "import vtk, slicer\n\nclass VentriculostomyUserEvents(object):\n LoadParametersToScene = vtk.vtkCommand.UserEvent + 150\n CheckSagittalCorrectionEvent = vtk.vtkCommand.UserEvent + 151\n TriggerDistalSelectionEvent = vtk.vtkCommand.UserEvent + 152\n UpdateCannulaTargetPoint = vtk.vtkCommand.UserEvent + 153\n SetSliceViewerEvent = vtk.vtkCommand.UserEvent + 154\n SaveModifiedFiducialEvent = vtk.vtkCommand.UserEvent + 155\n VentricleCylinderModified = vtk.vtkCommand.UserEvent + 156\n ReverseViewClicked = vtk.vtkCommand.UserEvent + 157\n CheckCurrentProgressEvent = vtk.vtkCommand.UserEvent + 158\n ResetButtonEvent = vtk.vtkCommand.UserEvent + 159\n SegmentVesselWithSeedsEvent = vtk.vtkCommand.UserEvent + 160\n SagittalCorrectionFinishedEvent = vtk.vtkCommand.UserEvent + 161" }, { "alpha_fraction": 0.7044684290885925, "alphanum_fraction": 0.7091753482818604, "avg_line_length": 39.85897445678711, "blob_id": "e755bd71ba5485b0d24d86f4a50f9637ab68d7e3", "content_id": "b903e683765e140567ea085275573f0026b0ee6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15934, "license_type": "no_license", "max_line_length": 150, "num_lines": 390, "path": "/VentriculostomyPlanning/VentriculostomyPlanningUtils/SlicerCaseManager.py", "repo_name": "tokjun/VentriculostomyPlanning", "src_encoding": "UTF-8", "text": "import os\nimport csv, re, numpy, json, ast, re\nimport shutil, datetime, logging\nimport ctk, vtk, qt, slicer, inspect\nfrom functools import wraps\n\nfrom slicer.ScriptedLoadableModule import *\nfrom SlicerDevelopmentToolboxUtils.widgets import BasicInformationWatchBox, DICOMBasedInformationWatchBox\nfrom SlicerDevelopmentToolboxUtils.helpers import WatchBoxAttribute\nfrom SlicerDevelopmentToolboxUtils.mixins import ModuleWidgetMixin, ModuleLogicMixin\nfrom SlicerDevelopmentToolboxUtils.constants import DICOMTAGS\n\ndef onReturnProcessEvents(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n func(*args, **kwargs)\n slicer.app.processEvents()\n return wrapper\n\n\ndef beforeRunProcessEvents(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n slicer.app.processEvents()\n func(*args, **kwargs)\n return wrapper\n\n\nclass DICOMFileMixedInformationWatchBox(DICOMBasedInformationWatchBox):\n\n CURRENTDIRTAG = \"currentdirtag\"\n def __init__(self, attributes, title=\"\", sourceFile=None, parent=None, columns=1):\n super(DICOMFileMixedInformationWatchBox, self).__init__(attributes, title, sourceFile, parent, columns)\n\n def reset(self):\n super(DICOMFileMixedInformationWatchBox, self).reset()\n\n def updateInformationFromWatchBoxAttribute(self, attribute):\n if attribute.tags and self.sourceFile:\n values = []\n for tag in attribute.tags:\n currentValue = ModuleLogicMixin.getDICOMValue(self.sourceFile, tag, \"\")\n if tag in self.DATE_TAGS_TO_FORMAT:\n currentValue = self._formatDate(currentValue)\n elif tag == DICOMTAGS.PATIENT_NAME:\n currentValue = self._formatPatientName(currentValue)\n elif tag == self.CURRENTDIRTAG:\n path = os.path.normpath(self.sourceFile)\n folderList = path.split(os.sep)\n if len(folderList)>=4:\n currentValue = folderList[-4]\n values.append(currentValue)\n return self._getTagValueFromTagValues(values)\n return \"\"\n\nclass SlicerCaseManager(ScriptedLoadableModule):\n def __init__(self, parent):\n ScriptedLoadableModule.__init__(self, parent)\n self.parent.title = \"SlicerCaseManager\"\n self.parent.categories = [\"Radiology\"]\n self.parent.dependencies = [\"\"]\n self.parent.contributors = [\"Longquan Chen(SPL)\",\"Christian Herz (SPL)\"]\n self.parent.helpText = \"\"\"A common module for case management in Slicer\"\"\"\n self.parent.acknowledgementText = \"\"\"Surgical Planning Laboratory, Brigham and Women's Hospital, Harvard\n Medical School, Boston, USA This work was supported in part by the National\n Institutes of Health through grants R01 EB020667, U24 CA180918,\n R01 CA111288 and P41 EB015898. The code is originated from the module SliceTracker\"\"\"\n\nclass SlicerCaseManagerWidget(ScriptedLoadableModuleWidget, ModuleWidgetMixin):\n @property\n def caseRootDir(self):\n return self._caseRootDir\n\n @caseRootDir.setter\n def caseRootDir(self, path):\n try:\n exists = os.path.exists(path)\n except TypeError:\n exists = False\n self._caseRootDir = path\n self.setSetting('CasesRootLocation', path if exists else None)\n self.casesRootDirectoryButton.toolTip = path\n self.rootDirectoryLabel.setText(str(self._caseRootDir))\n self.openCaseButton.enabled = exists\n self.createNewCaseButton.enabled = exists\n\n \n @property\n def caseDirectoryList(self):\n return self._caseDirectoryList\n\n @caseDirectoryList.setter\n def caseDirectoryList(self,list):\n self._caseDirectoryList = list \n \n @property\n def planningDataDir(self):\n return self._planningDataDir\n\n @planningDataDir.setter\n def planningDataDir(self, path):\n self._planningDataDir = path\n if path is None:\n return\n if os.path.exists(path):\n self.loadPlanningData()\n\n @property\n def planningDICOMDataDirectory(self):\n return os.path.join(self.currentCaseDirectory, \"DICOM\", \"Planning\") if self.currentCaseDirectory else \"\"\n\n @property\n def outputDir(self):\n return os.path.join(self.currentCaseDirectory, \"VentriclostomyOutputs\")\n\n @property\n def currentCaseDirectory(self):\n return self._currentCaseDirectory\n\n @currentCaseDirectory.setter\n def currentCaseDirectory(self, path):\n self._currentCaseDirectory = path\n self.patientWatchBox.setInformation(\"CurrentCaseDirectory\", os.path.relpath(path, self.caseRootDir), toolTip=path)\n\n @property\n def generatedOutputDirectory(self):\n return self._generatedOutputDirectory\n\n @generatedOutputDirectory.setter\n def generatedOutputDirectory(self, path):\n if not os.path.exists(path):\n self.logic.createDirectory(path)\n exists = os.path.exists(path)\n self._generatedOutputDirectory = path if exists else \"\"\n \n @property\n def mainGUIGroupBox(self):\n return self._mainGUIGroupBox\n\n @property\n def collapsibleDirectoryConfigurationArea(self):\n return self._collapsibleDirectoryConfigurationArea\n \n def __init__(self, parent=None):\n ScriptedLoadableModuleWidget.__init__(self, parent)\n self.logic = SlicerCaseManagerLogic()\n self.moduleName = \"slicerCaseManager\"\n #self.modulePath = os.path.dirname(slicer.util.modulePath(self.moduleName))\n self._caseRootDir = self.getSetting('CasesRootLocation')\n self._currentCaseDirectory = None\n self._caseDirectoryList = {}\n self.caseDirectoryList = {\"DICOM/Planning\", \"Results\"}\n self.warningBox = qt.QMessageBox()\n self.CloseCaseEvent = vtk.vtkCommand.UserEvent + 201\n self.LoadCaseCompletedEvent = vtk.vtkCommand.UserEvent + 202\n self.StartCaseImportEvent = vtk.vtkCommand.UserEvent + 203\n self.CreatedNewCaseEvent = vtk.vtkCommand.UserEvent + 204\n self.setup()\n\n def setup(self):\n ScriptedLoadableModuleWidget.setup(self)\n self._mainGUIGroupBox = qt.QGroupBox()\n self._collapsibleDirectoryConfigurationArea = ctk.ctkCollapsibleButton()\n self.mainGUIGroupBoxLayout = qt.QGridLayout()\n self._mainGUIGroupBox.setLayout(self.mainGUIGroupBoxLayout)\n self.createNewCaseButton = self.createButton(\"New case\")\n self.openCaseButton = self.createButton(\"Open case\")\n self.mainGUIGroupBoxLayout.addWidget(self.createNewCaseButton, 1, 0)\n self.mainGUIGroupBoxLayout.addWidget(self.openCaseButton, 1, 1)\n self.casesRootDirectoryButton = self.createDirectoryButton(text=\"Choose cases root location\",\n caption=\"Choose cases root location\",\n directory=self.getSetting('CasesRootLocation'))\n self.rootDirectoryLabel = qt.QLabel('')\n if self.getSetting('CasesRootLocation'):\n self.rootDirectoryLabel = qt.QLabel(self.getSetting('CasesRootLocation'))\n self.createPatientWatchBox()\n self.setupConnections()\n self.layout.addWidget(self._mainGUIGroupBox)\n slicer.mrmlScene.AddObserver(slicer.vtkMRMLScene.StartImportEvent, self.StartCaseImportCallback)\n slicer.mrmlScene.AddObserver(slicer.vtkMRMLScene.EndImportEvent, self.LoadCaseCompletedCallback)\n\n @vtk.calldata_type(vtk.VTK_OBJECT)\n def StartCaseImportCallback(self, caller, eventId, callData = None):\n print(\"loading case\")\n self.logic.update_observers(self.StartCaseImportEvent)\n\n @vtk.calldata_type(vtk.VTK_OBJECT)\n def LoadCaseCompletedCallback(self, caller, eventId, callData = None):\n print(\"case loaded\")\n self.logic.update_observers(self.LoadCaseCompletedEvent)\n\n def updateOutputFolder(self):\n if os.path.exists(self.generatedOutputDirectory):\n return\n if self.patientWatchBox.getInformation(\"PatientID\") != '' :\n if self.outputDir and not os.path.exists(self.outputDir):\n self.logic.createDirectory(self.outputDir)\n finalDirectory = self.patientWatchBox.getInformation(\"PatientID\") + \\\n str(qt.QDate().currentDate()) + \"-\" + qt.QTime().currentTime().toString().replace(\":\", \"\")\n self.generatedOutputDirectory = os.path.join(self.outputDir, finalDirectory, \"Planning\")\n else:\n self.generatedOutputDirectory = \"\"\n\n def createPatientWatchBox(self):\n WatchBoxAttribute.TRUNCATE_LENGTH = 30\n self.patientWatchBoxInformation = [WatchBoxAttribute('PatientID', 'Patient ID: ', DICOMTAGS.PATIENT_ID),\n WatchBoxAttribute('PatientName', 'Patient Name: ', DICOMTAGS.PATIENT_NAME),\n WatchBoxAttribute('DOB', 'Date of Birth: ', DICOMTAGS.PATIENT_BIRTH_DATE),\n WatchBoxAttribute('StudyDate', 'Planning Study Date: ', DICOMTAGS.STUDY_DATE),\n WatchBoxAttribute('CurrentCaseDirectory', 'Case Directory: ', DICOMFileMixedInformationWatchBox.CURRENTDIRTAG)]\n self.patientWatchBox = DICOMFileMixedInformationWatchBox(self.patientWatchBoxInformation)\n self.layout.addWidget(self.patientWatchBox)\n\n\n def setupConnections(self):\n self.createNewCaseButton.clicked.connect(self.onCreateNewCaseButtonClicked)\n self.openCaseButton.clicked.connect(self.onOpenCaseButtonClicked)\n self.casesRootDirectoryButton.directorySelected.connect(lambda: setattr(self, \"caseRootDir\",\n self.casesRootDirectoryButton.directory))\n\n def onCreateNewCaseButtonClicked(self):\n if not self.checkAndWarnUserIfCaseInProgress():\n return\n if not self.caseRootDir:\n self.warningBox.setText(\"The root directory for cases is not set up yet.\")\n self.warningBox.exec_()\n return\n self.clearData()\n self.caseDialog = NewCaseSelectionNameWidget(self.caseRootDir)\n selectedButton = self.caseDialog.exec_()\n if selectedButton == qt.QMessageBox.Ok:\n newCaseDirectory = self.caseDialog.newCaseDirectory\n os.mkdir(newCaseDirectory)\n for direcory in self.caseDirectoryList:\n subDirectory = direcory.split(\"/\")\n for iIndex in range(len(subDirectory)+1):\n fullPath = \"\"\n for jIndex in range(iIndex):\n fullPath = os.path.join(fullPath,subDirectory[jIndex])\n if not os.path.exists(os.path.join(newCaseDirectory,fullPath)): \n os.mkdir(os.path.join(newCaseDirectory,fullPath))\n self.currentCaseDirectory = newCaseDirectory\n self.logic.update_observers(self.CreatedNewCaseEvent)\n \n def onOpenCaseButtonClicked(self):\n if not self.checkAndWarnUserIfCaseInProgress():\n return\n if not self.caseRootDir:\n self.warningBox.setText(\"The root directory for cases is not set up yet.\")\n self.warningBox.exec_()\n return\n path = qt.QFileDialog.getExistingDirectory(self.parent.window(), \"Select Case Directory\", self.caseRootDir)\n if not path:\n return\n slicer.mrmlScene.Clear(0)\n self.logic.update_observers(self.CloseCaseEvent)\n self.currentCaseDirectory = path\n if (not os.path.exists(os.path.join(path, \"DICOM\", \"Planning\")) ) or (not os.path.exists(os.path.join(path, \"Results\")) ):\n slicer.util.warningDisplay(\"The selected case directory seems not to be valid\", windowTitle=\"\")\n self.clearData()\n else:\n # Here the both the slicer.vtkMRMLScene.StartImportEvent and slicer.vtkMRMLScene.EndImportEvent will be triggered\n sucess = slicer.util.loadScene(os.path.join(path, \"Results\",\"Results.mrml\"))\n\n def checkAndWarnUserIfCaseInProgress(self):\n proceed = True\n if self.currentCaseDirectory is not None:\n if not slicer.util.confirmYesNoDisplay(\"Current case will be closed. Do you want to proceed?\"):\n proceed = False\n return proceed\n\n def loadCaseData(self):\n # To do: load data from Json file\n pass\n\n def clearData(self):\n # To do: clear the flags\n if self.currentCaseDirectory:\n self.currentCaseDirectory = None\n slicer.mrmlScene.Clear(0)\n self.logic.update_observers(self.CloseCaseEvent)\n self.patientWatchBox.sourceFile = None\n pass\n\n\nclass SlicerCaseManagerLogic(ModuleLogicMixin, ScriptedLoadableModuleLogic):\n @property\n def caseCompleted(self):\n return self._caseCompleted\n\n @caseCompleted.setter\n def caseCompleted(self, value):\n self._caseCompleted = value\n \n def __init__(self):\n ScriptedLoadableModuleLogic.__init__(self)\n self.caseCompleted = True\n self.DEFAULT_JSON_FILE_NAME = \"results.json\"\n self.observers = []\n\n def register(self, observer):\n if not observer in self.observers:\n self.observers.append(observer)\n\n\n def unregister(self, observer):\n if observer in self.observers:\n self.observers.remove(observer)\n\n def unregister_all(self):\n if self.observers:\n del self.observers[:]\n\n @beforeRunProcessEvents\n def update_observers(self, EventID):\n for observer in self.observers:\n observer.updateFromCaseManager(EventID)\n \n def closeCase(self, directory):\n if os.path.exists(directory):\n self.caseCompleted = False\n if self.getDirectorySize(directory) == 0:\n shutil.rmtree(directory)\n #self.update_observers(self.CloseCaseEvent)\n \n def hasCaseBeenCompleted(self, directory):\n self.caseCompleted = False\n filename = os.path.join(directory, self.DEFAULT_JSON_FILE_NAME)\n if not os.path.exists(filename):\n return\n with open(filename) as data_file:\n data = json.load(data_file)\n self.caseCompleted = data[\"completed\"]\n return self.caseCompleted\n \nclass NewCaseSelectionNameWidget(qt.QMessageBox, ModuleWidgetMixin):\n\n PREFIX = \"Case\"\n SUFFIX = \"-\" + datetime.date.today().strftime(\"%Y%m%d\")\n SUFFIX_PATTERN = \"-[0-9]{8}\"\n CASE_NUMBER_DIGITS = 3\n PATTERN = PREFIX+\"[0-9]{\"+str(CASE_NUMBER_DIGITS-1)+\"}[0-9]{1}\"+SUFFIX_PATTERN\n\n def __init__(self, destination, parent=None):\n super(NewCaseSelectionNameWidget, self).__init__(parent)\n if not os.path.exists(destination):\n slicer.util.warningDisplay(\"Root directory is not set, please set the root in the 'Case Directory Settings' panel \", windowTitle=\"\")\n raise\n self.destinationRoot = destination\n self.newCaseDirectory = None\n self.minimum = self.getNextCaseNumber()\n self.setupUI()\n self.setupConnections()\n self.onCaseNumberChanged(self.minimum)\n\n def getNextCaseNumber(self):\n import re\n caseNumber = 0\n for dirName in [dirName for dirName in os.listdir(self.destinationRoot)\n if os.path.isdir(os.path.join(self.destinationRoot, dirName)) and re.match(self.PATTERN, dirName)]:\n number = int(re.split(self.SUFFIX_PATTERN, dirName)[0].split(self.PREFIX)[1])\n caseNumber = caseNumber if caseNumber > number else number\n return caseNumber+1\n\n def setupUI(self):\n self.setWindowTitle(\"Case Number Selection\")\n self.setText(\"Please select a case number for the new case.\")\n self.setIcon(qt.QMessageBox.Question)\n self.spinbox = qt.QSpinBox()\n self.spinbox.setRange(self.minimum, int(\"9\"*self.CASE_NUMBER_DIGITS))\n self.preview = qt.QLabel()\n self.notice = qt.QLabel()\n self.layout().addWidget(self.createVLayout([self.createHLayout([qt.QLabel(\"Proposed Case Number\"), self.spinbox]),\n self.preview, self.notice]), 2, 1)\n self.okButton = self.addButton(self.Ok)\n self.okButton.enabled = False\n self.cancelButton = self.addButton(self.Cancel)\n self.setDefaultButton(self.okButton)\n\n def setupConnections(self):\n self.spinbox.valueChanged.connect(self.onCaseNumberChanged)\n\n def onCaseNumberChanged(self, caseNumber):\n formatString = '%0'+str(self.CASE_NUMBER_DIGITS)+'d'\n caseNumber = formatString % caseNumber\n directory = self.PREFIX+caseNumber+self.SUFFIX\n self.newCaseDirectory = os.path.join(self.destinationRoot, directory)\n self.preview.setText(\"New case directory: \" + self.newCaseDirectory)\n self.okButton.enabled = not os.path.exists(self.newCaseDirectory)\n self.notice.text = \"\" if not os.path.exists(self.newCaseDirectory) else \"Note: Directory already exists.\"" }, { "alpha_fraction": 0.8552631735801697, "alphanum_fraction": 0.8684210777282715, "avg_line_length": 37, "blob_id": "ef17102a981fe42fbf7f9fd0864a78590e6c80a8", "content_id": "4ecdf4e30aec81fb6f3496d2d61e04adeb95be7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 76, "license_type": "no_license", "max_line_length": 49, "num_lines": 2, "path": "/README.md", "repo_name": "tokjun/VentriculostomyPlanning", "src_encoding": "UTF-8", "text": "# VentriculostomyPlanning\n3D Slicer extension for Ventriculostomy planning.\n" }, { "alpha_fraction": 0.7165675163269043, "alphanum_fraction": 0.7237707376480103, "avg_line_length": 42.3393669128418, "blob_id": "ba5863a808e606fc18e584322171b8f98ed6603b", "content_id": "2f56fb6e3ea425876ed63a2574b0c43912650b66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9579, "license_type": "no_license", "max_line_length": 161, "num_lines": 221, "path": "/VentriculostomyPlanning/VentriculostomyPlanningUtils/VentriclostomyButtons.py", "repo_name": "tokjun/VentriculostomyPlanning", "src_encoding": "UTF-8", "text": "import slicer, vtk\nfrom ctk import ctkAxesWidget\nfrom VentriculostomyPlanningUtils.UserEvents import VentriculostomyUserEvents\nfrom SlicerDevelopmentToolboxUtils.buttons import LayoutButton, CheckableIconButton, BasicIconButton\nfrom SlicerDevelopmentToolboxUtils.icons import Icons\nfrom SlicerDevelopmentToolboxUtils.mixins import ModuleWidgetMixin\nimport os\nimport qt\nimport numpy\n\nclass GreenSliceLayoutButton(LayoutButton):\n \"\"\" LayoutButton inherited class which represents a button for the SlicerLayoutOneUpGreenSliceView including the icon.\n\n Args:\n text (str, optional): text to be displayed for the button\n parent (qt.QWidget, optional): parent of the button\n\n .. code-block:: python\n\n from VentriculostomyPlanningUtils.buttons import GreenSliceLayoutButton\n\n button = GreenSliceLayoutButton()\n button.show()\n \"\"\"\n\n iconFileName=os.path.join(os.path.dirname(os.path.normpath(os.path.dirname(os.path.realpath(__file__)))),'Resources','Icons','LayoutOneUpGreenSliceView.png')\n _ICON = qt.QIcon(iconFileName)\n LAYOUT = slicer.vtkMRMLLayoutNode.SlicerLayoutOneUpGreenSliceView\n\n def __init__(self, text=\"\", parent=None, **kwargs):\n super(GreenSliceLayoutButton, self).__init__(text, parent, **kwargs)\n self.toolTip = \"Green Slice Only Layout\"\n\n\nclass ConventionalSliceLayoutButton(LayoutButton):\n \"\"\" LayoutButton inherited class which represents a button for the ConventionalSliceLayoutButton including the icon.\n\n Args:\n text (str, optional): text to be displayed for the button\n parent (qt.QWidget, optional): parent of the button\n\n .. code-block:: python\n\n from VentriculostomyPlanningUtils.buttons import ConventionalSliceLayoutButton\n\n button = ConventionalSliceLayoutButton()\n button.show()\n \"\"\"\n iconFileName=os.path.join(os.path.dirname(os.path.normpath(os.path.dirname(os.path.realpath(__file__)))),'Resources','Icons','LayoutConventionalSliceView.png')\n _ICON = qt.QIcon(iconFileName)\n LAYOUT = slicer.vtkMRMLLayoutNode.SlicerLayoutConventionalView\n\n def __init__(self, text=\"\", parent=None, **kwargs):\n super(ConventionalSliceLayoutButton, self).__init__(text, parent, **kwargs)\n self.toolTip = \"Conventional Slice Only Layout\"\n\n\nclass ScreenShotButton(BasicIconButton):\n \n iconFileName=os.path.join(os.path.dirname(os.path.normpath(os.path.dirname(os.path.realpath(__file__)))),'Resources','Icons','screenShot.png')\n _ICON = qt.QIcon(iconFileName)\n \n @property\n def caseResultDir(self):\n return self._caseResultDir\n\n @caseResultDir.setter\n def caseResultDir(self, value):\n self._caseResultDir = value\n self.imageIndex = 0\n\n def __init__(self, text=\"\", parent=None, **kwargs):\n super(ScreenShotButton, self).__init__(text, parent, **kwargs)\n import ScreenCapture\n self.cap = ScreenCapture.ScreenCaptureLogic()\n self.checkable = False\n self._caseResultDir = \"\"\n self.imageIndex = 0\n\n def _connectSignals(self):\n super(ScreenShotButton, self)._connectSignals()\n self.clicked.connect(self.onClicked)\n\n def onClicked(self):\n if self.caseResultDir:\n self.cap.showViewControllers(False)\n fileName = os.path.join(self._caseResultDir, 'Results', 'screenShot'+str(self.imageIndex)+'.png')\n if os.path.exists(fileName):\n self.imageIndex = self.imageIndex + 1\n fileName = os.path.join(self._caseResultDir, 'Results', 'screenShot' + str(self.imageIndex) + '.png')\n self.cap.captureImageFromView(None, fileName)\n self.cap.showViewControllers(True)\n self.imageIndex = self.imageIndex + 1\n else:\n slicer.util.warningDisplay(\"Case was not created, create a case first\")\n pass\n\nclass ReverseViewOnCannulaButton(CheckableIconButton):\n \n iconFileName=os.path.join(os.path.dirname(os.path.normpath(os.path.dirname(os.path.realpath(__file__)))),'Resources','Icons','ReverseView.png')\n _ICON = qt.QIcon(iconFileName)\n \n @property\n def cannulaNode(self):\n return self._cannulaNode\n\n @cannulaNode.setter\n def cannulaNode(self,value):\n self._cannulaNode = value\n self.cameraReversePos = None\n\n def __init__(self, text=\"\", parent=None, **kwargs):\n super(ReverseViewOnCannulaButton, self).__init__(text, parent, **kwargs)\n self._cannulaNode = None\n self._pitchAngle = 0.0\n self._yawAngle = 0.0\n self.cameraPos = [0.0] * 3\n self.cameraReversePos = None\n self.camera = None\n layoutManager = slicer.app.layoutManager()\n threeDView = layoutManager.threeDWidget(0).threeDView()\n displayManagers = vtk.vtkCollection()\n threeDView.getDisplayableManagers(displayManagers)\n for index in range(displayManagers.GetNumberOfItems()):\n if displayManagers.GetItemAsObject(index).GetClassName() == 'vtkMRMLCameraDisplayableManager':\n self.camera = displayManagers.GetItemAsObject(index).GetCameraNode().GetCamera()\n self.cameraPos = self.camera.GetPosition()\n self.toolTip = \"Reverse the view of the cannula from the other end\"\n\n def calculateAnglesBasedOnCannula(self):\n nFiducials = self.cannulaNode.GetNumberOfFiducials()\n if nFiducials>=1:\n firstPos = numpy.array([0.0, 0.0, 0.0])\n self.cannulaNode.GetNthFiducialPosition(0,firstPos)\n lastPos = numpy.array([0.0, 0.0, 0.0])\n self.cannulaNode.GetNthFiducialPosition(nFiducials-1,lastPos)\n self._pitchAngle = numpy.arctan2(lastPos[2] - firstPos[2], abs(lastPos[1] - firstPos[1])) * 180.0 / numpy.pi\n self._yawAngle = -numpy.arctan2(lastPos[0] - firstPos[0], abs(lastPos[1] - firstPos[1])) * 180.0 / numpy.pi\n return True\n return False\n\n def _onToggled(self, checked):\n if self.cannulaNode:\n layoutManager = slicer.app.layoutManager()\n threeDView = layoutManager.threeDWidget(0).threeDView()\n if checked == True and self.calculateAnglesBasedOnCannula():\n displayManagers = vtk.vtkCollection()\n threeDView.getDisplayableManagers(displayManagers)\n for index in range(displayManagers.GetNumberOfItems()):\n if displayManagers.GetItemAsObject(index).GetClassName() == 'vtkMRMLCameraDisplayableManager':\n self.camera = displayManagers.GetItemAsObject(index).GetCameraNode().GetCamera()\n self.cameraPos = self.camera.GetPosition()\n if not self.cameraReversePos:\n threeDView.lookFromViewAxis(ctkAxesWidget.Posterior)\n threeDView.pitchDirection = threeDView.PitchUp\n threeDView.yawDirection = threeDView.YawRight\n threeDView.setPitchRollYawIncrement(self._pitchAngle)\n threeDView.pitch()\n if self._yawAngle < 0:\n threeDView.setPitchRollYawIncrement(self._yawAngle)\n else:\n threeDView.setPitchRollYawIncrement(360 - self._yawAngle)\n threeDView.yaw()\n if self.cannulaNode and self.cannulaNode.GetNumberOfFiducials() >= 2:\n posSecond = [0.0] * 3\n self.cannulaNode.GetNthFiducialPosition(1, posSecond)\n threeDView.setFocalPoint(posSecond[0], posSecond[1], posSecond[2])\n self.cameraReversePos = self.camera.GetPosition()\n else:\n self.camera.SetPosition(self.cameraReversePos)\n threeDView.zoomIn() # to refresh the 3D viewer, when the view position is inside the skull model, the model is not rendered,\n threeDView.zoomOut() # Zoom in and out will refresh the viewer\n slicer.mrmlScene.InvokeEvent(VentriculostomyUserEvents.ReverseViewClicked)\n else:\n displayManagers = vtk.vtkCollection()\n threeDView.getDisplayableManagers(displayManagers)\n for index in range(displayManagers.GetNumberOfItems()):\n if displayManagers.GetItemAsObject(index).GetClassName() == 'vtkMRMLCameraDisplayableManager':\n self.camera = displayManagers.GetItemAsObject(index).GetCameraNode().GetCamera()\n self.cameraReversePos = self.camera.GetPosition()\n self.camera.SetPosition(self.cameraPos)\n threeDView.zoomIn() # to refresh the 3D viewer, when the view position is inside the skull model, the model is not rendered,\n threeDView.zoomOut() # Zoom in and out will refresh the viewer\n slicer.mrmlScene.InvokeEvent(VentriculostomyUserEvents.ReverseViewClicked)\n\nclass AlgorithmSettingsButton(BasicIconButton):\n\n def __init__(self, connectedLayout, text=\"\", parent=None, **kwargs):\n self.connectedLayout = connectedLayout\n self._ICON = Icons.settings\n super(AlgorithmSettingsButton, self).__init__(text, parent, **kwargs)\n self.settings = AlgorithmSettingsMessageBox(self.connectedLayout, slicer.util.mainWindow())\n\n def _connectSignals(self):\n super(AlgorithmSettingsButton, self)._connectSignals()\n self.clicked.connect(self.__onClicked)\n\n def __onClicked(self):\n self.settings = AlgorithmSettingsMessageBox(self.connectedLayout, slicer.util.mainWindow())\n self.settings.show()\n\n\nclass AlgorithmSettingsMessageBox(qt.QMessageBox, ModuleWidgetMixin):\n\n def __init__(self, connectedLayout, parent = None, **kwargs):\n qt.QMessageBox.__init__(self, parent, **kwargs)\n self.setStandardButtons(0)\n self.setLayout(qt.QGridLayout())\n self.algorithmFrame = qt.QFrame()\n self.algorithmFrame.setLayout(connectedLayout)\n self.layout().addWidget(self.algorithmFrame, 0, 0, 1, 1)\n self.okButton = self.createButton(\"OK\")\n self.addButton(self.okButton, qt.QMessageBox.AcceptRole)\n self.layout().addWidget(self.createHLayout([self.okButton]), 1, 0, 1, 1)\n\n def show(self):\n qt.QMessageBox.show(self)\n\n def setAlgorithmLayout(self, layout):\n self.algorithmLayout = layout\n self.algorithmFrame.setLayout(layout)\n\n" }, { "alpha_fraction": 0.6348314881324768, "alphanum_fraction": 0.6423221230506897, "avg_line_length": 27.157894134521484, "blob_id": "c2578ea719fad4329abfaa2c366747d878ffe2b4", "content_id": "ffccf609e9e0c58850fa8d53ac8b3e40d5cc687e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 534, "license_type": "no_license", "max_line_length": 86, "num_lines": 19, "path": "/VentriculostomyPlanning/VentriculostomyPlanningUtils/WatchDog.py", "repo_name": "tokjun/VentriculostomyPlanning", "src_encoding": "UTF-8", "text": "from qt import QTimer\nimport qt\nclass WatchDog:\n def __init__(self, timeout, userHandler=None): # timeout in seconds\n self.timeout = timeout\n self.handler = userHandler if userHandler is not None else self.defaultHandler\n self.timer = qt.QTimer()\n self.timer.timeout.connect(self.handler)\n\n def reset(self):\n self.timer.stop()\n self.timer.start(self.timeout*1000)\n\n def stop(self):\n self.timer.stop()\n\n def defaultHandler(self):\n print \"time out\"\n raise self" }, { "alpha_fraction": 0.7375803589820862, "alphanum_fraction": 0.7504845261573792, "avg_line_length": 42.665924072265625, "blob_id": "85dc7b3cbf2dd329ebd9454970ea14904e316a9b", "content_id": "ad524a46d2a5e03b02cb7458bf9ddf9f3a77674c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19606, "license_type": "no_license", "max_line_length": 135, "num_lines": 449, "path": "/VentriculostomyPlanning/VentriculostomyPlanningUtils/UsefulFunctions.py", "repo_name": "tokjun/VentriculostomyPlanning", "src_encoding": "UTF-8", "text": "import vtk, qt, ctk, slicer\nimport numpy\nimport SimpleITK as sitk\nimport sitkUtils\nimport math\n\nclass UsefulFunctions(object):\n\n def __init__(self):\n pass\n\n def clipVolumeWithModelNode(self, inputVolume, clippingModelNode, clipOutsideSurface, fillValue):\n \"\"\"\n Fill voxels of the input volume inside/outside the clipping model with the provided fill value\n \"\"\"\n # Determine the transform between the box and the image IJK coordinate systems\n rasToModel = vtk.vtkMatrix4x4()\n if clippingModelNode.GetTransformNodeID() != None:\n modelTransformNode = slicer.mrmlScene.GetNodeByID(clippingModelNode.GetTransformNodeID())\n boxToRas = vtk.vtkMatrix4x4()\n modelTransformNode.GetMatrixTransformToWorld(boxToRas)\n rasToModel.DeepCopy(boxToRas)\n rasToModel.Invert()\n polyData = clippingModelNode.GetPolyData()\n return self.clipVolumeWithPolyData(inputVolume, polyData, clipOutsideSurface, fillValue, rasToModel)\n\n def clipVolumeWithPolyData(self, inputVolume, polyData, clipOutsideSurface, fillValue, leftTransformMatrix = None):\n leftMatrix = vtk.vtkMatrix4x4()\n leftMatrix.Identity()\n if leftTransformMatrix:\n leftMatrix.DeepCopy(leftTransformMatrix)\n ijkToRas = vtk.vtkMatrix4x4()\n inputVolume.GetIJKToRASMatrix(ijkToRas)\n ijkToModel = vtk.vtkMatrix4x4()\n vtk.vtkMatrix4x4.Multiply4x4(leftMatrix, ijkToRas, ijkToModel)\n modelToIjkTransform = vtk.vtkTransform()\n modelToIjkTransform.SetMatrix(ijkToModel)\n modelToIjkTransform.Inverse()\n transformModelToIjk = vtk.vtkTransformPolyDataFilter()\n transformModelToIjk.SetTransform(modelToIjkTransform)\n transformModelToIjk.SetInputData(polyData)\n transformModelToIjk.Update()\n\n # Use the stencil to fill the volume\n\n # Convert model to stencil\n polyToStencil = vtk.vtkPolyDataToImageStencil()\n polyToStencil.SetInputConnection(transformModelToIjk.GetOutputPort())\n polyToStencil.SetOutputSpacing(inputVolume.GetImageData().GetSpacing())\n polyToStencil.SetOutputOrigin(inputVolume.GetImageData().GetOrigin())\n polyToStencil.SetOutputWholeExtent(inputVolume.GetImageData().GetExtent())\n\n # Apply the stencil to the volume\n stencilToImage = vtk.vtkImageStencil()\n stencilToImage.SetInputConnection(inputVolume.GetImageDataConnection())\n stencilToImage.SetStencilConnection(polyToStencil.GetOutputPort())\n if clipOutsideSurface:\n stencilToImage.ReverseStencilOff()\n else:\n stencilToImage.ReverseStencilOn()\n stencilToImage.SetBackgroundValue(fillValue)\n stencilToImage.Update()\n\n # Update the volume with the stencil operation result\n outputImageData = vtk.vtkImageData()\n outputImageData.DeepCopy(stencilToImage.GetOutput())\n return outputImageData\n\n def createHoleFilledVolumeNode(self, ventricleVolume, thresholdValue, samplingFactor, morphologyParameters):\n \n holeFillKernelSize = morphologyParameters[0]\n maskKernelSize = morphologyParameters[1]\n resampleFilter = sitk.ResampleImageFilter()\n ventricleImage = sitk.Cast(sitkUtils.PullFromSlicer(ventricleVolume.GetID()), sitk.sitkInt16)\n \n resampleFilter.SetSize(numpy.array(ventricleImage.GetSize()) / samplingFactor)\n resampleFilter.SetOutputSpacing(numpy.array(ventricleImage.GetSpacing()) * samplingFactor)\n resampleFilter.SetOutputDirection(ventricleImage.GetDirection())\n resampleFilter.SetOutputOrigin(numpy.array(ventricleImage.GetOrigin()))\n resampledImage = resampleFilter.Execute(ventricleImage)\n thresholdFilter = sitk.BinaryThresholdImageFilter()\n thresholdImage = thresholdFilter.Execute(resampledImage, thresholdValue, 10000, 1, 0)\n\n padFilter = sitk.ConstantPadImageFilter()\n padFilter.SetPadLowerBound(holeFillKernelSize)\n padFilter.SetPadUpperBound(holeFillKernelSize)\n paddedImage = padFilter.Execute(thresholdImage)\n \n dilateFilter = sitk.BinaryDilateImageFilter()\n dilateFilter.SetKernelRadius(holeFillKernelSize)\n dilateFilter.SetBackgroundValue(0)\n dilateFilter.SetForegroundValue(1)\n dilatedImage = dilateFilter.Execute(paddedImage)\n \n erodeFilter = sitk.BinaryErodeImageFilter()\n erodeFilter.SetKernelRadius(holeFillKernelSize)\n erodeFilter.SetBackgroundValue(0)\n erodeFilter.SetForegroundValue(1)\n erodedImage = erodeFilter.Execute(dilatedImage)\n \n fillHoleFilter = sitk.BinaryFillholeImageFilter()\n holefilledImage = fillHoleFilter.Execute(erodedImage)\n dilateFilter = sitk.BinaryDilateImageFilter()\n dilateFilter.SetKernelRadius(maskKernelSize)\n dilateFilter.SetBackgroundValue(0)\n dilateFilter.SetForegroundValue(1)\n dilatedImage = dilateFilter.Execute(holefilledImage)\n subtractFilter = sitk.SubtractImageFilter()\n subtractedImage = subtractFilter.Execute(dilatedImage, holefilledImage)\n holefilledImageNode = sitkUtils.PushToSlicer(holefilledImage, \"holefilledImage\", 0, False)\n subtractedImageNode = sitkUtils.PushToSlicer(subtractedImage, \"subtractedImage\", 0, False)\n return holefilledImageNode, subtractedImageNode\n\n\n def createHoleFilledVolumeNode2(self, ventricleVolume, thresholdValue, samplingFactor, morphologyParameters):\n\n maskKernelSize = morphologyParameters[1]\n\n ## Convert to binary image by threshold\n resampleFilter = sitk.ResampleImageFilter()\n ventricleImage = sitk.Cast(sitkUtils.PullFromSlicer(ventricleVolume.GetID()), sitk.sitkInt16)\n resampleFilter.SetSize(numpy.array(ventricleImage.GetSize()) / samplingFactor)\n resampleFilter.SetOutputSpacing(numpy.array(ventricleImage.GetSpacing()) * samplingFactor)\n resampleFilter.SetOutputDirection(ventricleImage.GetDirection())\n resampleFilter.SetOutputOrigin(numpy.array(ventricleImage.GetOrigin()))\n resampledImage = resampleFilter.Execute(ventricleImage)\n thresholdFilter = sitk.BinaryThresholdImageFilter()\n thresholdImage = thresholdFilter.Execute(resampledImage, thresholdValue, 10000, 1, 0)\n \n ## Close the holes at top and bottom slices\n inputSize = list(thresholdImage.GetSize())\n extractFilter = sitk.ExtractImageFilter()\n extractFilter.SetDirectionCollapseToStrategy(sitk.ExtractImageFilter.DIRECTIONCOLLAPSETOSUBMATRIX)\n extractFilter.SetSize([inputSize[0], inputSize[1], 0])\n\n pasteFilter = sitk.PasteImageFilter()\n pasteFilter.SetSourceIndex([0, 0, 0])\n pasteFilter.SetSourceSize([inputSize[0], inputSize[1], 1])\n sliceFillHoleFilter = sitk.BinaryFillholeImageFilter()\n \n # Close top slice\n extractFilter.SetIndex([0,0, 0])\n topSlice = extractFilter.Execute(thresholdImage)\n topSliceFillHole = sliceFillHoleFilter.Execute(topSlice)\n topVolumeFillHole = sitk.JoinSeries(topSliceFillHole)\n pasteFilter.SetDestinationIndex([0, 0, 0])\n topClosedThresholdImage = pasteFilter.Execute(thresholdImage, topVolumeFillHole)\n\n # Close bottom slice\n extractFilter.SetIndex([0,0,inputSize[2]-1])\n bottomSlice = extractFilter.Execute(thresholdImage)\n bottomSliceFillHole = sliceFillHoleFilter.Execute(bottomSlice)\n bottomVolumeFillHole = sitk.JoinSeries(bottomSliceFillHole)\n pasteFilter.SetDestinationIndex([0, 0, inputSize[2]-1])\n topBottomClosedThresholdImage = pasteFilter.Execute(topClosedThresholdImage, bottomVolumeFillHole)\n\n ## Padding\n padFilter = sitk.ConstantPadImageFilter()\n padFilter.SetPadLowerBound([1,1,1])\n padFilter.SetPadUpperBound([1,1,1])\n paddedImage = padFilter.Execute(topBottomClosedThresholdImage)\n \n ## Close\n closingFilter = sitk.BinaryMorphologicalClosingImageFilter()\n closingFilter.SetForegroundValue(1)\n closingFilter.SafeBorderOn()\n closedImage = closingFilter.Execute(paddedImage)\n\n ## Fill the holes in 3D\n fillHoleFilter = sitk.BinaryFillholeImageFilter()\n holefilledImage = fillHoleFilter.Execute(closedImage)\n \n dilateFilter = sitk.BinaryDilateImageFilter()\n dilateFilter.SetKernelRadius(maskKernelSize)\n dilateFilter.SetBackgroundValue(0)\n dilateFilter.SetForegroundValue(1)\n dilatedImage = dilateFilter.Execute(holefilledImage)\n \n subtractFilter = sitk.SubtractImageFilter()\n subtractedImage = subtractFilter.Execute(dilatedImage, holefilledImage)\n holefilledImageNode = sitkUtils.PushToSlicer(holefilledImage, \"holefilledImage\", 0, False)\n subtractedImageNode = sitkUtils.PushToSlicer(subtractedImage, \"subtractedImage\", 0, False)\n return holefilledImageNode, subtractedImageNode\n\n\n \n def createModelBaseOnVolume(self, holefilledImageNode, outputModelNode):\n if holefilledImageNode:\n holefilledImageData = holefilledImageNode.GetImageData()\n cast = vtk.vtkImageCast()\n cast.SetInputData(holefilledImageData)\n cast.SetOutputScalarTypeToUnsignedChar()\n cast.Update()\n labelVolumeNode = slicer.mrmlScene.CreateNodeByClass(\"vtkMRMLLabelMapVolumeNode\")\n slicer.mrmlScene.AddNode(labelVolumeNode)\n labelVolumeNode.SetName(\"Threshold\")\n labelVolumeNode.SetSpacing(holefilledImageData.GetSpacing())\n labelVolumeNode.SetOrigin(holefilledImageData.GetOrigin())\n matrix = vtk.vtkMatrix4x4()\n holefilledImageNode.GetIJKToRASMatrix(matrix)\n labelVolumeNode.SetIJKToRASMatrix(matrix)\n labelImage = cast.GetOutput()\n labelVolumeNode.SetAndObserveImageData(labelImage)\n transformIJKtoRAS = vtk.vtkTransform()\n matrix = vtk.vtkMatrix4x4()\n labelVolumeNode.GetRASToIJKMatrix(matrix)\n transformIJKtoRAS.SetMatrix(matrix)\n transformIJKtoRAS.Inverse()\n padder = vtk.vtkImageConstantPad()\n padder.SetInputData(labelImage)\n padder.SetConstant(0)\n extent = labelImage.GetExtent()\n padder.SetOutputWholeExtent(extent[0], extent[1] + 2,\n extent[2], extent[3] + 2,\n extent[4], extent[5] + 2)\n cubes = vtk.vtkDiscreteMarchingCubes()\n cubes.SetInputConnection(padder.GetOutputPort())\n cubes.GenerateValues(1, 1, 1)\n cubes.Update()\n\n smoother = vtk.vtkWindowedSincPolyDataFilter()\n smoother.SetInputConnection(cubes.GetOutputPort())\n smoother.SetNumberOfIterations(10)\n smoother.BoundarySmoothingOn()\n smoother.FeatureEdgeSmoothingOff()\n smoother.SetFeatureAngle(120.0)\n smoother.SetPassBand(0.001)\n smoother.NonManifoldSmoothingOn()\n smoother.NormalizeCoordinatesOn()\n smoother.Update()\n\n pthreshold = vtk.vtkThreshold()\n pthreshold.SetInputConnection(smoother.GetOutputPort())\n pthreshold.ThresholdBetween(1, 1) ## Label 1\n pthreshold.ReleaseDataFlagOn()\n\n geometryFilter = vtk.vtkGeometryFilter()\n geometryFilter.SetInputConnection(pthreshold.GetOutputPort())\n geometryFilter.ReleaseDataFlagOn()\n\n decimator = vtk.vtkDecimatePro()\n decimator.SetInputConnection(geometryFilter.GetOutputPort())\n decimator.SetFeatureAngle(60)\n decimator.SplittingOff()\n decimator.PreserveTopologyOn()\n decimator.SetMaximumError(1)\n decimator.SetTargetReduction(0.5) #0.001 only reduce the points by 0.1%, 0.5 is 50% off\n decimator.ReleaseDataFlagOff()\n decimator.Update()\n\n smootherPoly = vtk.vtkSmoothPolyDataFilter()\n smootherPoly.SetRelaxationFactor(0.33)\n smootherPoly.SetFeatureAngle(60)\n smootherPoly.SetConvergence(0)\n\n if transformIJKtoRAS.GetMatrix().Determinant() < 0:\n reverser = vtk.vtkReverseSense()\n reverser.SetInputConnection(decimator.GetOutputPort())\n reverser.ReverseNormalsOn()\n reverser.ReleaseDataFlagOn()\n smootherPoly.SetInputConnection(reverser.GetOutputPort())\n else:\n smootherPoly.SetInputConnection(decimator.GetOutputPort())\n\n Smooth = 10\n smootherPoly.SetNumberOfIterations(Smooth)\n smootherPoly.FeatureEdgeSmoothingOff()\n smootherPoly.BoundarySmoothingOff()\n smootherPoly.ReleaseDataFlagOn()\n smootherPoly.Update()\n\n transformer = vtk.vtkTransformPolyDataFilter()\n transformer.SetInputConnection(smootherPoly.GetOutputPort())\n transformer.SetTransform(transformIJKtoRAS)\n transformer.ReleaseDataFlagOn()\n transformer.Update()\n\n normals = vtk.vtkPolyDataNormals()\n normals.SetInputConnection(transformer.GetOutputPort())\n normals.SetFeatureAngle(60)\n normals.SetSplitting(True)\n normals.ReleaseDataFlagOn()\n\n stripper = vtk.vtkStripper()\n stripper.SetInputConnection(normals.GetOutputPort())\n stripper.ReleaseDataFlagOff()\n stripper.Update()\n\n outputModel = stripper.GetOutput()\n outputModelNode.SetAndObservePolyData(outputModel)\n outputModelNode.SetAttribute(\"vtkMRMLModelNode.modelCreated\",\"True\")\n outputModelNode.GetDisplayNode().SetVisibility(1)\n slicer.mrmlScene.RemoveNode(labelVolumeNode)\n pass\n\n def getClosedCuttedModel(self, cutPlanes, polyData):\n clipper = vtk.vtkClipClosedSurface()\n clipper.SetClippingPlanes(cutPlanes)\n clipper.SetActivePlaneId(2)\n clipper.SetInputData(polyData)\n clipper.Update()\n cuttedPolyData = clipper.GetOutput()\n return cuttedPolyData\n\n def sortVTKPoints(self, inputPointVector, referencePoint):\n minDistanceIndex = 0\n minDistance = 1e10\n for iPos in range(inputPointVector.GetNumberOfPoints()):\n currentPos = numpy.array(inputPointVector.GetPoint(iPos))\n minDistance = numpy.linalg.norm(currentPos-referencePoint)\n minDistanceIndex = iPos\n for jPos in range(iPos, inputPointVector.GetNumberOfPoints()):\n posModelPost = numpy.array(inputPointVector.GetPoint(jPos))\n distanceModelPostNasion = numpy.linalg.norm(posModelPost-referencePoint)\n if distanceModelPostNasion < minDistance:\n minDistanceIndex = jPos\n minDistance = distanceModelPostNasion\n inputPointVector.SetPoint(iPos,inputPointVector.GetPoint(minDistanceIndex))\n inputPointVector.SetPoint(minDistanceIndex,currentPos)\n pass\n\n def calculateLineModelIntersect(self, polyData, posFirst, posSecond, intersectionNode=None):\n if polyData:\n obbTree = vtk.vtkOBBTree()\n obbTree.SetDataSet(polyData)\n obbTree.BuildLocator()\n pointsVTKintersection = vtk.vtkPoints()\n hasIntersection = obbTree.IntersectWithLine(posFirst, posSecond, pointsVTKintersection, None)\n if hasIntersection>0:\n pointsVTKIntersectionData = pointsVTKintersection.GetData()\n numPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples()\n if intersectionNode:\n validPosIndex = intersectionNode.GetNumberOfFiducials()\n for idx in range(numPointsVTKIntersection):\n posTuple = pointsVTKIntersectionData.GetTuple3(idx)\n if ((posTuple[0]-posFirst[0])*(posSecond[0]-posFirst[0])>0) and abs(posTuple[0]-posFirst[0])<abs(posSecond[0]-posFirst[0]):\n # check if the intersection if within the posFist and posSecond\n intersectionNode.AddFiducial(0,0,0)\n intersectionNode.SetNthFiducialPositionFromArray(validPosIndex,posTuple)\n intersectionNode.SetNthFiducialLabel(validPosIndex,\"\")\n intersectionNode.SetNthFiducialVisibility(validPosIndex,True)\n validPosIndex = validPosIndex + 1\n return numPointsVTKIntersection\n else:\n if intersectionNode:\n numOfFiducial = intersectionNode.GetNumberOfFiducials()\n for idx in range(1, numOfFiducial):\n intersectionNode.SetNthFiducialLabel(idx,\"invalid\")\n return 0\n\n def generateCubeModelWithYawAngle(self, centerPoint, sagittalYawAngle, dimension):\n cube = vtk.vtkCubeSource()\n fullMatrix = self.calculateMatrixBasedPos(centerPoint, sagittalYawAngle, 0.0, 0.0)\n cube.SetCenter(centerPoint[0], centerPoint[1], centerPoint[2])\n cube.SetXLength(dimension[0])\n cube.SetYLength(dimension[1])\n cube.SetZLength(dimension[2])\n cube.Update()\n sagittalTransform = vtk.vtkTransform()\n sagittalTransform.SetMatrix(fullMatrix)\n sagittalTransform.Inverse()\n sagittalTransformFilter = vtk.vtkTransformPolyDataFilter()\n sagittalTransformFilter.SetTransform(sagittalTransform)\n sagittalTransformFilter.SetInputData(cube.GetOutput())\n sagittalTransformFilter.Update()\n return sagittalTransformFilter.GetOutput()\n\n def generateConeModel(self, tipPos, basePos, radius, height):\n cone = vtk.vtkConeSource()\n ventricleDirect = (basePos - tipPos) / numpy.linalg.norm(\n tipPos - basePos)\n coneTipPoint = tipPos - numpy.linalg.norm(basePos - tipPos) / 2.0 * ventricleDirect\n angle = 180.0 / math.pi * math.atan(2 * radius / numpy.linalg.norm(\n tipPos - basePos))\n coneCenter = height / 2.0 * ventricleDirect + coneTipPoint\n cone.SetHeight(height)\n cone.SetResolution(60)\n cone.SetCenter(coneCenter)\n cone.SetDirection(-1.0 * ventricleDirect) # we want the open end of the cone towards outside\n cone.SetAngle(angle)\n cone.Update()\n return cone.GetOutput()\n\n def generateCylinderModelWithTransform(self, radius, height, transform):\n cylinderTop = vtk.vtkCylinderSource()\n cylinderTop.SetCenter(numpy.array([0.0, 0.0, 0.0]))\n cylinderTop.SetRadius(radius)\n cylinderTop.SetHeight(height)\n cylinderTop.SetResolution(200)\n cylinderTop.Update()\n transformFilter = vtk.vtkTransformPolyDataFilter()\n transformFilter.SetInputConnection(cylinderTop.GetOutputPort())\n transformFilter.SetTransform(transform)\n transformFilter.ReleaseDataFlagOn()\n transformFilter.Update()\n return transformFilter.GetOutput()\n\n def calculateMatrixBasedPos(self, pos, yaw, pitch, roll):\n tempMatrix = vtk.vtkMatrix4x4()\n tempMatrix.Identity()\n tempMatrix.SetElement(0, 3, -pos[0])\n tempMatrix.SetElement(1, 3, -pos[1])\n tempMatrix.SetElement(2, 3, -pos[2])\n yawMatrix = vtk.vtkMatrix4x4()\n yawMatrix.Identity()\n yawMatrix.SetElement(0, 0, math.cos(yaw))\n yawMatrix.SetElement(0, 1, math.sin(yaw))\n yawMatrix.SetElement(1, 0, -math.sin(yaw))\n yawMatrix.SetElement(1, 1, math.cos(yaw))\n pitchMatrix = vtk.vtkMatrix4x4()\n pitchMatrix.Identity()\n pitchMatrix.SetElement(1, 1, math.cos(pitch))\n pitchMatrix.SetElement(1, 2, math.sin(pitch))\n pitchMatrix.SetElement(2, 1, -math.sin(pitch))\n pitchMatrix.SetElement(2, 2, math.cos(pitch))\n rollMatrix = vtk.vtkMatrix4x4()\n rollMatrix.Identity()\n rollMatrix.SetElement(0, 0, math.cos(roll))\n rollMatrix.SetElement(0, 2, -math.sin(roll))\n rollMatrix.SetElement(2, 0, math.sin(roll))\n rollMatrix.SetElement(2, 2, math.cos(roll))\n rollMatrix.SetElement(0, 3, pos[0])\n rollMatrix.SetElement(1, 3, pos[1])\n rollMatrix.SetElement(2, 3, pos[2])\n totalMatrix = vtk.vtkMatrix4x4()\n totalMatrix.Multiply4x4(yawMatrix, tempMatrix, totalMatrix)\n totalMatrix.Multiply4x4(pitchMatrix, totalMatrix, totalMatrix)\n totalMatrix.Multiply4x4(rollMatrix, totalMatrix, totalMatrix)\n return totalMatrix\n\n def inverseVTKImage(self, inputImageData):\n imgvtk = vtk.vtkImageData()\n imgvtk.DeepCopy(inputImageData)\n imgvtk.GetPointData().GetScalars().FillComponent(0, 1)\n subtractFilter = vtk.vtkImageMathematics()\n subtractFilter.SetInput1Data(imgvtk)\n subtractFilter.SetInput2Data(inputImageData)\n subtractFilter.SetOperationToSubtract() # performed inverse operation on the\n subtractFilter.Update()\n return subtractFilter.GetOutput()\n\n def getClosedCuttedModel(self, cutPlanes, polyData):\n clipper = vtk.vtkClipClosedSurface()\n clipper.SetClippingPlanes(cutPlanes)\n clipper.SetActivePlaneId(2)\n clipper.SetInputData(polyData)\n clipper.Update()\n cuttedPolyData = clipper.GetOutput()\n return cuttedPolyData\n" } ]
9
k7jto/programmingmb
https://github.com/k7jto/programmingmb
4274c166f5d124c0a1c9f8bfa534c8d49a6189ca
67a430c4e36beaa2cd02f7e0cc766ec822b21e15
949bdf769c768711de269cc77779dbaaddf3932f
refs/heads/master
2021-01-22T11:48:00.070745
2014-11-26T13:04:49
2014-11-26T13:04:49
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5352258086204529, "alphanum_fraction": 0.5481290221214294, "avg_line_length": 28.135337829589844, "blob_id": "3e9ce07a024930c8a684f6a9d729396c6334267a", "content_id": "6fa5c1a2dae08763ff142874842ab368117d94ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3875, "license_type": "no_license", "max_line_length": 92, "num_lines": 133, "path": "/Arduino/Calculator/Calculator.ino", "repo_name": "k7jto/programmingmb", "src_encoding": "UTF-8", "text": "// Variables for input\n// char readChar; // char buffer for input\nconst int NUMBER_OF_FIELDS = 2; // how many comma-sep fields expected\nint fieldIndex = 0; // the current field being received\nint values[NUMBER_OF_FIELDS]; // array to hold the values\n\nvoid setup() {\n Serial.begin(9600);\n Serial.println(\"Math Test\");\n Serial.println(\"Enter two numbers, separated by commas, and an operator.\");\n Serial.println(\"The first two numbers are the numbers to be operated against.\");\n Serial.println(\"The operator specifies the operation:\");\n Serial.println(\" + Addition\");\n Serial.println(\" - Subtraction\");\n Serial.println(\" x Multiplication\");\n Serial.println(\" / Division\");\n Serial.println(\"For example: 1,4+\");\n}\n\nvoid loop() {\n // Get string from user\n while (Serial.available()) {\n // Expect user to input comma-sep string of 2 numeric values terminated with an operator\n // Copied from \"Arduino Cookbook\" (Margolis, Michael. OReilly Media, Inc. 2011), p 98-99\n char readChar = Serial.read(); //gets one byte from serial buffer\n delay(5);\n \n // Read in string and make sure these are ASCII digits between 0 and 9\n if(readChar >= '0' && readChar <= '9') \n {\n // yes, accumulate the value\n values[fieldIndex] = (values[fieldIndex] * 10) + (readChar - '0');\n Serial.println(values[fieldIndex]);\n }\n // Or check if it's a comma\n else if (readChar == ',')\n {\n // Move to the next field\n if(fieldIndex < NUMBER_OF_FIELDS-1)\n {\n fieldIndex++; // increment field index\n }\n }\n else\n // Everything else terminates input\n {\n // Only do work if we have values\n if (values[0] > 0 && values[1] > 0 && readChar > 0)\n {\n // Everything has to happen here\n \n // First create variables\n // When you change to doubles, change the following 5 instances of \"int\":\n int answer = 0;\n int y = int(values[0]);\n int z = int(values[1]);\n \n // Next perform math based on the supplied operator\n switch(readChar)\n {\n case '+':\n Serial.print(\"The sum of \");\n Serial.print(values[0]);\n Serial.print(\" and \");\n Serial.print(values[1]);\n Serial.print(\" is \");\n answer = doAddition(y, z);\n break;\n case '-':\n Serial.print(\"The difference of \");\n Serial.print(values[0]);\n Serial.print(\" and \");\n Serial.print(values[1]);\n Serial.print(\" is \");\n answer = doSubtraction(y, z);\n Serial.println(answer);\n break;\n case 'x':\n Serial.print(\"The product of \");\n Serial.print(values[0]);\n Serial.print(\" and \");\n Serial.print(values[1]);\n Serial.print(\" is \");\n answer = doMultiplication(y, z);\n break;\n case '/':\n Serial.print(\"The quotient of \");\n Serial.print(values[0]);\n Serial.print(\" and \");\n Serial.print(values[1]);\n Serial.print(\" is \");\n answer = doDivision(y, z);\n break;\n }\n \n Serial.println(answer);\n delay(100);\n } // Closing if statement\n \n // Clean up\n for(int i=0; i<=fieldIndex; i++)\n {\n values[i] = 0; // set to 0 for next message\n }\n fieldIndex = 0; // ready to start over\n }\n } // close while (Serial.available)\n \n} // close loop\n\nint doAddition(int a, int b)\n{\n int sum = a + b;\n return sum;\n}\n\nint doSubtraction(int a, int b)\n{\n int difference = a - b;\n return difference;\n}\n\nint doMultiplication(int a, int b)\n{\n int product = a * b;\n return product;\n}\n\nint doDivision(int a, int b)\n{\n int quotient = a / b;\n return quotient;\n}\n" }, { "alpha_fraction": 0.5763918161392212, "alphanum_fraction": 0.6061113476753235, "avg_line_length": 22.431371688842773, "blob_id": "5b325cdfb7b2d98b4c1eca54dbc9f98bbf26ef5b", "content_id": "5bed717399b0fec697e6d255b4b8ffb18cfb9ec7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2389, "license_type": "no_license", "max_line_length": 66, "num_lines": 102, "path": "/python/python/calculator.py", "repo_name": "k7jto/programmingmb", "src_encoding": "UTF-8", "text": "# calculator with all buttons\n\n\nimport simplegui\n\n# intialize globals\nstack1 = 0\nstack2 = 0\noperator = \"\"\nwidth = 300\nheight = 300\ncalc_start = \"Not Started\"\ntemp_num = 0\n\n# event handlers for calculator with a store and operand\n\ndef output():\n \"\"\"prints contents of store and operand\"\"\"\n print \"Stack 2 = \", stack2\n print \"Stack 1 = \", stack1\n print \"\"\n \ndef swap():\n \"\"\" swap contents of store and operand\"\"\"\n global stack1, stack2\n stack1, stack2 = stack2, stack1\n output()\n\ndef state():\n global calc_start, stack1, stack2, temp_num\n if calc_start == \"Started\":\n temp_num = float(input.get_text())\n elif calc_start == \"Not Started\":\n stack1 = float(input.get_text())\n calc_start = \"Started\"\n \ndef add():\n \"\"\" add operand to store\"\"\"\n global stack1, stack2, temp_num, calc_start\n state()\n if calc_start == \"Started\":\n stack1 = stack1 + temp_num\n elif calc_start == \"RPN\":\n stack1 = stack2 + stack1\n stack2 = 0\n calc_start = \"Started\"\n output()\n\ndef sub():\n \"\"\" subtract operand from store\"\"\"\n \"\" Put your code here \"\"\n output()\n\ndef mult():\n \"\"\" multiply store by operand\"\"\"\n \"\" Put your code here \"\"\n output()\n\ndef div():\n \"\" Put your code here \"\"\n output()\n\ndef enter(t):\n \"\"\" enter a new operand\"\"\"\n global stack1, calc_start, stack2\n if calc_start == \"Not Started\":\n stack1 = float(input.get_text())\n calc_start = \"Started\"\n elif calc_start == \"Started\":\n stack2 = stack1\n stack1 = float(input.get_text())\n calc_start = \"RPN\"\n output()\n\ndef clear():\n \"\"\" clears results \"\"\"\n global stack1, stack2, calc_start\n stack1, stack2 = 0, 0\n calc_start = \"Not Started\"\n output()\n\ndef draw(canvas):\n global stack1, stack2, operator, width, height\n #expression = store + \" \" + operator + \" \" + operand + \" = \"\n\n \n# create frame\nf = simplegui.create_frame(\"Calculator\",width,height)\n\n# register event handlers and create control elements\nf.add_button(\"Print\", output, 100)\nf.add_button(\"Swap\", swap, 100)\nf.add_button(\"Add\", add, 100)\nf.add_button(\"Sub\", sub, 100)\nf.add_button(\"Mult\", mult, 100)\nf.add_button(\"Div\", div, 100)\nf.add_button(\"Clear\", clear, 100)\ninput = f.add_input(\"Type a number and press 'Enter'\", enter, 100)\n\n# get frame rolling\nf.start()\nf.set_draw_handler(draw)" }, { "alpha_fraction": 0.6612903475761414, "alphanum_fraction": 0.6612903475761414, "avg_line_length": 14.5, "blob_id": "59edf72a32f3c5f5447870825e45c6866cd17c92", "content_id": "5ed2bc8a7d5df870846e52b71c27de2fb74b38b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 62, "license_type": "no_license", "max_line_length": 32, "num_lines": 4, "path": "/README.md", "repo_name": "k7jto/programmingmb", "src_encoding": "UTF-8", "text": "programmingmb\n=============\n\nCode for Programming Merit Badge\n" }, { "alpha_fraction": 0.5816457271575928, "alphanum_fraction": 0.5879261493682861, "avg_line_length": 35.457942962646484, "blob_id": "1cfca47f8e6eaa9ef7f6256339510ce43fc2f544", "content_id": "97c4a7634f47e3b83838eaba676f43dbb222882b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7802, "license_type": "no_license", "max_line_length": 92, "num_lines": 214, "path": "/BSACalculator/BSACalculator_FINAL/app/src/main/java/org/k7jto/bsacalculator/MainActivity.java", "repo_name": "k7jto/programmingmb", "src_encoding": "UTF-8", "text": "package org.k7jto.bsacalculator;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.view.View;\nimport android.content.DialogInterface;\nimport android.app.AlertDialog;\nimport android.widget.TextView;\n\n\npublic class MainActivity extends Activity {\n\n private int operand; // switch on this int to determine which math operation\n\n // These are strings to make the refactoring activity easier\n private String numA; // Variable to store first number entered\n private String numB; // Variable to store second number entered\n private String result; // Variable to store result\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.menu_main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n // Handle action bar item clicks here. The action bar will\n // automatically handle clicks on the Home/Up button, so long\n // as you specify a parent activity in AndroidManifest.xml.\n\n\n AlertDialog.Builder alertbox = new AlertDialog.Builder(this);\n\n // set the message to display\n alertbox.setMessage(getString(R.string.app_descrip));\n\n // add a neutral button to the alert box and assign a click listener\n alertbox.setNeutralButton(\"Ok\", new DialogInterface.OnClickListener() {\n\n // click listener on the alert box\n public void onClick(DialogInterface arg0, int arg1) {\n // the button was clicked\n\n }\n });\n\n // show it\n alertbox.show();\n\n return true;\n\n\n }\n\n\n // This function takes the user's current keystroke and appends it to the\n // numeric display (EditText) at the top\n public void appendNumber(View v) {\n\n // First, we have to find the EditText from the controls on the page\n EditText myEditText = (EditText)findViewById(R.id.txtDisplay);\n\n //Next, we need to figure out WHICH button was tapped\n switch (v.getId()) {\n // \"1\" button was tapped\n case R.id.btn1: myEditText.setText(myEditText.getText() + \"1\");\n break;\n // \"2\" button was tapped\n case R.id.btn2: myEditText.setText(myEditText.getText() + \"2\");\n break;\n // \"3\" button was tapped\n case R.id.btn3: myEditText.setText(myEditText.getText() + \"3\");\n break;\n // \"4\" button was tapped\n case R.id.btn4: myEditText.setText(myEditText.getText() + \"4\");\n break;\n // \"5\" button was tapped\n case R.id.btn5: myEditText.setText(myEditText.getText() + \"5\");\n break;\n // \"6\" button was tapped\n case R.id.btn6: myEditText.setText(myEditText.getText() + \"6\");\n break;\n // \"7\" button was tapped\n case R.id.btn7: myEditText.setText(myEditText.getText() + \"7\");\n break;\n // \"8\" button was tapped\n case R.id.btn8: myEditText.setText(myEditText.getText() + \"8\");\n break;\n // \"9\" button was tapped\n case R.id.btn9: myEditText.setText(myEditText.getText() + \"9\");\n break;\n // \"0\" button was tapped\n case R.id.btn0: myEditText.setText(myEditText.getText() + \"0\");\n break;\n }\n }\n\n // If the \"C\" button is tapped, clear everything\n public void clearDisplay(View v) {\n // Have to get a 'handle' on the EditText button\n EditText myEditText = (EditText)findViewById(R.id.txtDisplay);\n myEditText.setText(\"\"); // Now set the EditText text to \"\" (empty)\n numA = \"\"; // Now set numA to empty\n numB = \"\"; // Now set numB to empty\n result = \"\"; // And set result to empty\n }\n\n\n\n // This function is called when one of the 4 operation buttons is clicked\n // (add, subtract, mutliple, divide). It clears the EditText field, sets\n // the operand, and enables the \"=\" button\n public void clickOperand(View v) {\n // Have to get a 'handle' on the EditText button\n EditText myEditText = (EditText)findViewById(R.id.txtDisplay);\n\n // In casting, it's a good idea to be careful and wrap everything in a\n // try... catch statement\n try {\n numA = myEditText.getText().toString(); // Getting text and putting it into numA\n myEditText.setText(\"\"); // Clear edit text\n\n // Now set the operand based on which button was clicked\n switch (v.getId()) {\n case R.id.btnAdd: operand = 1;\n break;\n case R.id.btnSubtract: operand = 2;\n break;\n case R.id.btnMultiply: operand = 3;\n break;\n case R.id.btnDivide: operand = 4;\n break;\n }\n\n // Now that we have numA and an operand, enable the calculate button\n Button myCalcButton = (Button) findViewById(R.id.btnCalculate);\n myCalcButton.setEnabled(true);\n }\n catch (Exception ex) {\n myEditText.setText(\"Err Parsing\");\n }\n }\n\n\n\n // What to do when the calculate button is tapped\n public void clickCalculate(View v) {\n // As always, need a 'handle' on the EditText field\n EditText myEditText = (EditText)findViewById(R.id.txtDisplay);\n k7jtoMath myk7jtoMath = new k7jtoMath();\n try {\n numB = myEditText.getText().toString(); // Get the value for numB from EditText\n\n // Now choose which math to do, based on the operand we set when the user\n // tapped an operation button\n switch (operand) {\n case 1: result = myk7jtoMath.doAddition(numA, numB);\n break;\n case 2: result = myk7jtoMath.doSubtraction(numA, numB);\n break;\n case 3: result = myk7jtoMath.doMultiplication(numA, numB);\n break;\n case 4: result = myk7jtoMath.doDivision(numA, numB);\n break;\n }\n\n myEditText.setText(result); // Now that we have a result, display it\n\n // Now reset UI\n Button myCalcButton = (Button) findViewById(R.id.btnCalculate);\n myCalcButton.setEnabled(false);\n numA = \"\";\n numB = \"\";\n result = \"\";\n }\n catch(Exception ex) {\n myEditText.setText(\"Err Parsing\");\n }\n }\n\n\n\n /* THIS IS THE ABOUT DIALOG */\n protected void showAbout(View v) {\n // Inflate the about message contents\n View messageView = getLayoutInflater().inflate(R.layout.about, null, false);\n\n // When linking text, force to always use default color. This works\n // around a pressed color state bug.\n TextView textView = (TextView) messageView.findViewById(R.id.about_credits);\n int defaultColor = textView.getTextColors().getDefaultColor();\n textView.setTextColor(defaultColor);\n\n AlertDialog.Builder builder = new AlertDialog.Builder(this);\n builder.setIcon(R.drawable.ic_launcher);\n builder.setTitle(R.string.app_name);\n builder.setView(messageView);\n builder.create();\n builder.show();\n }\n\n}\n" } ]
4
rajdeep-biswas/tag-everyone-on-facebook
https://github.com/rajdeep-biswas/tag-everyone-on-facebook
77ee7d907ad41e71768d61b39d9af514323aab42
e7a2cfd9f14432f1ea6e0f2346f702378b5f722c
b34c5c8c829a39e89f65a8d31b0d635feba424a1
refs/heads/master
2022-12-05T06:55:02.139144
2020-09-02T08:04:37
2020-09-02T08:04:37
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6647966504096985, "alphanum_fraction": 0.6647966504096985, "avg_line_length": 31.363636016845703, "blob_id": "eb116704efa8310624fb9517b51f77ebba06f083", "content_id": "f381bce1037472f7de4ffd7b44bd147153d296f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 713, "license_type": "no_license", "max_line_length": 99, "num_lines": 22, "path": "/failedrequest.py", "repo_name": "rajdeep-biswas/tag-everyone-on-facebook", "src_encoding": "UTF-8", "text": "import requests\n\npayload = {\n 'email': 'rajdeeprusted',\n 'pass': 'notmypassword'\n}\n\npage = requests.get('https://www.facebook.com/rajdeeprusted/friends')\ntree = html.fromstring(page.content)\nfriends = tree.xpath('//a/span/text()')\n\n# Use 'with' to ensure the session context is closed after use.\nwith requests.Session() as s:\n p = s.post('https://www.facebook.com', data=payload)\n # print the html returned or something more intelligent to see if it's a successful login page.\n tree = html.fromstring(p.content)\n friends = tree.xpath('//imaage/href/text()')\n print(\"Facebook\" in p.text)\n # An authorised request.\n #r = s.get('A protected web page url')\n #print r.text\n # etc...\n\n" }, { "alpha_fraction": 0.7172236442565918, "alphanum_fraction": 0.7210797071456909, "avg_line_length": 29.920000076293945, "blob_id": "18701fef46fd31cedc506476b9d3340d5ab8b22c", "content_id": "8fe43450063c7eac568d31ac0d09f4ac9f6ada44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 778, "license_type": "no_license", "max_line_length": 136, "num_lines": 25, "path": "/lister.py", "repo_name": "rajdeep-biswas/tag-everyone-on-facebook", "src_encoding": "UTF-8", "text": "# pip install selenium\n# find and install browser version specific webdrivers\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom time import sleep\nfrom lxml import html\n\ndriver = webdriver.Chrome(executable_path='..\\chromedriver.exe')\n\nsleep(3)\ncount = 1\n\ndriver.get(\"https://www.facebook.com\")\ninput(\"log in to your account from the browser window (you might need to enable cookies and then type something and press enter here: \")\n\n\nwhile False:\n \n st = \"faggot\" + str(count)\n driver.find_element(By.XPATH, '//div[@aria-label=\"Write a comment...\"]').send_keys(st)\n driver.find_element(By.XPATH, '//div[@aria-label=\"Write a comment...\"]').send_keys(Keys.RETURN) \n\n count += 1\n \n" } ]
2
pekrau/BeerClub
https://github.com/pekrau/BeerClub
4c2b0abf71404a748d7b84c66d93e7c5b4f06f14
fde9a69189a079ce3b4e16636db738fe462579c8
25f9ff775d8aea21a778b05052eb1ea4238256a7
refs/heads/master
2021-08-17T16:25:26.134906
2021-06-10T18:39:41
2021-06-10T18:39:41
152,759,152
3
2
null
2018-10-12T14:02:46
2021-06-02T10:28:52
2021-06-02T10:28:49
Python
[ { "alpha_fraction": 0.6830986142158508, "alphanum_fraction": 0.6830986142158508, "avg_line_length": 24.81818199157715, "blob_id": "2513b112d4ed7722c167fc2658256a961262873c", "content_id": "118f59aad50eb47aeba0c5c2654055237f86bcc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1136, "license_type": "no_license", "max_line_length": 79, "num_lines": 44, "path": "/beerclub/constants.py", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "\"Various constants.\"\n\nBEERCLUB = 'beerclub'\n\n# CouchDB\n# For view ranges: CouchDB uses the Unicode Collation Algorithm,\n# which is not the same as the ASCII collation sequence.\n# The endkey is inclusive, by default.\nCEILING = 'ZZZZZZZZ'\n\n# Entity documents\nDOCTYPE = 'beerclub_doctype'\nMEMBER = 'member'\nEVENT = 'event'\nSNAPSHOT = 'snapshot'\nENTITIES = (MEMBER, EVENT, SNAPSHOT)\n\n# Member status\nPENDING = 'pending'\nENABLED = 'enabled'\nDISABLED = 'disabled'\nSTATUSES = (PENDING, ENABLED, DISABLED)\n\n# Member roles\nADMIN = 'admin'\nMEMBER = 'member'\nROLES = (ADMIN, MEMBER)\n\n# Event actions\nTRANSFER = 'transfer' # Bank account transfer into Beer Club account.\nPURCHASE = 'purchase' # Purchase of beer for the Beer Club.\nPAYMENT = 'payment' # Paying for beer from the Beer Club.\nCASH = 'cash' # Cash transfer into Beer Club acount.\n\n# Payment identifier (hardwired)\nEXPENDITURE = 'expenditure'\n\n# Misc\nCORRECTION = '__correction__'\nUSER_COOKIE = 'beerclub_user'\nEMAIL_PATTERN = '*@*.*'\nAPI_KEY_HEADER = 'X-BeerClub-API-key'\nJSON_MIME = 'application/json'\nCSV_MIME = 'text/csv'\n" }, { "alpha_fraction": 0.727213978767395, "alphanum_fraction": 0.7485455870628357, "avg_line_length": 23.55555534362793, "blob_id": "11b731bfab705f4c6016b1f3dd9c87f0513c3676", "content_id": "acc990959fd40e469c395be90f1255ad859946e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1547, "license_type": "no_license", "max_line_length": 81, "num_lines": 63, "path": "/README.md", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "# BeerClub\n\nA web application to keep track of the beer accounts for registered members.\n\n## Development\n\nThe contribution model is to fork the main repository and submit pull requests.\n\nTo test changes, please deploy the website locally.\n\n## Local Deployment\n\nIt's recommended to use conda to keep the installation environment clean.\n\nFirst, create a new environment and install the dependencies:\n\n```bash\nconda create --name BeerClub --yes python=3.6.8\nconda activate BeerClub\npip install -r requirements.txt\n```\n\nNext, make a new `settings.json` file based on the template:\n\n```bash\ncd beerclub\ncp template_settings.json settings.json\n```\n\nThe BeerClub site uses CouchDB to store data.\nYou can install this locally if you want, or use Docker:\n\n```bash\ndocker run -p 5984:5984 -d couchdb\n```\n\nOnce the docker image is running, go to http://127.0.0.1:5984/_utils/#/setup\nand add a user with a password. Then create a new database.\nThe `template_settings.json` file contains the following defaults\n(obviously for local testing only!):\n\n```json\n\"DATABASE_ACCOUNT\": \"admin\",\n\"DATABASE_PASSWORD\": \"admin\",\n\"DATABASE_SERVER\": \"http://0.0.0.0:5984/\",\n\"DATABASE_NAME\": \"beerclub\",\n\"DATABASE_PASSWORD\": \"beerclub\",\n```\n\nThe BeerClub site needs to have it's directory added to the `PYTHONPATH` to work,\nso from the repository root directory run the following:\n\n```bash\nexport PYTHONPATH=$PWD:$PYTHONPATH\n```\n\nFinally, run the tornado web server:\n\n```bash\npython app_beerclub.py\n```\n\nThe BeerClub website should now be running at http://localhost:8888/\n" }, { "alpha_fraction": 0.5846154093742371, "alphanum_fraction": 0.5938461422920227, "avg_line_length": 20.66666603088379, "blob_id": "ba093a83f6b49c72551820e5ae38d9e756943472", "content_id": "5bf950bfe9d51224e3e811e56f07bfcfb8b0122e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 325, "license_type": "no_license", "max_line_length": 48, "num_lines": 15, "path": "/beerclub/html/register.html", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "{# Page for admin to register a member. #}\n\n{% extends 'base.html' %}\n\n{% block head_title %}Register a member{% end %}\n\n{% block body_title %}Register a member{% end %}\n\n{% block content %}\n<div class=\"row mt-3\">\n <div class=\"col-md-10\">\n {% include 'register_form.html' %}\n </div>\n</div>\n{% end %} {# block content #}\n" }, { "alpha_fraction": 0.6057233810424805, "alphanum_fraction": 0.6100386381149292, "avg_line_length": 32.739463806152344, "blob_id": "73ed7947c4c7177946f9cd5dee2ab95895cd24e4", "content_id": "e344da2e445b496e78f06da2b6f04d35bb8bd7ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8806, "license_type": "no_license", "max_line_length": 107, "num_lines": 261, "path": "/beerclub/utils.py", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "\"Various supporting functions.\"\n\nimport datetime\nimport email.mime.text\nimport hashlib\nimport json\nimport logging\nimport os\nimport smtplib\nimport string\nimport sys\nimport time\nimport urllib # formerly: urlparse\nimport uuid\n\nimport couchdb\n\nimport beerclub\nfrom beerclub import constants\nfrom beerclub import designs\nfrom beerclub import settings\n\n\ndef setup():\n \"Setup: read settings, set logging.\"\n with open(os.path.join(settings['ROOT_DIR'], 'settings.json')) as infile:\n site = json.load(infile)\n settings.update(site)\n # Set up logging\n if settings.get('LOGGING_DEBUG'):\n kwargs = dict(level=logging.DEBUG)\n else:\n kwargs = dict(level=logging.INFO)\n try:\n kwargs['format'] = settings['LOGGING_FORMAT']\n except KeyError:\n pass\n try:\n filepath = settings['LOGGING_FILEPATH']\n if not filepath: raise KeyError\n kwargs['filename'] = filepath\n except KeyError:\n pass\n try:\n filemode = settings['LOGGING_FILEMODE']\n if not filemode: raise KeyError\n kwargs['filemode'] = filemode\n except KeyError:\n pass\n logging.basicConfig(**kwargs)\n logging.info(\"BeerClub version %s\", beerclub.__version__)\n logging.info(\"ROOT_DIR: %s\", settings['ROOT_DIR'])\n logging.info(\"logging debug: %s\", settings['LOGGING_DEBUG'])\n # Check required settings\n if not settings['COOKIE_SECRET']:\n logging.error('variable COOKIE_SECRET not set')\n sys.exit(1)\n if not settings['PASSWORD_SALT']:\n logging.error('variable PASSWORD_SALT not set')\n sys.exit(1)\n if not settings['EMAIL']['HOST']:\n logging.error(\"email host EMAIL['HOST'] not defined\")\n sys.exit(1)\n # Compute settings\n if not settings.get('PORT'):\n parts = urllib.parse.urlparse(settings['BASE_URL'])\n settings['PORT'] = parts.port or 80\n settings['MONEY_DECIMAL_STEP'] = 10**(-settings['MONEY_DECIMAL_PLACES'])\n # Convert format specifiers in statements.\n settings['POLICY_STATEMENT'] = settings['POLICY_STATEMENT'].format(**settings)\n settings['PRIVACY_STATEMENT'] = settings['PRIVACY_STATEMENT'].format(**settings)\n\ndef get_dbserver():\n \"Get the server connection, with credentials if any.\"\n server = couchdb.Server(settings['DATABASE_SERVER'])\n if settings.get('DATABASE_ACCOUNT') and settings.get('DATABASE_PASSWORD'):\n server.resource.credentials = (settings.get('DATABASE_ACCOUNT'),\n settings.get('DATABASE_PASSWORD'))\n return server\n\ndef get_db():\n \"Return the handle for the CouchDB database.\"\n server = get_dbserver()\n try:\n return server[settings['DATABASE_NAME']]\n except couchdb.http.ResourceNotFound:\n raise couchdb.http.ResourceNotFound(\"CouchDB database '%s' does not exist.\" %\n settings.get('DATABASE_NAME'))\n except couchdb.http.Unauthorized:\n raise couchdb.http.Unauthorized(\"CouchDB account '%s' is not authorized to access database '%s'.\" %\n (settings.get('DATABASE_ACCOUNT'), settings.get('DATABASE_NAME')))\n\ndef initialize(db=None):\n \"Load the design documents, or update.\"\n if db is None:\n db = get_db()\n designs.load_design_documents(db)\n\ndef get_doc(db, key, viewname=None):\n \"\"\"Get the document with the given id, or from the given view.\n Raise KeyError if not found.\n \"\"\"\n if viewname is None:\n try:\n return db[key]\n except couchdb.http.ResourceNotFound:\n raise KeyError\n else:\n view = db.view(viewname, include_docs=True, reduce=False)\n result = list(view[str(key)])\n if len(result) != 1:\n raise KeyError(\"%i items found\", len(result))\n return result[0].doc\n\ndef get_docs(db, viewname, key=None, last=None, **kwargs):\n \"\"\"Get the list of documents using the named view and\n the given key or interval.\n \"\"\"\n view = db.view(viewname, include_docs=True, reduce=False, **kwargs)\n if key is None:\n iterator = view\n elif last is None:\n iterator = view[key]\n else:\n iterator = view[key:last]\n return [i.doc for i in iterator]\n\ndef get_member(db, email):\n \"\"\"Get the member identified by the email address.\n If Swish is enabled, then also check if 'email' is\n a Swish number, which must match exactly.\n Raise KeyError if no such member.\n \"\"\"\n email = email.strip().lower()\n try:\n return get_doc(db, email, 'member/email')\n except KeyError:\n if settings['MEMBER_SWISH']:\n try:\n return get_doc(db, email, 'member/swish')\n except KeyError:\n pass\n raise KeyError(\"no such member %s\" % email)\n\ndef get_balances(db, members):\n \"Get and set the balances for all input members.\"\n # Prepare lookup of all input members.\n lookup = {}\n for member in members:\n lookup[member['email']] = member\n # Default balance is zero\n member['balance'] = 0.0\n # Simple but effective: get all balances in one go.\n view = db.view('event/credit', group_level=1, reduce=True)\n for row in view:\n try:\n lookup[row.key]['balance'] = row.value\n except KeyError:\n pass\n\ndef get_latest_events(db, members):\n \"Get and set the latest event for all input members.\"\n for member in members:\n events = get_docs(db, 'event/member', \n key=[member['email'], constants.CEILING],\n last=[member['email'], ''],\n descending=True,\n limit=1)\n if events:\n member['latest_event'] = events[0]\n else:\n member['latest_event'] = None\n\ndef get_iuid():\n \"Return a unique instance identifier.\"\n return uuid.uuid4().hex\n\ndef hashed_password(password):\n \"Return the password in hashed form.\"\n sha256 = hashlib.sha256(settings['PASSWORD_SALT'].encode('utf-8'))\n sha256.update(password.encode('utf-8'))\n return sha256.hexdigest()\n\ndef check_password(password):\n \"\"\"Check that the password is long and complex enough.\n Raise ValueError otherwise.\"\"\"\n if len(password) < settings['MIN_PASSWORD_LENGTH']:\n raise ValueError(\"Password must be at least {0} characters.\".\n format(settings['MIN_PASSWORD_LENGTH']))\n\ndef timestamp(days=None):\n \"\"\"Current date and time (UTC) in ISO format, with millisecond precision.\n Add the specified offset in days, if given.\n \"\"\"\n instant = datetime.datetime.utcnow()\n if days:\n instant += datetime.timedelta(days=days)\n instant = instant.isoformat()\n return instant[:17] + \"%06.3f\" % float(instant[17:]) + \"Z\"\n\ndef today(days=None):\n \"\"\"Current date (UTC) in ISO format.\n Add the specified offset in number of days, if given.\n \"\"\"\n instant = datetime.datetime.utcnow()\n if days:\n instant += datetime.timedelta(days=days)\n result = instant.isoformat()\n return result[:result.index('T')]\n\ndef normalize_swish(value):\n \"Return normalized Swish phone number. Get rid of all non-digits.\"\n return ''.join([c for c in value if c in string.digits])\n\ndef timeit(label):\n logging.debug(\"%f %f %s\", time.clock(), time.time(), label)\n\n\nclass EmailServer(object):\n \"A connection to an email server for sending emails.\"\n\n def __init__(self):\n \"\"\"Open the connection to the email server.\n Raise ValueError if no email server host has been defined.\n \"\"\"\n host = settings['EMAIL']['HOST']\n if not host:\n raise ValueError('no email server host defined')\n try:\n port = settings['EMAIL']['PORT']\n except KeyError:\n self.server = smtplib.SMTP(host)\n else:\n self.server = smtplib.SMTP(host, port=port)\n if settings['EMAIL'].get('TLS'):\n self.server.starttls()\n try:\n user = settings['EMAIL']['USER']\n password = settings['EMAIL']['PASSWORD']\n except KeyError:\n pass\n else:\n self.server.login(user, password)\n\n def __del__(self):\n \"Close the connection to the email server.\"\n try:\n self.server.quit()\n except AttributeError:\n pass\n\n def send(self, recipient, subject, text):\n \"Send an email.\"\n mail = email.mime.text.MIMEText(text, 'plain', 'utf-8')\n mail['Subject'] = subject\n mail['From'] = settings['EMAIL']['SENDER']\n mail['To'] = recipient\n self.server.sendmail(settings['EMAIL']['SENDER'],\n [recipient],\n mail.as_string())\n logging.debug(\"Sent email to %s\", recipient)\n" }, { "alpha_fraction": 0.5711365342140198, "alphanum_fraction": 0.5744072198867798, "avg_line_length": 31.613332748413086, "blob_id": "1b217a515abb5ffcb3566722b7e5cb27974bdbfd", "content_id": "d010bcfcd728be9e70e57ca4d5e4f08d21d20907", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2446, "license_type": "no_license", "max_line_length": 79, "num_lines": 75, "path": "/beerclub/dump.py", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "\"\"\"Dump the database into a tar.gz file.\n\nBy default, the dump file will be called 'dump_{ISO date}.tar.gz'\nusing today's date.\n\"\"\"\n\nimport argparse\nimport io\nimport json\nimport logging\nimport os\nimport sys\nimport tarfile\nimport time\n\nfrom beerclub import constants\nfrom beerclub import utils\n\n\ndef dump(db, filepath):\n \"\"\"Dump contents of the database to a tar file, optionally gzip compressed.\n Skip any entity that does not contain a doctype field.\n \"\"\"\n count_items = 0\n count_files = 0\n if filepath.endswith('.gz'):\n mode = 'w:gz'\n else:\n mode = 'w'\n outfile = tarfile.open(filepath, mode=mode)\n for key in db:\n doc = db[key]\n # Only documents that explicitly belong to the application.\n if doc.get(constants.DOCTYPE) is None: continue\n del doc['_rev']\n info = tarfile.TarInfo(doc['_id'])\n data = json.dumps(doc)\n info.size = len(data)\n outfile.addfile(info, io.BytesIO(data.encode('utf-8')))\n count_items += 1\n for attname in doc.get('_attachments', dict()):\n info = tarfile.TarInfo(\"{0}_att/{1}\".format(doc['_id'], attname))\n attfile = db.get_attachment(doc, attname)\n if attfile is None:\n data = ''\n else:\n data = attfile.read()\n attfile.close()\n info.size = len(data)\n outfile.addfile(info, io.BytesIO(data))\n count_files += 1\n outfile.close()\n logging.info(\"dumped %s items and %s files to %s\",\n count_items, count_files, filepath)\n\n\nif __name__ == '__main__':\n utils.setup()\n utils.initialize()\n parser = argparse.ArgumentParser(description='Write dump of database.')\n parser.add_argument('-d', '--dumpfile', metavar='FILE',\n action='store', dest='dumpfile',\n help='The full path of the dump file.')\n parser.add_argument('-D', '--dumpdir', metavar='DIR',\n action='store', dest='dumpdir',\n help='The directory to write the dump file'\n ' (with standard name) in.')\n args = parser.parse_args()\n if args.dumpfile:\n filepath = args.dumpfile\n else:\n filepath = \"dump_{0}.tar.gz\".format(time.strftime(\"%Y-%m-%d\"))\n if args.dumpdir:\n filepath = os.path.join(args.dumpdir, filepath)\n dump(utils.get_db(), filepath)\n" }, { "alpha_fraction": 0.5870041847229004, "alphanum_fraction": 0.591189980506897, "avg_line_length": 37.89147186279297, "blob_id": "47c6840e14003195bbd48dff2f60a565a67a7757", "content_id": "23fadc696a118519ee93d01e56f951431fe6bc42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 5017, "license_type": "no_license", "max_line_length": 83, "num_lines": 129, "path": "/beerclub/html/register_form.html", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "{# Form part of register page. #}\n\n<form action=\"{{ reverse_url('register') }}\"\n role=\"form\"\n method=\"POST\">\n {% module xsrf_form_html() %}\n <div class=\"row form-group\">\n <label for=\"emailRegister\" class=\"col-md-2 col-form-label\">Email</label>\n <div class=\"col-md-10\">\n <input type=\"email\" class=\"form-control\" required\n name=\"email\" id=\"emailRegister\"\n aria-describedby=\"emailRegisterHelp\">\n <small id=\"emailRegisterHelp\" class=\"form-text text-muted\">\n Your email address. This is your member account identifier.\n <strong class=\"text-danger\">Required.</strong>\n <br>\n {% if settings['MEMBER_EMAIL_AUTOENABLE'] %}\n If it matches the pattern\n <code>{{ settings['MEMBER_EMAIL_AUTOENABLE'] }}</code>\n your member account will be enabled directly.\n <br>\n Otherwise, the {{ settings['SITE_NAME'] }} administrator\n will enable your member account after inspection.\n {% else %}\n The {{ settings['SITE_NAME'] }} administrator will enable\n your member account after inspection.\n {% end %}\n </small>\n </div>\n </div>\n <div class=\"row form-group\">\n <label for=\"first_name\" class=\"col-md-2 col-form-label\">\n First name</label>\n <div class=\"col-md-10\">\n <input type=\"text\" class=\"form-control\" required\n name=\"first_name\" id=\"first_name\"\n aria-describedby=\"first_nameHelp\">\n <small id=\"first_nameHelp\" class=\"form-text text-muted\">\n Your given name.\n <strong class=\"text-danger\">Required.</strong>\n </small>\n </div>\n </div>\n <div class=\"row form-group\">\n <label for=\"last_name\" class=\"col-md-2 col-form-label\">Last name</label>\n <div class=\"col-md-10\">\n <input type=\"text\" class=\"form-control\" required\n name=\"last_name\" id=\"last_name\"\n aria-describedby=\"last_nameHelp\">\n <small id=\"last_nameHelp\" class=\"form-text text-muted\">\n Your family name.\n <strong class=\"text-danger\">Required.</strong>\n </small>\n </div>\n </div>\n {% if settings['MEMBER_SWISH'] %}\n <div class=\"row form-group\">\n <label for=\"swish\" class=\"col-md-2 col-form-label\">Swish</label>\n <div class=\"col-md-10\">\n <input type=\"text\" class=\"form-control\"\n name=\"swish\" id=\"swish\"\n aria-describedby=\"swishHelp\">\n <small id=\"swishHelp\" class=\"form-text text-muted\">\n Your Swish phone number.\n </small>\n </div>\n </div>\n {% if not settings['GLOBAL_SWISH_LAZY'] %}\n <div class=\"row form-group\">\n <label class=\"col-md-2 col-form-label\">Swish mode</label>\n <div class=\"col-md-10\">\n <div class=\"form-check\">\n <input class=\"form-check-input\" type=\"radio\"\n name=\"swish_lazy\" id=\"swish_lazy_true\" value=\"true\"\n {{ settings['DEFAULT_MEMBER_SWISH_LAZY'] and 'checked' or '' }}>\n <label class=\"form-check-label\" for=\"swish_lazy_true\">\n <strong>Swish lazy</strong> mode.\n Every Swish payment implies a corresponding purchase.\n You must not record purchases separately in this app.\n </label>\n </div>\n <div class=\"form-check\">\n <input class=\"form-check-input\" type=\"radio\"\n name=\"swish_lazy\" id=\"swish_lazy_false\" value=\"false\"\n {{ not settings['DEFAULT_MEMBER_SWISH_LAZY'] and 'checked' or '' }}>\n <label class=\"form-check-label\" for=\"swish_mode_false\">\n You will always record purchases in this app.\n Every Swish payment will go towards reducing your debt.\n </label>\n </div>\n <small id=\"swishmodeHelp\" class=\"form-text text-muted\">\n The <strong>Swish lazy</strong> mode implies that you cannot\n reduce your debt by Swish payment.\n </small>\n </div>\n </div>\n {% end %} {# if not settings['GLOBAL_SWISH_LAZY'] #}\n {% end %} {# if settings['MEMBER_SWISH'] #}\n {% if settings['MEMBER_ADDRESS'] %}\n <div class=\"row form-group\">\n <label for=\"address\" class=\"col-md-2 col-form-label\">Address</label>\n <div class=\"col-md-10\">\n <input type=\"text\" class=\"form-control\"\n name=\"address\" id=\"address\"\n aria-describedby=\"addressHelp\">\n <small id=\"addressHelp\" class=\"form-text text-muted\">\n Your address (floor, building, affiliation, etc).\n </small>\n </div>\n </div>\n {% end %}\n <div class=\"row form-group\">\n <div class=\"col-md-2\"></div>\n <div class=\"col-md-10\">\n <button type=\"submit\" class=\"btn btn-secondary\"\n aria-describedby=\"registerHelp\">Register</button>\n <small id=\"registerHelp\" class=\"form-text text-muted\">\n <p>\n By registering, you promise to follow the rules for the {{\n settings['SITE_NAME'] }}. See below.\n </p>\n <p>\n When your member account has been enabled, you will receive\n an email with a unique link to set your password.\n </p>\n </small>\n </div>\n </div>\n</form>\n" }, { "alpha_fraction": 0.5380092263221741, "alphanum_fraction": 0.5438891053199768, "avg_line_length": 33.50724792480469, "blob_id": "4208bd3066855a23d491cf7cd4247b9d8ae039a8", "content_id": "172912a955641c344b88acd5deb615ef272de3a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2381, "license_type": "no_license", "max_line_length": 84, "num_lines": 69, "path": "/beerclub/html/expenditure.html", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "{# Expenditure page. #}\n\n{% extends 'base.html' %}\n\n{% block head_title %}Expenditure{% end %}\n\n{% block body_title %}Expenditure{% end %}\n\n{% block content %}\n<div class=\"row\">\n <div class=\"col-md-8\">\n Record of a balance-changing event for the central\n {{ settings['SITE_NAME'] }} account.\n </div>\n <div class=\"col-md\">\n <a href=\"{{ reverse_url('ledger') }}\"\n role=\"button\" class=\"btn btn-secondary w-100\">Cancel</a>\n </div>\n</div>\n<div class=\"card mt-2\">\n <div class=\"card-body\">\n <form action=\"{{ reverse_url('expenditure') }}\"\n role=\"form\"\n method=\"POST\">\n {% module xsrf_form_html() %}\n <div class=\"row form-group\">\n <label for=\"amount\" class=\"col-md-2 col-form-label\">Amount</label>\n <div class=\"col-md-4\">\n <input type=\"number\" step=\"{{ settings['MONEY_DECIMAL_STEP'] }}\"\n class=\"form-control\" name=\"amount\" id=\"amount\"\n aria-describedby=\"amountHelp\" required>\n <small id=\"amountHelp\" class=\"form-text text-muted\">\n The amount expended, in {{ settings['CURRENCY'] }}.\n </small>\n </div>\n </div>\n <div class=\"row form-group\">\n <label for=\"date\" class=\"col-md-2 col-form-label\">Date</label>\n <div class=\"col-md-4\">\n <input type=\"text\" class=\"form-control datepicker\"\n name=\"date\" id=\"date\"\n aria-describedby=\"dateHelp\"\n value=\"{% module Date() %}\">\n <small id=\"dateHelp\" class=\"form-text text-muted\">\n The date of the expenditure.\n </small>\n </div>\n </div>\n <div class=\"row form-group\">\n <label for=\"description\" class=\"col-md-2 col-form-label\">Description</label>\n <div class=\"col-md-8\">\n <textarea class=\"form-control\"\n name=\"description\" id=\"description\"\n aria-describedby=\"descriptionHelp\"></textarea>\n <small id=\"descriptionHelp\" class=\"form-text text-muted\">\n Description of the expenditure: Who obtained what?\n </small>\n </div>\n </div>\n <div class=\"row form-group\">\n <div class=\"col-md-2\"></div>\n <div class=\"col-md-10\">\n <button type=\"submit\" class=\"btn btn-warning\">Expend</button>\n </div>\n </div>\n </form>\n </div>\n</div>\n{% end %} {# block content #}\n" }, { "alpha_fraction": 0.6094129085540771, "alphanum_fraction": 0.6142649054527283, "avg_line_length": 33.93220520019531, "blob_id": "e6826e0e57821e971a779c1288ebe67b587d71ac", "content_id": "3908eb562695b475fd078c6886717537762acf44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2061, "license_type": "no_license", "max_line_length": 79, "num_lines": 59, "path": "/beerclub/undump.py", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "\"\"\"Load a dump tar file into the CouchDB database.\n\nThe file to load must be given as a command line argument.\n\nNOTE: The dabase instance must exist, and should be empty. If it is not\nempty, this script may overwrite existing documents.\n\"\"\"\n\nimport argparse\nimport json\nimport os\nimport tarfile\nimport time\n\nfrom beerclub import utils\n\n\ndef undump(db, filepath):\n \"\"\"Reverse of dump; load all items from a tar file.\n NOTE: Items are just added to the database. Any existing data may\n be overwritten. Should only be used with an empty database.\n \"\"\"\n count_items = 0\n count_files = 0\n attachments = dict()\n infile = tarfile.open(filepath, mode='r')\n for item in infile:\n itemfile = infile.extractfile(item)\n itemdata = itemfile.read()\n itemfile.close()\n if item.name in attachments:\n # This relies on an attachment being after its item in the tarfile.\n db.put_attachment(doc, itemdata, **attachments.pop(item.name))\n count_files += 1\n else:\n doc = json.loads(itemdata)\n atts = doc.pop('_attachments', dict())\n db.save(doc)\n count_items += 1\n for attname, attinfo in atts.items():\n key = \"{0}_att/{1}\".format(doc['_id'], attname)\n attachments[key] = dict(filename=attname,\n content_type=attinfo['content_type'])\n if count_items % 100 == 0:\n print(count_items, 'items loaded...')\n infile.close()\n # This will be executed on the command line, so output to console, not log.\n print('undumped', count_items, 'items and', \n count_files, 'files from', filepath)\n\n\nif __name__ == '__main__':\n utils.setup()\n utils.initialize()\n parser = argparse.ArgumentParser(description='Load dump into database.')\n parser.add_argument('dumpfile', metavar='FILE', type=str,\n help='Dump file to load into the database.')\n args = parser.parse_args()\n undump(utils.get_db(), args.dumpfile)\n" }, { "alpha_fraction": 0.48755311965942383, "alphanum_fraction": 0.4899817705154419, "avg_line_length": 26.450000762939453, "blob_id": "a1ddf3205cc0574d405bc8fb17f08eb65b420b5f", "content_id": "ee78e28e93b68b8698fb292987e76293ec2bd8dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1647, "license_type": "no_license", "max_line_length": 73, "num_lines": 60, "path": "/beerclub/html/activity.html", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "{# Page for members having made credit-affecting purchases recently. #}\n\n{% extends 'base.html' %}\n\n{% block head_title %}Active members{% end %}\n\n{% block body_title %}\nActive members\n<small>in the last {{ settings['DISPLAY_ACTIVITY_DAYS'] }} days</small>\n{% end %}\n\n{% block content %}\n<div class=\"row my-4\">\n <div class=\"col-md\">\n <table id=\"members\" class=\"table table-sm\">\n <thead>\n <th scope=\"col\"></th>\n <th scope=\"col\">Member</th>\n <th scope=\"col\">First name</th>\n <th scope=\"col\">Last name</th>\n <th scope=\"col\">Balance ({{ settings['CURRENCY'] }})</th>\n <th scope=\"col\">Activity</th>\n </thead>\n <tbody>\n {% for member in members %}\n <tr>\n <td>\n <a href=\"{{ reverse_url('payment', member['email']) }}\">\n <span class=\"badge badge-warning\">Payment</span>\n </a>\n </td>\n <td>\n <a href=\"{{ reverse_url('account', member['email']) }}\">\n {{ member['email'] }}</a>\n </td>\n <td>{{ member['first_name'] }}</td>\n <td>{{ member['last_name'] }}</td>\n <td>{% module Money(member['balance'], currency=False) %}</td>\n <td>\n <span class=\"localtime small\">{{ member['activity'] }}</span>\n </td>\n </tr>\n {% end %}\n </tbody>\n </table>\n </div>\n</div>\n{% end %} {# block content #}\n\n{% block javascript %}\n<script>\n $(function() {\n $(\"#members\").DataTable( {\n \"pagingType\": \"full_numbers\",\n \"pageLength\": 25,\n \"order\": [[ 5, \"desc\"]],\n });\n });\n</script>\n{% end %} {# block javascript #}\n" }, { "alpha_fraction": 0.5440356731414795, "alphanum_fraction": 0.544593095779419, "avg_line_length": 32.849056243896484, "blob_id": "848c54f24b4aed85b97223f9274e96e6ec47eb8b", "content_id": "83e75754143c3cb43a8aeca129ec6e71b284e18e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1794, "license_type": "no_license", "max_line_length": 66, "num_lines": 53, "path": "/beerclub/standalone/email_server.py", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "\"Email server connection.\"\n\nimport email.mime.text\nimport smtplib\n\n\nclass EmailServer(object):\n \"A connection to an email server for sending emails.\"\n\n def __init__(self, settings):\n \"\"\"Open the connection to the email server.\n Raise ValueError if no email server host has been defined.\n \"\"\"\n assert settings.get('EMAIL')\n assert settings['EMAIL'].get('SENDER')\n self.settings = settings\n host = settings['EMAIL'].get('HOST')\n if not host:\n raise ValueError('no email server host defined')\n try:\n port = settings['EMAIL']['PORT']\n except KeyError:\n self.server = smtplib.SMTP(host)\n else:\n self.server = smtplib.SMTP(host, port=port)\n if settings['EMAIL'].get('TLS'):\n self.server.starttls()\n try:\n user = settings['EMAIL']['USER']\n password = settings['EMAIL']['PASSWORD']\n except KeyError:\n pass\n else:\n self.server.login(user, password)\n\n def send(self, recipient, subject, text):\n \"Send an email to a single recipient.\"\n mail = email.mime.text.MIMEText(text, 'plain', 'utf-8')\n mail['Subject'] = subject\n mail['From'] = self.settings['EMAIL']['SENDER']\n mail['To'] = recipient\n self.server.sendmail(self.settings['EMAIL']['SENDER'],\n [recipient],\n mail.as_string())\n\nif __name__ == '__main__':\n import json\n server = EmailServer(json.load(open('email_settings.json')))\n for recipient in ['Per Kraulis <[email protected]>',\n 'Per Kraulis <[email protected]>']:\n server.send(recipient,\n 'testing email',\n 'testing email sender script')\n" }, { "alpha_fraction": 0.5615079402923584, "alphanum_fraction": 0.5625, "avg_line_length": 31.780487060546875, "blob_id": "df7f3b3d3ce62641e27f3171e8ce8b4e972cbd0b", "content_id": "a9f22183e9171c5e6c42a62a9b1438fcddef9719", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4032, "license_type": "no_license", "max_line_length": 79, "num_lines": 123, "path": "/beerclub/home.py", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "\"Home page, and misc others.\"\n\nimport csv\nfrom io import StringIO\nimport logging\n\nimport tornado.web\n\nfrom beerclub import constants\nfrom beerclub import settings\nfrom beerclub import utils\nfrom beerclub.requesthandler import RequestHandler\n\n\nclass Home(RequestHandler):\n \"Home page; login or payment and member info.\"\n\n def get(self):\n if self.current_user:\n self.current_user['balance'] = self.get_balance(self.current_user)\n self.current_user['count'] = self.get_count(self.current_user)\n self.render('home_member.html')\n else:\n self.render('home_login.html')\n\n\nclass Snapshots(RequestHandler):\n \"Display snapshots table.\"\n\n @tornado.web.authenticated\n def get(self):\n self.check_admin()\n try:\n from_ = self.get_argument('from')\n except tornado.web.MissingArgumentError:\n from_ = utils.today(-settings['DISPLAY_SNAPSHOT_DAYS'])\n try:\n to = self.get_argument('to')\n except tornado.web.MissingArgumentError:\n to = utils.today()\n if from_ > to:\n to = from_\n snapshots = self.get_docs('snapshot/date',\n key=from_,\n last=to+constants.CEILING)\n self.render('snapshots.html',\n snapshots=snapshots,\n from_=from_,\n to=to)\n\n\nclass SnapshotsCsv(Snapshots):\n \"Output CSV for snapshots data.\"\n\n def render(self, template, snapshots, from_, to):\n csvbuffer = StringIO()\n writer = csv.writer(csvbuffer)\n row = ['Date',\n 'BeerClub',\n 'members',\n 'surplus']\n row.extend(constants.STATUSES)\n writer.writerow(row)\n for snapshot in snapshots:\n row = [snapshot['date'],\n snapshot['beerclub_balance'],\n snapshot['members_balance'],\n snapshot['beerclub_balance'] - snapshot['members_balance']]\n for status in constants.STATUSES:\n row.append(snapshot['member_counts'][status])\n writer.writerow(row)\n self.write(csvbuffer.getvalue())\n self.set_header('Content-Type', constants.CSV_MIME)\n filename = \"snapshots_%s_%s.csv\" % (from_, to)\n self.set_header('Content-Disposition', \n 'attachment; filename=\"%s\"' % filename)\n\n\nclass Dashboard(RequestHandler):\n \"Dashboard display of various interesting data.\"\n\n @tornado.web.authenticated\n def get(self):\n self.check_admin()\n try:\n from_ = self.get_argument('from')\n except tornado.web.MissingArgumentError:\n from_ = utils.today(-settings['DISPLAY_SNAPSHOT_DAYS'])\n try:\n to = self.get_argument('to')\n except tornado.web.MissingArgumentError:\n to = utils.today()\n if from_ > to:\n to = from_\n self.render('dashboard.html',\n beerclub_balance=self.get_beerclub_balance(),\n members_balance=self.get_balance(),\n from_=from_,\n to=to)\n\n\nclass BalanceCsv(Snapshots):\n \"Output CSV for snapshots balance data.\"\n\n def render(self, template, snapshots, from_, to):\n csvbuffer = StringIO()\n writer = csv.writer(csvbuffer)\n row = ['date',\n 'amount',\n 'type']\n row.extend(constants.STATUSES)\n writer.writerow(row)\n for snapshot in snapshots:\n row = [snapshot['date'], snapshot['beerclub_balance'], 'beerclub']\n writer.writerow(row)\n row[1] = snapshot['members_balance']\n row[2] = 'members'\n writer.writerow(row)\n row[1] = snapshot['beerclub_balance'] - snapshot['members_balance']\n row[2] = 'surplus'\n writer.writerow(row)\n self.write(csvbuffer.getvalue())\n self.set_header('Content-Type', constants.CSV_MIME)\n" }, { "alpha_fraction": 0.8055555820465088, "alphanum_fraction": 0.8055555820465088, "avg_line_length": 71, "blob_id": "f6c8663b294578d4f700a31c1fe0d730c5da080b", "content_id": "bd6b6433b8525ed8b58e7fb0bc21a230461b1003", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 72, "license_type": "no_license", "max_line_length": 71, "num_lines": 1, "path": "/beerclub/standalone/README.md", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "This directory contains stand-alone scripts, some of which use the API.\n" }, { "alpha_fraction": 0.5657599568367004, "alphanum_fraction": 0.5686848163604736, "avg_line_length": 35.37234115600586, "blob_id": "a4b7d999d837262456f9543361932d73e9d981b5", "content_id": "c67d03e062dcc8b3540542186f800a0e1819afd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10257, "license_type": "no_license", "max_line_length": 79, "num_lines": 282, "path": "/beerclub/requesthandler.py", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "\"RequestHandler subclass.\"\n\nimport base64\nimport json\nimport logging\nimport urllib\nfrom collections import OrderedDict as OD\n\nimport couchdb\nimport tornado.web\n\nfrom . import constants\nfrom . import settings\nfrom . import utils\nfrom .saver import Saver\n\n\nclass SnapshotSaver(Saver):\n doctype = constants.SNAPSHOT\n\n\nclass RequestHandler(tornado.web.RequestHandler):\n \"Base request handler.\"\n\n def prepare(self):\n \"Get the database connection.\"\n try:\n self.db = utils.get_dbserver()[settings['DATABASE_NAME']]\n except couchdb.http.ResourceNotFound:\n raise KeyError(\"CouchDB database '%s' does not exist.\" % \n settings['DATABASE_NAME'])\n\n def get_template_namespace(self):\n \"Set the variables accessible within the template.\"\n result = super().get_template_namespace()\n result['constants'] = constants\n result['settings'] = settings\n result['is_admin'] = self.is_admin()\n result['error'] = self.get_cookie('error', '').replace('_', ' ')\n self.clear_cookie('error')\n result['message'] = self.get_cookie('message', '').replace('_', ' ')\n self.clear_cookie('message')\n return result\n\n def see_other(self, name, *args, **kwargs):\n \"\"\"Redirect to the absolute URL given by name\n using HTTP status 303 See Other.\"\"\"\n query = kwargs.copy()\n try:\n self.set_error_flash(query.pop('error'))\n except KeyError:\n pass\n try:\n self.set_message_flash(query.pop('message'))\n except KeyError:\n pass\n url = self.absolute_reverse_url(name, *args, **query)\n self.redirect(url, status=303)\n\n def absolute_reverse_url(self, name, *args, **query):\n \"Get the absolute URL given the handler name, arguments and query.\"\n if name is None:\n path = ''\n else:\n path = self.reverse_url(name, *args, **query)\n return settings['BASE_URL'].rstrip('/') + path\n\n def reverse_url(self, name, *args, **query):\n \"Allow adding query arguments to the URL.\"\n url = super().reverse_url(name, *args)\n url = url.rstrip('?') # tornado bug? sometimes left-over '?'\n if query:\n url += '?' + urllib.parse.urlencode(query)\n return url\n\n def set_message_flash(self, message):\n \"Set message flash cookie.\"\n self.set_flash('message', message)\n\n def set_error_flash(self, message):\n \"Set error flash cookie message.\"\n self.set_flash('error', message)\n\n def set_flash(self, name, message):\n message = message.replace(' ', '_')\n message = message.replace(';', '_')\n message = message.replace(',', '_')\n self.set_cookie(name, message)\n\n def get_doc(self, key, viewname=None):\n \"\"\"Get the document with the given id, or from the given view.\n Raise KeyError if not found.\n \"\"\"\n return utils.get_doc(self.db, key, viewname=viewname)\n\n def get_docs(self, viewname, key=None, last=None, **kwargs):\n \"\"\"Get the list of documents using the named view\n and the given key or interval.\n \"\"\"\n return utils.get_docs(self.db, viewname, key=key, last=last, **kwargs)\n\n def get_member(self, email, check=False):\n \"\"\"Get the member identified by the email address.\n If Swish is enabled, then also check if 'email' is\n a Swish number, which must match exactly.\n Raise KeyError if no such member or if not allowed to view it.\n \"\"\"\n try:\n member = utils.get_member(self.db, email)\n except KeyError:\n raise KeyError('No such member account.')\n if check:\n if not (self.is_admin() or \n member['email'] == self.current_user['email']):\n raise KeyError('You may not view the member account.')\n return member\n\n def get_balance(self, member=None):\n \"Get the current balance for the member, or the sum of all members.\"\n if member is None:\n result = list(self.db.view('event/credit', group=False))\n else:\n result = list(self.db.view('event/credit',\n key=member['email'],\n group_level=1))\n if result:\n return result[0].value\n else:\n return 0\n\n def get_beerclub_balance(self):\n \"Get the current balance for the Beer Club account (i.e. payments).\"\n result = list(self.db.view('event/payment', group=False))\n if result:\n return result[0].value\n else:\n return 0\n\n def get_count(self, member, date=None):\n \"Get the number of beverages purchased on the given date.\"\n if date is None:\n date = utils.today()\n result = list(self.db.view('event/beverage',\n key=[member['email'], date],\n group_level=2))\n if result:\n return result[0].value\n else:\n return 0\n\n def get_current_user(self):\n \"\"\"Get the currently logged-in user member, or None.\n This overrides a tornado function, otherwise it should have\n been called 'get_current_member', since the term 'member'\n is used in this code rather than 'user'.\"\"\"\n try:\n user = self.get_current_user_session()\n except ValueError:\n try:\n user = self.get_current_user_basic()\n except ValueError:\n try:\n user = self.get_current_user_api_key()\n except ValueError:\n return None\n self.create_snapshot(user)\n return user\n\n def get_current_user_session(self):\n \"\"\"Get the current user from a secure login session cookie.\n Raise ValueError if no or erroneous authentication.\n \"\"\"\n email = self.get_secure_cookie(\n constants.USER_COOKIE,\n max_age_days=settings['LOGIN_SESSION_DAYS'])\n if not email: raise ValueError\n email = email.decode('utf-8')\n try:\n member = self.get_member(email)\n except KeyError:\n raise ValueError\n # Disabled; must not be allowed to login.\n if member.get('disabled'):\n logging.info(\"Session auth: DISABLED %s\", member['email'])\n raise ValueError\n else:\n # Check if valid login session.\n if member.get('login') is None: raise ValueError\n # All fine.\n logging.info(\"Session auth: %s\", member['email'])\n return member\n\n def get_current_user_basic(self):\n \"\"\"Get the current user by HTTP Basic authentication.\n This should be used only if the site is using TLS (SSL, https).\n Raise ValueError if no or erroneous authentication.\n \"\"\"\n try:\n auth = self.request.headers['Authorization']\n except KeyError:\n raise ValueError\n try:\n auth = auth.split()\n if auth[0].lower() != 'basic': raise ValueError\n auth = base64.b64decode(auth[1])\n email, password = auth.split(':', 1)\n member = self.get_member(email)\n print('given', utils.hashed_password(password))\n print('stored', member.get('password'))\n if utils.hashed_password(password) != member.get('password'):\n raise ValueError\n except (IndexError, ValueError, TypeError):\n raise ValueError\n if member.get('disabled'):\n logging.info(\"Basic auth login: DISABLED %s\", member['email'])\n raise ValueError\n else:\n logging.info(\"Basic auth login: %s\", member['email'])\n return member\n\n def get_current_user_api_key(self):\n \"\"\"Get the current user by API key authentication.\n Raise ValueError if no or erroneous authentication.\n \"\"\"\n try:\n api_key = self.request.headers[constants.API_KEY_HEADER]\n except KeyError:\n raise ValueError\n else:\n try:\n member = self.get_doc(api_key, 'member/api_key')\n except KeyError:\n raise ValueError\n if member.get('status') != constants.ENABLED:\n logging.info(\"API key login: NOT ENABLED %s\", member['email'])\n raise ValueError\n else:\n logging.info(\"API key login: %s\", member['email'])\n return member\n\n def is_admin(self):\n \"Is the current user an administrator?\"\n if not self.current_user: return False\n return self.current_user['role'] == constants.ADMIN\n\n def check_admin(self):\n \"Check that the current user is an administrator.\"\n if not self.is_admin():\n raise tornado.web.HTTPError(403, reason=\"Role 'admin' is required\")\n\n def create_snapshot(self, user):\n \"Create snapshot if not done today.\"\n # The snapshot is of the state of things the day before.\n date = utils.today(-1)\n try:\n self.get_doc(date, 'snapshot/date')\n except KeyError:\n # Explicit member is required to avoid infinite recursion.\n with SnapshotSaver(rqh=self, member=user) as saver:\n saver['date'] = date\n saver['beerclub_balance'] = self.get_beerclub_balance()\n saver['members_balance'] = self.get_balance()\n counts = dict([(s, 0) for s in constants.STATUSES])\n for row in self.db.view('member/status'):\n counts[row.key] += 1\n saver['member_counts'] = counts\n\n\nclass ApiMixin(object):\n \"Mixin for API and JSON handling.\"\n\n def get_json_body(self):\n \"Return the body of the request interpreted as JSON.\"\n content_type = self.request.headers.get('Content-Type', '')\n if content_type.startswith(constants.JSON_MIME):\n return json.loads(self.request.body)\n else:\n return {}\n\n def check_xsrf_cookie(self):\n \"Do not check for XSRF cookie when API.\"\n pass\n" }, { "alpha_fraction": 0.44736841320991516, "alphanum_fraction": 0.6842105388641357, "avg_line_length": 14.199999809265137, "blob_id": "c80e802c3cc454e46dda583f1ccab37e9a75e926", "content_id": "a85d5444a42db46d877ad3af0501abfeda813f90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 152, "license_type": "no_license", "max_line_length": 19, "num_lines": 10, "path": "/requirements.txt", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "certifi==2021.05.30\nchardet==4.0.0\nCouchDB==1.2\net-xmlfile==1.1.0\nidna==2.10\njdcal==1.4.1\nopenpyxl==3.0.7\nrequests==2.25.1\ntornado==6.1\nurllib3==1.26.5\n" }, { "alpha_fraction": 0.5395383238792419, "alphanum_fraction": 0.5398552417755127, "avg_line_length": 36.41304397583008, "blob_id": "1b5a1de48562e7182b090780272becf37d045665", "content_id": "764a415796ac283ff34d10f0cabb401f6519649e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18931, "license_type": "no_license", "max_line_length": 80, "num_lines": 506, "path": "/beerclub/member.py", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "\"Member account handling; member of Beer Club.\"\n\nimport csv\nimport logging\nimport fnmatch\nfrom io import StringIO\n\nimport tornado.web\n\nfrom beerclub import constants\nfrom beerclub import settings\nfrom beerclub import utils\nfrom beerclub.requesthandler import RequestHandler, ApiMixin\nfrom beerclub.saver import Saver\n\nEMAIL_SENT = 'An email with instructions has been sent.'\nPENDING_MESSAGE = 'An administrator will inspect your registration.' \\\n ' An email will be sent if your member account is enabled.'\n\nPENDING_SUBJECT = \"A {site} member account {email} is pending\"\nPENDING_TEXT = \"\"\"A {site} member account {email} is pending.\n\nInspect the member account at {url} and enable or disable.\n\"\"\"\n\nRESET_SUBJECT = \"Your {site} member account password has been reset.\"\nRESET_TEXT = \"\"\"Your {site} member account {email} password has been reset.\n\nTo set a new password, go to {url}. \n\nThis unique link contains a code allowing you to set the password.\n\nPlease also check and correct your settings.\n\nYours,\nThe {site} administrators\n\"\"\"\n\nENABLED_SUBJECT = \"Your {site} member account has been enabled\"\nENABLED_TEXT = \"\"\"Your {site} member account {email} has been enabled.\n\nYou need to set the password for it. Go to {url}.\n\nThis unique link contains a code allowing you to set the password.\n\nYours,\nThe {site} administrators\n\"\"\"\n\n\nclass MemberSaver(Saver):\n doctype = constants.MEMBER\n\n def initialize(self):\n self['status'] = constants.PENDING\n self['password'] = None\n\n def set_name(self):\n try:\n self['first_name'] = self.rqh.get_argument('first_name')\n self['last_name'] = self.rqh.get_argument('last_name')\n except tornado.web.MissingArgumentError:\n raise ValueError('Missing first or last name.')\n\n def set_swish(self):\n try:\n swish = self.rqh.get_argument('swish')\n if swish:\n swish = utils.normalize_swish(swish)\n try:\n other = self.rqh.get_member(swish)\n except KeyError:\n pass\n else:\n if other['email'] != self.doc['email']:\n raise ValueError('Swish number is already in use.')\n self['swish'] = swish or None\n except tornado.web.MissingArgumentError:\n self['swish'] = None\n try:\n lazy = self.rqh.get_argument('swish_lazy')\n self['swish_lazy'] = lazy.lower() == 'true'\n except tornado.web.MissingArgumentError:\n self['swish_lazy'] = settings['DEFAULT_MEMBER_SWISH_LAZY']\n\n def set_address(self):\n self['address'] = self.rqh.get_argument('address', None) or None\n\n def set_api_key(self):\n if not self.rqh.is_admin(): return\n if self['role'] != constants.ADMIN: return\n try:\n if self.rqh.get_argument('api_key', False):\n self['api_key'] = utils.get_iuid()\n except (tornado.web.MissingArgumentError, ValueError):\n pass\n\n def set_role(self):\n if not self.rqh.is_admin(): return\n if self.rqh.current_user['email'] == self['email']: return\n try:\n role = self.rqh.get_argument('role')\n if role not in constants.ROLES: raise ValueError\n self['role'] = role\n except (tornado.web.MissingArgumentError, ValueError):\n pass\n\n\nclass Member(RequestHandler):\n \"View a member account.\"\n\n @tornado.web.authenticated\n def get(self, email):\n try:\n member = self.get_member(email, check=True)\n except KeyError:\n self.see_other('home')\n else:\n member['balance'] = self.get_balance(member)\n utils.get_latest_events(self.db, [member])\n deletable = not member['latest_event'] and \\\n member['role'] != constants.ADMIN\n self.render('member.html', member=member, deletable=deletable)\n\n @tornado.web.authenticated\n def post(self, email):\n \"Delete this member; only if has no events and is not admin.\"\n self.check_admin()\n try:\n member = self.get_member(email, check=True)\n utils.get_latest_events(self.db, [member])\n except KeyError:\n self.see_other('home')\n return\n if self.get_argument('_http_method', None) == 'DELETE' and \\\n not member['latest_event'] and member['role'] != constants.ADMIN:\n self.db.delete(member)\n url = self.get_argument('next', None)\n if url:\n self.redirect(url)\n else:\n self.see_other('home')\n\n\nclass Settings(RequestHandler):\n \"Edit a member account; change values, enable or disable.\"\n\n @tornado.web.authenticated\n def get(self, email):\n try:\n member = self.get_member(email, check=True)\n except KeyError:\n self.see_other('home')\n else:\n self.render('settings.html', member=member)\n\n @tornado.web.authenticated\n def post(self, email):\n try:\n member = self.get_member(email, check=True)\n except KeyError:\n self.see_other('home')\n return\n try:\n with MemberSaver(doc=member, rqh=self) as saver:\n saver.set_name()\n saver.set_swish()\n saver.set_address()\n saver.set_api_key()\n saver.set_role()\n except ValueError as error:\n self.set_error_flash(str(error))\n self.see_other('settings', member['email'])\n return\n if self.is_admin():\n self.see_other('member', member['email'])\n else:\n self.see_other('home')\n\n\nclass Members(RequestHandler):\n \"View a table of all member accounts.\"\n\n @tornado.web.authenticated\n def get(self):\n self.check_admin()\n members = self.get_docs('member/email')\n utils.get_balances(self.db, members)\n utils.get_latest_events(self.db, members)\n self.render('members.html', members=members)\n\n\nclass MembersCsv(Members):\n \"CSV output of members accounts.\"\n\n def render(self, template, members):\n csvbuffer = StringIO()\n writer = csv.writer(csvbuffer)\n row = ['Member',\n 'First name',\n 'Last name',\n 'Balance',\n 'Role',\n 'Status',\n 'Last login']\n if settings['MEMBER_SWISH']:\n row.append('Swish')\n if not settings['GLOBAL_SWISH_LAZY']:\n row.append('Swish lazy')\n if settings['MEMBER_ADDRESS']:\n row.append('Address')\n writer.writerow(row)\n for member in members:\n row = [member['email'],\n member['first_name'],\n member['last_name'],\n member['balance'],\n member['role'],\n member['status'],\n member.get('last_login') or '']\n if settings['MEMBER_SWISH']:\n row.append(member.get('swish') or '')\n if not settings['GLOBAL_SWISH_LAZY']:\n row.append(member.get('swish_lazy') or '')\n if settings['MEMBER_ADDRESS']:\n row.append(member.get('address') or '')\n writer.writerow(row)\n self.write(csvbuffer.getvalue())\n self.set_header('Content-Type', constants.CSV_MIME)\n self.set_header('Content-Disposition', \n 'attachment; filename=\"members.csv\"')\n\n\nclass Pending(RequestHandler):\n \"View a table of pending member accounts.\"\n\n @tornado.web.authenticated\n def get(self):\n self.check_admin()\n members = self.get_docs('member/status', key=constants.PENDING)\n members.sort(key=lambda m: m['email'])\n self.render('pending.html', members=members)\n\n\nclass Login(RequestHandler):\n \"Login resource.\"\n\n def post(self):\n \"Login to a member account. Set a secure cookie.\"\n try:\n email = self.get_argument('email').lower()\n password = self.get_argument('password')\n except tornado.web.MissingArgumentError:\n self.set_error_flash('Missing email or password argument.')\n self.see_other('home')\n return\n try:\n member = self.get_member(email)\n if member['status'] == constants.DISABLED:\n raise ValueError\n if utils.hashed_password(password) != member.get('password'):\n raise KeyError\n except KeyError:\n self.set_error_flash('No such member or invalid password.')\n except ValueError:\n self.set_error_flash(\"Your member account is disabled.\"\n \" Contact the %s administrators.\"\n % settings['SITE_NAME'])\n else:\n with MemberSaver(doc=member, rqh=self) as saver:\n saver['login'] = utils.timestamp() # Set login session.\n saver['last_login'] = saver['login'] # Set last login.\n logging.info(\"Login auth: %s\", member['email'])\n self.set_secure_cookie(constants.USER_COOKIE,\n member['email'],\n expires_days=settings['LOGIN_SESSION_DAYS'])\n self.see_other('home')\n\n\nclass Logout(RequestHandler):\n \"Logout; unset the secure cookie, and invalidate login session.\"\n\n @tornado.web.authenticated\n def post(self):\n with MemberSaver(doc=self.current_user, rqh=self) as saver:\n saver['login'] = None # Unset login session.\n self.set_secure_cookie(constants.USER_COOKIE, '')\n self.see_other('home')\n\n\nclass Reset(RequestHandler):\n \"Reset the password of a member account.\"\n\n def post(self):\n try:\n member = self.get_member(self.get_argument('email'))\n except (tornado.web.MissingArgumentError, KeyError):\n self.see_other('home', error='No such member account.')\n else:\n if member.get('status') == constants.PENDING:\n self.see_other('home', error='Cannot reset password.'\n ' Member account has not been enabled.')\n return\n elif member.get('status') == constants.DISABLED:\n self.see_other('home', error='Cannot reset password.'\n ' Member account is disabled.')\n return\n with MemberSaver(doc=member, rqh=self) as saver:\n saver['password'] = None\n saver['code'] = utils.get_iuid()\n data = dict(email=member['email'],\n site=settings['SITE_NAME'],\n url = self.absolute_reverse_url('password',\n email=member['email'],\n code=member['code']))\n email_server = utils.EmailServer()\n email_server.send(member['email'],\n RESET_SUBJECT.format(**data),\n RESET_TEXT.format(**data))\n if self.current_user and not self.is_admin():\n # Log out the user if not admin\n self.set_secure_cookie(constants.USER_COOKIE, '')\n self.see_other('home', message=EMAIL_SENT)\n\n\nclass Password(RequestHandler):\n \"Set the password of a member account; requires a code.\"\n\n def get(self):\n self.render('password.html',\n email=self.get_argument('email', default=''),\n code=self.get_argument('code', default=''))\n\n def post(self):\n try:\n member = self.get_member(self.get_argument('email'))\n if member.get('code') != self.get_argument('code'):\n raise ValueError\n except (tornado.web.MissingArgumentError, KeyError, ValueError):\n self.see_other('home',\n error=\"Either the email address or the code\" +\n \" for setting password was wrong.\" +\n \" Try doing 'Reset' again.\")\n return\n password = self.get_argument('password', '')\n try:\n if len(password) < settings['MIN_PASSWORD_LENGTH']:\n raise ValueError('The password is too short.')\n except ValueError as msg:\n self.see_other('password',\n email=self.get_argument('email') or '',\n code=self.get_argument('code') or '',\n error=str(msg))\n return \n with MemberSaver(doc=member, rqh=self) as saver:\n saver['password'] = utils.hashed_password(password)\n saver['login'] = utils.timestamp() # Set login session.\n saver['last_login'] = saver['login'] # Set last login.\n saver['code'] = None\n self.set_secure_cookie(constants.USER_COOKIE,\n member['email'],\n expires_days=settings['LOGIN_SESSION_DAYS'])\n self.see_other('home')\n\n\nclass Register(RequestHandler):\n \"Register a member account.\"\n\n @tornado.web.authenticated\n def get(self):\n \"Register a member. Only admin should be able to register someone else.\"\n self.check_admin()\n self.render('register.html')\n\n def post(self):\n try:\n with MemberSaver(rqh=self) as saver:\n try:\n email = self.get_argument('email').lower()\n if not email: raise ValueError\n except (tornado.web.MissingArgumentError, ValueError):\n raise ValueError('No email address provided.')\n if not fnmatch.fnmatch(email, constants.EMAIL_PATTERN):\n raise ValueError('Invalid email address provided.')\n try:\n member = self.get_doc(email, 'member/email')\n except KeyError:\n pass\n else:\n raise ValueError('Member account exists!'\n ' Please use Reset password.')\n saver['email'] = email\n saver.set_name()\n saver.set_swish()\n saver.set_address()\n # Set the very first member account in the database\n # to be admin and enabled.\n count = len(self.get_docs('member/email', key='',\n last=constants.CEILING, limit=2))\n if count == 0:\n saver['role'] = constants.ADMIN\n saver['status'] = constants.ENABLED\n saver['code'] = code = utils.get_iuid()\n else:\n saver['role'] = constants.MEMBER\n ptn = settings['MEMBER_EMAIL_AUTOENABLE']\n # Enable directly if pattern match.\n if ptn and fnmatch.fnmatch(saver['email'], ptn):\n saver['status'] = constants.ENABLED\n saver['code'] = code = utils.get_iuid()\n except ValueError as error:\n self.set_message_flash(str(error))\n self.see_other('home')\n return\n member = saver.doc\n data = dict(email=member['email'], site=settings['SITE_NAME'])\n email_server = utils.EmailServer()\n if member['status'] == constants.ENABLED:\n data['url'] = self.absolute_reverse_url('password',\n email=email,\n code=code)\n email_server.send(member['email'],\n ENABLED_SUBJECT.format(**data),\n ENABLED_TEXT.format(**data))\n self.set_message_flash(EMAIL_SENT)\n else:\n data['url'] = self.absolute_reverse_url('member', data['email'])\n subject = PENDING_SUBJECT.format(**data)\n text = PENDING_TEXT.format(**data)\n for admin in self.get_docs('member/role', key=constants.ADMIN):\n email_server.send(admin['email'], subject, text)\n self.set_message_flash(PENDING_MESSAGE)\n if self.is_admin():\n self.see_other('member', member['email'])\n else:\n self.see_other('home')\n\n\nclass Enable(RequestHandler):\n \"Enable a member account.\"\n\n @tornado.web.authenticated\n def post(self, email):\n self.check_admin()\n member = self.get_member(email)\n with MemberSaver(doc=member, rqh=self) as saver:\n saver['status'] = constants.ENABLED\n saver['login'] = None\n saver['password'] = None\n saver['code'] = utils.get_iuid()\n email_server = utils.EmailServer()\n data = dict(email=member['email'],\n site=settings['SITE_NAME'],\n url=self.absolute_reverse_url('password',\n email=member['email'],\n code=member['code']))\n email_server.send(member['email'],\n ENABLED_SUBJECT.format(**data),\n ENABLED_TEXT.format(**data))\n self.set_message_flash(EMAIL_SENT)\n url = self.get_argument('next', None)\n if url:\n self.redirect(url)\n else:\n self.see_other('member', member['email'])\n\n\nclass Disable(RequestHandler):\n \"Disable a member account.\"\n\n @tornado.web.authenticated\n def post(self, email):\n self.check_admin()\n member = self.get_member(email)\n with MemberSaver(doc=member, rqh=self) as saver:\n saver['status'] = constants.DISABLED\n saver['login'] = None\n saver['password'] = None\n saver['code'] = None\n url = self.get_argument('next', None)\n if url:\n self.redirect(url)\n else:\n self.see_other('member', member['email'])\n\n\nclass MemberApiV1(ApiMixin, RequestHandler):\n \"Get member data.\"\n\n @tornado.web.authenticated\n def get(self, email):\n self.check_admin()\n try:\n member = self.get_member(email)\n except KeyError:\n raise tornado.web.HTTPError(404, reason='no such member')\n data = {}\n for key in ['email', 'first_name', 'last_name', 'role', 'status']:\n data[key] = member.get(key)\n if settings['MEMBER_SWISH']:\n data['swish'] = member.get('swish')\n if not settings['GLOBAL_SWISH_LAZY']:\n data['swish_lazy'] = member.get('swish_lazy')\n if settings['MEMBER_ADDRESS']:\n data['address'] = member.get('address')\n self.write(data)\n" }, { "alpha_fraction": 0.5814415216445923, "alphanum_fraction": 0.5976163744926453, "avg_line_length": 33.891090393066406, "blob_id": "dabbb173501152b9021c3e45070d27daf9a53f46", "content_id": "194fed00050915baeba8e8d4d564d359bfca377e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3524, "license_type": "no_license", "max_line_length": 80, "num_lines": 101, "path": "/beerclub/__init__.py", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "\"\"\"\"BeerClub\nA web application to keep track of the beer purchases for registered users.\n\"\"\"\n\nimport os\n\n__version__ = '2.2.3'\n\nsettings = dict(\n VERSION=__version__,\n ROOT_DIR=os.path.dirname(__file__),\n SITE_NAME='Beer Club',\n BASE_URL='http://localhost:8888',\n GITHUB_HREF=\"https://github.com/pekrau/BeerClub\",\n LOGGING_DEBUG=False,\n TORNADO_DEBUG=False,\n LOGGING_FORMAT='%(levelname)s [%(asctime)s] %(message)s',\n LOGGING_FILEPATH=None,\n LOGGING_FILEMODE=None,\n DATABASE_SERVER='http://localhost:5984/',\n DATABASE_NAME='beerclub',\n DATABASE_ACCOUNT=None,\n DATABASE_PASSWORD=None,\n COOKIE_SECRET=None, # Set to a secret long string of random characters.\n PASSWORD_SALT=None, # Set to a secret long string of random characters.\n MIN_PASSWORD_LENGTH=8,\n LOGIN_SESSION_DAYS=31,\n MEMBER_EMAIL_AUTOENABLE=None,\n EMAIL=dict(HOST='localhost',\n PORT=None,\n TLS=False,\n USER=None,\n PASSWORD=None,\n SENDER=None),\n CONTACT_EMAIL=None,\n DISPLAY_NAVBAR_THEME='navbar-dark',\n DISPLAY_NAVBAR_BG_COLOR='bg-dark',\n DISPLAY_NAVBAR_STYLE_COLOR=None,\n DISPLAY_NAVBAR_LOGO='BeerClubLogo.svg',\n DISPLAY_ACTIVITY_DAYS=6,\n DISPLAY_LEDGER_DAYS=7,\n DISPLAY_ACCOUNT_DAYS=7,\n DISPLAY_PAYMENT_DAYS=7,\n DISPLAY_SNAPSHOT_DAYS=60,\n GLOBAL_ALERT=None,\n RULES_HTML=\"<ul><li>You must be a registered member to buy beer.</li></ul>\",\n PAYMENT_INFO_HTML=None,\n POLICY_STATEMENT=\"The {SITE_NAME} is a non-profit group arranging pub\"\n \" evenings for its members. Volunteer members must obtain the beer\"\n \" from the shop, and will be reimbursed by the {SITE_NAME} administrator.\",\n PRIVACY_STATEMENT=\"By registering, you agree to allow the personal data\"\n \" you provide to be handled by the {SITE_NAME} according to\"\n \" applicable laws. No data will be transferred to any external entity.\",\n MEMBER_SWISH=True, # Enable Swish phone number field for member.\n GLOBAL_SWISH_LAZY=False, # Enforce Swish lazy mode for all.\n DEFAULT_MEMBER_SWISH_LAZY=False, # Swish lazy mode default for new account.\n MEMBER_ADDRESS=True, # Enable address field for member.\n CREDIT_CLASSES=[(-500, 'bg-danger text-light'),\n (-250, 'bg-warning'),\n (-1, 'text-danger')],\n BEVERAGE=[\n dict(identifier='beer',\n label='beer',\n price=20,\n description='One can or bottle of beer.'),\n ],\n PURCHASE=[\n dict(identifier='cash',\n change=False,\n label='cash',\n style='success',\n action='I paid cash.',\n description='I paid cash for one %s.'),\n dict(identifier='credit',\n change=True,\n label='credit',\n style='warning',\n action='Put it on my credit.',\n description='Put the amount for one %s on my credit.'),\n ],\n PAYMENT=[\n dict(identifier='cash',\n label='Cash paid to the admin.',\n default=True),\n dict(identifier='swish',\n label='Verified Swish payment.'),\n dict(identifier='bank',\n label='Bank account transfer.'),\n ],\n CURRENCY='kr',\n MONEY_DECIMAL_PLACES=2,\n MONEY_DECIMAL_POINT='.',\n MONEY_THOUSAND_DELIMITER=',',\n SWISH_NUMBER_PREFIXES = {\n '35': '0035',\n '39': '0039',\n '46': '0',\n '48': '0048',\n '49': '0049'\n }\n)\n" }, { "alpha_fraction": 0.5731995105743408, "alphanum_fraction": 0.5743801593780518, "avg_line_length": 28.20689582824707, "blob_id": "2a82cbbdc2c0dce0d1990ee7dedf064435faa6fc", "content_id": "50e357ca2b38bc0e69729aa77aaa7c05f8fbe54f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3388, "license_type": "no_license", "max_line_length": 69, "num_lines": 116, "path": "/beerclub/designs.py", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "\"CouchDB design documents (view index definitions).\"\n\nimport logging\n\nimport couchdb\n\n\nDESIGNS = dict(\n\n member=dict(\n email=dict(map= # member/email\n\"\"\"function(doc) {\n if (doc.beerclub_doctype !== 'member') return;\n emit(doc.email, doc.status);\n}\"\"\"),\n role=dict(map= # member/role\n\"\"\"function(doc) {\n if (doc.beerclub_doctype !== 'member') return;\n emit(doc.role, doc.email);\n}\"\"\"),\n status=dict(map= # member/status\n\"\"\"function(doc) {\n if (doc.beerclub_doctype !== 'member') return;\n emit(doc.status, doc.email);\n}\"\"\"),\n swish=dict(map= # member/swish\n\"\"\"function(doc) {\n if (doc.beerclub_doctype !== 'member') return;\n if (!doc.swish) return;\n emit(doc.swish, doc.email);\n}\"\"\"),\n api_key=dict(map= # member/api_key\n\"\"\"function(doc) {\n if (doc.beerclub_doctype !== 'member') return;\n if (!doc.api_key) return;\n emit(doc.api_key, doc.email);\n}\"\"\"),\n ),\n\n event=dict(\n credit=dict(reduce=\"_sum\", # event/credit\n map=\n\"\"\"function(doc) {\n if (doc.beerclub_doctype !== 'event') return;\n if (doc.member === 'beerclub') return;\n emit(doc.member, doc.credit);\n}\"\"\"),\n beverage=dict(reduce=\"_count\", # event/beverage\n map=\n\"\"\"function(doc) {\n if (doc.beerclub_doctype !== 'event') return;\n if (doc.action !== 'purchase') return;\n emit([doc.member, doc.log.date], doc.beverage);\n}\"\"\"),\n member=dict(map= # event/member\n\"\"\"function(doc) {\n if (doc.beerclub_doctype !== 'event') return;\n emit([doc.member, doc.log.timestamp], null);\n}\"\"\"),\n ledger=dict(reduce=\"_sum\", # event/ledger\n map=\n\"\"\"function(doc) {\n if (doc.beerclub_doctype !== 'event') return;\n emit(doc.log.timestamp, doc.credit);\n}\"\"\"),\n activity=dict(map= # event/activity\n\"\"\"function(doc) {\n if (doc.beerclub_doctype !== 'event') return;\n if (doc.action !== 'purchase') return;\n if (doc.credit === 0.0) return;\n emit(doc.log.timestamp, doc.member);\n}\"\"\"),\n payment=dict(reduce=\"_sum\", # event/payment\n map=\n\"\"\"function(doc) {\n if (doc.beerclub_doctype !== 'event') return;\n if (doc.action !== 'payment') return;\n emit(doc.date, doc.credit);\n}\"\"\"),\n ),\n snapshot=dict(\n date=dict(map=\n\"\"\"function(doc) {\n if (doc.beerclub_doctype !== 'snapshot') return;\n emit(doc.date, doc.beerclub_balance);\n}\"\"\")\n ),\n)\n\n\ndef load_design_documents(db):\n \"Load the design documents (view index definitions).\"\n for entity, designs in DESIGNS.items():\n updated = update_design_document(db, entity, designs)\n if updated:\n for view in designs:\n name = \"%s/%s\" % (entity, view)\n logging.info(\"regenerating index for view %s\" % name)\n list(db.view(name, limit=10))\n\ndef update_design_document(db, design, views):\n \"Update the design document (view index definition).\"\n docid = \"_design/%s\" % design\n try:\n doc = db[docid]\n except couchdb.http.ResourceNotFound:\n logging.info(\"loading design document %s\", docid)\n db.save(dict(_id=docid, views=views))\n return True\n else:\n if doc['views'] != views:\n doc['views'] = views\n logging.info(\"updating design document %s\", docid)\n db.save(doc)\n return True\n return False\n" }, { "alpha_fraction": 0.48925113677978516, "alphanum_fraction": 0.4932671785354614, "avg_line_length": 39.31428527832031, "blob_id": "3af02c35d33f711be92e76ec3838c738b0212e35", "content_id": "862f0db0ad1a54c60353a47bee4417fbae9f23b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4233, "license_type": "no_license", "max_line_length": 75, "num_lines": 105, "path": "/beerclub/app_beerclub.py", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "\"A web application to keep track of the beer tabs for registered users.\"\n\nimport logging\nimport os\n\nimport tornado.web\nimport tornado.ioloop\n\nfrom beerclub import settings\nfrom beerclub import uimodules\nfrom beerclub import utils\nfrom beerclub.home import (Home,\n Snapshots,\n SnapshotsCsv,\n Dashboard,\n BalanceCsv)\nfrom beerclub.member import (Member,\n Settings,\n Members,\n MembersCsv,\n Pending,\n Login,\n Logout,\n Reset,\n Password,\n Register,\n Enable,\n Disable,\n MemberApiV1)\nfrom beerclub.event import (Event,\n Purchase,\n Payment,\n Load,\n Expenditure,\n Cash,\n Account,\n Activity,\n Ledger,\n LedgerCsv,\n Payments,\n PaymentsCsv,\n EventApiV1,\n MemberEventApiV1)\n\ndef main():\n url = tornado.web.url\n handlers = [\n url(r'/', Home, name='home'),\n url(r'/purchase', Purchase, name='purchase'),\n url(r'/purchase/([^/]+)', Purchase, name='purchase_member'),\n url(r'/payment/([^/]+)', Payment, name='payment'),\n url(r'/load', Load, name='load'),\n url(r'/member/([^/]+)', Member, name='member'),\n url(r'/settings/([^/]+)', Settings, name='settings'),\n url(r'/enable/([^/]+)', Enable, name='enable'),\n url(r'/disable/([^/]+)', Disable, name='disable'),\n url(r'/activity', Activity, name='activity'),\n url(r'/pending', Pending, name='pending'),\n url(r'/members', Members, name='members'),\n url(r'/members.csv', MembersCsv, name='members_csv'),\n url(r'/account/([^/]+)', Account, name='account'),\n url(r'/expenditure', Expenditure, name='expenditure'),\n url(r'/cash', Cash, name='cash'),\n url(r'/ledger', Ledger, name='ledger'),\n url(r'/ledger.csv', LedgerCsv, name='ledger_csv'),\n url(r'/payments', Payments, name='payments'),\n url(r'/payments.csv', PaymentsCsv, name='payments_csv'),\n url(r'/snapshots', Snapshots, name='snapshots'),\n url(r'/snapshots.csv', SnapshotsCsv, name='snapshots_csv'),\n url(r'/dashboard', Dashboard, name='dashboard'),\n url(r'/balance.csv', BalanceCsv, name='balance_csv'),\n url(r'/event/([0-9a-f]{32})', Event, name='event'),\n url(r'/login', Login, name='login'),\n url(r'/logout', Logout, name='logout'),\n url(r'/reset', Reset, name='reset'),\n url(r'/password', Password, name='password'),\n url(r'/register', Register, name='register'),\n url(r'/api/v1/event/([0-9a-f]{32})', EventApiV1, name='api_event'),\n url(r'/api/v1/member/([^/]+)', MemberApiV1, name='api_member'),\n url(r'/api/v1/event/member/([^/]+)',\n MemberEventApiV1, name='api_member_event'),\n url(r'/([^/]+)', tornado.web.StaticFileHandler,\n {'path': os.path.join(settings['ROOT_DIR'], 'static')}),\n ]\n\n application = tornado.web.Application(\n handlers=handlers,\n debug=settings.get('TORNADO_DEBUG', False),\n cookie_secret=settings['COOKIE_SECRET'],\n xsrf_cookies=True,\n ui_modules=uimodules,\n template_path=os.path.join(settings['ROOT_DIR'], 'html'),\n static_path=os.path.join(settings['ROOT_DIR'], 'static'),\n login_url=r'/',\n )\n application.listen(settings['PORT'], xheaders=True)\n logging.info(\"tornado debug: %s\", settings['TORNADO_DEBUG'])\n logging.info(\"web server %s\", settings['BASE_URL'])\n tornado.ioloop.IOLoop.instance().start()\n\n\nif __name__ == \"__main__\":\n utils.setup()\n utils.initialize()\n main()\n" }, { "alpha_fraction": 0.5547232627868652, "alphanum_fraction": 0.5580524206161499, "avg_line_length": 35.96923065185547, "blob_id": "dcc5e3eeefb4c171ddd87f5584758455bb472f47", "content_id": "132cf0f6c3ec599bb71c27aa1354a4cf8f19f881", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2403, "license_type": "no_license", "max_line_length": 76, "num_lines": 65, "path": "/beerclub/standalone/email_debt.py", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "\"Send email to enabled members having a debt to the SciLifeLab Beer Club.\"\n\nimport argparse\nimport csv\nimport json\nimport time\n\nfrom email_server import EmailServer\n\nDEFAULT_PAUSE = 3.0\n\nEMAIL = 0\nFIRST_NAME = 1\nLAST_NAME = 2\nBALANCE = 3\nSTATUS = 5\n\n\ndef email_debt(settings, csvfile, subject, messagefile, execute=True):\n \"Send email to enabled members having a debt to the Beer Club.\"\n emailserver = EmailServer(settings)\n message = messagefile.read()\n reader = csv.reader(csvfile)\n next(reader) # Skip past header.\n for row in reader:\n balance = float(row[BALANCE])\n if balance >= 0 : continue\n if row[STATUS] != 'enabled': continue\n name = f\"{row[FIRST_NAME]} {row[LAST_NAME]}\"\n recipient = f\"{name} <{row[EMAIL]}>\"\n msg = message.format(name=name, amount=abs(balance))\n print(recipient, balance)\n if execute:\n emailserver.send(recipient, subject, msg)\n time.sleep(settings['EMAIL'].get('PAUSE', DEFAULT_PAUSE))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description='Send email to indebted enabled members.')\n parser.add_argument('-s', '--settings',\n type=argparse.FileType('r'),\n default='email_settings.json',\n help='Settings for connecting to the email server.')\n parser.add_argument('-c', '--csvfile',\n type=argparse.FileType('r'),\n default='members.csv',\n help='CSV file of BeerClub members.')\n parser.add_argument('-S', '--subject',\n type=str,\n default='Your debt to the SciLifeLab Beer Club',\n help='Subject of the email message.')\n parser.add_argument('-t', '--messagefile',\n type=argparse.FileType('r'),\n default='email_debt_message.txt',\n help='File containing the email message.')\n parser.add_argument('-x', '--execute',\n action='store_true', default=False,\n help='Actually send the messages.')\n args = parser.parse_args()\n email_debt(json.load(args.settings),\n args.csvfile,\n args.subject,\n args.messagefile,\n execute=args.execute)\n" }, { "alpha_fraction": 0.511855959892273, "alphanum_fraction": 0.5132372379302979, "avg_line_length": 36.126495361328125, "blob_id": "383dba4a98bb3b445aac99d79e5ea4772d6f0d90", "content_id": "c5d51da8d728ac01a90c60a1667d851adebb6738", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21719, "license_type": "no_license", "max_line_length": 85, "num_lines": 585, "path": "/beerclub/event.py", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "\"Event: purchase, payment, etc.\"\n\nimport csv\nimport datetime\nimport logging\nimport tempfile\nfrom io import StringIO\n\nimport openpyxl\nimport tornado.web\n\nfrom . import constants\nfrom . import settings\nfrom . import utils\nfrom .requesthandler import RequestHandler, ApiMixin\nfrom .saver import Saver\n\n\nclass EventSaver(Saver):\n doctype = constants.EVENT\n\n def set(self, data):\n action = data.get('action')\n if action == constants.PURCHASE:\n self.set_purchase(**data)\n elif action == constants.PAYMENT:\n self.set_payment(**data)\n elif action == constants.TRANSFER:\n self.set_transfer(**data)\n else:\n raise ValueError('invalid action')\n\n def set_purchase(self, **kwargs):\n self['action'] = constants.PURCHASE\n pid = kwargs.get('purchase')\n for purchase in settings['PURCHASE']:\n if pid == purchase['identifier']: break\n else:\n raise ValueError(\"no such purchase %s\" % pid)\n bid = kwargs.get('beverage')\n for beverage in settings['BEVERAGE']:\n if bid == beverage['identifier']: break\n else:\n beverage = None\n if beverage:\n self['beverage'] = beverage['identifier']\n self['description'] = purchase['identifier']\n if purchase['change']:\n self['credit'] = - beverage['price']\n else:\n self['credit'] = 0.0\n self.message = \"You purchased one %s.\" % beverage['label']\n else: # Special case 'Swish lazy'\n self['beverage'] = 'unknown beverage'\n self['description'] = kwargs.get('description', '')\n if purchase['change'] and kwargs.get('amount'):\n self['credit'] = - kwargs.get('amount')\n else:\n self['credit'] = 0.0\n self.message = 'You purchased some beverage.'\n self['date'] = kwargs.get('date') or utils.today()\n\n def set_payment(self, **kwargs):\n self['action'] = constants.PAYMENT\n try:\n amount = float(kwargs['amount'])\n except (KeyError, ValueError, TypeError):\n raise ValueError('invalid amount')\n pid = kwargs.get('payment')\n if pid == constants.EXPENDITURE:\n self['description'] = \"%s: %s\" % (constants.EXPENDITURE,\n kwargs.get('description'))\n self['credit'] = - amount\n elif pid == constants.CASH:\n self['description'] = 'cash transfer'\n self['credit'] = amount\n else:\n for payment in settings['PAYMENT']:\n if pid == payment['identifier']: break\n else:\n raise ValueError(\"no such payment %s\" % pid)\n self['description'] = payment['identifier']\n self['credit'] = amount\n self['date'] = kwargs.get('date') or utils.today()\n\n def set_transfer(self, **kwargs):\n self['action'] = constants.TRANSFER\n try:\n amount = float(kwargs['amount'])\n except (KeyError, ValueError, TypeError):\n raise ValueError('invalid amount')\n self['credit'] = amount\n self['description'] = kwargs.get('description')\n self['date'] = kwargs.get('date') or utils.today()\n\n\nclass Event(RequestHandler):\n \"View an event; purchase, payment, etc. Admin may delete it.\"\n\n @tornado.web.authenticated\n def get(self, iuid):\n try:\n event = self.get_doc(iuid)\n except KeyError:\n self.set_error_flash('No such event.')\n self.see_other('account', self.current_user['email'])\n else:\n # Check view access privilege\n if self.is_admin() or event['member']==self.current_user['email']:\n self.render('event.html', event=event)\n else:\n self.set_error_flash('You may not view the event data.')\n self.see_other('home')\n\n @tornado.web.authenticated\n def post(self, iuid):\n \"Delete the event.\"\n self.check_admin()\n event = self.get_doc(iuid)\n if self.get_argument('_http_method', None) == 'DELETE':\n self.db.delete(event)\n self.see_other('account', event['member'])\n\n\nclass Purchase(RequestHandler):\n \"Buying one beverage.\"\n\n @tornado.web.authenticated\n def get(self, email=None):\n \"This page for admin to record purchases on behalf of a member.\"\n self.check_admin()\n if email is None:\n member = self.current_user\n else:\n try:\n member = self.get_member(email, check=True)\n except KeyError as error:\n self.set_error_flash(str(error))\n self.see_other('home')\n return\n self.render('purchase.html', member=member)\n\n @tornado.web.authenticated\n def post(self, email=None):\n if email is None:\n member = self.current_user\n else:\n try:\n member = self.get_member(email, check=True)\n except KeyError as error:\n self.set_error_flash(str(error))\n self.see_other('home')\n return\n try:\n with EventSaver(rqh=self) as saver:\n saver['member'] = member['email']\n saver.set_purchase(purchase=self.get_argument('purchase',None),\n beverage=self.get_argument('beverage',None))\n except ValueError as error:\n self.set_error_flash(str(error))\n else:\n self.set_message_flash(saver.message)\n if email is None:\n self.see_other('home')\n else:\n self.see_other('account', member['email'])\n\n\nclass Payment(RequestHandler):\n \"Payment to increase the credit of a member, or correction.\"\n\n @tornado.web.authenticated\n def get(self, email):\n self.check_admin()\n try:\n member = self.get_member(email, check=True)\n except KeyError as error:\n self.set_error_flash(str(error))\n self.see_other('home')\n else:\n member['balance'] = self.get_balance(member)\n self.render('payment.html', member=member)\n\n @tornado.web.authenticated\n def post(self, email):\n self.check_admin()\n try:\n member = self.get_member(email, check=True)\n except KeyError as error:\n self.set_error_flash(str(error))\n self.see_other('home')\n return\n try:\n try:\n amount = float(self.get_argument('amount', None))\n except (KeyError, ValueError, TypeError):\n amount = 0.0\n payment = self.get_argument('payment', None)\n if payment is None:\n raise ValueError('no payment type specified')\n if payment == constants.CORRECTION:\n with EventSaver(rqh=self) as saver:\n saver['member'] = member['email']\n saver.set_transfer(amount=amount,\n description='manual correction')\n else:\n with EventSaver(rqh=self) as saver:\n saver['member'] = member['email']\n saver.set_payment(payment=payment,\n amount=amount,\n date=self.get_argument('date', None))\n lazy = self.get_argument('swish_lazy', False)\n if lazy and lazy.lower() == 'true':\n with EventSaver(rqh=self) as saver:\n saver['action'] = constants.PURCHASE\n saver['member'] = member['email']\n saver['beverage'] = 'unknown beverage'\n saver['description'] = 'Swish lazy'\n saver['credit'] = - amount\n except ValueError as error:\n self.set_error_flash(str(error))\n self.see_other('account', member['email'])\n\n \nclass Load(RequestHandler):\n \"Load payments data file, e.g. Excel XLSX Swish records.\"\n\n @tornado.web.authenticated\n def get(self):\n self.check_admin()\n self.render('load.html', missing=[])\n\n @tornado.web.authenticated\n def post(self):\n self.check_admin()\n missing = []\n try:\n infiles = self.request.files.get('xlsxfile')\n if not infiles:\n raise ValueError('no XLSX file selected')\n infile = infiles[0]\n tmp = tempfile.NamedTemporaryFile(suffix='.xlsx')\n tmp.write(infile['body'])\n tmp.seek(0)\n wb = openpyxl.load_workbook(tmp.name)\n records = list(wb.active.values)\n header_cell = self.get_argument('header_cell')\n if not header_cell:\n raise ValueError('no header cell value provided')\n for header_pos, header in enumerate(records):\n if header[0] == header_cell:\n break\n else:\n raise ValueError('could not find header in XLSX file')\n try:\n swish_pos = int(self.get_argument('swish_pos')) - 1\n if swish_pos < 0: raise ValueError\n except (TypeError, ValueError):\n raise ValueError('missing or invalid Swish number column')\n try:\n amount_pos = int(self.get_argument('amount_pos')) - 1\n if amount_pos < 0: raise ValueError\n except (TypeError, ValueError):\n raise ValueError('missing or invalid amount column')\n try:\n date_pos = int(self.get_argument('date_pos')) - 1\n if date_pos < 0: raise ValueError\n except (TypeError, ValueError):\n date_pos = None\n try:\n name_pos = int(self.get_argument('name_pos')) - 1\n if name_pos < 0: raise ValueError\n except (TypeError, ValueError):\n name_pos = None\n\n payments = []\n for record in records[header_pos+1:]:\n if name_pos is None:\n name = None\n else:\n name = str(record[name_pos])\n swish = str(record[swish_pos])\n for prefix, replacement in settings['SWISH_NUMBER_PREFIXES'].items():\n if swish.startswith(prefix):\n swish = replacement + swish[len(prefix):]\n break\n try:\n member = self.get_member(swish)\n except KeyError:\n if name:\n missing.append(f\"{swish} {name}\")\n else:\n missing.append(swish)\n else:\n if date_pos is None:\n date = datetime.date.today().isoformat()\n else:\n date = record[date_pos]\n if isinstance(date, datetime.datetime):\n date = date.date().isoformat()\n elif isinstance(date, datetime.date):\n date = date.isoformat()\n else:\n date = str(date)\n payments.append({'member': member['email'],\n 'lazy': settings['GLOBAL_SWISH_LAZY'] or\n member.get('swish_lazy'),\n 'date': date,\n 'amount': float(record[amount_pos])})\n if missing:\n raise ValueError('Swish number(s) missing')\n for payment in payments:\n with EventSaver(rqh=self) as saver:\n saver['member'] = payment['member']\n saver.set_payment(payment='swish',\n amount=payment['amount'],\n date=payment['date'])\n if payment['lazy']:\n with EventSaver(rqh=self) as saver:\n saver['member'] = payment['member']\n saver.set_purchase(purchase='credit',\n amount=payment['amount'],\n description='Swish lazy',\n date=payment['date'])\n except (IndexError, TypeError, ValueError, IOError) as error:\n self.set_error_flash(str(error))\n self.render('load.html', missing=missing)\n else:\n self.see_other('ledger')\n\nclass Expenditure(RequestHandler):\n \"Expenditure that reduces the credit of the BeerClub master virtual member.\"\n\n @tornado.web.authenticated\n def get(self):\n self.check_admin()\n self.render('expenditure.html')\n\n @tornado.web.authenticated\n def post(self):\n self.check_admin()\n try:\n with EventSaver(rqh=self) as saver:\n saver['member'] = constants.BEERCLUB\n saver.set_payment(\n payment=constants.EXPENDITURE,\n amount=self.get_argument('amount', None),\n description=self.get_argument('description', None),\n date=self.get_argument('date', utils.today()))\n except ValueError as error:\n self.set_error_flash(str(error))\n self.see_other('payments')\n\n\nclass Cash(RequestHandler):\n \"\"\"Cash transfer from cash box via some admin.\n Increases the credit of the BeerClub master virtual member.\n \"\"\"\n\n @tornado.web.authenticated\n def get(self):\n self.check_admin()\n self.render('cash.html')\n\n @tornado.web.authenticated\n def post(self):\n self.check_admin()\n try:\n with EventSaver(rqh=self) as saver:\n saver['member'] = constants.BEERCLUB\n saver.set_payment(\n payment=constants.CASH,\n amount=self.get_argument('amount', None),\n date=self.get_argument('date', utils.today()))\n except ValueError as error:\n self.set_error_flash(str(error))\n self.see_other('payments')\n\n\nclass Account(RequestHandler):\n \"View events for a member account.\"\n\n @tornado.web.authenticated\n def get(self, email):\n try:\n member = self.get_member(email, check=True)\n except KeyError:\n self.see_other('home')\n return \n member['balance'] = self.get_balance(member)\n member['count'] = self.get_count(member)\n try:\n from_ = self.get_argument('from')\n except tornado.web.MissingArgumentError:\n from_ = utils.today(-settings['DISPLAY_ACCOUNT_DAYS'])\n try:\n to = self.get_argument('to')\n except tornado.web.MissingArgumentError:\n to = utils.today()\n if from_ > to:\n events = []\n else:\n events = self.get_docs('event/member',\n key=[member['email'], from_],\n last=[member['email'], to+constants.CEILING])\n self.render('account.html',\n member=member, events=events, from_=from_, to=to)\n\n\nclass Activity(RequestHandler):\n \"Members having made credit-affecting purchases recently.\"\n\n @tornado.web.authenticated\n def get(self):\n self.check_admin()\n activity = dict()\n from_ = utils.today(-settings['DISPLAY_ACTIVITY_DAYS'])\n to = utils.today()\n view = self.db.view('event/activity')\n for row in view[from_ : to+constants.CEILING]:\n try:\n activity[row.value] = max(activity[row.value], row.key)\n except KeyError:\n activity[row.value] = row.key\n activity.pop(constants.BEERCLUB, None)\n activity = list(activity.items())\n activity.sort(key=lambda i: i[1])\n # This is more efficient than calling for each member.\n all_members = self.get_docs('member/email')\n lookup = {}\n for member in all_members:\n lookup[member['email']] = member\n members = []\n for email, timestamp in activity:\n member = lookup[email]\n member['activity'] = timestamp\n members.append(member)\n utils.get_balances(self.db, members)\n self.render('activity.html', members=members)\n\n\nclass Ledger(RequestHandler):\n \"Ledger page for listing recent events.\"\n\n @tornado.web.authenticated\n def get(self):\n \"Display recent events.\"\n try:\n from_ = self.get_argument('from')\n except tornado.web.MissingArgumentError:\n from_ = utils.today(-settings['DISPLAY_LEDGER_DAYS'])\n try:\n to = self.get_argument('to')\n except tornado.web.MissingArgumentError:\n to = utils.today()\n if from_ > to:\n events = []\n else:\n events = self.get_docs('event/ledger',\n key=from_,\n last=to+constants.CEILING)\n self.render('ledger.html',\n beerclub_balance=self.get_beerclub_balance(),\n members_balance=self.get_balance(),\n events=events,\n from_=from_,\n to=to)\n\n\nclass LedgerCsv(Ledger):\n \"CSV output of ledger data.\"\n\n def render(self, template, events, from_, to, **kwargs):\n csvbuffer = StringIO()\n writer = csv.writer(csvbuffer)\n row = ['Action',\n 'Id',\n 'Member',\n 'Beverage',\n 'Description',\n 'Credit',\n 'Date',\n 'Actor',\n 'Timestamp']\n writer.writerow(row)\n for event in events:\n writer.writerow([event['action'],\n event['_id'],\n event['member'],\n event.get('beverage') or '',\n event.get('description') or '',\n event['credit'],\n event.get('date') or '',\n event['log'].get('member') or '',\n event['log']['timestamp']])\n self.write(csvbuffer.getvalue())\n self.set_header('Content-Type', constants.CSV_MIME)\n self.set_header('Content-Disposition', \n 'attachment; filename=\"ledger.csv')\n\n\nclass Payments(RequestHandler):\n \"Page for listing recent payment events, and the Beer Club balance.\"\n\n @tornado.web.authenticated\n def get(self):\n \"Display recent payment events.\"\n try:\n from_ = self.get_argument('from')\n except tornado.web.MissingArgumentError:\n from_ = utils.today(-settings['DISPLAY_PAYMENT_DAYS'])\n try:\n to = self.get_argument('to')\n except tornado.web.MissingArgumentError:\n to = utils.today()\n if from_ > to:\n events = []\n else:\n events = self.get_docs('event/payment',\n key=from_,\n last=to+constants.CEILING)\n self.render('payments.html', events=events, from_=from_, to=to)\n\n\nclass PaymentsCsv(Payments):\n \"CSV output of payment data.\"\n\n def render(self, template, events, from_, to, **kwargs):\n csvbuffer = StringIO()\n writer = csv.writer(csvbuffer)\n row = ['Id',\n 'Member',\n 'Description',\n 'Credit',\n 'Date',\n 'Actor',\n 'Timestamp']\n writer.writerow(row)\n for event in events:\n writer.writerow([event['_id'],\n event['member'],\n event.get('description') or '',\n event['credit'],\n event.get('date') or '',\n event['log'].get('member') or '',\n event['log']['timestamp']])\n self.write(csvbuffer.getvalue())\n self.set_header('Content-Type', constants.CSV_MIME)\n self.set_header('Content-Disposition', \n 'attachment; filename=\"payments.csv')\n\n\nclass EventApiV1(ApiMixin, RequestHandler):\n \"Return event data.\"\n\n @tornado.web.authenticated\n def get(self, iuid):\n self.check_admin()\n event = self.get_doc(iuid)\n if event.get(constants.DOCTYPE) != constants.EVENT:\n raise tornado.web.HTTPError(404, reason='no such event')\n data = dict(iuid=event['_id'])\n for key in ['action', 'beverage', 'credit',\n 'date', 'description', 'log']:\n data[key] = event.get(key)\n self.write(data)\n\n\nclass MemberEventApiV1(ApiMixin, RequestHandler):\n \"Add an event for the member.\"\n\n @tornado.web.authenticated\n def post(self, email):\n self.check_admin()\n try:\n member = self.get_member(email)\n except KeyError:\n raise tornado.web.HTTPError(404, reason='no such member')\n try:\n with EventSaver(rqh=self) as saver:\n saver['member'] = member['email']\n saver.set(self.get_json_body())\n except ValueError as error:\n raise tornado.web.HTTPError(400, reason=str(error))\n self.write(dict(iuid=saver.doc['_id']))\n" }, { "alpha_fraction": 0.5346347689628601, "alphanum_fraction": 0.5352644920349121, "avg_line_length": 26.61739158630371, "blob_id": "0dc9e5fcb4c1a6b9f028733cb3332783a3894c07", "content_id": "182464947192c149d1aeeba5e3ea55a251fb5e24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3176, "license_type": "no_license", "max_line_length": 74, "num_lines": 115, "path": "/beerclub/saver.py", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "\"Context handler for saving a document. \"\n\nimport logging\n\nimport couchdb\nimport tornado.web\n\nfrom beerclub import constants\nfrom beerclub import utils\n\n\nclass Saver(object):\n \"Context manager saving the data for the document.\"\n\n doctype = None\n\n def __init__(self, doc=None, rqh=None, db=None, member=None):\n assert self.doctype in constants.ENTITIES\n if rqh is not None:\n self.rqh = rqh\n self.db = rqh.db\n self.member = member or rqh.current_user\n elif db is not None:\n self.rqh = None\n self.db = db\n self.member = member\n else:\n raise AttributeError('neither db nor rqh given')\n self.doc = doc or dict()\n self.changed = dict()\n if '_id' in self.doc:\n assert self.doctype == self.doc[constants.DOCTYPE]\n else:\n self.doc['_id'] = utils.get_iuid()\n self.doc[constants.DOCTYPE] = self.doctype\n self.initialize()\n self.setup()\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, tb):\n if type is not None: return False # No exceptions handled here.\n self.finalize()\n self.db.save(self.doc)\n self.post_process()\n\n def __setitem__(self, key, value):\n \"Update the key/value pair.\"\n try:\n checker = getattr(self, \"check_{0}\".format(key))\n except AttributeError:\n pass\n else:\n checker(value)\n try:\n converter = getattr(self, \"convert_{0}\".format(key))\n except AttributeError:\n pass\n else:\n value = converter(value)\n try:\n if self.doc[key] == value: return\n except KeyError:\n pass\n self.doc[key] = value\n self.changed[key] = value\n\n def __getitem__(self, key):\n return self.doc[key]\n\n def __delitem__(self, key):\n try:\n del self.doc[key]\n except KeyError:\n pass\n else:\n self.changed[key] = '__del__'\n\n def get(self, key, default=None):\n try:\n return self[key]\n except KeyError:\n return default\n\n def initialize(self):\n \"Set the initial values for the new document.\"\n pass\n\n def setup(self):\n \"Any additional setup. To be redefined.\"\n pass\n\n def finalize(self):\n \"Set the log fields for the event.\"\n log = dict(timestamp=utils.timestamp(),\n date=utils.today())\n if self.rqh:\n # xheaders argument to HTTPServer takes care of X-Real-Ip\n # and X-Forwarded-For\n log['remote_ip'] = self.rqh.request.remote_ip\n try:\n log['user_agent'] = self.rqh.request.headers['User-Agent']\n except KeyError:\n pass\n if self.member:\n try:\n log['member'] = self.member['email']\n except (TypeError, AttributeError, KeyError):\n pass\n self['log'] = log\n\n def post_process(self):\n \"Perform any actions after having saved the document.\"\n pass\n" }, { "alpha_fraction": 0.5406855344772339, "alphanum_fraction": 0.5445603728294373, "avg_line_length": 29.2252254486084, "blob_id": "938bddbc5ad0caadf1b75f57975f6667cf3e1a3e", "content_id": "345ff0c9d7619bca8676fa71d9ad634071fdd3dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3355, "license_type": "no_license", "max_line_length": 95, "num_lines": 111, "path": "/beerclub/uimodules.py", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "\"User interface modules.\"\n\nimport logging\n\nimport tornado.web\n\nfrom . import constants\nfrom . import settings\nfrom . import utils\n\n\nclass Money(tornado.web.UIModule):\n \"HTML for a money value.\"\n\n FORMAT = '<span class=\"text-monospace text-nowrap %s\" style=\"margin-left: %sch;\">%s</span>'\n\n def render(self, money, currency=True, padding=5):\n if money is None: money = 0\n fmt = \"{:.%if}\" % settings['MONEY_DECIMAL_PLACES']\n value = fmt.format(money)\n minus = value[:1] == '-'\n if minus:\n value = value[1:]\n iv, dv = value.split('.')\n if settings['MONEY_THOUSAND_DELIMITER']:\n ivl = []\n while len(iv):\n ivl.append(iv[-3:])\n iv = iv[:-3]\n iv = settings['MONEY_THOUSAND_DELIMITER'].join(reversed(ivl))\n value = iv + settings['MONEY_DECIMAL_POINT'] + dv\n if minus:\n value = '-' + value\n if currency:\n value += ' ' + settings['CURRENCY']\n padding = max(0, padding - len(str(int(money)))) + 0.2\n for cutoff, klass in settings['CREDIT_CLASSES']:\n if money <= cutoff: break\n else:\n klass = ''\n return self.FORMAT % (klass, padding, value)\n\nclass Status(tornado.web.UIModule):\n \"HTML for member status.\"\n\n def render(self, member):\n if member['status'] == constants.ENABLED:\n return '<strong class=\"text-success\">%s</strong>' % member['status']\n elif member['status'] == constants.DISABLED:\n return '<strong class=\"text-danger\">disabled</strong>'\n elif member['status'] == constants.PENDING:\n return '<strong class=\"text-warning\">pending</strong>'\n else: \n return member['status']\n\nclass Role(tornado.web.UIModule):\n \"HTML for member role.\"\n\n def render(self, member):\n if member['role'] == constants.ADMIN:\n return '<strong class=\"text-danger\">admin</strong>'\n else: \n return member['role']\n\nclass Datetime(tornado.web.UIModule):\n \"HTML for a datetime value.\"\n\n def render(self, datetime, small=True):\n if datetime:\n small = small and 'small' or ''\n return f'<span class=\"localtime {small}\">{datetime}</span>'\n else: \n return '-'\n\nclass NavitemActive(tornado.web.UIModule):\n \"Output active class depending on handler.\"\n\n def render(self, navbar):\n if self.handler.__class__.__name__.lower() == navbar:\n return 'active'\n else:\n return ''\n\nclass Step(tornado.web.UIModule):\n \"Step to next item in list and output whenever there is a new value.\"\n\n def render(self, value, items, store):\n if value == store.get('value'):\n pos = store.get('pos')\n if pos is None:\n pos = 0\n else:\n pos = store.get('pos')\n if pos is None:\n pos = 0\n else:\n pos += 1\n if pos >= len(items):\n pos = 0\n store['pos'] = pos\n store['value'] = value\n return items[pos]\n\nclass Date(tornado.web.UIModule):\n \"Output the date; today if no value given.\"\n\n def render(self, date=None):\n if date is None:\n return utils.today()\n else:\n return date\n" }, { "alpha_fraction": 0.6162790656089783, "alphanum_fraction": 0.6279069781303406, "avg_line_length": 30.272727966308594, "blob_id": "181142a3b3adbaedabc052b6450cc4822e89af91", "content_id": "3ff4934d7f9444134c59f9032dd81f54d6748eeb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 344, "license_type": "no_license", "max_line_length": 78, "num_lines": 11, "path": "/beerclub/html/balance_row.html", "repo_name": "pekrau/BeerClub", "src_encoding": "UTF-8", "text": "<div class=\"row my-3\">\n <div class=\"col-md\">\n Beer Club balance: {% module Money(beerclub_balance, padding=0) %}\n </div>\n <div class=\"col-md\">\n Members balance: {% module Money(members_balance, padding=0) %}\n </div>\n <div class=\"col-md\">\n Surplus: {% module Money(beerclub_balance - members_balance, padding=0) %}\n </div>\n</div>\n" } ]
23
amilacsw/TentMap_Python
https://github.com/amilacsw/TentMap_Python
6b6be30ad0d94919be6e08cf731d09c2b59986ea
4bdf3d75ad1aed1194c2659205baff5d36c7193f
b2de2c658941f819440346780266c0c60d7960e6
refs/heads/master
2021-01-10T14:28:07.810268
2016-03-27T19:29:40
2016-03-27T19:29:40
54,844,441
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3073446452617645, "alphanum_fraction": 0.3333333432674408, "avg_line_length": 21.71794891357422, "blob_id": "5c1f3439e0a66587e83074e5399cabb6d6987b55", "content_id": "397863db228cb727cf3bf27529685ef66110c061", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 885, "license_type": "no_license", "max_line_length": 63, "num_lines": 39, "path": "/1_Amila_XNvsN_1stweek.py", "repo_name": "amilacsw/TentMap_Python", "src_encoding": "UTF-8", "text": "import matplotlib\nimport pylab as pl\nimport math\n\n#-------------------------------------------------------------#\n# Constants\n#-------------------------------------------------------------#\nx0=0.2\nN=19\n\n#-------------------------------------------------------------#\n# Initial condition\n#-------------------------------------------------------------#\nz=[x0,]\ny=[x0,]\n\n#-------------------------------------------------------------#\n# Defining the function f(mu)\n#-------------------------------------------------------------#\ndef fmu(x,alpha):\n if x<0.5:\n return 2*alpha*x\n else:\n return 2*alpha*(1-x)\n\nfmu(z[0],0.7)\n\nfor i in range(N):\n y.append(fmu(y[i],0.4))\n z.append(fmu(z[i],0.7))\n\n \npl.plot(z,label=r'$\\alpha$ = 0.7')\npl.plot(y,label=r'$\\alpha$ = 0.4')\npl.legend(loc='lower right')\npl.xlabel('N')\npl.ylabel('$X_N$')\npl.title(r'$X_N$ Vs N')\npl.show()" }, { "alpha_fraction": 0.42103472352027893, "alphanum_fraction": 0.4748128056526184, "avg_line_length": 30.602149963378906, "blob_id": "b29382f3fa7efa1361d6d6a012af8067d123f891", "content_id": "e2dd55a296844c0c802a9a250d00a1d9394d8992", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2938, "license_type": "no_license", "max_line_length": 71, "num_lines": 93, "path": "/2_python_Amila_tent_map_1stweek.py", "repo_name": "amilacsw/TentMap_Python", "src_encoding": "UTF-8", "text": "import matplotlib\nimport pylab as pl\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n#-------------------------------------------------------------#\n# Initial condition\n#-------------------------------------------------------------#\nx0=np.linspace(0.0,1.0,100)\n\n\n# List of alpha's\nalpha_list=[0.1,0.4,0.8]\n\n#-------------------------------------------------------------#\n# Creating zero 3*100 matrices\n# I'm going to use columns to represent xN values for different alpha's\n# Rows will be different x0 values\n#-------------------------------------------------------------#\nz0 = np.zeros((100,3))\nz1 = np.zeros((100,3))\nz2 = np.zeros((100,3))\nz3 = np.zeros((100,3))\nz4 = np.zeros((100,3))\nz5 = np.zeros((100,3))\n# z1,z2,... means z-matrix for N=1,2,... iterations\n\n#-------------------------------------------------------------#\n#defining the function f(mu)\n#-------------------------------------------------------------#\ndef fmu(x,alpha):\n if x<0.5:\n return 2*alpha*x\n else:\n return 2*alpha*(1-x)\n\n\n#-------------------------------------------------------------#\n# Constructing z-matrices\n#-------------------------------------------------------------#\n\nfor m in range(3):\n for n in range(100):\n z0[n][m]=x0[n]\n z1[n][m]=fmu(z0[n][m],alpha_list[m])\n z2[n][m]=fmu(z1[n][m],alpha_list[m])\n z3[n][m]=fmu(z2[n][m],alpha_list[m])\n z4[n][m]=fmu(z3[n][m],alpha_list[m])\n z5[n][m]=fmu(z4[n][m],alpha_list[m])\n\n#-------------------------------------------------------------#\n# Plotting\n#-------------------------------------------------------------#\n\n# Each column is for different alpha\n\nplt.subplot(3, 1, 1)\nplt.plot(x0,z1[:,0],linestyle='-',color='r',label='N=1')\nplt.plot(x0,z2[:,0],linestyle='-',color='b',label='N=2')\nplt.plot(x0,z3[:,0],linestyle='-',color='g',label='N=3')\nplt.plot(x0,z4[:,0],linestyle='-',color='m',label='N=4')\nplt.plot(x0,z5[:,0],linestyle='-',color='c',label='N=5')\nplt.xlabel('$X_0$')\nplt.ylabel('$X_N$')\nplt.title(r'$\\alpha$ = 0.1')\nplt.legend(loc='upper right')\n\nplt.subplot(3, 1, 2)\nplt.plot(x0,z1[:,1],linestyle='-',color='r',label='N=1')\nplt.plot(x0,z2[:,1],linestyle='-',color='b',label='N=2')\nplt.plot(x0,z3[:,1],linestyle='-',color='g',label='N=3')\nplt.plot(x0,z4[:,1],linestyle='-',color='m',label='N=4')\nplt.plot(x0,z5[:,1],linestyle='-',color='c',label='N=5')\nplt.xlabel('$X_0$')\nplt.ylabel('$X_N$')\nplt.title(r'$\\alpha$ = 0.4')\nplt.legend(loc='upper right')\n\nplt.subplot(3, 1, 3)\nplt.plot(x0,z1[:,2],linestyle='-',color='r',label='N=1')\nplt.plot(x0,z2[:,2],linestyle='-',color='b',label='N=2')\nplt.plot(x0,z3[:,2],linestyle='-',color='g',label='N=3')\nplt.plot(x0,z4[:,2],linestyle='-',color='m',label='N=4')\nplt.plot(x0,z5[:,2],linestyle='-',color='c',label='N=5')\nplt.xlabel('$X_0$')\nplt.ylabel('$X_N$')\nplt.title(r'$\\alpha$ = 0.8')\nplt.legend(loc='upper right')\n\nplt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)\nplt.show()" }, { "alpha_fraction": 0.7848101258277893, "alphanum_fraction": 0.7848101258277893, "avg_line_length": 30.600000381469727, "blob_id": "19d5cd7097b3fe06bf15b4fb5bb231c2ffff2755", "content_id": "fe47aee9b9c9dddfed211df86e5990e3ecddcc7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 158, "license_type": "no_license", "max_line_length": 95, "num_lines": 5, "path": "/README.md", "repo_name": "amilacsw/TentMap_Python", "src_encoding": "UTF-8", "text": "# TentMap_Python\n\nThis is a project on discrete-time dynamical systems to obtain the bifurcation of the tent map.\n\nFile three and four take some time to run.\n" }, { "alpha_fraction": 0.4496487081050873, "alphanum_fraction": 0.477751761674881, "avg_line_length": 27.16483497619629, "blob_id": "7023edb960c83133572e608f0821fdd040a31690", "content_id": "77ef59e4cbb09c048df064c5fad5ca5bfc0b4388", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2562, "license_type": "no_license", "max_line_length": 100, "num_lines": 91, "path": "/4_Amila_bifurcation_fill.py", "repo_name": "amilacsw/TentMap_Python", "src_encoding": "UTF-8", "text": "import matplotlib\nimport pylab as pl\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle\n\n#-------------------------------------------------------------#\n# Initial condition\n#-------------------------------------------------------------#\n\nx0=0.2\n\n\n# List of alpha's\nalpha_list=np.linspace(0.1,0.9,81)\n\n# List of N values (Total number of iterations=length of x)\nx=range(2000)\n\n# Index corresponding to alpha=0.5\nmstart=(len(alpha_list)-1)/2\n\n#-------------------------------------------------------------#\n# Creating zero matrices\n# I'm going to use columns to represent xN values for different alpha's\n# Rows will be different xN values for N=0 to len(x)\n#-------------------------------------------------------------#\n\nz=np.zeros((len(x),len(alpha_list)))\nz2=np.zeros((len(x),len(alpha_list)))\nz3=np.zeros((len(x),len(alpha_list)))\n\n\nfor m in range(len(alpha_list)):\n z[0][m]=x0\n\n\n#-------------------------------------------------------------#\n#defining the function f(mu)\n#-------------------------------------------------------------#\ndef fmu(x,alpha):\n if x<0.5:\n return 2*alpha*x\n else:\n return 2*alpha*(1-x)\n\n\n#-------------------------------------------------------------#\n# Constructing z-matrix, XN's in rows and columns corresponds to alpha values\n#-------------------------------------------------------------#\n\nfor m in range(len(alpha_list)):\n for n in range(len(x)-1):\n z[n+1][m]= fmu(z[n][m],alpha_list[m]) \n\n# Counting number of times z[n][m] appears in the mth row= z2 matrix\nfor m in range(len(alpha_list)):\n for n in range(len(x)):\n z1=(((z[n][m]-0.005 < z[:,m]) & (z[:,m] < z[n][m]+0.005)).sum())/500.\n z2[n][m]=z1 \n# Normalization:\nfor m in range(len(alpha_list)):\n rowmax=max(z2[:,m]) # maximum value of a certain row in z2 matrix\n for n in range(len(x)):\n z2elemnt=z2[n][m]\n z3[n][m]=z2elemnt/rowmax # normalized z2 matrix\n \n \n\n#-------------------------------------------------------------#\n# Plotting\n#-------------------------------------------------------------#\n\ndx=0.005\ndy=0.005\n\nfig = plt.figure()\nax = fig.add_subplot(111, aspect='equal')\ncmap=plt.get_cmap('Greys')\n#cmap = plt.cm.hot\n\nfor m in range(mstart,len(alpha_list)):\n for n in range(1000,len(x)):\n ax.add_artist(Rectangle(xy=(alpha_list[m],z[n][m]),color=cmap(z3[n][m]),width=dx,height=dy))\n plt.hold(True) \nplt.axis([0.5,1,0,1])\nplt.xlabel('Alpha')\nplt.ylabel('$X_N$')\nplt.title('Tent Map')\nplt.show()" }, { "alpha_fraction": 0.40868598222732544, "alphanum_fraction": 0.4270601272583008, "avg_line_length": 25.82089614868164, "blob_id": "045a5cbd8d742f8f578e4d93174c466043ab9e05", "content_id": "26b88c98cd1afd54a184b9b259b06c79d32a36e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1796, "license_type": "no_license", "max_line_length": 86, "num_lines": 67, "path": "/3_Amila_bifurcation.py", "repo_name": "amilacsw/TentMap_Python", "src_encoding": "UTF-8", "text": "import matplotlib\nimport pylab as pl\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n#-------------------------------------------------------------#\n# Initial condition\n#-------------------------------------------------------------#\n\nx0=0.2\n\n\n# List of alpha's\nalpha_list=np.linspace(0.1,0.9,81)\n\n# List of N values (Total number of iterations=length of x)\nx=range(2000)\n\n# Index corresponding to alpha=0.5\nmstart=(len(alpha_list)-1)/2\n\n#-------------------------------------------------------------#\n# Creating zero matrices\n# I'm going to use columns to represent xN values for different alpha's\n# Rows will be different xN values for N=0 to len(x)\n#-------------------------------------------------------------#\n\nz=np.zeros((len(x),len(alpha_list)))\n\nfor m in range(len(alpha_list)):\n z[0][m]=x0\n\n\n#-------------------------------------------------------------#\n#defining the function f(mu)\n#-------------------------------------------------------------#\ndef fmu(x,alpha):\n if x<0.5:\n return 2*alpha*x\n else:\n return 2*alpha*(1-x)\n\n\n#-------------------------------------------------------------#\n# Constructing z-matrix, XN's in rows and columns corresponds to alpha values\n#-------------------------------------------------------------#\n\nfor m in range(len(alpha_list)):\n for n in range(len(x)-1):\n z[n+1][m]= fmu(z[n][m],alpha_list[m]) \n\n\n#-------------------------------------------------------------#\n# Plotting\n#-------------------------------------------------------------#\n\nfor m in range(mstart,len(alpha_list)):\n for n in range(1000,len(x)):\n plt.scatter(alpha_list[m],z[n][m],marker='s',facecolor='0.5',edgecolor='none')\n plt.hold(True) \n\nplt.xlabel('Alpha')\nplt.ylabel('$X_N$')\nplt.title('Tent Map')\nplt.show()" } ]
5
ashwinij9/advanced_linear_regression
https://github.com/ashwinij9/advanced_linear_regression
669f430ab56d42f54cab50a55ea9fa5449732885
a33584a049ead8c7f7e5e64d60fa0a5085f3174d
e2ae5b575c3bea3abf9c01e07fdd9da2af23f4ea
refs/heads/master
2021-07-25T06:37:03.488614
2017-11-05T15:00:11
2017-11-05T15:00:11
108,285,968
0
0
null
2017-10-25T15:02:52
2017-10-12T12:47:16
2017-10-25T11:14:00
null
[ { "alpha_fraction": 0.7080000042915344, "alphanum_fraction": 0.7179999947547913, "avg_line_length": 34.71428680419922, "blob_id": "5e100c5d156c5e5f4173f8f65034ac1b04f9d365", "content_id": "d9a051c7c5633c39e15a90ddb685c796617bc1af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 500, "license_type": "no_license", "max_line_length": 92, "num_lines": 14, "path": "/q02_Max_important_feature/build.py", "repo_name": "ashwinij9/advanced_linear_regression", "src_encoding": "UTF-8", "text": "# Default imports\nfrom greyatomlib.advanced_linear_regression.q01_load_data.build import load_data\nimport numpy as np\nimport pandas as pd\n# We have already loaded the data for you\ndata_set, X_train, X_test, y_train, y_test = load_data('data/house_prices_multivariate.csv')\n\ndef Max_important_feature(data_set, target_varilable, n=4):\n a=data_set.corr()[\"SalePrice\"]\n ser = pd.Series(a.values,a.index)\n a = ser.sort_values(ascending=False)\n b=a[1:5]\n c=np.asarray(b.index)\n return c\n" }, { "alpha_fraction": 0.7481481432914734, "alphanum_fraction": 0.7611111402511597, "avg_line_length": 32.75, "blob_id": "fdb58c50b8a9ade9d3fb0325c12eacf776fcd539", "content_id": "6972b62c9c768b9f6d9da3ca12a82457698416d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 540, "license_type": "no_license", "max_line_length": 92, "num_lines": 16, "path": "/q06_cross_validation/build.py", "repo_name": "ashwinij9/advanced_linear_regression", "src_encoding": "UTF-8", "text": "# Default imports\nfrom sklearn.model_selection import cross_val_score\nimport numpy as np\nfrom sklearn.linear_model import Ridge\nfrom greyatomlib.advanced_linear_regression.q01_load_data.build import load_data\n\nnp.random.seed(9)\n# We have already loaded the data for you\ndata_set, X_train, X_test, y_train, y_test = load_data('data/house_prices_multivariate.csv')\n\nmodel=Ridge(alpha=0.01)\n\n\ndef cross_validation(model,X,y):\n scores = cross_val_score(model , X_train,y_train,scoring=\"neg_mean_squared_error\",cv=5)\n return scores.mean()\n" }, { "alpha_fraction": 0.7219101190567017, "alphanum_fraction": 0.7317415475845337, "avg_line_length": 32.904762268066406, "blob_id": "35417eb12ff6772e0cc1809ed60dacbe6eddfd5d", "content_id": "48961fc1cf6642b1ed2507f221c4a621846eb307", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 712, "license_type": "no_license", "max_line_length": 92, "num_lines": 21, "path": "/q05_lasso/build.py", "repo_name": "ashwinij9/advanced_linear_regression", "src_encoding": "UTF-8", "text": "# Default imports\nfrom sklearn.linear_model import Lasso\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error\nfrom greyatomlib.advanced_linear_regression.q01_load_data.build import load_data\nnp.random.seed(9)\n\n# We have already loaded the data for you\ndata_set, X_train, X_test, y_train, y_test = load_data('data/house_prices_multivariate.csv')\n\ndef lasso(a=0.01):\n model = Lasso(alpha=a,normalize=True,random_state=9)\n model = model.fit(X_train,y_train)\n y_train_pred = model.predict(X_train)\n y_test_predict = model.predict(X_test)\n\n a= np.sqrt(mean_squared_error(y_train,y_train_pred))\n b = np.sqrt(mean_squared_error(y_test,y_test_predict))\n\n return a,b\n" }, { "alpha_fraction": 0.7213114500045776, "alphanum_fraction": 0.7349726557731628, "avg_line_length": 28.280000686645508, "blob_id": "ddc88622e353ea18da2e0dc2972e825b3498a9d8", "content_id": "fc9bf7035a6b9cc8bf1f76aadadaf602c57a8499", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 732, "license_type": "no_license", "max_line_length": 92, "num_lines": 25, "path": "/q04_ridge/build.py", "repo_name": "ashwinij9/advanced_linear_regression", "src_encoding": "UTF-8", "text": "# Default imports\nfrom sklearn.linear_model import Ridge\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error\nfrom greyatomlib.advanced_linear_regression.q01_load_data.build import load_data\nnp.random.seed(9)\n\n# We have already loaded the data for you\ndata_set, X_train, X_test, y_train, y_test = load_data('data/house_prices_multivariate.csv')\n\ndef ridge(alpha1=0.01):\n #np.random.seed(9)\n model = Ridge(alpha=alpha1,normalize=True,random_state=9)\n model=model.fit(X_train,y_train)\n ytrain_pred= model.predict(X_train)\n\n\n ytest_pred = model.predict(X_test)\n\n\n a=np.sqrt(mean_squared_error(y_train,ytrain_pred))\n b=np.sqrt(mean_squared_error(y_test,ytest_pred))\n\n return a,b\n" } ]
4
cpoll/flask-mongo-test
https://github.com/cpoll/flask-mongo-test
d423652c2ded09a3565f3a996b5f0964c7b785de
4b2d3209141a71456aa1c5f79ed270ff314ea709
031ac0a7ae7f9b109219f42c2d78deacaa4cb965
refs/heads/develop
2020-11-29T15:22:01.630598
2017-04-12T02:21:40
2017-04-12T02:21:40
87,484,265
0
0
null
2017-04-06T23:28:53
2017-04-07T00:34:48
2017-04-12T02:21:40
Python
[ { "alpha_fraction": 0.7530120611190796, "alphanum_fraction": 0.7831325531005859, "avg_line_length": 40.5, "blob_id": "3b03a4c4dffaf5cd23f0ca8c4fd15237acceef8b", "content_id": "798ebca1ae58bb770f9bfd3e5efc1c7b8b97bd43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 166, "license_type": "no_license", "max_line_length": 59, "num_lines": 4, "path": "/integration_test.sh", "repo_name": "cpoll/flask-mongo-test", "src_encoding": "UTF-8", "text": "echo \"Begin tests\"\nexport flask_mongo_test_client=\"mongodb://localhost:27017/\"\nexport flask_mongo_test_db=\"flask_mongo_test_integration\"\npytest ./test_integration -v\n" }, { "alpha_fraction": 0.5839040875434875, "alphanum_fraction": 0.6130136847496033, "avg_line_length": 23.33333396911621, "blob_id": "2c5498e44c693199e8803758a6ad30cb7895c867", "content_id": "25cf991e2ea712787d79aeef9d121b65d5152714", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 584, "license_type": "no_license", "max_line_length": 91, "num_lines": 24, "path": "/server/helpers/fizzbuzz_helper.py", "repo_name": "cpoll/flask-mongo-test", "src_encoding": "UTF-8", "text": "__MAX_ALLOWED_FIZZBUZZ_NUMBER = 100000\n\n\ndef get_fizzbuzz_range(number):\n \"\"\"\n Get an array of fizzbuzz values from 1 to number (inclusive)\n or empty array if the number is invalid\n \"\"\"\n\n if not isinstance(number, int) or number < 1 or number > __MAX_ALLOWED_FIZZBUZZ_NUMBER:\n return []\n\n return list(map(get_fizzbuzz_value, range(1, number+1)))\n\n\ndef get_fizzbuzz_value(number):\n if number % 15 == 0:\n return \"FizzBuzz\"\n elif number % 3 == 0:\n return \"Fizz\"\n elif number % 5 == 0:\n return \"Buzz\"\n else:\n return number\n" }, { "alpha_fraction": 0.7417840361595154, "alphanum_fraction": 0.751173734664917, "avg_line_length": 14.142857551574707, "blob_id": "ef083d9577b4a5ac92361ee7043b387a98d7d2c4", "content_id": "b61611e5e95ff094d39dcee82dde9ddfed6761d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 213, "license_type": "no_license", "max_line_length": 63, "num_lines": 14, "path": "/README.md", "repo_name": "cpoll/flask-mongo-test", "src_encoding": "UTF-8", "text": "Test repo for Flask + MongoDB\n\n\n\nGetting it working:\n---\nStart up mongodb\n\nsource dev_setup.sh\n OR add the environment variables within to your environment\n\npip3 install -U -r requirements.txt\n\npython3 run.py\n\n" }, { "alpha_fraction": 0.6596701741218567, "alphanum_fraction": 0.6671664118766785, "avg_line_length": 27, "blob_id": "2b9b87e7355e67fa2b89de41b4b724f57e46cd35", "content_id": "6cdadefc1207ab5ed1fa96d5140d7e3e18ead92c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 667, "license_type": "no_license", "max_line_length": 86, "num_lines": 23, "path": "/server/routes/login_route.py", "repo_name": "cpoll/flask-mongo-test", "src_encoding": "UTF-8", "text": "import json\r\nfrom flask import Blueprint, jsonify, request\r\nfrom server.access_api.authentication import Authentication\r\n\r\n\r\nLOGIN_BLUEPRINT = Blueprint('login', __name__)\r\n\r\n\r\n@LOGIN_BLUEPRINT.route('/login/', methods=[\"POST\"])\r\ndef login_route():\r\n\r\n username = request.args.get('login')\r\n password = request.data.decode('utf-8') # TODO: Make sure utf-8 works in all cases\r\n\r\n authentication = Authentication()\r\n auth_token = authentication.authenticate(username, password)\r\n\r\n if auth_token:\r\n return auth_token\r\n else:\r\n response = jsonify({'message': 'login failed'})\r\n response.status_code = 401\r\n return response\r\n" }, { "alpha_fraction": 0.7105262875556946, "alphanum_fraction": 0.7105262875556946, "avg_line_length": 18, "blob_id": "ed047b8c053c1566d48d4cffb8149fe29a673f97", "content_id": "8acc292b79b3de5a0f1817410d55569e293109a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 38, "license_type": "no_license", "max_line_length": 18, "num_lines": 2, "path": "/test.sh", "repo_name": "cpoll/flask-mongo-test", "src_encoding": "UTF-8", "text": "echo \"Begin tests\"\npytest ./server -v\n" }, { "alpha_fraction": 0.5571635365486145, "alphanum_fraction": 0.6049203872680664, "avg_line_length": 26.600000381469727, "blob_id": "683841bbf4bfa7ee1f7c8bed17cf43938f458336", "content_id": "f604916f3398d8dfecd6d5dc8e6ae80b5f7acdfc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 691, "license_type": "no_license", "max_line_length": 79, "num_lines": 25, "path": "/server/helpers/test_fizzbuzz_helper.py", "repo_name": "cpoll/flask-mongo-test", "src_encoding": "UTF-8", "text": "from .fizzbuzz_helper import get_fizzbuzz_range\n\n\ndef test_fizzbuzz_thirty():\n expected = [1, 2, \"Fizz\", 4, \"Buzz\", \"Fizz\", 7, 8, \"Fizz\", \"Buzz\",\n 11, \"Fizz\", 13, 14, \"FizzBuzz\", 16, 17, \"Fizz\", 19, \"Buzz\",\n \"Fizz\", 22, 23, \"Fizz\", \"Buzz\", 26, \"Fizz\", 28, 29, \"FizzBuzz\"]\n\n assert get_fizzbuzz_range(30) == expected\n\n\ndef test_fizzbuzz_one():\n assert get_fizzbuzz_range(1) == [1]\n\n\ndef test_fizzbuzz_zero_returns_empty_list():\n assert get_fizzbuzz_range(0) == []\n\n\ndef test_fizzbuzz_negative_returns_empty_list():\n assert get_fizzbuzz_range(-1) == []\n\n\ndef test_fizzbuzz_string_returns_empty_list():\n assert get_fizzbuzz_range(\"hello\") == []\n\n" }, { "alpha_fraction": 0.6045801639556885, "alphanum_fraction": 0.609160304069519, "avg_line_length": 30.190475463867188, "blob_id": "73a64156ee41b7052eecac975ee9196c381ee417", "content_id": "fd47981daf1829ff17d593deedf1f4cef0dc7f2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 655, "license_type": "no_license", "max_line_length": 64, "num_lines": 21, "path": "/server/routes/require_authentication.py", "repo_name": "cpoll/flask-mongo-test", "src_encoding": "UTF-8", "text": "from flask import jsonify, request\nfrom server.access_api.authentication import Authentication\n\n\ndef require_authentication(user_type):\n def decorator(function):\n def wrapper(*args, **kwargs):\n token = request.headers.get('Session-Token')\n authentication = Authentication()\n session_valid = authentication.verify_session(token)\n\n if session_valid:\n return function(*args, **kwargs)\n else:\n response = jsonify({'message': 'access denied'})\n response.status_code = 401\n return response\n\n\n return wrapper\n return decorator\n" }, { "alpha_fraction": 0.5962411165237427, "alphanum_fraction": 0.5975372791290283, "avg_line_length": 23.109375, "blob_id": "71a224d50556547913c80b26eadd72a468671973", "content_id": "564a6bec3c9da02be951c77c925bb19dc36c3057", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1543, "license_type": "no_license", "max_line_length": 79, "num_lines": 64, "path": "/server/access_api/accounts.py", "repo_name": "cpoll/flask-mongo-test", "src_encoding": "UTF-8", "text": "\"\"\"\n Methods used for user registration / login.\n\"\"\"\n\nfrom .connectionwrapper import ConnectionWrapper\nimport bcrypt\n\n\nclass Accounts:\n\n def __init__(self):\n self.accounts = ConnectionWrapper().db.accounts\n\n\n \"\"\"\n Given a username/password pair, creates the user.\n \"\"\"\n def create_user(self, username, password):\n\n if not username or not password:\n return False\n\n user = self.accounts.find_one({\"username\": username})\n if user:\n return False\n\n salt = bcrypt.gensalt()\n hashed_password = bcrypt.hashpw(password.encode('utf-8'), salt)\n new_account = {\n \"username\": username,\n \"hashed_password\": hashed_password,\n \"salt\": salt\n }\n\n self.accounts.insert_one(new_account)\n\n return True\n\n\n\n \"\"\"\n Given a username/password pair, returns whether the user is valid\n \"\"\"\n def verify_user(self, username, password):\n\n user = self.accounts.find_one({\"username\": username})\n if not user:\n return False\n\n hashed_password = bcrypt.hashpw(password.encode('utf-8'), user[\"salt\"])\n\n return hashed_password == user[\"hashed_password\"]\n\n\"\"\"\nTODO: Turn into integration tests\nif __name__ == \"__main__\":\n a = Accounts()\n\n print(a.create_user(\"cristian\", \"changeme\"))\n print(a.verify_user(\"cristian\", \"changeme\"))\n print(a.verify_user(\"cristian\", \"badpass\"))\n print(a.verify_user(\"lala\", \"lala\"))\n print(a.create_user(\"cristian\", \"changeme\"))\n\"\"\"\n" }, { "alpha_fraction": 0.6953441500663757, "alphanum_fraction": 0.6983805894851685, "avg_line_length": 32.068965911865234, "blob_id": "bf20f4d07d0abbd20ed0bb75fc0066d2bca651eb", "content_id": "afc4c8e21426cb433262a33650e433f00549e738", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 988, "license_type": "no_license", "max_line_length": 89, "num_lines": 29, "path": "/server/routes/fizzbuzz_route.py", "repo_name": "cpoll/flask-mongo-test", "src_encoding": "UTF-8", "text": "import json\r\nfrom flask import Blueprint, jsonify\r\nfrom server.helpers.fizzbuzz_helper import get_fizzbuzz_range\r\nfrom server.access_api.fizzbuzzcache import FizzbuzzCache\r\nfrom .require_authentication import require_authentication\r\n\r\n\r\nFIZZBUZZ_BLUEPRINT = Blueprint('fizzbuzz', __name__)\r\n\r\n\r\n@FIZZBUZZ_BLUEPRINT.route('/fizzbuzz/<number>', methods=[\"GET\"])\r\n@require_authentication(\"user\")\r\ndef fizzbuzz_route(number):\r\n try:\r\n number = int(number)\r\n except ValueError:\r\n response = jsonify({'message': 'input must take the form of /fizzbuzz/<number>'})\r\n response.status_code = 400\r\n return response\r\n\r\n fizzbuzz_cache = FizzbuzzCache()\r\n fizzbuzz_value = fizzbuzz_cache.get_fizzbuzz_value(number)\r\n\r\n if not fizzbuzz_value:\r\n print(\"fizzbuzz cache miss\")\r\n fizzbuzz_value = get_fizzbuzz_range(number)\r\n fizzbuzz_cache.cache_fizzbuzz_value(number, fizzbuzz_value)\r\n\r\n return json.dumps({'fizzbuzz': fizzbuzz_value})\r\n" }, { "alpha_fraction": 0.6137005686759949, "alphanum_fraction": 0.616525411605835, "avg_line_length": 27.31999969482422, "blob_id": "6cb10bb34a2e4d76b5f39d2c35f96a2444e88958", "content_id": "0f916940aadf4f9d9129a0d0ef2d018cd7e1f475", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1416, "license_type": "no_license", "max_line_length": 111, "num_lines": 50, "path": "/server/access_api/authentication.py", "repo_name": "cpoll/flask-mongo-test", "src_encoding": "UTF-8", "text": "\"\"\"\n Methods used for user login and token auth.\n\"\"\"\n\nfrom .connectionwrapper import ConnectionWrapper\nfrom datetime import datetime, timedelta\nfrom .accounts import Accounts\nimport random\n\nclass Authentication:\n\n __TOKEN_LENGTH = 100\n __VALID_TOKEN_CHARACTERS = \"abcdefghijklmnopqrstuvwxyz1234567890\"\n\n def __init__(self):\n self.sessions = ConnectionWrapper().db.sessions\n self.accounts = Accounts()\n\n\n \"\"\"\n Given valid username/password pair, returns auth token. Else returns False\n \"\"\"\n def authenticate(self, username, password):\n if self.accounts.verify_user(username, password):\n token = self.__create_token()\n\n session_entry = {\n \"token\" : token,\n \"date\" : datetime.now()\n }\n self.sessions.insert_one(session_entry)\n\n return token\n else:\n return False;\n\n\n \"\"\"\n Given a token, returns whether the token is valid\n \"\"\"\n def verify_session(self, token):\n session = self.sessions.find_one({\"token\": token})\n return session and self.__verify_session_validity(session)\n\n @staticmethod\n def __verify_session_validity(session):\n return session[\"date\"] and session[\"date\"] > (datetime.now() - timedelta(days=1))\n\n def __create_token(self):\n return ''.join(map(lambda x: random.choice(self.__VALID_TOKEN_CHARACTERS), range(self.__TOKEN_LENGTH)))\n" }, { "alpha_fraction": 0.6577181220054626, "alphanum_fraction": 0.6577181220054626, "avg_line_length": 22.526315689086914, "blob_id": "e1a15eca02d229c88b68e389554a49ff4ee2cb00", "content_id": "209eb78ae997dcc6bbc5d72a75a9e578dbcfb8f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 447, "license_type": "no_license", "max_line_length": 64, "num_lines": 19, "path": "/server/access_api/connectionwrapper.py", "repo_name": "cpoll/flask-mongo-test", "src_encoding": "UTF-8", "text": "\"\"\"\n Wrapper for mongo connections\n\"\"\"\n\nfrom pymongo import MongoClient\nimport os\n\n\nclass ConnectionWrapper:\n\n def __init__(self):\n mongo_client_key = 'flask_mongo_test_client'\n mongo_db_key = 'flask_mongo_test_db'\n\n assert mongo_client_key in os.environ\n assert mongo_db_key in os.environ\n\n mongo_client = MongoClient(os.environ[mongo_client_key])\n self.db = mongo_client[os.environ[mongo_db_key]]\n" }, { "alpha_fraction": 0.7358490824699402, "alphanum_fraction": 0.7830188870429993, "avg_line_length": 52, "blob_id": "7b7bbfca4ec967b629da7b97c9cda5b083f357e8", "content_id": "3b52eaea9ce78a4e304b04db4841f28406d6aec8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 106, "license_type": "no_license", "max_line_length": 59, "num_lines": 2, "path": "/dev_setup.sh", "repo_name": "cpoll/flask-mongo-test", "src_encoding": "UTF-8", "text": "export flask_mongo_test_client=\"mongodb://localhost:27017/\"\nexport flask_mongo_test_db=\"flask_mongo_test\"\n" }, { "alpha_fraction": 0.6512166857719421, "alphanum_fraction": 0.6512166857719421, "avg_line_length": 30.962963104248047, "blob_id": "0ce5f4b69ecc27bd38996ec2a2e1e0bb15c3e8e8", "content_id": "df5f43017aa963c75740a1be73db2bc8c8071232", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 863, "license_type": "no_license", "max_line_length": 66, "num_lines": 27, "path": "/server/access_api/fizzbuzzcache.py", "repo_name": "cpoll/flask-mongo-test", "src_encoding": "UTF-8", "text": "\"\"\"\n Methods used to store and retrieve permanently cached values\n for the 'computationally expensive'* fizzbuzz algorithm.\n *obviously not actually true or a good idea.\n\"\"\"\n\nfrom .connectionwrapper import ConnectionWrapper\n\n\nclass FizzbuzzCache:\n def __init__(self):\n self.cache = ConnectionWrapper().db.fizzbuzz_cache\n\n def get_fizzbuzz_value(self, number):\n fizzbuzz_entry = self.cache.find_one({\"number\": number})\n if fizzbuzz_entry and \"fizzbuzz_result\" in fizzbuzz_entry:\n return fizzbuzz_entry[\"fizzbuzz_result\"]\n else:\n return False\n\n def cache_fizzbuzz_value(self, number, fizzbuzz_result):\n fizzbuzz_entry = {\n \"number\": number,\n \"fizzbuzz_result\": fizzbuzz_result\n }\n cache_id = self.cache.insert_one(fizzbuzz_entry)\n return cache_id\n" }, { "alpha_fraction": 0.4137931168079376, "alphanum_fraction": 0.6379310488700867, "avg_line_length": 13.25, "blob_id": "676cecb2749616d86f72d0589d0c09039221ce5d", "content_id": "79d1b49e6b2aaeef79b9dba7f1bfa60284f1fc58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 58, "license_type": "no_license", "max_line_length": 14, "num_lines": 4, "path": "/requirements.txt", "repo_name": "cpoll/flask-mongo-test", "src_encoding": "UTF-8", "text": "pytest==3.0.7\nFlask==0.12.1\npymongo==3.4.0\nbcrypt==3.1.3\n\n" }, { "alpha_fraction": 0.7742718458175659, "alphanum_fraction": 0.7791262269020081, "avg_line_length": 23.235294342041016, "blob_id": "7bd84ba2bda925720daf032ab2249ec9e5ba9cc9", "content_id": "e55235ce1af6f8526de4bffcdb3604988d9b1278", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 412, "license_type": "no_license", "max_line_length": 53, "num_lines": 17, "path": "/server/server.py", "repo_name": "cpoll/flask-mongo-test", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nfrom flask import Flask\n\nfrom .routes.fizzbuzz_route import FIZZBUZZ_BLUEPRINT\nfrom .routes.login_route import LOGIN_BLUEPRINT\nfrom .routes.register_route import REGISTER_BLUEPRINT\n\nAPP = Flask(__name__)\n\n\[email protected](\"/\")\ndef hello():\n return \"Hello World4!\"\n\nAPP.register_blueprint(FIZZBUZZ_BLUEPRINT)\nAPP.register_blueprint(LOGIN_BLUEPRINT)\nAPP.register_blueprint(REGISTER_BLUEPRINT)\n" }, { "alpha_fraction": 0.6377952694892883, "alphanum_fraction": 0.6503937244415283, "avg_line_length": 26.863636016845703, "blob_id": "2ec47917b3a8b7fb4e5ec975fcceeb4e8b0e0f66", "content_id": "30e301180ff59603a85d2c2abe3a8cd1bb44fbb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 635, "license_type": "no_license", "max_line_length": 86, "num_lines": 22, "path": "/server/routes/register_route.py", "repo_name": "cpoll/flask-mongo-test", "src_encoding": "UTF-8", "text": "from flask import Blueprint, jsonify, request\r\nfrom server.access_api.accounts import Accounts\r\n\r\n\r\nREGISTER_BLUEPRINT = Blueprint('register', __name__)\r\n\r\n\r\n@REGISTER_BLUEPRINT.route('/register/', methods=[\"POST\"])\r\ndef login_route():\r\n\r\n username = request.args.get('login')\r\n password = request.data.decode('utf-8') # TODO: Make sure utf-8 works in all cases\r\n\r\n accounts = Accounts()\r\n result = accounts.create_user(username, password)\r\n\r\n if result:\r\n return '', 200\r\n else:\r\n response = jsonify({'message': 'account creation failed'})\r\n response.status_code = 409\r\n return response\r\n" } ]
16
MMSB-MOBI/motif-broker-request
https://github.com/MMSB-MOBI/motif-broker-request
886968bbc1f26298ad9e6058503411b0ba235252
12b5e132ca98a1e91781a05398f9e5b0c3739f70
058828be9b0a110df81b3f463a5f2c031e879466
refs/heads/master
2022-12-19T23:50:51.676210
2020-10-06T12:19:55
2020-10-06T12:19:55
294,398,736
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6825938820838928, "alphanum_fraction": 0.6877133250236511, "avg_line_length": 31.61111068725586, "blob_id": "9c08ec788544c95eb449cab5c242e6fa28fdc347", "content_id": "5bd97503a69ee9591cbf93a4072a6a54e678737f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 586, "license_type": "no_license", "max_line_length": 82, "num_lines": 18, "path": "/setup.py", "repo_name": "MMSB-MOBI/motif-broker-request", "src_encoding": "UTF-8", "text": "import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"motif-broker-request\", # Replace with your own username\n version=\"1.0.0\",\n author=\"Cécile Hilpert\",\n author_email=\"[email protected]\",\n description=\"Package to interrogate motif-broker JS microservice with python\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/MMSB-MOBI/motif-broker-request\",\n packages=setuptools.find_packages('src'),\n package_dir={'': 'src'},\n install_requires=['requests']\n)" }, { "alpha_fraction": 0.6125786304473877, "alphanum_fraction": 0.6220125555992126, "avg_line_length": 30.176469802856445, "blob_id": "397a43a27bcbb8e10ada74de88f3c9a0806c40ff", "content_id": "510fc70a68656fc0dbeafdc40d9b70430c45142b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1590, "license_type": "no_license", "max_line_length": 120, "num_lines": 51, "path": "/src/motif_broker_request/request.py", "repo_name": "MMSB-MOBI/motif-broker-request", "src_encoding": "UTF-8", "text": "import requests, time\n\nMOTIF_BROKER_ENDPOINT = \"http://localhost:3282\"\nBULK_LENGTH = 50000\nNB_JOKER = 15\nSESSION = requests.Session()\nSESSION.trust_env = False\n\ndef _default_filter(mb_res, **kwargs):\n return mb_res\n\ndef _default_transform(mb_res):\n return mb_res\n\ndef configure(motif_broker_endpoint:str):\n global MOTIF_BROKER_ENDPOINT\n MOTIF_BROKER_ENDPOINT = motif_broker_endpoint\n\ndef set_bulk_length(bulk_length:int):\n global BULK_LENGTH\n BULK_LENGTH = bulk_length\n\ndef get(list_key, filter_predicate = _default_filter, transform_predicate = _default_transform, **kwargs):\n try:\n SESSION.get(MOTIF_BROKER_ENDPOINT + \"/handshake\")\n except:\n raise Exception(f\"Can't ping motif-broker at {MOTIF_BROKER_ENDPOINT}\")\n\n bulk_requests = [list_key[i:i + BULK_LENGTH] for i in range(0, len(list_key), BULK_LENGTH)]\n\n results = {}\n\n for bulk in bulk_requests:\n joker = 0\n request_sliced = {\"keys\" : bulk}\n while True:\n try:\n raw_res = SESSION.post(MOTIF_BROKER_ENDPOINT + \"/bulk_request\",json=request_sliced).json()[\"request\"]\n except Exception:\n joker += 1\n if joker > NB_JOKER:\n raise Exception(f\"Can't interrogate motif-broker at {MOTIF_BROKER_ENDPOINT} after {NB_JOKER} tries\")\n time.sleep(5)\n continue\n \n filtered = filter_predicate(raw_res, **kwargs)\n transformed = transform_predicate(filtered)\n results.update(transformed)\n break\n\n return results\n" }, { "alpha_fraction": 0.5159420371055603, "alphanum_fraction": 0.6215320825576782, "avg_line_length": 25.52747344970703, "blob_id": "d57a26138caa22dbbb2729426f0598f4b5a72bf3", "content_id": "b8460e99b9426be13acbaa56f7be0d02e9b166c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2415, "license_type": "no_license", "max_line_length": 143, "num_lines": 91, "path": "/README.md", "repo_name": "MMSB-MOBI/motif-broker-request", "src_encoding": "UTF-8", "text": "# motif-broker-request\n\nExample in test/test.py\n\n## Configure motif-broker-request\n\n```python\nimport motif_broker_request.request as mb_request\n\nmb_request.configure(\"http://localhost:5984\") #Default is localhost:3282\n```\n\nYou can also change bulk length \n```python\nmb_request.set_bulk_length(10000) #Default is 50000\n```\n\n## Request motif-broker \n\n```python\nsgrnas = [\"AAAAAAAAAAAAAAAAAAATGGG\", \"TCCAAAAAAAAACAGTGGATTGG\", \"CACTAAAAAAGAAGACCAAGCGG\"] # sgRNAs you want to search\nres = mb_request.get(sgrnas)\n\nprint(res)\n```\n```\n>>> {\n 'AAAAAAAAAAAAAAAAAAATGGG': {\n 'dd6cfb980c8a3659acffa4f002ea7404': {\n 'NZ_LR214986.1': ['+(575298,575320)']\n }\n },\n 'TCCAAAAAAAAACAGTGGATTGG': {\n 'dd6cfb980c8a3659acffa4f002f7e935': {\n 'NZ_CP047242.1': ['+(3037771,3037793)']\n }\n },\n 'CACTAAAAAAGAAGACCAAGCGG': {\n 'dd6cfb980c8a3659acffa4f0029ff84a': {\n 'NC_009785.1': ['-(1746678,1746700)']\n },\n 'dd6cfb980c8a3659acffa4f002a00a06': {\n 'NZ_LR134336.1': ['+(192321,192343)']\n }\n }\n}\n```\n\n## Request motif-broker with some filter\nYou can write filter functions. This functions have to take motif_broker results as arguments and return the filtered version with same format \n\n**Example of function that just keep given genomes in results :**\n```python\ndef filter_genomes(mb_res, **kwargs):\n if not \"genomes\" in kwargs:\n raise Exception(\"you must provide 'genomes' argument to get function for filter_genomes function\")\n genomes = kwargs[\"genomes\"]\n\n filtered_results = {}\n for sgrna in mb_res: \n added = False \n for org in mb_res[sgrna]:\n if org in genomes:\n if added:\n filtered_results[sgrna][org] = mb_res[sgrna][org]\n else:\n filtered_results[sgrna] = {org : mb_res[sgrna][org]}\n \n return filtered_results\n```\n\nApplied this way to get results : \n```python\nres = mb_request.get(sgrnas, filter_predicate=filter_genomes, genomes=[\"dd6cfb980c8a3659acffa4f002ea7404\", \"dd6cfb980c8a3659acffa4f0029ff84a\"])\nprint(res)\n```\n```\n>>> \n{\n 'AAAAAAAAAAAAAAAAAAATGGG': {\n 'dd6cfb980c8a3659acffa4f002ea7404': {\n 'NZ_LR214986.1': ['+(575298,575320)']\n }\n },\n 'CACTAAAAAAGAAGACCAAGCGG': {\n 'dd6cfb980c8a3659acffa4f0029ff84a': {\n 'NC_009785.1': ['-(1746678,1746700)']\n }\n }\n}\n```\n\n" }, { "alpha_fraction": 0.6223628520965576, "alphanum_fraction": 0.6571729779243469, "avg_line_length": 35.5, "blob_id": "c87df93cdd4f4f1e73b8866cef466c81ee376817", "content_id": "9f5839159d6bf7eb0a847c5716555b274d111e0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 948, "license_type": "no_license", "max_line_length": 176, "num_lines": 26, "path": "/test/test.py", "repo_name": "MMSB-MOBI/motif-broker-request", "src_encoding": "UTF-8", "text": "import motif_broker_request.request as mb_request\n\ndef filter_genomes(mb_res, **kwargs):\n if not \"genomes\" in kwargs:\n raise Exception(\"you must provide 'genomes' argument to get function for filter_genomes function\")\n genomes = kwargs[\"genomes\"]\n\n filtered_results = {}\n for sgrna in mb_res: \n added = False \n for org in mb_res[sgrna]:\n if org in genomes:\n if added:\n filtered_results[sgrna][org] = mb_res[sgrna][org]\n else:\n filtered_results[sgrna] = {org : mb_res[sgrna][org]}\n \n return filtered_results\n\ndef transform(mb_res):\n return mb_res\n\nsgrnas = [\"AAAAAAAAAAAAAAAAAAATGGG\", \"TCCAAAAAAAAACAGTGGATTGG\", \"CACTAAAAAAGAAGACCAAGCGG\"] \n\nres = mb_request.get(sgrnas, filter_predicate=filter_genomes, transform_predicate = transform, genomes=[\"dd6cfb980c8a3659acffa4f002ea7404\", \"dd6cfb980c8a3659acffa4f0029ff84a\"])\nprint(res)" } ]
4
cabelotaina/craw
https://github.com/cabelotaina/craw
07f1d805464792f82d97480b171be08fe7edb651
eb71acbb7abc84d9a6a26c44182cb461ee9065f1
b0284a93f419b2f5582db15d2fe0286e705cf49a
refs/heads/master
2020-12-23T20:53:33.220520
2020-02-18T07:39:02
2020-02-18T07:39:02
237,271,765
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.508228063583374, "alphanum_fraction": 0.5154275894165039, "avg_line_length": 32.69306945800781, "blob_id": "11093bdc82d9aee8068675ad96a00b87c6c1016c", "content_id": "b51b8eab070667d7eaf4813faeacefaf7791a8ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6810, "license_type": "no_license", "max_line_length": 160, "num_lines": 202, "path": "/main.py", "repo_name": "cabelotaina/craw", "src_encoding": "UTF-8", "text": "import requests\n\nimport urllib3\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\nfrom urllib.parse import urlparse, urljoin\nimport datetime\nimport re\nimport time\nimport numpy as np\n\nclass PyCrawler(object):\n def __init__(self, starting_url = \"https://google.com\", topical = True, silence_mode = False, limit = 500, wait = False):\n self.limit = limit\n self.topical = topical\n self.starting_url = starting_url\n self.visited = set()\n self.links = open(\"links.txt\", \"w\")\n self.silence_mode = silence_mode\n self.content_types = {\"pdf\", \"jpg\", \"zip\", \"exe\"} # Determine file types to skip unwanted files (e.g. .jpg, .zip, .exe)\n self.TENKB = 10*1024\n self.ONEHUNDREDKB = 100*1024\n self.loc_normal = 10\n self.wait = wait\n self.index = 0\n\n def get_content_type(self, link):\n # Can issue ‘HEAD’ HTTP commands to get Content-Type (MIME) headers, but may cause overhead of extra Internet requests\n headers = {'user-agent': \"Some students from UAM\", 'Accept-Encoding': 'gzip'}\n try:\n h = requests.head(link, verify=False, headers=headers)\n header = h.headers\n content_type = header.get('content-type')\n return str(content_type).lower()\n except Exception as e: # Do not stop if a download fails\n print(e)\n return False\n\n def get_next_wait(self):\n return np.abs(np.random.normal(size = 1, loc=self.loc_normal*3))[0]\n\n def get_next_timeout(self):\n return np.abs(np.random.normal(size = 1, loc=self.loc_normal))[0]\n\n def get_base(self, url):\n o = urlparse(url)\n base = \"\"\n if o.scheme:\n base = f\"{o.scheme}://{o.netloc}\"\n else:\n base = f\"\"\"http:{o.geturl()}\"\"\"\n\n return base\n\n def get_html(self, url): # Fetcher must be robust\n headers = {\n \"Range\": f\"\"\"bytes={str(self.TENKB)}-{str(self.ONEHUNDREDKB)}\"\"\", # Avoid reading too much data: typically get only the first 10-100 KB per page\n 'user-agent': \"Some students from UAM\",\n 'Accept-Encoding': 'gzip'\n }\n try:\n html = requests.get(url, verify=False, timeout=self.get_next_timeout(), headers=headers) # Use a timeout mechanism (10 sec?)\n # watch URL\n # print(f\"\"\"\n # URL: {html.url}\n # Size; {len(html.content)}\n # Time: {html.elapsed.total_seconds()}\n # History: {(\n # str([(l.status_code, l.url) for l in html.history])\n # )}\n # Headers: {str(html.headers.items())}\n # Cookies: {str(html.cookies.items())}\n # \"\"\")\n except Exception as e: # Do not stop if a download fails\n print(e)\n # try the same web site with more time\n return \"\"\n return html.content.decode('latin-1')\n\n def get_links(self, url):\n html = self.get_html(url)\n\n # extract base URL\n\n base = self.get_base(url)\n\n links = re.findall('''<a\\s+(?:[^>]*?\\s+)?href=\"([^\"]*)\"''', html)\n for i, link in enumerate(links):\n if not urlparse(link).netloc:\n if link:\n if link[0] == \"/\":\n link_with_base = base + link\n else:\n link_with_base = base + \"/\" + link\n else:\n link_with_base = base\n links[i] = link_with_base\n\n return set(filter(lambda x: 'mailto' not in x, links))\n\n def extract_info(self, url):\n html = self.get_html(url)\n meta = re.findall(\"<meta .*?name=[\\\"'](.*?)['\\\"].*?content=[\\\"'](.*?)['\\\"].*?>\", html)\n return dict(meta)\n\n def url_canonization(self, url):\n # DOING: URLcanonization\n\n \"\"\" All of these URLs\n http://www.cnn.com/TECH\n http://WWW.CNN.COM/TECH/\n http://www.cnn.com:80/TECH/\n http://www.cnn.com/bogus/../TECH/\n are really equivalent to the following canonical form\n http://www.cnn.com/TECH/\n A crawler must define a set of transformation rules \"\"\"\n\n o = urlparse(url)\n\n # resolve path of current or parent directory\n o = urlparse(urljoin(o.geturl(), o.path))\n\n # remove dafault number\n if o.port == 80:\n o._replace(netloc=o.netloc.replace(str(\":\"+str(o.port)), \"\"))\n\n # remove fragment\n o._replace(fragment=\"\")\n\n # authority/netloc to lower\n # http://example.com/ == http://example.com\n netloc = o.netloc.lower()\n if netloc[len(netloc)-1] == \"/\":\n o._replace(netloc=o.netloc.lower())\n else:\n o._replace(netloc=o.netloc.lower()+\"/\")\n\n # http://example.com/data == http://example.com/data/\n path = o.path.lower()\n if path:\n if path[len(path)-1] == \"/\":\n o._replace(path=o.path.lower())\n else:\n o._replace(path=o.path.lower()+\"/\")\n\n # scheme to lower\n if o.scheme:\n o._replace(scheme=o.scheme.lower())\n url = o.geturl()\n else:\n url = f\"\"\"http:{o.geturl()}\"\"\"\n\n return url\n\n def crawl(self, url):\n for link in self.get_links(url):\n\n base = self.get_base(url)\n\n self.index += 1\n\n if (base != self.starting_url and self.topical):\n continue\n self.index -= 1\n\n if self.index == self.limit:\n break\n\n if (self.wait):\n time.sleep(self.get_next_wait())\n\n # print(\"Initial URL: \"+url)\n link = self.url_canonization(link)\n # print(\"Before canonization: \"+url)\n\n # Keep a lookup (hash) table of visited pages\n if link in self.visited: # Avoid fetching the same page twice\n continue\n self.index -= 1\n content_type = self.get_content_type(link)\n if content_type in self.content_types:\n continue\n self.index -= 1\n # TODO: save HTML\n info = self.extract_info(link+\"\\n\")\n\n self.links.write(link+\"\\n\")\n self.visited.add(link)\n if not self.silence_mode:\n print(f\"\"\"\n Link: {link}\n Description: {info.get('description')}\n Keywords: {info.get('keywords')}\n \"\"\")\n\n self.crawl(link)\n\n def start(self):\n self.crawl(self.starting_url)\n\nif __name__ == \"__main__\":\n crawler = PyCrawler(\"https://www.google.com\", True, False, 500, False)\n crawler.start()\n" }, { "alpha_fraction": 0.43290042877197266, "alphanum_fraction": 0.4458874464035034, "avg_line_length": 32.68333435058594, "blob_id": "b23a024a0aabf58c38941b364d40fdeca255b2dd", "content_id": "8e2c2d853be5f3355e8721868493ac2e88e4b4cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2079, "license_type": "no_license", "max_line_length": 182, "num_lines": 60, "path": "/crawler01.py", "repo_name": "cabelotaina/craw", "src_encoding": "UTF-8", "text": "import requests \r\nimport re \r\nfrom urllib.parse import urlparse \r\nimport time\r\nimport calendar\r\n\r\n \r\n\r\nclass PyCrawler(object): \r\n \r\n def __init__(self, starting_url): \r\n self.starting_url = starting_url \r\n self.visited = set()\r\n ts = calendar.timegm(time.gmtime())\r\n self.out = open(\"link\"+str(ts)+\".txt\" ,\"w\") \r\n\r\n def get_html(self, url): \r\n try: \r\n html = requests.get(url) \r\n except Exception as e: \r\n print(e) \r\n return \"\" \r\n return html.content.decode('latin-1') \r\n\r\n def get_links(self, url): \r\n html = self.get_html(url) \r\n parsed = urlparse(url) \r\n base = f\"{parsed.scheme}://{parsed.netloc}\" \r\n links = re.findall('''<a\\s+(?:[^>]*?\\s+)?href=\"([^\"]*)\"''', html) \r\n for i, link in enumerate(links): \r\n if not urlparse(link).netloc: \r\n link_with_base = base + link \r\n links[i] = link_with_base \r\n\r\n return set(filter(lambda x: 'mailto' not in x, links)) \r\n\r\n def extract_info(self, url): \r\n html = self.get_html(url) \r\n return None \r\n\r\n def crawl(self, url): \r\n \r\n for link in self.get_links(url): \r\n if link in self.visited: \r\n continue \r\n print(link)\r\n \r\n self.out.write(link+\"\\n\") \r\n self.visited.add(link) \r\n info = self.extract_info(link) \r\n self.crawl(link) \r\n\r\n def start(self): \r\n self.crawl(self.starting_url) \r\n \r\n \r\n\r\nif __name__ == \"__main__\": \r\n crawler = PyCrawler(\"https://www.google.com/search?q=learning+analytics&rlz=1C1CHBF_esES880ES880&oq=learn&aqs=chrome.1.69i57j35i39j0l6.2092j0j8&sourceid=chrome&ie=UTF-8\") \r\n crawler.start()" }, { "alpha_fraction": 0.6621704697608948, "alphanum_fraction": 0.6621704697608948, "avg_line_length": 33, "blob_id": "90a5744ebffd9a2def3fcc16b8f0e855d6b64ff4", "content_id": "eee3a68b87e58c7ea953531a05ef65c01b6b3130", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1631, "license_type": "no_license", "max_line_length": 100, "num_lines": 48, "path": "/myspider.py", "repo_name": "cabelotaina/craw", "src_encoding": "UTF-8", "text": "import scrapy\nfrom scrapy.crawler import CrawlerRunner\nfrom scrapy.utils.log import configure_logging\n\n# spiders documentation\n# https://docs.scrapy.org/en/latest/topics/spiders.html\n\n# spiders in practice, see below more informations ->\n# https://docs.scrapy.org/en/latest/topics/practices.html\n\n# from twisted.internet import reactor\n# from scrapy.linkextractors import LinkExtractor\n\nclass CoursesSpider(scrapy.Spider):\n\n name = \"edxCourses\"\n start_urls = ['https://www.edx.org/course']\n\n def parse(self, response):\n hxs = scrapy.Selector(response)\n all_links = hxs.xpath('*//a/@href').extract()\n\n for link in all_links:\n yield scrapy.http.Request(url=link, callback=print_this_link)\n\n def print_this_link(self, link):\n print(\"Link --> {this_link}\".format(this_link=link))\n\nclass CourseSpider(scrapy.Spider):\n name = 'edx'\n start_urls = ['https://www.edx.org/course/intro-to-data-science']\n\n def parse(self, response):\n for description in response.xpath(\"/html/body//div[contains(@class,'course-description')]\"):\n if description.css('p ::text').get().strip():\n yield {'description': description.css('p ::text').get()}\n\n for category in response.xpath(\"/html/body//a[contains(@href,'subject')]\"):\n if category.css('a ::text').get().strip():\n yield {'category': category.css('a ::text').get()}\n\n # for next_page in response.css('a.next-posts-link'):\n # yield response.follow(next_page, self.parse)\n\nconfigure_logging()\nrunner = CrawlerRunner()\nrunner.crawl(CoursesSpider)\nrunner.start()" }, { "alpha_fraction": 0.7381905317306519, "alphanum_fraction": 0.8150520324707031, "avg_line_length": 47.07692337036133, "blob_id": "f4c77545a317ef2b65c4fd2f5b09153479a4ea5c", "content_id": "bbadc53aa124b70fc81fcc4da6a436d7bcc6381b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1249, "license_type": "no_license", "max_line_length": 299, "num_lines": 26, "path": "/README.md", "repo_name": "cabelotaina/craw", "src_encoding": "UTF-8", "text": "# craw\n\n## bibliografy\n\nhttps://books.google.es/books?id=2gd5_ttNvEoC&pg=PA116&lpg=PA116&dq=canonical+form+transformation+crawler&source=bl&ots=3WL4TmvqOa&sig=ACfU3U0F1_tY10YhdyWOEBmcxG31bUxh1Q&hl=pt-BR&sa=X&ved=2ahUKEwil_ajhy6vnAhXPesAKHZbgBL4Q6AEwC3oECAcQAQ#v=onepage&q=canonical%20form%20transformation%20crawler&f=false\nhttps://books.google.es/books?id=jnCi0Cq1YVkC&pg=PA319&lpg=PA319&dq=crawler+canonical+form&source=bl&ots=SmcnnrQkke&sig=ACfU3U2Rqilml5Wy1GcvSGYXZCSWMqWwuQ&hl=pt-BR&sa=X&ved=2ahUKEwiZxuObyqvnAhUiVBUIHXrCAWsQ6AEwC3oECAkQAQ#v=onepage&q=crawler%20canonical%20form&f=false\npg 320 canonization\n\nhttps://github.com/whatwg/url/issues/369\nhttps://www.springer.com/gp/book/9789491216329\n\nhttps://moz.com/learn/seo/canonicalization\nhttps://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html\n\n\n### project based\nhttps://dev.to/fprime/how-to-create-a-web-crawler-from-scratch-in-python-2p46\nhttps://posgrado.uam.es/pluginfile.php/1312943/mod_label/intro/wm1920-unit2.1-slides-WebCrawling.pdf\n\n\n### libs\nhttps://docs.python.org/3/library/urllib.parse.html\nhttps://www.digitalocean.com/community/tutorials/como-fazer-crawling-em-uma-pagina-web-com-scrapy-e-python-3-pt\n\n### SVG\nhttps://github.com/fredwu/crawler/tree/master/lib/crawler/fetcher" } ]
4
gnfrazier/pb-combine
https://github.com/gnfrazier/pb-combine
f35c4c37599b7e32fa18fe6177568c845d768ca8
556d2e7af2d883de949f9567375b8d12c8888918
e0d587ee5020aed4346258568a07ae71e3621bac
refs/heads/master
2020-04-02T20:13:39.086219
2016-08-18T00:48:34
2016-08-18T00:48:34
65,695,557
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5280898809432983, "alphanum_fraction": 0.5347482562065125, "avg_line_length": 33.080291748046875, "blob_id": "95808da13f72bd3a948a46047919b6dce28831df", "content_id": "0ccef3423f118a918b901a6f143695768f65e064", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4806, "license_type": "no_license", "max_line_length": 120, "num_lines": 137, "path": "/pb-combine.py", "repo_name": "gnfrazier/pb-combine", "src_encoding": "UTF-8", "text": "import pandas as pd\r\nimport glob\r\nimport re\r\n\r\n\r\n'''\r\nUse to combine Performance Merch forms into Apsvia compatible price event\r\ntext-tab file.\r\n\r\nInput must be on ECOMM tab with column names of:\r\n'Load Pricing (Y/N)','ItemNo','Description','MSRP','Everyday REG Price','Sale Price','','Color','Callout/Feature/Notes'\r\n\r\ncols=['Load Pricing (Y/N)','ItemNo','Everyday REG Price','Sale Price']\r\n\r\nOutput is .txt text tab delim file for upload\r\n\r\nTODO: read load pricing flag\r\n change import to be dynamic based on working directory\r\n roll up into .exe file\r\n gui with input box?\r\n\r\n\r\n'''\r\n\r\n\r\ndef get_files():\r\n \r\n files = glob.glob(\"C:\\scripts\\combine\\*.xlsx\")# get the excel file names\r\n \r\n return files\r\n\r\ndef get_suffix(files):\r\n file_name = re.split(r'\\\\',files[0]) # parse the first file name from path\r\n parse = re.split('_', file_name[-1]) # split on _ \r\n name = re.sub('\\.xlsx','',parse[-1]) # remove the extension\r\n suffix = parse[0] + '-' + name # Concat the suffix/file name body\r\n print(suffix)\r\n return(suffix)\r\n\r\ndef create_dataframe(files):\r\n # files = str(r'c:\\merge\\pb-combine\\160711_PB10_Direct_Superflash.xlsx')\r\n df = pd.DataFrame()\r\n colnames=['Load Pricing (Y/N)',\r\n 'ItemNo',\r\n 'Description',\r\n 'MSRP',\r\n 'Everyday REG Price',\r\n 'Sale Price',\r\n '',\r\n 'Color',\r\n 'Callout/Feature/Notes'] # must match names on Merch Form\r\n cols=['Load Pricing (Y/N)','ItemNo','Everyday REG Price','Sale Price'] # names columns to be imported into dataframe\r\n dtype= object\r\n try:\r\n for f in files:\r\n data = pd.read_excel(f,\r\n sheetname='Ecomm',\r\n skiprows=3,\r\n usecols=cols,\r\n na_values=['',' ',0,0.00,'0','0.00','00.00']\r\n )\r\n df = df.append(data,ignore_index=True)\r\n except (ValueError, xlrd.biffh.XLRDError, NameError):\r\n print(\"One of the files does not conform to the import template\")\r\n except:\r\n print(\"Unexpected error:\", sys.exc_info()[0])\r\n raise \r\n return df\r\n\r\ndef groom_data(df, suffix):\r\n df.dropna(inplace=True) #strips out blank or bad rows\r\n df['set']='' #adds set column (no value)\r\n df['PageNo']=1 #adds pageno column (default 1)\r\n df['Suffix']=suffix #adds suffix column\r\n '''df.rename(index=str, columns = {'Everyday REG Price':'Event Regular Price',\r\n 'Sale Price':'Event Sale Price'}) # rename columns for upload file\r\n '''\r\n # print(df.head(10))\r\n return df\r\n\r\ndef get_file_name(suffix):\r\n file_name = suffix + \".txt\"\r\n\r\n return file_name\r\n \r\n\r\ndef write_txt(all_data, file_name, path_name):\r\n full_name = path_name + file_name + \".txt\" # concat file name from path suffix and extension\r\n out_columns=['PageNo','Set','ItemNo','Suffix','Everyday REG Price','Sale Price'] # sets the output order\r\n head_columns=['PageNo','Set','ItemNo','Suffix','Event Regular Price','Event Sale Price']\r\n all_data.to_csv(path_or_buf = full_name,\r\n sep='\\t',\r\n columns = out_columns,\r\n header = head_columns,\r\n index=False,\r\n float_format=\"%.2f\",\r\n dtype={'ItemNo': object,\r\n 'Everyday REG Price': float,\r\n 'Event Sale Price': float}) #writes file \\t denotes txt tab\r\n\r\n return(full_name)\r\n\r\ndef write_xlsx(all_data, file_name, path_name):\r\n full_name = path_name + file_name + \".xlxs\" # concat file name from path suffix and extension\r\n out_columns=['PageNo',\r\n 'Set',\r\n 'ItemNo',\r\n 'Suffix',\r\n 'Event Regular Price',\r\n 'Event Sale Price'] # sets the output order\r\n all_data.to_csv(path_or_buf = full_name,\r\n sep='\\t',\r\n columns = out_columns,\r\n header = out_columns,\r\n index=False,\r\n float_format=\"%.2f\",\r\n dtype={'ItemNo': object,\r\n 'Event Regular Price': float,\r\n 'Event Sale Price': float}) #writes file \\t denotes txt tab\r\n\r\n return(full_name)\r\n \r\ndef main():\r\n path_name=''\r\n files = get_files()\r\n suffix = get_suffix(files)\r\n file_name = get_file_name(suffix)\r\n df = create_dataframe(files)\r\n pfile = groom_data(df, suffix)\r\n txt_name = write_txt(pfile, suffix, path_name)\r\n # csv_to_txt(csv_name, suffix, path_name)\r\n print(txt_name)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n" } ]
1
brandonsfick/Helix_Eye_InTheSky
https://github.com/brandonsfick/Helix_Eye_InTheSky
d8784889fba28eefd464916a941e0c9ac160ac99
eb6eddd86325b23b5b8df00ded118c22c3eedda4
7b42fa22ad42b6238cb3718e0449c8c336cfc122
refs/heads/master
2020-04-29T08:58:40.037453
2019-05-22T22:27:11
2019-05-22T22:27:11
176,006,595
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.5997926592826843, "alphanum_fraction": 0.6168999671936035, "avg_line_length": 34.09090805053711, "blob_id": "deabe5226d21c74b61699410ca7db555bb8dd954", "content_id": "d27149914fa21f41b9fa539b8b99a80e4ab114f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1929, "license_type": "no_license", "max_line_length": 96, "num_lines": 55, "path": "/Helix_Eye_InTheSky/Photoeditor.py", "repo_name": "brandonsfick/Helix_Eye_InTheSky", "src_encoding": "UTF-8", "text": "import os.path\nimport os\nfrom PIL import Image\nglobal img_name\ndef get_img_dir(path):\n img_dir = os.path.join(path)\n return img_dir\n\ndef open_img(path):\n img_dir = get_img_dir(path)\n img_name = i\n full_img_path = os.path.join(img_dir, img_name)\n img = Image.open(full_img_path)\n return img\n\ndef crop_image(img, xy, scale_factor):\n '''Crop the image around the tuple xy\n\n Inputs:\n -------\n img: Image opened with PIL.Image\n xy: tuple with relative (x,y) position of the center of the cropped image\n x and y shall be between 0 and 1\n scale_factor: the ratio between the original image's size and the cropped image's size\n '''\n center = (img.size[0] * xy[0], img.size[1] * xy[1])\n new_size = (img.size[0] / scale_factor, img.size[1] / scale_factor)\n left = max (0, (int) (center[0] - new_size[0] / 2))\n right = min (img.size[0], (int) (center[0] + new_size[0] / 2))\n upper = max (0, (int) (center[1] - new_size[1] / 2))\n lower = min (img.size[1], (int) (center[1] + new_size[1] / 2))\n cropped_img = img.crop((left, upper, right, lower))\n return cropped_img\n\ndef save_img(img, img_name):\n img_dir = get_img_dir()\n full_img_path = os.path.join(img_dir, img_name)\n img.save(full_img_path)\n\nif __name__ == '__main__':\n def copyFile(sourceDir,targetDir):\n for files in os.listdir(sourceDir):\n sourceFile=os.path.join(sourceDir,files)\n if os.path.isfile(sourceFile) and sourceFile.find('.jpg')>0:\n shutil.copy(sourceFile,targetDir)\n \n dirname = r'/Users/BFick/Dropbox/Apps/Camera_Images/Apps/Camera_Images'\n\n for filename in os.listdir(dirname):\n if os.path.isdir(i):\n path = os.path.join('/Users/BFick/Dropbox/Apps/Camera_Images/Apps/Camera_Images', i)\n ams = open_img(path,i)\n\n crop_ams = crop_image(ams, (0.58, 0.68), 1.7)\n save_img(crop_ams, \"Crop_\"+ ImageName)" }, { "alpha_fraction": 0.5654761791229248, "alphanum_fraction": 0.5694444179534912, "avg_line_length": 26.01785659790039, "blob_id": "73247a7abbe3445a4cfa43ce3f7173c57798c2e9", "content_id": "361fbecb7faac1eace21c3f05d12355d402f259a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1512, "license_type": "no_license", "max_line_length": 127, "num_lines": 56, "path": "/Helix/app.py", "repo_name": "brandonsfick/Helix_Eye_InTheSky", "src_encoding": "UTF-8", "text": "import os\nimport os, time\nimport pandas as pd\nimport numpy as np\nfrom pw import * \nimport sqlalchemy\nfrom flask_pymongo import PyMongo\nfrom flask import send_file\nimport dropbox\n\nfrom flask import Flask, render_template, redirect\nfrom flask import send_from_directory\n\napp = Flask(__name__)\n\n\n\ndbx = dropbox.Dropbox(access_token)\nk=0\nglobal before \nbefore = dict ([(f, None) for f in dbx.files_list_folder('/Apps/Camera_Images/Test/').entries])\[email protected](\"/\")\ndef home():\n global k\n global dbx\n global before\n while 1:\n added = ''\n \n after = dict ([(f, None) for f in dbx.files_list_folder('/Apps/Camera_Images/Test').entries]) # Load 'after' dictionary\n added = [f for f in after if not f in before] # Was anything added?\n removed = [f for f in before if not f in after] # Was anything removed?\n k=k+1\n before = after\n print(before)\n print(after)\n print(added)\n time.sleep (60) # 5 sec between polling\n # if added: \n # print(added)\n \n \n # target = \"/Apps/Camera_Images/\" # the target folder\n # targetfile = target + filename # the target path and file name\n\n # f, metadata = client.get_file_and_metadata(target+ added)\n \n # out = open(j)\n # out.write(f.read())\n # out.close()\n # print metadata\n\n \n\nif __name__ == \"__main__\":\n app.run(debug=True)" }, { "alpha_fraction": 0.8088376522064209, "alphanum_fraction": 0.8097983002662659, "avg_line_length": 27.135135650634766, "blob_id": "8af623318a72d5e97bc3f744c59ba9b58de3743f", "content_id": "f31ee9caf757f64ae9659ee8cac6a771b16542ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1043, "license_type": "no_license", "max_line_length": 147, "num_lines": 37, "path": "/README.md", "repo_name": "brandonsfick/Helix_Eye_InTheSky", "src_encoding": "UTF-8", "text": "# Helix_Eye_InTheSky\nMachine Learning Enhancements to Home Security Camera System\n\n# Challenge\nMany of today’s home security cameras send users an alert when any movement is detected and recorded. \nMovement can be caused by \nPeople\nVehicles\nWildlife\nWeather (moving tree limbs/leaves, rain, snow, etc.) \nInsects\nBlowing trash\nChanges in ambient lighting \n\nReceiving too many false positive alerts can be overwhelming, and can lead users to ignore alerts, or deactivate this important feature altogether.\n\n# Solution\nReduce the number of false positive alerts using a machine learning system to evaluate and identify specific content in a security camera image.\n\nSend alerts only when the presence of a person or unrecognized automobile is captured by the camera.\n# Tools Used\nPython Pandas\nPython Flask\nPython Scikit\nMongoDB Database\nKeras Pre-Trained Models\nSupervised Learning K-Means Model\nImageNet\nTwilio\nDropbox\nHTML/CSS/Bootstrap\nYouTube Livestream\nSV3C IP POE HD Camera\nCamera Software\n\nProject by:\nBrandon Fick, Raleigh Love, Franko Ortmann, and Scott Stevener\n" }, { "alpha_fraction": 0.7072758078575134, "alphanum_fraction": 0.7143824100494385, "avg_line_length": 30.11578941345215, "blob_id": "6347d437d09eb9d2c571a955151861e03da08ab5", "content_id": "61f9ee3fda959436945f7b2f17023e01a3be7241", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2955, "license_type": "no_license", "max_line_length": 241, "num_lines": 95, "path": "/Helix_Eye_InTheSky/app.py", "repo_name": "brandonsfick/Helix_Eye_InTheSky", "src_encoding": "UTF-8", "text": "import os\nimport os, time\nimport pandas as pd\nimport numpy as np\nimport pandas\n\nimport sqlalchemy\nfrom flask import send_file\nfrom flask import Flask, render_template\n# import dropbox\nimport glob\nimport datetime\nfrom shutil import copy2\nimport re\nimport fnmatch\nimport random\nimport shutil\nimport static\nimport sys\napp = Flask(__name__)\n\nglobal path_to_watch\n\n\n\[email protected](\"/\")\ndef index():\n #imports logs and extracts the SSIM and XCP variable\n dfOther = pandas.read_csv('OtherphotoLog.csv')\n dfPerson = pandas.read_csv('PeopleLog.csv')\n dfVehicle = pandas.read_csv('VehicleLog.csv')\n OtherPercent=dfOther.tail(1)\n VehiclePercent =dfVehicle.tail(1)\n PersonPercent= dfPerson.tail(1)\n\n OtherPercent=OtherPercent.XCP.values[0]\n VehiclePercent=VehiclePercent.SSIM.values[0]\n PersonPercent=PersonPercent.SSIM.values[0]\n\n #finds file and the path\n def newest(path):\n\n files = os.listdir(path)\n paths = [os.path.join(path, basename) for basename in files]\n recentPath=max(paths, key=os.path.getctime)\n result = recentPath.split('/')[-1]\n return result\n NewCarpath= r\"/Users/BFick/Desktop/Helix_Eye_InTheSky/Helix_Eye_InTheSky/static/NewCar_image/\" # UPDATE for your computer\n NewPersonpath= r\"/Users/BFick/Desktop/Helix_Eye_InTheSky/Helix_Eye_InTheSky/static/NewPerson_image/\" # UPDATE for your computer\n NonAlertpath =r\"/Users/BFick/Desktop/Helix_Eye_InTheSky/Helix_Eye_InTheSky/static/NonAlert_image/\" # UPDATE for your computer\n \n NewCarImage=newest(NewCarpath)\n NewCarPath = \"static/NewCar_image/\" + NewCarImage\n print(NewCarPath)\n\n NewPersonImage=newest(NewPersonpath)\n NewPersonpath = \"static/NewPerson_image/\" + NewPersonImage\n print(NewPersonpath)\n\n NonAlertpath=newest(NonAlertpath)\n NonAlertpath = \"static/NonAlert_image/\" + NonAlertpath\n print(NonAlertpath)\n \n return render_template(\"index.html\", Most_Recent_Car_Image=NewCarPath, Most_Recent_Person_Image=NewPersonpath, Most_Recent_NonAlert_Image=NonAlertpath,OtherPercent=OtherPercent,VehiclePercent=VehiclePercent, PersonPercent=PersonPercent )\n\[email protected](\"/all_images.html\")\ndef index2():\n \n def files(path):\n files_path = os.path.join(path, '*')\n files = sorted(glob.iglob(files_path), key=os.path.getctime, reverse=True) \n return files\n \n NewPath = r\"/Users/BFick/Desktop/Helix_Eye_InTheSky/Helix_Eye_InTheSky/static/Last20\" # UPDATE for your computer\n filePaths=files(NewPath)\n s=0\n updatedfiles=[]\n for s in range(0,20):\n filename=filePaths[s].rsplit('/',1)[1]\n updatedfiles.append(r\"/static/Last20/\" +filename)\n return render_template(\"all_images.html\", files=updatedfiles)\n\[email protected](\"/about.html\")\ndef index3():\n\n return render_template(\"about.html\")\n\[email protected](\"/live_feed.html\")\ndef index4():\n\n return render_template(\"live_feed.html\")\n\nif __name__ == \"__main__\":\n #app.debug = True\n app.run()" }, { "alpha_fraction": 0.544219434261322, "alphanum_fraction": 0.5643821358680725, "avg_line_length": 36.641693115234375, "blob_id": "87d3b42c0570ff536dd6ed392f3563a05c7766f1", "content_id": "dc6d7365344a88e393b042403c4be1f10beba7bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11556, "license_type": "no_license", "max_line_length": 153, "num_lines": 307, "path": "/Helix_Eye_InTheSky/theEyeapp.py", "repo_name": "brandonsfick/Helix_Eye_InTheSky", "src_encoding": "UTF-8", "text": "#import libraries\nimport scipy.io as sio\nimport pandas as pd\nimport numpy as np\nimport os\nimport tensorflow as tf\nimport keras\nimport matplotlib.pyplot as plt\nimport csv\nfrom datetime import datetime\nimport time\nimport glob\nfrom shutil import copy2\nimport shutil\nfrom twilio.rest import Client \nimport api_key\n\n\n#preliminary model libraries\nfrom keras import regularizers\nfrom keras.preprocessing import image\nfrom keras.layers import Dense, GlobalAveragePooling2D, Dropout\nfrom keras.models import Model\nfrom keras.applications.xception import (\n Xception, preprocess_input, decode_predictions)\n\n#comparator libraries\nfrom skimage import io, measure\nfrom skimage.measure import compare_ssim\nimport cv2\n\n#declare globals\npath_to_watch = r\"/Users/BFick/Dropbox/Apps/Camera_Images/Apps/Camera_Images/\" # Watching Desktop\npath = r\"/Users/BFick/Dropbox/Apps/Camera_Images_Cropped/Apps/Camera_Images_Cropped\"\nbefore = dict ([(f, None) for f in os.listdir (path)]) # Load 'before' dictionary\n\n\ndef newest(path):\n files = os.listdir(path)\n paths = [os.path.join(path, basename) for basename in files]\n recentPath=max(paths, key=os.path.getctime)\n return recentPath\n\ndef files(path):\n files_path = os.path.join(path, '*')\n files = sorted(glob.iglob(files_path), key=os.path.getctime, reverse=True) \n return files\n\ndef Model(Image_path):\n Alertlist = [False,\"V/P\",\"SSIM\",\"XCP\"]\n\n #Load Pre-trained model\n model = Xception(\n include_top=True,\n weights='imagenet')\n image_size = (299, 299, 3)\n\n #load pre-trained model categories\n VID = pd.read_csv(r\"/Users/BFick/Desktop/Helix_Eye_InTheSky/vehicle_categories.txt\", sep='\\t')\n CID = pd.read_csv(r\"/Users/BFick/Desktop/Helix_Eye_InTheSky/clothing_categories.txt\", sep='\\t')\n\n\n #Run image through Primary Model\n data2 = []\n ismatch = 0\n\n image_size = (299, 299, 3)\n\n #image_path = newest(path)\n img = image.load_img(Image_path, target_size=image_size)\n\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n x = preprocess_input(x)\n\n predictions = model.predict(x)\n\n result = decode_predictions(predictions, top=3)\n topresult = result[0][0]\n result2 = result[0][1]\n result3 = result[0][2]\n\n if (topresult[0] in VID['Serial'].values) or (result2[0] in VID['Serial'].values) or (result3[0] in VID['Serial'].values):\n imgclass = \"Vehicle\"\n if (topresult[0] in VID['Serial'].values):\n classp = str((round(topresult[2]*1000))/10)\n elif (result2[0] in VID['Serial'].values):\n classp = str((round(result2[2]*1000))/10)\n else: # (result3[0] in VID['Serial'].values):\n classp = str((round(result3[2]*1000))/10)\n ismatch = 1 \n elif (topresult[0] in CID['Serial'].values) or (result2[0] in CID['Serial'].values) or (result3[0] in CID['Serial'].values):\n imgclass = \"Person\"\n if (topresult[0] in CID['Serial'].values):\n classp = str((round(topresult[2]*1000))/10)\n elif (result2[0] in CID['Serial'].values):\n classp = str((round(result2[2]*1000))/10)\n else: #(result3[0] in CID['Serial'].values):\n classp = str((round(result3[2]*1000))/10) \n ismatch = 2\n else:\n imgclass = \"Other\"# + str((round(topresult[2]*1000))/10)\n classp = str((round(topresult[2]*1000))/10)\n Alertlist = [False,\"Other\",\"N/A\",classp]\n return Alertlist\n\n Alertlist[3] = classp\n\n data2.append([topresult[0],topresult[1],(round(topresult[2]*1000))/10,imgclass, classp, ismatch])\n data2 = pd.DataFrame(data2, columns = ['Serial','Pred','Prob','Class','Class Pr','Match'])\n\n #load Scenario images for the comparator\n Sarray = [0]\n for scen in range(1,19):\n Sarray.append(io.imread(r'/Users/BFick/Desktop/Helix_Eye_InTheSky/Car Data/cam_base/S%s.jpg' %(scen)))\n\n comparray = []\n i1 =0\n\n #cycle through photo backlog\n for img1 in data2['Serial']:\n #for img1 in range(120,130):\n i1+=1\n # print(i1,data2[data2.Serial==img1].Match.item())\n \n #cycle through scenarios for each photo\n resultarray = []\n \n imgpathio = io.imread(Image_path)\n \n if data2[data2.Serial==img1].Match.item() ==2:\n #if photo matched to person, run against S1 & S10\n for R in (1,10):\n scenario = Sarray[R]\n combossim = round(compare_ssim(imgpathio,scenario,multichannel=True)*1000)/10\n\n resultarray.append([R,combossim,\"P\"])\n else: \n #if photo matched to vehicle, run against all\n for S in range(1,19):\n scenario = Sarray[S]\n combossim = round(compare_ssim(imgpathio,scenario,multichannel=True)*1000)/10\n\n resultarray.append([S,combossim,\"V\"])\n resultdf = pd.DataFrame(resultarray, columns = ['Scenario','SSIM','Type']) \n \n\n #find best match\n Y = int(str(resultdf.loc[resultdf['SSIM'].idxmax()][0]).split('.')[0])\n Bestmatch = Y\n Bestssim = resultdf.loc[resultdf['SSIM'].idxmax()][1]\n Type = resultdf.loc[resultdf['SSIM'].idxmax()][2]\n #Mark high & Low\n\n #Person thresholds are different from vehicle thresholds \n if data2[data2.Serial==img1].Match.item() ==2:#Is it a person\n Alertlist[1] = \"P\"\n if Bestssim >76:\n Alertlist[0] = False\n else:\n Alertlist[0] = True\n else: #or is it a vehicle\n Alertlist[1] = \"V\" \n if Bestssim >82:\n Alertlist[0] = False\n else:\n Alertlist[0] = True\n Alertlist[2] = Bestssim\n \n return Alertlist\n\ndef RunModel():\n #find most recent file\n inputfile = newest(path)\n #run modle on most reent file\n ImageCheck = Model(inputfile)\n with open(\"ImageLog.csv\", \"a\") as outfile:\n #add new line\n outfile.write(\"\\n\")\n #add timestamp from file\n outfile.write(datetime.utcfromtimestamp(int(os.path.getctime(inputfile))).strftime('%Y-%m-%d %H:%M:%S'))\n for entries in ImageCheck:\n outfile.write(\", \")\n outfile.write(str(entries))\n\n if ImageCheck[1] == \"V\":\n with open(\"VehicleLog.csv\", \"a\") as outfile:\n #add new line\n outfile.write(\"\\n\")\n #add timestamp from file\n outfile.write(datetime.utcfromtimestamp(int(os.path.getctime(inputfile))).strftime('%Y-%m-%d %H:%M:%S'))\n for entries in ImageCheck:\n outfile.write(\", \")\n outfile.write(str(entries))\n elif ImageCheck[1] ==\"P\":\n with open(\"PeopleLog.csv\", \"a\") as outfile:\n #add new line\n outfile.write(\"\\n\")\n #add timestamp from file\n outfile.write(datetime.utcfromtimestamp(int(os.path.getctime(inputfile))).strftime('%Y-%m-%d %H:%M:%S'))\n for entries in ImageCheck:\n outfile.write(\", \")\n outfile.write(str(entries))\n else:\n with open(\"OtherphotoLog.csv\", \"a\") as outfile:\n #add new line\n outfile.write(\"\\n\")\n #add timestamp from file\n outfile.write(datetime.utcfromtimestamp(int(os.path.getctime(inputfile))).strftime('%Y-%m-%d %H:%M:%S'))\n for entries in ImageCheck:\n outfile.write(\", \")\n outfile.write(str(entries))\n #send alert or not\n return ImageCheck\n\nwhile 1:\n NewCarpath= r\"/Users/BFick/Desktop/Helix_Eye_InTheSky/Helix_Eye_InTheSky/static/NewCar_image/\" # * means all if need specific format then *.csv\n NewPersonpath= r\"/Users/BFick/Desktop/Helix_Eye_InTheSky/Helix_Eye_InTheSky/static/NewPerson_image/\" # * means all if need specific format then *.csv\n NonAlertpath =r\"/Users/BFick/Desktop/Helix_Eye_InTheSky/Helix_Eye_InTheSky/static/NonAlert_image/\"\n Car = None\n Person = None\n nonAlert = None\n added = ''\n after = dict ([(f, None) for f in os.listdir (path_to_watch)]) # Load 'after' dictionary\n added = [f for f in after if not f in before] # Was anything added?\n removed = [f for f in before if not f in after] # Was anything removed?\n \n if added: \n print(\"Added: \", \", \".join (added))\n \n filePaths=files(path_to_watch)\n\n NewPath = r\"/Users/BFick/Desktop/Helix_Eye_InTheSky/Helix_Eye_InTheSky/static/Last20\"\n shutil.rmtree(NewPath)\n os.makedirs(NewPath)\n s=0\n updatedfiles=[]\n for s in range(0,20):\n copy2(filePaths[s], NewPath)\n if before != after:\n before = after\n\n # open the file and upload it\n # with open(filepath, \"rb\") as f:\n \n #Run Model, receives input as a file path using newest(path)\n \n Sendtext = RunModel()\n\n \n\n \n # statVar=\n if Sendtext[0]==False:\n filelist = glob.glob(os.path.join(NonAlertpath, \"*.jpg\"))\n for f in filelist:\n os.remove(f)\n NonAlertpath=newest(path_to_watch)\n result = NonAlertpath.split('/')[-1]\n NewAlertpath = \"static/NonAlert_image/\" + result\n shutil.copyfile(NonAlertpath, NewAlertpath)\n print(NonAlertpath)\n \n elif Sendtext[1] == \"V\":\n filelist = glob.glob(os.path.join(NewCarpath, \"*.*\"))\n for f in filelist:\n os.remove(f)\n # os.mkdir(NewCarpath)\n NewCarImage=newest(path_to_watch)\n result = NewCarImage.split('/')[-1]\n NewCarpath = \"static/NewCar_image/\" + result\n shutil.copyfile(NewCarImage, NewCarpath) \n\n print(NewCarpath)\n\n elif Sendtext[1] == \"P\":\n filelist = glob.glob(os.path.join(NewPersonpath, \"*.*\"))\n for f in filelist:\n os.remove(f)\n # os.mkdir(NewPersonpath)\n NewPersonImage=newest(path_to_watch)\n result = NewPersonImage.split('/')[-1]\n NewPersonpath = \"static/NewPerson_image/\" + result\n shutil.copyfile(NewPersonImage, NewPersonpath) \n\n print(NewPersonpath)\n\n if Sendtext[0]:\n \n # Your Account Sid and Auth Token from twilio.com/console\n # DANGER! This is insecure. See http://twil.io/secure\n # account_sid = str(account_sid1)\n # auth_token = str(auth_token1)\n client = Client(api_key.account_sid, api_key.auth_token)\n if Sendtext[1] == \"V\":\n text_message = \"Danger Will Robinson...We have identified an unidentified vehicle. Alert Alert. Danger.\" \n else:\n text_message =\"Danger Will Robinson...We have identified a Person. Alert Alert. Danger.\"\n message = client.messages \\\n .create(\n body= text_message,\n from_='+13142072684',\n to='+1314-537-5418'\n )\n print(message.sid) \n\n time.sleep (1) # 5 sec between polling\n" } ]
5
carolinepie/udacity_ml_capstone
https://github.com/carolinepie/udacity_ml_capstone
33b884c0d1024d3b2646a3bb213728fcfd8f925d
f6e5fd2f5b0283f9405fe6612b86508cd9fa19e6
be129c0a1752e55adb10e26c51a0379ff5e49a50
refs/heads/master
2023-06-24T17:51:35.866504
2021-07-26T07:24:54
2021-07-26T07:24:54
388,325,975
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6819277405738831, "alphanum_fraction": 0.6827309131622314, "avg_line_length": 28.654762268066406, "blob_id": "2f8f9b558ea816d59543f9dabe5eba76d03bd03a", "content_id": "d1f8d053cdc42efd832d4b9b7713861ae770de10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2490, "license_type": "no_license", "max_line_length": 107, "num_lines": 84, "path": "/lstm/predict.py", "repo_name": "carolinepie/udacity_ml_capstone", "src_encoding": "UTF-8", "text": "import argparse\n# import json\nimport os\n# import pickle\nimport sys\n# import sagemaker_containers\n# import pandas as pd\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.utils.data\n\n# from io import StringIO\nfrom six import BytesIO\n\nfrom model import LSTMClassifier\nNP_CONTENT_TYPE = 'application/x-npy'\n\ndef model_fn(model_dir):\n \"\"\"Load model\"\"\"\n print(\"Load model.\")\n\n # First, load the parameters used to create the model.\n model_info = {}\n model_info_path = os.path.join(model_dir, 'model_info.pth')\n with open(model_info_path, 'rb') as f:\n model_info = torch.load(f)\n\n print(\"model_info: {}\".format(model_info))\n\n # Determine the device and construct the model.\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model = LSTMClassifier(model_info['sequence_size'], model_info['input_size'], model_info['hidden_dim'])\n\n # Load the stored model parameters.\n model_path = os.path.join(model_dir, 'model.pth')\n with open(model_path, 'rb') as f:\n model.load_state_dict(torch.load(f))\n\n # set to eval mode\n model.to(device).eval()\n\n print(\"Done loading model.\")\n return model\n\n# Provided input data loading\ndef input_fn(input_data, content_type):\n# return input_data\n print('Deserializing the input data.')\n if content_type == NP_CONTENT_TYPE:\n stream = BytesIO(input_data)\n return np.load(stream)\n raise Exception('Requested unsupported ContentType in content_type: ' + content_type)\n\n# Provided output data handling\ndef output_fn(prediction_output, accept):\n# return prediction_output\n print('Serializing the generated output.')\n if accept == NP_CONTENT_TYPE:\n stream = BytesIO()\n np.save(stream, prediction_output)\n return stream.getvalue(), accept\n raise Exception('Requested unsupported ContentType in Accept: ' + accept)\n\n# Provided predict function\ndef predict_fn(input_data, model):\n print('Predicting value for the input data...')\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n \n # Process input_data so that it is ready to be sent to our model.\n data = torch.from_numpy(input_data.astype('float32'))\n print(data)\n data = data.to(device)\n\n # Put the model into evaluation mode\n model.eval()\n\n # Compute the result of applying the model to the input data\n out = model(data)\n out_np = out.cpu().detach().numpy()\n\n return out_np" }, { "alpha_fraction": 0.5627095699310303, "alphanum_fraction": 0.5794768333435059, "avg_line_length": 34.52381134033203, "blob_id": "d4522ffdc4bb49c646cd2e6495f13d6bfc4b8d9f", "content_id": "732873177ed06a7aeceae4900694b60e7f413cbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1491, "license_type": "no_license", "max_line_length": 108, "num_lines": 42, "path": "/lstm/model.py", "repo_name": "carolinepie/udacity_ml_capstone", "src_encoding": "UTF-8", "text": "import torch.nn as nn\nfrom torch.nn.init import kaiming_normal_\n\nclass LSTMClassifier(nn.Module):\n def __init__(self, sequence_size, input_size, hidden_dim):\n \"\"\"\n Initialize the model by settingg up the various layers.\n \"\"\"\n super(LSTMClassifier, self).__init__()\n\n self.lstm = nn.LSTM(input_size=input_size, hidden_size = hidden_dim, batch_first=True, num_layers=1)\n kaiming_normal_(self.lstm.weight_ih_l0)\n kaiming_normal_(self.lstm.weight_hh_l0)\n self.lstm.bias_ih_l0.data.zero_()\n self.lstm.bias_hh_l0.data.zero_()\n n = self.lstm.bias_hh_l0.size(0)\n start, end = n//4, n//2\n self.lstm.bias_hh_l0.data[start:end].fill_(1.)\n \n interim = 12\n self.dense = nn.Linear(in_features=hidden_dim, out_features=interim)\n kaiming_normal_(self.dense.weight.data)\n self.activation = nn.ReLU()\n \n self.dense2 = nn.Linear(in_features=interim, out_features=1)\n kaiming_normal_(self.dense2.weight.data)\n self.activation2 = nn.ReLU()\n def forward(self, x):\n \"\"\"\n Perform a forward pass of our model on some input.\n \"\"\"\n lstm_out, (h_n, c_n) = self.lstm(x)\n out = self.dense(lstm_out[:, -1])\n linear1 = self.activation(out)\n \n out2 = self.dense2(linear1)\n# final = self.activation2(out2) \n final = out2\n \n# print('final')\n# print(final)\n return final" }, { "alpha_fraction": 0.6169758439064026, "alphanum_fraction": 0.621737003326416, "avg_line_length": 38.558441162109375, "blob_id": "77103160f6f7581fff61a4a6e99feedf595ab093", "content_id": "c1d68c7ae4fa3fde74e0de4607885c0019791509", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6091, "license_type": "no_license", "max_line_length": 127, "num_lines": 154, "path": "/lstm/train.py", "repo_name": "carolinepie/udacity_ml_capstone", "src_encoding": "UTF-8", "text": "import argparse\nimport json\nimport os\nimport pandas as pd\nimport numpy as np\nimport torch\nimport torch.optim as optim\nimport torch.utils.data\nimport torchvision.transforms as transforms\n\n# imports the model in model.py by name\nfrom model import LSTMClassifier\nfrom window_dataset import WindowDataset\ndef model_fn(model_dir):\n \"\"\"Load model\"\"\"\n print(\"Load model.\")\n\n # First, load the parameters used to create the model.\n model_info = {}\n model_info_path = os.path.join(model_dir, 'model_info.pth')\n with open(model_info_path, 'rb') as f:\n model_info = torch.load(f)\n\n print(\"model_info: {}\".format(model_info))\n\n # Determine the device and construct the model.\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model = LSTMClassifier(model_info['sequence_size'], model_info['input_size'], model_info['hidden_dim'])\n\n # Load the stored model parameters.\n model_path = os.path.join(model_dir, 'model.pth')\n with open(model_path, 'rb') as f:\n model.load_state_dict(torch.load(f))\n\n # set to eval mode\n model.to(device).train()\n\n print(\"Done loading model.\")\n return model\n\ndef _get_train_data_loader(input_size, seq_length, batch_size, training_dir, train_file):\n print(\"Get train data loader.\")\n print('batch_size: ' + str(batch_size))\n\n train_data = pd.read_csv(os.path.join(training_dir, train_file), header=None, names=None)\n \n train_y = torch.from_numpy(train_data[[0]].values).float().squeeze()\n train_x = torch.from_numpy(np.reshape(train_data.drop([0], axis=1).iloc[:,:input_size].values, (-1, input_size))).float()\n \n train_ds = WindowDataset(train_x, train_y, seq_length=seq_length)\n return torch.utils.data.DataLoader(train_ds, batch_size=batch_size)\n\n\n# Provided training function\ndef train(model, train_loader, epochs, criterion, optimizer, device):\n \"\"\"\n This is the training method that is called by the PyTorch training script. The parameters\n passed are as follows:\n model - The PyTorch model that we wish to train.\n train_loader - The PyTorch DataLoader that should be used during training.\n epochs - The total number of epochs to train for.\n criterion - The loss function used for training. \n optimizer - The optimizer to use during training.\n device - Where the model and data should be loaded (gpu or cpu).\n \"\"\"\n print('epochs: ' + str(epochs))\n # training loop is provided\n for epoch in range(1, epochs + 1):\n model.train() # Make sure that the model is in training mode.\n\n total_loss = 0\n\n for batch in train_loader:\n # get data\n batch_x, batch_y = batch\n# print('batch_x')\n# print(batch_x)\n# print('batch_y')\n# print(batch_y)\n batch_x = batch_x.to(device)\n batch_y = batch_y.to(device)\n\n optimizer.zero_grad()\n\n # get predictions from model\n y_pred = model(batch_x).squeeze()\n# print(y_pred)\n \n # perform backprop\n loss = criterion(y_pred, batch_y)\n loss.backward()\n optimizer.step()\n \n total_loss += loss.data.item()\n\n print(\"Epoch: {}, Loss: {}\".format(epoch, total_loss / len(train_loader)))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--output-data-dir', type=str, default=os.environ['SM_OUTPUT_DATA_DIR'])\n parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])\n parser.add_argument('--data-dir', type=str, default=os.environ['SM_CHANNEL_TRAIN'])\n \n # training params\n parser.add_argument('--batch-size', type=int, default=10, metavar='N',\n help='input batch size for training (default: 16)')\n parser.add_argument('--epochs', type=int, default=500, metavar='N',\n help='number of epochs to train (default: 500)')\n parser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\n parser.add_argument('--input-size', type=int, default=8, metavar='N',\n help='hidden dimension (default: 8)')\n parser.add_argument('--sequence-size', type=int, default=8, metavar='N',\n help='hidden dimension (default: 8)')\n parser.add_argument('--hidden-dim', type=int, default=8, metavar='N',\n help='hidden dimension (default: 8)')\n parser.add_argument('--learning-rate', type=float, default=0.1, metavar='N',\n help='learning rate (default: 0.1)')\n parser.add_argument('--train-file', type=str, default='', metavar='N',\n help='training file')\n args = parser.parse_args()\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n print(\"Using device {}.\".format(device))\n\n torch.manual_seed(args.seed)\n\n # Load training data.\n train_loader = _get_train_data_loader(args.input_size, args.sequence_size, args.batch_size, args.data_dir, args.train_file)\n\n model = LSTMClassifier(args.sequence_size, args.input_size, args.hidden_dim).to(device)\n optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate)\n criterion = torch.nn.MSELoss() # we are using MSE as we are using RMSE to evaluate the model\n\n # Trains the model\n train(model, train_loader, args.epochs, criterion, optimizer, device)\n\n model_info_path = os.path.join(args.model_dir, 'model_info.pth')\n with open(model_info_path, 'wb') as f:\n model_info = {\n 'train_file': args.train_file,\n 'input_size': args.input_size,\n 'hidden_dim': args.hidden_dim,\n 'learning_rate': args.learning_rate,\n 'sequence_size': args.sequence_size\n }\n torch.save(model_info, f) \n\n # Save the model parameters\n model_path = os.path.join(args.model_dir, 'model.pth')\n with open(model_path, 'wb') as f:\n torch.save(model.cpu().state_dict(), f)" }, { "alpha_fraction": 0.5247410535812378, "alphanum_fraction": 0.5304948091506958, "avg_line_length": 35.04166793823242, "blob_id": "d653a1e31f4b60fd8acdc113b60520f0f7849dcb", "content_id": "4649e377fa07060ff3c7c8090b0f31871aa400c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 869, "license_type": "no_license", "max_line_length": 83, "num_lines": 24, "path": "/lstm/window_dataset.py", "repo_name": "carolinepie/udacity_ml_capstone", "src_encoding": "UTF-8", "text": "import torch\nimport torch.utils.data as data\n\n# full x, full y: \n\nclass WindowDataset(data.Dataset):\n def __init__(self, x, y, seq_length):\n self.x = x\n self.y = y\n \n self.seq_length = seq_length\n def __len__(self):\n# print(self.x.__len__())\n# print(self.seq_length)\n return self.x.__len__() - self.seq_length + 1 \n def __getitem__(self, idx):\n# if idx + self.seq_length >= self.__len__():\n# x_final = torch.zeros(self.seq_length, self.x[0].__len__())\n# y_final = torch.zeros(self.seq_length)\n# x_final[:self.x.__len__()-idx] = self.x[idx:]\n# return x_final, self.y[-1]\n# else:\n# return self.x[idx:idx+self.seq_length], self.y[idx+self.seq_length-1]\n return self.x[idx:idx+self.seq_length], self.y[idx+self.seq_length -1]\n " } ]
4
lowks/ubelt
https://github.com/lowks/ubelt
a616da13ba7aa461ad7cf9c7c47759194dd033ba
ba081667c1959d48213abfb5c84fb6890f0f0ed1
8970fd747027d98269d774c72d56bdfc910581ab
refs/heads/master
2020-12-31T00:41:02.831525
2017-02-01T15:18:00
2017-02-01T15:18:00
80,632,957
0
0
null
2017-02-01T15:23:32
2017-01-30T22:47:17
2017-02-01T15:17:31
null
[ { "alpha_fraction": 0.6519607901573181, "alphanum_fraction": 0.656862735748291, "avg_line_length": 22.720930099487305, "blob_id": "844274ed03e2e3b366f528bfc5a48bfe2e269d72", "content_id": "b82f6ad900a2a97090311f2ddfb017d1059c2e22", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1020, "license_type": "permissive", "max_line_length": 82, "num_lines": 43, "path": "/ubelt/__init__.py", "repo_name": "lowks/ubelt", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# flake8: noqa\n\"\"\"\nCommandLine:\n # Partially regenerate __init__.py\n python -c \"import ubelt\"\n python -c \"import ubelt\" --print-ubelt-init\n python -c \"import ubelt\" --update-ubelt-init\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\n__version__ = '0.0.1'\n\nGLOBAL_MODULES = [\n 'util_dict',\n 'util_list',\n 'util_time',\n]\n\n\n__DYNAMIC__ = False\n\nif __DYNAMIC__:\n # If dynamic, imports can be autogenerated\n from ubelt._internal import dynamic_make_init\n dynamic_make_init.dynamic_import(__name__, GLOBAL_MODULES)\n _DOELSE = False\nelse:\n # Run the autogenerated imports\n _DOELSE = True\n\nif _DOELSE:\n # <AUTOGEN_INIT>\n\n from ubelt import util_dict\n from ubelt import util_list\n from ubelt import util_time\n from ubelt.util_dict import (group_items,)\n from ubelt.util_list import (compress, flatten, take,)\n from ubelt.util_time import (Timer, Timerit, VERBOSE_TIME,)\n # </AUTOGEN_INIT>\n\ndel _DOELSE\n" }, { "alpha_fraction": 0.5172064900398254, "alphanum_fraction": 0.5328947305679321, "avg_line_length": 22.5238094329834, "blob_id": "bbc1d886fefc5e253fc83cf6abc507ba923af8c3", "content_id": "27d26bf9c97de3975c87a6ba47456749fa02343f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1976, "license_type": "permissive", "max_line_length": 82, "num_lines": 84, "path": "/ubelt/util_list.py", "repo_name": "lowks/ubelt", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport itertools as it\n\n\ndef take(items, indices):\n r\"\"\"\n Selects a subset of a list based on a list of indices.\n This is similar to np.take, but pure python.\n\n Args:\n items (list): some indexable object\n indices (list OR slice OR int): some indexing object\n\n Returns:\n iter or scalar: subset of the list\n\n SeeAlso:\n ub.dict_subset\n\n Example:\n >>> import ubelt as ub\n >>> items = [0, 1, 2, 3]\n >>> indices = [2, 0]\n >>> ub.take(items, indices)\n [2, 0]\n\n Example:\n >>> import ubelt as ub\n >>> items = [0, 1, 2, 3]\n >>> index = 2\n >>> ub.take(items, index)\n 2\n\n Example:\n >>> import ubelt as ub\n >>> items = [0, 1, 2, 3]\n >>> index = slice(1, None, 2)\n >>> ub.take(items, index)\n [1, 3]\n \"\"\"\n try:\n return [items[index] for index in indices]\n except TypeError:\n return items[indices]\n\n\ndef compress(items, flags):\n r\"\"\"\n Selects items where the corresponding value in flags is True\n This is similar to np.compress and it.compress\n\n Args:\n items (iterable): a sequence\n flags (iterable): corresponding sequence of bools\n\n Returns:\n list: a subset of masked items\n\n Example:\n >>> import ubelt as ub\n >>> items = [1, 2, 3, 4, 5]\n >>> flags = [False, True, True, False, True]\n >>> ub.compress(items, flags)\n [2, 3, 5]\n \"\"\"\n return list(it.compress(items, flags))\n\n\ndef flatten(nested_list):\n r\"\"\"\n Args:\n nested_list (list): list of lists\n\n Returns:\n list: flat list\n\n Example:\n >>> import ubelt as ub\n >>> nested_list = [['a', 'b'], ['c', 'd']]\n >>> ub.flatten(nested_list)\n ['a', 'b', 'c', 'd']\n \"\"\"\n return list(it.chain.from_iterable(nested_list))\n" }, { "alpha_fraction": 0.6262680292129517, "alphanum_fraction": 0.6273358464241028, "avg_line_length": 27.815383911132812, "blob_id": "4dcfdc0412c83f6fec9671120bbe07b056d17ed5", "content_id": "0d9b59086b542a469fd18c58441207a2ce9cb4ab", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1873, "license_type": "permissive", "max_line_length": 77, "num_lines": 65, "path": "/setup.py", "repo_name": "lowks/ubelt", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nInstallation:\n pip install git+https://github.com/Erotemic/ubelt.git\n\nDeveloping:\n git clone https://github.com/Erotemic/ubelt.git\n pip install -e ubelt\n\nPypi:\n # First tag the source-code\n VERSION=$(python -c \"import setup; print(setup.version)\")\n echo $VERSION\n git tag $VERSION -m \"tarball tag $VERSION\"\n git push --tags origin master\n\n # Register on Pypi test\n python setup.py register -r pypitest\n python setup.py sdist upload -r pypitest\n\n # Check the url to make sure everything worked\n https://testpypi.python.org/pypi?:action=display&name=ubelt\n\n # Register on Pypi live\n python setup.py register -r pypi\n # Note you need to temporarily edit your ~/.pypirc to include a password\n python setup.py sdist upload -r pypi\n\n # Check the url to make sure everything worked\n https://pypi.python.org/pypi?:action=display&name=ubelt\n\"\"\"\nfrom setuptools import setup\n\n\ndef parse_version():\n \"\"\" Statically parse the version number from __init__.py \"\"\"\n from os.path import dirname, join\n import ast\n init_fpath = join(dirname(__file__), 'ubelt', '__init__.py')\n with open(init_fpath) as file_:\n sourcecode = file_.read()\n pt = ast.parse(sourcecode)\n class VersionVisitor(ast.NodeVisitor):\n def visit_Assign(self, node):\n for target in node.targets:\n if target.id == '__version__':\n self.version = node.value.s\n visitor = VersionVisitor()\n visitor.visit(pt)\n return visitor.version\n\nversion = parse_version()\n\n\nif __name__ == '__main__':\n setup(\n name='ubelt',\n version=version,\n author='Jon Crall',\n author_email='[email protected]',\n url='https://github.com/Erotemic/ubelt',\n license='Apache 2',\n packages=['ubelt'],\n )\n" }, { "alpha_fraction": 0.5286920666694641, "alphanum_fraction": 0.5367913246154785, "avg_line_length": 32.15999984741211, "blob_id": "2ab98f5100a40cb788d3bec2898e7fe7a885ff89", "content_id": "7e556927fbeb5ef91568f8e3f00b74e4f42a300c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5803, "license_type": "permissive", "max_line_length": 82, "num_lines": 175, "path": "/ubelt/util_time.py", "repo_name": "lowks/ubelt", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport time\nimport sys\n\nVERBOSE_TIME = 1\n\n# Use time.clock in win32\ndefault_timer = time.clock if sys.platform.startswith('win32') else time.time\n\n\nclass Timer(object):\n r\"\"\"\n Timer with-statment context object.\n\n Example:\n >>> import ubelt as ub\n >>> timer = ub.Timer('Timer test!', verbose=1)\n >>> with timer:\n >>> prime = ub.get_nth_prime(400)\n >>> assert timer.ellapsed > 0\n \"\"\"\n def __init__(self, label='', verbose=None, newline=True):\n if verbose is None:\n verbose = VERBOSE_TIME\n self.label = label\n self.verbose = verbose\n self.newline = newline\n self.tstart = -1\n self.ellapsed = -1\n self.write = sys.stdout.write\n self.flush = sys.stdout.flush\n\n def tic(self):\n \"\"\" starts the timer \"\"\"\n if self.verbose:\n self.flush()\n self.write('\\ntic(%r)' % self.label)\n if self.newline:\n self.write('\\n')\n self.flush()\n self.tstart = default_timer()\n\n def toc(self):\n \"\"\" stops the timer \"\"\"\n ellapsed = default_timer() - self.tstart\n if self.verbose:\n self.write('...toc(%r)=%.4fs\\n' % (self.label, ellapsed))\n self.flush()\n return ellapsed\n\n def __enter__(self):\n self.tic()\n return self\n\n def __exit__(self, type_, value, trace):\n self.ellapsed = self.toc()\n if trace is not None:\n # return False on error\n return False\n\n\nclass Timerit(object):\n r\"\"\"\n Reports the average time to run a block of code.\n\n Unlike `timeit`, `Timerit` can handle multiline blocks of code\n\n Args:\n num (int): number of times to run the loop\n label (str): identifier for printing\n unit (str): reporting unit of time (e.g. 'ms', 's', None)\n verbose (int): verbosity level\n\n CommandLine:\n python -m utool.util_time Timerit\n python -m utool.util_time Timerit:0\n python -m utool.util_time Timerit:1\n\n Example:\n >>> import ubelt as ub\n >>> num = 15\n >>> t1 = ub.Timerit(num)\n >>> for timer in t1:\n >>> # <write untimed setup code here> this example has no setup\n >>> with timer:\n >>> # <write code to time here> for example...\n >>> ub.get_nth_prime_bruteforce(100)\n >>> # <you can now access Timerit attributes>\n >>> print('t1.total_time = %r' % (t1.total_time,))\n >>> assert t1.total_time > 0\n >>> assert t1.n_loops == t1.num\n >>> assert t1.n_loops == num\n\n Example:\n >>> import ubelt as ub\n >>> num = 10000\n >>> n = 50\n >>> # If the timer object is unused, time will still be recoreded,\n >>> # but with less precision.\n >>> for _ in ub.Timerit(num, 'inprecise'):\n >>> ub.get_nth_prime_bruteforce(n)\n >>> # Using the timer object results in the most precise timeings\n >>> for timer in ub.Timerit(num, 'precise'):\n >>> with timer:\n >>> ub.get_nth_prime_bruteforce(n)\n \"\"\"\n def __init__(self, num, label=None, unit=None, verbose=None):\n if verbose is None:\n verbose = VERBOSE_TIME\n self.num = num\n self.label = label\n self.times = []\n self.verbose = verbose\n self.total_time = None\n self.n_loops = None\n self.unit = unit\n\n def __iter__(self):\n if self.verbose > 1:\n if self.label is None:\n print('Timing for %d loops' % self.num)\n else:\n print('Timing %s for %d loops.' % (self.label, self.num,))\n self.n_loops = 0\n self.total_time = 0\n # Create a foreground and background timer\n bg_timer = Timer(verbose=0) # (ideally this is unused)\n fg_timer = Timer(verbose=0) # (used directly by user)\n # Core timing loop\n for i in range(self.num):\n # Start background timer (in case the user doesnt use fg_timer)\n # Yield foreground timer to let the user run a block of code\n # When we return from yield the user code will have just finishec\n # Then record background time + loop overhead\n bg_timer.tic()\n yield fg_timer\n bg_time = bg_timer.toc()\n # Check if the fg_timer object was used, but fallback on bg_timer\n if fg_timer.ellapsed >= 0:\n block_time = fg_timer.ellapsed # high precision\n else:\n block_time = bg_time # low precision\n # record timeings\n self.times.append(block_time)\n self.total_time += block_time\n self.n_loops += 1\n # Timeing complete, print results\n assert len(self.times) == self.num, 'incorrectly recorded times'\n if self.verbose > 0:\n self._print_report(self.verbose)\n\n @property\n def ave_secs(self):\n return self.total_time / self.n_loops\n\n def _print_report(self, verbose=1):\n ave_secs = self.ave_secs\n if self.label is None:\n print('Timing complete, %d loops' % (self.n_loops,))\n else:\n print('Timing complete for: %s, %d loops' % (self.label,\n self.n_loops))\n if verbose > 2:\n print(' body took: %s seconds' % self.total_time)\n print(' time per loop : %s seconds' % (ave_secs,))\n\nif __name__ == '__main__':\n r\"\"\"\n CommandLine:\n python -m ubelt.util_time\n python -m ubelt.util_time --allexamples\n \"\"\"\n # TODO ub.doctest_funcs()\n pass\n" }, { "alpha_fraction": 0.7827585935592651, "alphanum_fraction": 0.7827585935592651, "avg_line_length": 28, "blob_id": "9b53dc54391317d2796adadb6b292a2f5dbf2bbc", "content_id": "4942c6b985c68977c56e9cc0d0f8a8a9c930a9b5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 290, "license_type": "permissive", "max_line_length": 73, "num_lines": 10, "path": "/README.txt", "repo_name": "lowks/ubelt", "src_encoding": "UTF-8", "text": "This is a migration of the most useful parts of `utool` into a standalone\nlibrary with full test coverage and minimal dependencies.\n\nSo far this is very much a work in progress.\n\nTo Install:\npip install git+https://github.com/Erotemic/ubelt.git\n\nSee Also:\nhttps://github.com/Erotemic/utool\n" }, { "alpha_fraction": 0.6018878221511841, "alphanum_fraction": 0.6041088104248047, "avg_line_length": 37.319149017333984, "blob_id": "f872ad2ff87a53bfa1db591a54a92dc5f6beeed1", "content_id": "3a5d9fcf6018e4358e7b798a4d70f5578facf637", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1801, "license_type": "permissive", "max_line_length": 94, "num_lines": 47, "path": "/ubelt/util_dict.py", "repo_name": "lowks/ubelt", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport collections\nimport operator as op\nfrom six.moves import zip\n\n\ndef group_items(item_list, groupid_list, sorted_=True):\n r\"\"\"\n Groups a list of items by group id.\n\n Args:\n item_list (list): a list of items to group\n groupid_list (list): a corresponding list of item groupids\n sorted_ (bool): if True preserves the ordering of items within groups\n (default = True)\n\n Returns:\n dict: groupid_to_items: maps a groupid to a list of items\n\n Example:\n >>> import ubelt as ub\n >>> item_list = ['ham', 'jam', 'spam', 'eggs', 'cheese', 'bannana']\n >>> groupid_list = ['protein', 'fruit', 'protein', 'protein', 'dairy', 'fruit']\n >>> ub.group_items(item_list, iter(groupid_list))\n >>> #groupid_to_items = ub.group_items(item_list, iter(groupid_list))\n >>> #result = ut.dict_str(groupid_to_items, nl=False, strvals=False)\n >>> #print(result)\n {'dairy': ['cheese'], 'fruit': ['jam', 'bannana'], 'protein': ['ham', 'spam', 'eggs']}\n \"\"\"\n pair_list_ = list(zip(groupid_list, item_list))\n if sorted_:\n # Sort by groupid for cache efficiency\n try:\n pair_list = sorted(pair_list_, key=op.itemgetter(0))\n except TypeError:\n # Python 3 does not allow sorting mixed types\n pair_list = sorted(pair_list_, key=lambda tup: str(tup[0]))\n else:\n pair_list = pair_list_\n\n # Initialize a dict of lists\n groupid_to_items = collections.defaultdict(list)\n # Insert each item into the correct group\n for groupid, item in pair_list:\n groupid_to_items[groupid].append(item)\n return groupid_to_items\n" } ]
6
sammy1209/websiteBlocker
https://github.com/sammy1209/websiteBlocker
319450aef2eac5ae3b8102089cc4f73e78b38b39
f30524289fa89eeb1aa49d3a42b324f82af79579
ee73868826ce2dc9276980b0bd547eb4061a22ac
refs/heads/main
2023-02-20T05:58:45.704847
2021-01-21T12:06:07
2021-01-21T12:06:07
331,614,812
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5372480154037476, "alphanum_fraction": 0.5591586232185364, "avg_line_length": 33.57575607299805, "blob_id": "a99a5c8f2ee0744e1604b86cfd6bbe2a07774df3", "content_id": "11a7154f8da0051ce9364304b30ae969d5a3a021", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1141, "license_type": "no_license", "max_line_length": 83, "num_lines": 33, "path": "/main.py", "repo_name": "sammy1209/websiteBlocker", "src_encoding": "UTF-8", "text": "from datetime import datetime\nhost_path = 'C:/Windows/System32/drivers/etc/hosts'\nredirect = '127.0.0.1'\nwebsite_list=[\"www.facebook.com\", \"www.instagram.com\", \"facebook.com\"]\n\nstart_date = datetime(2020,11,19)\nend_date = datetime(2020,11,20)\ntoday_date = datetime(datetime.now().year,datetime.now().month, datetime.now().day)\n\n\nwhile True:\n if start_date <= today_date < end_date:\n with open(host_path,\"r+\") as file:\n content = file.read()\n for site in website_list:\n if site in content:\n pass\n else:\n file.write(redirect+\" \"+site+\"\\n\")\n print(\"all sites are blocked\")\n break\n else:#end_date < today_date\n with open(host_path, \"r+\") as file:\n content = file.readlines()\n file.seek(0)\n for line in content:\n #list comprehension\n if not any(site in line for site in website_list):\n file.write(line)\n #to save the file after complition the task\n file.truncate()\n print(\"all sites are blocked\")\n break\n" } ]
1
siensyax/submitt-file-to-web-site
https://github.com/siensyax/submitt-file-to-web-site
bac841b6d630c1dc57aba394cd8ec95270625208
4f774963dd50a118cd5631a1cc0c6e58a1b4dfac
7c733059081318d15a4104e2974cf9a42b466318
refs/heads/master
2022-11-24T02:57:39.665161
2020-07-08T10:56:10
2020-07-08T10:56:10
278,058,321
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6463621258735657, "alphanum_fraction": 0.6565144062042236, "avg_line_length": 27.549999237060547, "blob_id": "822779c7720ab18e036e90639cc7a576c585e6fd", "content_id": "48adf95e093eb9302ea7f02e78c8665fffe4d20f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3656, "license_type": "no_license", "max_line_length": 85, "num_lines": 80, "path": "/9所得エクセルを点検サイトへ提出 公開用.py", "repo_name": "siensyax/submitt-file-to-web-site", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jun 6 16:40:33 2020\r\n\r\n実行した日と同じexcelファイルを提出するスクリプト\r\n\r\n\"\"\"\r\n\r\n# エクセルファイル名所得用モジュールインポート部分\r\nimport glob\r\nimport os\r\nfrom datetime import datetime\r\n# エクセルファイル提出用モジュールインポート部分\r\nfrom selenium import webdriver\r\nimport time\r\n\r\n\r\n# エクセルファイルの親パスを変数に宣言しとく\r\nexcel_path = '提出したいexcelファイルのディレクトリ名'\r\n\r\n# ChromeDriverのフルパスを変数に宣言しとく\r\nChromeDriver_path = 'ChromeDriverのフルパス'\r\n\r\n# ログインIDとパスワードを先に変数で宣言しとく\r\nID = 'サイトへのログインID'\r\npassword_var = 'サイトへのログインパスワード'\r\n\r\n# 今日の年月日を年.月.日の形式で所得できるようにする\r\nnow_date = datetime.now().strftime(\"%y.%m.%d\")\r\n\r\n# glob関数を使って親パスの中のエクセルファイルのフルパスすべてを変数に代入する\r\nexcel_filename_fulls = glob.glob(excel_path + '*xlsx')\r\n\r\n# 変数はフルパスのリストになっているのでforで取り出して拡張子を除いたファイル名にする\r\nfor excel_filename_full in excel_filename_fulls:\r\n # splitext関数を使ってフルパスを拡張子を除いたファイル名に変換して変数に代入する\r\n excel_filename = os.path.splitext(os.path.basename(excel_filename_full))[0]\r\n # 変数に代入したやつをコンソール上に表示する\r\n print(excel_filename, end=' ')\r\n # print(type(excel_filename))\r\n # 条件分岐で今日の年月日と上で直接変数に代入されてる年月日を比較する\r\n # 日付が一致した時 エクセルファイルを自主点検のほうにコピーする\r\n if excel_filename == now_date:\r\n print(\"日付が一致しました\")\r\n # 点検担当のサイトにログインする\r\n # ブラウザを開く。\r\n driver = webdriver.Chrome(executable_path=ChromeDriver_path)\r\n # 点検担当のサイトを開く\r\n driver.get(\"提出したいサイトのURL\")\r\n # 3秒待機\r\n time.sleep(5)\r\n # ログインIDを入力\r\n login_id = driver.find_element_by_name(\"username\")\r\n login_id.send_keys(ID)\r\n # 2秒待機\r\n time.sleep(2)\r\n # パスワードを入力\r\n password = driver.find_element_by_name(\"password\")\r\n password.send_keys(password_var)\r\n # 2秒待機\r\n time.sleep(2)\r\n # ログインボタンをクリックする\r\n login_btn = driver.find_element_by_xpath('//*[@id=\"login\"]/form/input[4]')\r\n login_btn.click()\r\n # 10秒待機\r\n time.sleep(5)\r\n\r\n # ログインした点検担当のサイト上でエクセルファイルを提出する\r\n # ファイル選択テキストボックスを指定するオブジェクトを生成する\r\n file_select = driver.find_element_by_name('upfile')\r\n # オブジェクトのsecd_keysを使って提出するエクセルファイルのフルパスを入力する\r\n file_select.send_keys(excel_filename_full)\r\n # ファイル提出の送信ボタンを押す\r\n file_upload = driver.find_element_by_xpath('//*[@id=\"upload\"]/form/input[3]')\r\n file_upload.click()\r\n # エクセルファイルをちゃんと提出したことがわかるようにわざとchromeは終了させない\r\n\r\n # 日付が一致しない時 falseをコンソール上に表示\r\n else:\r\n print(\"false\")\r\n" }, { "alpha_fraction": 0.7888268232345581, "alphanum_fraction": 0.8044692873954773, "avg_line_length": 15.574073791503906, "blob_id": "d14d5341ac6406a9c4668cf31759cdaa2a70f682", "content_id": "e026ea0efa392cf18c41a9fad73a29e7fe4a6194", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1833, "license_type": "no_license", "max_line_length": 73, "num_lines": 54, "path": "/README.md", "repo_name": "siensyax/submitt-file-to-web-site", "src_encoding": "UTF-8", "text": "# submitt-file-to-web-site\nPythonでWebサイトへエクセルファイルを提出するスクリプトです\n\nこのスクリプトをwindows10のタスクスケジューラーに登録し,自動送信を実現しました.\n\n用いたライブラリは以下の二つです.\n- glob\n- os\n- datetime\n- selenium\n- time\n\nこの中でseleniumは,サードパーティー製ライブラリなので\n\npip install selenium\n\nでインストールする必要があります.\n\nまた,実際に操作するブラウザである,Chromeドライバーをインストールが必要です.\n\nhttps://chromedriver.storage.googleapis.com/index.html?path=83.0.4103.39/\n\n上のサイトから\n\nchromedriver_win32.zip\n\nをダウンロードして,解凍してください.\n\nその解凍先をスクリプト内で用います.\n\n# タスクスケジューラーへのPythonスクリプトの登録方法\n- ctrl + Rを押す\n- 出てきたボックスに,Taskschd.msc,を入力する(タスクスケジューラーが起動される)\n- フォルダをタスクスケジューラーライブラリに変える\n- 基本タスクの生成\n- 名前と説明をわかるように入力\n- 次へ\n- いつタスクを開始するか指定(毎日,毎週,毎週,1回限り,コンピューターの起動時,ログオン時,特定のイベントへのログの記録時)\n- 次へ\n- いつやるかを具体的に指定\n- 次へ\n- プログラムの開始\n- 次へ\n- プログラム/スクリプトの欄へ,python.exeを指定する\n- 引数の追加の欄へ,pythonスクリプトのファイル名を指定する\n- 開始(オプション)の欄へ,pythonスクリプトのある場所(パス)を指定する\n- 次へ\n- 完了\n\n参考サイト\n\nhttps://rdk.me/anaconda/\n\nhttps://tonari-it.com/windows-task-schdeuler/\n" } ]
2
thonagan-H/NW-DATAVISBOOTCAMP-HW
https://github.com/thonagan-H/NW-DATAVISBOOTCAMP-HW
0ff3e3e06602c521c13531956cf53ea6d65edaff
efb1b5de6b602c3a4cd90d664b551192d404be56
1d4623555216f2fbd36da34e1ce20cfd906cc1a9
refs/heads/master
2021-05-05T08:51:43.919919
2018-07-04T00:04:28
2018-07-04T00:04:28
119,197,338
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6566767692565918, "alphanum_fraction": 0.6684370040893555, "avg_line_length": 20.406503677368164, "blob_id": "8a66d7b4a40733b204e3ad59faac7adc172bf639", "content_id": "1220f9b446bbc8c9c4a4b710f0c9e3f093b25e2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2636, "license_type": "no_license", "max_line_length": 140, "num_lines": 123, "path": "/HW 5/README.md", "repo_name": "thonagan-H/NW-DATAVISBOOTCAMP-HW", "src_encoding": "UTF-8", "text": "\n\n```python\n#Dependencies:\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\n#PSEUDOCODE:\n#read in csvs as DF \n#merge both csvs on cities \n#Avg fare per city - y axis \n#Total rides per city - x-axis\n#Total number of drivers per city - s value in scatter plot\n#City type -colors\n```\n\n\n```python\n#Read in csv:\nfile_path_one = \"city_data.csv\"\nfile_path_two = \"ride_data.csv\"\n\ncity_df = pd.read_csv(file_path_one)\nride_df = pd.read_csv(file_path_two)\ncity_df = city_df.sort_values('city',ascending = True)\ncity_df['type'].value_counts().index\n```\n\n\n\n\n Index(['Urban', 'Suburban', 'Rural'], dtype='object')\n\n\n\n\n```python\n#Merge dataframes on city\npyber_df = pd.merge(city_df,ride_df,on = 'city')\npyber_df = pyber_df.sort_values('city',ascending = True)\n```\n\n\n```python\n#Get avg fares per city - Y-AXIS\npyber_gpby = pyber_df.groupby('city')\navg_fare = pyber_gpby['fare'].sum()/pyber_gpby['fare'].count()\n\n#total rides per city - X-AXIS\ntot_rides = pyber_gpby['fare'].count()\n\n#total number of drivers per city - S values\ntot_drivers = city_df['driver_count']\n```\n\n\n```python\ncolors = {'Urban':'gold',\"Suburban\":'lightskyblue','Rural':'lightcoral'}\ntypes = ['Urban','Suburban','Rural']\n\nfor i in types:\n plt.scatter(tot_rides, avg_fare, s=tot_drivers*5, c=city_df['type'].apply(lambda x: colors[x]), \n alpha=0.5,label = i)\n\nplt.legend()\nplt.xlabel('Total Number of Rides(Per City)')\nplt.ylabel('Avg Fare per City($)')\nplt.title('Pyber Ride Sharing Data')\nplt.show()\n\n```\n\n\n![png](output_5_0.png)\n\n\n\n```python\n#PIE CHART - \nexplode = (0.2,0.2,0)\ncolors_list = ['gold','lightskyblue','lightcoral']\nfares_sum = pyber_df.groupby('type')['fare'].sum()\nride_count = pyber_df.groupby('type').count()\nrides_count = ride_count['city']\ndrivers_sum = pyber_df.groupby('type')['driver_count'].sum()\n```\n\n\n```python\n# % Total Fares by City Type:\nplt.pie(fares_sum.values, explode = explode, labels=fares_sum.index, colors=colors_list, autopct=\"%1.1f%%\", shadow=True, startangle=140)\nplt.title('% Total Fares by City Type')\nplt.show()\n```\n\n\n![png](output_7_0.png)\n\n\n\n```python\n# % Total Rides by City Type:\nplt.pie(rides_count.values, explode = explode, labels=rides_count.index, colors=colors_list, autopct=\"%1.1f%%\", shadow=True, startangle=140)\nplt.title('% Total Rides by City Type')\nplt.show()\n```\n\n\n![png](output_8_0.png)\n\n\n\n```python\n# % Total Drivers by City Type:\nplt.pie(drivers_sum.values, explode = explode, labels=drivers_sum.index, colors=colors_list, autopct=\"%1.1f%%\", shadow=True, startangle=140)\nplt.title('% Total Rides by City Type')\nplt.show()\n```\n\n\n![png](output_9_0.png)\n\n" }, { "alpha_fraction": 0.4873756766319275, "alphanum_fraction": 0.49885234236717224, "avg_line_length": 35.91304397583008, "blob_id": "f94eb0a73280d3f66e12db486deed05853cd22bd", "content_id": "b517ea38476ff50bd439efba6f7d181407fdb7ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2614, "license_type": "no_license", "max_line_length": 99, "num_lines": 69, "path": "/HW3/HW3-Polling.py", "repo_name": "thonagan-H/NW-DATAVISBOOTCAMP-HW", "src_encoding": "UTF-8", "text": "from collections import Counter\r\nimport csv\r\npath_name = 'election_data_2.csv'\r\n\r\n\r\nwith open(path_name,newline='')as csvfile:\r\n bd = csv.reader(csvfile,delimiter=',')\r\n \r\n vote_count = 0 \r\n next(bd) #skip header in loop\r\n cand_lst = []\r\n candidate = set() #sets store unique values\r\n ####################################################################\r\n \r\n #List of candidates and total vote count\r\n for i in bd:\r\n vote_count += 1\r\n cand_lst.append(i[2])\r\n candidate.add(i[2])\r\n \r\n candidates = list(candidate)\r\n print(\"The candidates are as follows:\")\r\n for j in candidate:\r\n print(j) #gives list of unique candidates \r\n print (\"\\nThe total votes are \" +str(vote_count))\r\n #####################################################################\r\n \r\n #Votes and % votes per candidate \r\n\r\n #Counter gives the number of times a value appears in a list \r\n #and returns a dictionary \r\n unique_votes = Counter(cand_lst) \r\n percent_votes = []\r\n individual_votes = []\r\n \r\n for key,value in unique_votes.items():\r\n #.items loops over a dictionary and returns the key value pairs\r\n individual_votes.append(str(value))\r\n percent_votes.append(\"%1.f\"%((value/vote_count)*100))\r\n \r\n #print(\"The candidate \"+key +\" won \"+ str(value) +\" votes\")\r\n #print(\"(\" + str(percent_votes) + \"%\"+\")\") \r\n print(candidates)\r\n z = max(percent_votes)\r\n print(z)\r\n winner = {candidates[0]:percent_votes[0],\r\n candidates[1]:percent_votes[1],\r\n candidates[2]:percent_votes[2],\r\n candidates[3]:percent_votes[3]}\r\n \r\n for keys,values in winner.items():\r\n if z == values:\r\n final_winner = keys\r\n print(final_winner)\r\n########################################################################## \r\n\r\n#Writing to a file\r\n\r\nwith open(\"Election_results.txt\",'w',encoding = 'utf-8') as f:\r\n f.write(\"Election Results: \\n\\n\")\r\n f.write(\"----------------------------------------------\\n\")\r\n f.write(\"Total Votes: \"+ repr(vote_count) +\"\\n\")\r\n f.write(\"----------------------------------------------\\n\\n\")\r\n f.write(candidates[0] + \": \" + percent_votes[0] + \"% \" + \"(\" + individual_votes[0] + \")\" + \"\\n\")\r\n f.write(candidates[1] + \": \" + percent_votes[1] + \"% \" + \"(\" + individual_votes[1] + \")\" + \"\\n\")\r\n f.write(candidates[2] + \": \" + percent_votes[2] + \"% \" + \"(\" + individual_votes[2] + \")\" + \"\\n\")\r\n f.write(candidates[3] + \": \" + percent_votes[3] + \"% \" + \"(\" + individual_votes[3] + \")\" + \"\\n\")\r\n f.write(\"----------------------------------------------\\n\\n\")\r\n f.write(\"Winner: \" + final_winner + \"\\n\")" }, { "alpha_fraction": 0.529411792755127, "alphanum_fraction": 0.529411792755127, "avg_line_length": 17, "blob_id": "5a84eb90008617e33f1c130b5e0eacc863ec7e3a", "content_id": "ba1114c81e4d2a17c3b21c3c103fb2abed4b651e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17, "license_type": "no_license", "max_line_length": 17, "num_lines": 1, "path": "/HW 6/config.py", "repo_name": "thonagan-H/NW-DATAVISBOOTCAMP-HW", "src_encoding": "UTF-8", "text": "api_key = \"11aac60211fe4ca5ad4b015b21ff06b4\"" }, { "alpha_fraction": 0.7539253830909729, "alphanum_fraction": 0.7604890465736389, "avg_line_length": 46.66257858276367, "blob_id": "9fb8a95f7c2c90ab4a746a5f25aa4eb3effcd65f", "content_id": "ffe925d70d2e1041999618511bc7224a10bc3fb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 7770, "license_type": "no_license", "max_line_length": 150, "num_lines": 163, "path": "/HW 8-10/SQL HW - 1.sql", "repo_name": "thonagan-H/NW-DATAVISBOOTCAMP-HW", "src_encoding": "UTF-8", "text": "use sakila;\n\n#1a. Display the first and last names of all actors from the table actor.\nselect first_name,last_name from actor;\n\n#1b. Display the first and last name of each actor in a single column in upper case letters. Name the column Actor Name.\nselect concat(first_name,' ',last_name) as Actor_Name from actor;\n\n#2a. You need to find the ID number, first name, and last name of an actor, of whom you know only the first name, \"Joe.\" \n#What is one query would you use to obtain this information?\nselect actor_id,first_name,last_name from actor where first_name = 'Joe';\n\n#2b. Find all actors whose last name contain the letters GEN:\nselect * from actor where last_name like '%GEN%';\n\n#2c. Find all actors whose last names contain the letters LI. This time, order the rows by last name and first name, in that order:\nselect last_name,first_name from actor where last_name like '%LI%';\n\n#2d. Using IN, display the country_id and country columns of the following countries: Afghanistan, Bangladesh, and China:\nselect country_id,country from country where country_id and country in ('Afghanistan','Bangladesh','China');\n\n#3a. Add a middle_name column to the table actor. Position it between first_name and last_name. Hint: you will need to specify the data type.\nalter table actor add column middle_name varchar(255) after first_name;\n\n#3b. You realize that some of these actors have tremendously long last names. Change the data type of the middle_name column to blobs.\nalter table actor modify column middle_name blob;\n\n#3c. Now delete the middle_name column.\nalter table actor drop column middle_name;\n\n#4a. List the last names of actors, as well as how many actors have that last name.\nselect last_name,count(last_name) from actor group by last_name;\n\n#4b. List last names of actors and the number of actors who have that last name, but only for names that are shared by at least two actors\nselect last_name,count(last_name) from actor group by last_name having count(last_name)>2;\n\n#4c. Oh, no! The actor HARPO WILLIAMS was accidentally entered in the actor table as GROUCHO WILLIAMS, \n#the name of Harpo's second cousin's husband's yoga teacher. Write a query to fix the record.\nupdate actor set first_name = 'HARPO'\nwhere actor_id = 172;\n\n#4d. Perhaps we were too hasty in changing GROUCHO to HARPO. It turns out that GROUCHO was the correct name after all! \n#In a single query, if the first name of the actor is currently HARPO, change it to GROUCHO. \n#Otherwise, change the first name to MUCHO GROUCHO, as that is exactly what the actor will be with the grievous error. \n#BE CAREFUL NOT TO CHANGE THE FIRST NAME OF EVERY ACTOR TO MUCHO GROUCHO, HOWEVER! (Hint: update the record using a unique identifier.)\nupdate actor set first_name = 'GROUCHO'\nwhere first_name = 'HARPO' and last_name = 'WILLIAMS';\n\n#5a. You cannot locate the schema of the address table. Which query would you use to re-create it?\nshow create table address;\n\n#6a. Use JOIN to display the first and last names, as well as the address, of each staff member. Use the tables staff and address:\nselect staff.first_name,staff.last_name,address.address from staff left join address on staff.address_id = address.address_id;\n\n#6b. Use JOIN to display the total amount rung up by each staff member in August of 2005. Use tables staff and payment.\nselect staff.first_name, staff.last_name, sum(payment.amount)\nfrom staff\nleft join payment on staff.staff_id = payment.staff_id\nwhere payment_date like '%2005-08%'\nGROUP BY staff.first_name, staff.last_name;\n\n#6c. List each film and the number of actors who are listed for that film. Use tables film_actor and film. Use inner join.\nselect film.title, count(film_actor.actor_id)\nfrom film \ninner join film_actor on film.film_id = film_actor.film_id\ngroup by film.title;\n\n#6d. How many copies of the film Hunchback Impossible exist in the inventory system?\nselect total from (select film.title, count(film_actor.actor_id) as total\nfrom film \ninner join film_actor on film.film_id = film_actor.film_id\ngroup by film.title) as f\nwhere title = 'Hunchback Impossible';\n\n#6e. Using the tables payment and customer and the JOIN command, list the total paid by each customer. List the customers alphabetically by last name:\nselect c.last_name,c.first_name, sum(p.amount) as amount_payed\nfrom customer as c\nleft join payment as p on c.customer_id = p.customer_id\ngroup by c.last_name,c.first_name\norder by c.last_name;\n\n#7a. The music of Queen and Kris Kristofferson have seen an unlikely resurgence. \n#As an unintended consequence, films starting with the letters K and Q have also soared in popularity. \n#Use subqueries to display the titles of movies starting with the letters K and Q whose language is English.\nselect title\nfrom film\nwhere (title like 'K%' or 'Q%') \nand language_id = \n(\nselect language_id \nfrom language\nwhere name = 'English'\n);\n\n# 7b. Use subqueries to display all actors who appear in the film Alone Trip.\nSELECT first_name, last_name\nFROM actor\nWHERE actor_id\nIN (SELECT actor_id FROM film_actor WHERE film_id \nIN (SELECT film_id from film where title='ALONE TRIP'));\n\n#7c. You want to run an email marketing campaign in Canada, for which you will need the names and email addresses of all Canadian customers. \n#Use joins to retrieve this information.\nSELECT first_name, last_name, email \nFROM customer cu\nJOIN address a ON (cu.address_id = a.address_id)\nJOIN city cit ON (a.city_id=cit.city_id)\nJOIN country cntry ON (cit.country_id=cntry.country_id);\n\n#7d. Sales have been lagging among young families, and you wish to target all family movies for a promotion. \n#Identify all movies categorized as famiy films.\nSELECT title from film f\nJOIN film_category fcat on (f.film_id=fcat.film_id)\nJOIN category c on (fcat.category_id=c.category_id);\n\n#7e. Display the most frequently rented movies in descending order.\nSELECT title, COUNT(f.film_id) AS 'Count_of_Rented_Movies'\nFROM film f\nJOIN inventory i ON (f.film_id= i.film_id)\nJOIN rental r ON (i.inventory_id=r.inventory_id)\nGROUP BY title ORDER BY Count_of_Rented_Movies DESC;\n\n#7f. Write a query to display how much business, in dollars, each store brought in.\nSELECT s.store_id, SUM(p.amount) \nFROM payment p\nJOIN staff s ON (p.staff_id=s.staff_id)\nGROUP BY store_id;\n\n#7g. Write a query to display for each store its store ID, city, and country.\nSELECT store_id, city, country FROM store s\nJOIN address a ON (s.address_id=a.address_id)\nJOIN city c ON (a.city_id=c.city_id)\nJOIN country cntry ON (c.country_id=cntry.country_id);\n\n#7h. List the top five genres in gross revenue in descending order. \n#(Hint: you may need to use the following tables: category, film_category, inventory, payment, and rental.)\nSELECT c.name AS 'Top Five', SUM(p.amount) AS 'Gross' \nFROM category c\nJOIN film_category fc ON (c.category_id=fc.category_id)\nJOIN inventory i ON (fc.film_id=i.film_id)\nJOIN rental r ON (i.inventory_id=r.inventory_id)\nJOIN payment p ON (r.rental_id=p.rental_id)\nGROUP BY c.name ORDER BY Gross LIMIT 5;\n\n#8a. In your new role as an executive, you would like to have an easy way of viewing the Top five genres by gross revenue. \n#Use the solution from the problem above to create a view. \n#If you haven't solved 7h, you can substitute another query to create a view.\nSELECT c.name AS 'Top Five', SUM(p.amount) AS 'Gross' \nFROM category c\nJOIN film_category fc ON (c.category_id=fc.category_id)\nJOIN inventory i ON (fc.film_id=i.film_id)\nJOIN rental r ON (i.inventory_id=r.inventory_id)\nJOIN payment p ON (r.rental_id=p.rental_id)\nGROUP BY c.name ORDER BY Gross LIMIT 5;\n\n#8b. How would you display the view that you created in 8a?\nSELECT* FROM TopFive;\n\n#8c. You find that you no longer need the view top_five_genres. Write a query to delete it.\nDROP VIEW TopFive;\n\n\nselect * from film_actor;\n\n" }, { "alpha_fraction": 0.8260869383811951, "alphanum_fraction": 0.8260869383811951, "avg_line_length": 23, "blob_id": "869fafea075a579dd2600a9c35ef18b2b0f35102", "content_id": "36c9fb2da62b105df5b8c4fbdbd24800c0ba4d03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 23, "license_type": "no_license", "max_line_length": 23, "num_lines": 1, "path": "/README.md", "repo_name": "thonagan-H/NW-DATAVISBOOTCAMP-HW", "src_encoding": "UTF-8", "text": "# NW-DATAVISBOOTCAMP-HW" }, { "alpha_fraction": 0.5431879162788391, "alphanum_fraction": 0.551202118396759, "avg_line_length": 27.605262756347656, "blob_id": "1737d83db4d337215e6e996cc264cf7389755e7f", "content_id": "18d2605103f82c9900de73b048f5868a44f14fe6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1123, "license_type": "no_license", "max_line_length": 74, "num_lines": 38, "path": "/HW3/HW3-BankData.py", "repo_name": "thonagan-H/NW-DATAVISBOOTCAMP-HW", "src_encoding": "UTF-8", "text": "import csv\r\npath_name = 'budget_data_1.csv'\r\n\r\nwith open(path_name,newline='')as csvfile:\r\n bd = csv.reader(csvfile,delimiter=',')\r\n print(csvfile)\r\n month_count = 0\r\n tot_rev = 0\r\n header = next(bd)\r\n lst =[]\r\n diff = 0\r\n diff_lst = []\r\n \r\n for i in bd:\r\n month_count += 1\r\n x = int(i[1])\r\n lst.append(x)\r\n tot_rev = tot_rev + x\r\n \r\n print(tot_rev)\r\n print(month_count)\r\n\r\n #Gives difference of list values\r\n for i in range(len(lst)-1):\r\n diff_lst.append(lst[i+1]-lst[i])\r\n sums = sum(diff_lst)\r\n average_rev = (abs(sums/len(diff_lst)))\r\n greatest = max(diff_lst)\r\n least = min(diff_lst)\r\n\r\nwith open(\"Bank_Data.txt\",'w',encoding = 'utf-8') as f:\r\n f.write(\"Financial Analysis\\n\\n\")\r\n f.write(\"----------------------------------------------\\n\\n\")\r\n f.write(\"Total Months: \"+ repr(month_count) +\"\\n\")\r\n f.write(\"Total Revenue: \"+ \"$\" + repr(tot_rev) + \"\\n\")\r\n f.write(\"Average change in revenue: \"+ \"$\" + repr(average_rev) + \"\\n\")\r\n f.write(\"Greatest increase in revenue: \"+ \"$\" + repr(greatest) + \"\\n\")\r\n f.write(\"Greatest decrease in revenue: \"+ \"$\" + repr(least) + \"\\n\")" }, { "alpha_fraction": 0.5767599940299988, "alphanum_fraction": 0.5793045163154602, "avg_line_length": 22.5625, "blob_id": "a3df0eb8759d7c4a866f3941b5c8afab81e9f790", "content_id": "af54d1b78ee399b3d2011d89785b3ae2be179ec0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1179, "license_type": "no_license", "max_line_length": 84, "num_lines": 48, "path": "/HW 13-14/app.py", "repo_name": "thonagan-H/NW-DATAVISBOOTCAMP-HW", "src_encoding": "UTF-8", "text": "# import necessary libraries\r\nfrom flask import (\r\n Flask,\r\n render_template,\r\n jsonify,\r\n request,\r\n redirect)\r\n\r\nfrom biodiversity import *\r\nfrom samples_data import sample_vals_list\r\nfrom flask_sqlalchemy import SQLAlchemy\r\n\r\napp = Flask(__name__)\r\n\r\n# create route that renders index.html template\r\[email protected](\"/\")\r\ndef home():\r\n return render_template(\"index.html\")\r\n\r\[email protected](\"/names\")\r\ndef names():\r\n return jsonify(id_list)\r\n\r\[email protected](\"/otu\")\r\ndef otu():\r\n return jsonify(otu_descr)\r\n\r\[email protected](\"/metadata/<sample>\")\r\ndef metadata(sample):\r\n for i in metadata_samples:\r\n if i['SAMPLEID'] == int(sample.split('_')[1]):\r\n return jsonify(i)\r\n\r\[email protected](\"/wfreq/<sample>\")\r\ndef wfreq(sample):\r\n sampleid = int(sample.split('_')[1])\r\n wfreq = df_met_csv_2.loc[sampleid]['WFREQ']\r\n return ('The weekly washing frequency is ' + str(wfreq)) \r\n\r\[email protected](\"/samples/<sample>\")\r\ndef samples(sample):\r\n for i in sample_vals_list:\r\n for j in i.keys():\r\n if j == sample:\r\n return jsonify(i.get(j))\r\n\r\nif __name__ == \"__main__\":\r\n app.run()\r\n" }, { "alpha_fraction": 0.4667373299598694, "alphanum_fraction": 0.5164682865142822, "avg_line_length": 17.494720458984375, "blob_id": "08de255baba29fe14ba2a7f58550827e073ef5e9", "content_id": "00d213a1d32b554a324aaa38b449863510fc8e90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 12266, "license_type": "no_license", "max_line_length": 127, "num_lines": 663, "path": "/HW 4/HeroesOfPymoli_JupyterNotebook.md", "repo_name": "thonagan-H/NW-DATAVISBOOTCAMP-HW", "src_encoding": "UTF-8", "text": "\n\n```python\nimport pandas as pd\nimport numpy as np\n```\n\n\n```python\ndata_file = \"purchase_data.json\"\n```\n\n\n```python\ndata_file_pd = pd.read_json(data_file)\ndata_file_pd.head(12)\n```\n\n\n\n\n<div>\n<style scoped>\n .dataframe tbody tr th:only-of-type {\n vertical-align: middle;\n }\n\n .dataframe tbody tr th {\n vertical-align: top;\n }\n\n .dataframe thead th {\n text-align: right;\n }\n</style>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>Age</th>\n <th>Gender</th>\n <th>Item ID</th>\n <th>Item Name</th>\n <th>Price</th>\n <th>SN</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>38</td>\n <td>Male</td>\n <td>165</td>\n <td>Bone Crushing Silver Skewer</td>\n <td>3.37</td>\n <td>Aelalis34</td>\n </tr>\n <tr>\n <th>1</th>\n <td>21</td>\n <td>Male</td>\n <td>119</td>\n <td>Stormbringer, Dark Blade of Ending Misery</td>\n <td>2.32</td>\n <td>Eolo46</td>\n </tr>\n <tr>\n <th>2</th>\n <td>34</td>\n <td>Male</td>\n <td>174</td>\n <td>Primitive Blade</td>\n <td>2.46</td>\n <td>Assastnya25</td>\n </tr>\n <tr>\n <th>3</th>\n <td>21</td>\n <td>Male</td>\n <td>92</td>\n <td>Final Critic</td>\n <td>1.36</td>\n <td>Pheusrical25</td>\n </tr>\n <tr>\n <th>4</th>\n <td>23</td>\n <td>Male</td>\n <td>63</td>\n <td>Stormfury Mace</td>\n <td>1.27</td>\n <td>Aela59</td>\n </tr>\n <tr>\n <th>5</th>\n <td>20</td>\n <td>Male</td>\n <td>10</td>\n <td>Sleepwalker</td>\n <td>1.73</td>\n <td>Tanimnya91</td>\n </tr>\n <tr>\n <th>6</th>\n <td>20</td>\n <td>Male</td>\n <td>153</td>\n <td>Mercenary Sabre</td>\n <td>4.57</td>\n <td>Undjaskla97</td>\n </tr>\n <tr>\n <th>7</th>\n <td>29</td>\n <td>Female</td>\n <td>169</td>\n <td>Interrogator, Blood Blade of the Queen</td>\n <td>3.32</td>\n <td>Iathenudil29</td>\n </tr>\n <tr>\n <th>8</th>\n <td>25</td>\n <td>Male</td>\n <td>118</td>\n <td>Ghost Reaver, Longsword of Magic</td>\n <td>2.77</td>\n <td>Sondenasta63</td>\n </tr>\n <tr>\n <th>9</th>\n <td>31</td>\n <td>Male</td>\n <td>99</td>\n <td>Expiration, Warscythe Of Lost Worlds</td>\n <td>4.53</td>\n <td>Hilaerin92</td>\n </tr>\n <tr>\n <th>10</th>\n <td>24</td>\n <td>Male</td>\n <td>57</td>\n <td>Despair, Favor of Due Diligence</td>\n <td>3.81</td>\n <td>Chamosia29</td>\n </tr>\n <tr>\n <th>11</th>\n <td>20</td>\n <td>Male</td>\n <td>47</td>\n <td>Alpha, Reach of Ending Hope</td>\n <td>1.55</td>\n <td>Sally64</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\n\n```python\n#Total number of players in the dataframe\nunique_names = data_file_pd[\"SN\"].unique()\nunique_name_count = len(unique_names)\n\n```\n\n\n```python\n#Purchasing analysis - Number of unique items\nnum_unique_items = data_file_pd[\"Item Name\"].value_counts()\n#new_df = data_file_pd.groupby(\"Item Name\")\n#new_df.size()\n```\n\n\n```python\n#Purchasing Analysis - Price Mean:\ndata_file_pd[\"Price\"].mean()\n```\n\n\n\n\n 2.931192307692303\n\n\n\n\n```python\n#Purchasing Analysis - Total Number of Purchases\nnum_unique_items.count()\n```\n\n\n\n\n 179\n\n\n\n\n```python\n#Purchasing Analysis - Total Revenue\ndata_file_pd[\"Price\"].sum()\n```\n\n\n\n\n 2286.3299999999999\n\n\n\n\n```python\n#Gender Demographics - Percentage and count of male players:\ngender_vals = data_file_pd[\"Gender\"].value_counts()\ntotal_players = gender_vals.sum()\ngender_m_count = gender_vals.values[0]\ngender_f_count = gender_vals.values[1]\ngender_o_count = gender_vals.values[2]\npercentages_m = (gender_m_count/total_players)*100\npercentages_f = (gender_f_count/total_players)*100\npercentages_o = (gender_o_count/total_players)*100\ngender_m_count\n\n```\n\n\n\n\n 633\n\n\n\n\n```python\n#Purchase Count: \ngender_purchase_count = data_file_pd.groupby([\"Gender\"])[\"Price\"].count()\n\n#Average price of individual player by gender\ngender_player_items_count = data_file_pd.groupby([\"Gender\",\"SN\"])[\"Price\"].count()\ngender_player_items_sum = data_file_pd.groupby([\"Gender\",\"SN\"])[\"Price\"].sum()\ngender_player_items_avg = gender_player_items_sum/gender_player_items_count\n\n#total value of goods by gender\ngender_tot_val = data_file_pd.groupby([\"Gender\"])[\"Price\"].sum()\n\n#Normalized Total\nnorm_tot_gender = gender_purchase_count/gender_vals\ngender_tot_val\n\n```\n\n\n\n\n Gender\n Female 382.91\n Male 1867.68\n Other / Non-Disclosed 35.74\n Name: Price, dtype: float64\n\n\n\n\n```python\n#bins\n#I thought about using the range function with the intital value set at 1 less than age_min \n#and the final value set at 1 greater than age_max for the bins, but I was unable to figure out how to label these bins without\n#hard coding them in\n\nage_max = data_file_pd[\"Age\"].max()\nage_min = data_file_pd[\"Age\"].min()\nbins = [age_min-1,10,14,19,24,29,34,39,44,age_max+1]\nbin_range = [\"<10\",\"10-14\",\"15-19\",\"20-24\",\"25-29\",\"30-34\",\"35-39\",\"40-44\",\"45-49\"]\ndata_file_pd[\"Age Bins\"] = pd.cut(data_file_pd[\"Age\"],bins,labels = bin_range)\n\n#Purchase Count\nage_purchase_count = data_file_pd.groupby([\"Age Bins\"]).count()\n\n\n#Total Purchase Value\nage_tot_purchase_val = data_file_pd.groupby([\"Age Bins\"])[\"Price\"].sum()\n\n#Average purcahse price of each player by age\nage_player_items_count = data_file_pd.groupby([\"Age Bins\",\"SN\"])[\"Price\"].count()\nage_player_items_sum = data_file_pd.groupby([\"Age Bins\",\"SN\"])[\"Price\"].sum()\nage_player_items_avg = age_player_items_sum/age_player_items_count\n\n#Normalized Total \nnorm_tot_age = age_tot_purchase_val/age_purchase_count[\"Price\"]\nage_purchase_count\n\n```\n\n\n\n\n<div>\n<style scoped>\n .dataframe tbody tr th:only-of-type {\n vertical-align: middle;\n }\n\n .dataframe tbody tr th {\n vertical-align: top;\n }\n\n .dataframe thead th {\n text-align: right;\n }\n</style>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>Age</th>\n <th>Gender</th>\n <th>Item ID</th>\n <th>Item Name</th>\n <th>Price</th>\n <th>SN</th>\n </tr>\n <tr>\n <th>Age Bins</th>\n <th></th>\n <th></th>\n <th></th>\n <th></th>\n <th></th>\n <th></th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>&lt;10</th>\n <td>32</td>\n <td>32</td>\n <td>32</td>\n <td>32</td>\n <td>32</td>\n <td>32</td>\n </tr>\n <tr>\n <th>10-14</th>\n <td>31</td>\n <td>31</td>\n <td>31</td>\n <td>31</td>\n <td>31</td>\n <td>31</td>\n </tr>\n <tr>\n <th>15-19</th>\n <td>133</td>\n <td>133</td>\n <td>133</td>\n <td>133</td>\n <td>133</td>\n <td>133</td>\n </tr>\n <tr>\n <th>20-24</th>\n <td>336</td>\n <td>336</td>\n <td>336</td>\n <td>336</td>\n <td>336</td>\n <td>336</td>\n </tr>\n <tr>\n <th>25-29</th>\n <td>125</td>\n <td>125</td>\n <td>125</td>\n <td>125</td>\n <td>125</td>\n <td>125</td>\n </tr>\n <tr>\n <th>30-34</th>\n <td>64</td>\n <td>64</td>\n <td>64</td>\n <td>64</td>\n <td>64</td>\n <td>64</td>\n </tr>\n <tr>\n <th>35-39</th>\n <td>42</td>\n <td>42</td>\n <td>42</td>\n <td>42</td>\n <td>42</td>\n <td>42</td>\n </tr>\n <tr>\n <th>40-44</th>\n <td>16</td>\n <td>16</td>\n <td>16</td>\n <td>16</td>\n <td>16</td>\n <td>16</td>\n </tr>\n <tr>\n <th>45-49</th>\n <td>1</td>\n <td>1</td>\n <td>1</td>\n <td>1</td>\n <td>1</td>\n <td>1</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\n\n```python\n#Top Spenders \nts_tot_price = data_file_pd.groupby([\"SN\"])[\"Price\"].sum()\nts_item_count = data_file_pd.groupby([\"SN\"])[\"Price\"].count()\nts_avg_price = ts_tot_price/ts_item_count\n\nts_df = ts_tot_price.to_frame(name=\"Total Purchase Amount\")\nts_df[\"item count\"] = ts_item_count.values\nts_df[\"avg price\"] = ts_avg_price\nsorted_ts_df = ts_df.sort_values(\"Total Purchase Amount\",ascending = False)\nsorted_ts_df.head(5)\n```\n\n\n\n\n<div>\n<style scoped>\n .dataframe tbody tr th:only-of-type {\n vertical-align: middle;\n }\n\n .dataframe tbody tr th {\n vertical-align: top;\n }\n\n .dataframe thead th {\n text-align: right;\n }\n</style>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>Total Purchase Amount</th>\n <th>item count</th>\n <th>avg price</th>\n </tr>\n <tr>\n <th>SN</th>\n <th></th>\n <th></th>\n <th></th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>Undirrala66</th>\n <td>17.06</td>\n <td>5</td>\n <td>3.412000</td>\n </tr>\n <tr>\n <th>Saedue76</th>\n <td>13.56</td>\n <td>4</td>\n <td>3.390000</td>\n </tr>\n <tr>\n <th>Mindimnya67</th>\n <td>12.74</td>\n <td>4</td>\n <td>3.185000</td>\n </tr>\n <tr>\n <th>Haellysu29</th>\n <td>12.73</td>\n <td>3</td>\n <td>4.243333</td>\n </tr>\n <tr>\n <th>Eoda93</th>\n <td>11.58</td>\n <td>3</td>\n <td>3.860000</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\n\n```python\n#Top Items by purchase count\nti_purchase_count = data_file_pd.groupby([\"Item Name\"])[\"Price\"].count()\nti_purchase_value = data_file_pd.groupby([\"Item Name\"])[\"Price\"].sum()\nti_item_price = ti_purchase_value/ti_purchase_count\n\nti_df = ti_purchase_value.to_frame(name=\"Total Purchase Value\")\nti_df[\"item count\"] = ti_purchase_count.values\nti_df[\"Price\"] = ti_item_price.values\nsorted_ti_df = ti_df.sort_values(\"item count\",ascending = False)\nsorted_ti_df.head(5)\n```\n\n\n\n\n<div>\n<style scoped>\n .dataframe tbody tr th:only-of-type {\n vertical-align: middle;\n }\n\n .dataframe tbody tr th {\n vertical-align: top;\n }\n\n .dataframe thead th {\n text-align: right;\n }\n</style>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>Total Purchase Value</th>\n <th>item count</th>\n <th>Price</th>\n </tr>\n <tr>\n <th>Item Name</th>\n <th></th>\n <th></th>\n <th></th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>Final Critic</th>\n <td>38.60</td>\n <td>14</td>\n <td>2.757143</td>\n </tr>\n <tr>\n <th>Arcane Gem</th>\n <td>24.53</td>\n <td>11</td>\n <td>2.230000</td>\n </tr>\n <tr>\n <th>Betrayal, Whisper of Grieving Widows</th>\n <td>25.85</td>\n <td>11</td>\n <td>2.350000</td>\n </tr>\n <tr>\n <th>Stormcaller</th>\n <td>34.65</td>\n <td>10</td>\n <td>3.465000</td>\n </tr>\n <tr>\n <th>Woeful Adamantite Claymore</th>\n <td>11.16</td>\n <td>9</td>\n <td>1.240000</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\n\n```python\n#Top Items by purchase value\nsorted_ti_df_pv = ti_df.sort_values(\"Total Purchase Value\",ascending = False)\nsorted_ti_df_pv.head(5)\n```\n\n\n\n\n<div>\n<style scoped>\n .dataframe tbody tr th:only-of-type {\n vertical-align: middle;\n }\n\n .dataframe tbody tr th {\n vertical-align: top;\n }\n\n .dataframe thead th {\n text-align: right;\n }\n</style>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>Total Purchase Value</th>\n <th>item count</th>\n <th>Price</th>\n </tr>\n <tr>\n <th>Item Name</th>\n <th></th>\n <th></th>\n <th></th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>Final Critic</th>\n <td>38.60</td>\n <td>14</td>\n <td>2.757143</td>\n </tr>\n <tr>\n <th>Retribution Axe</th>\n <td>37.26</td>\n <td>9</td>\n <td>4.140000</td>\n </tr>\n <tr>\n <th>Stormcaller</th>\n <td>34.65</td>\n <td>10</td>\n <td>3.465000</td>\n </tr>\n <tr>\n <th>Spectral Diamond Doomblade</th>\n <td>29.75</td>\n <td>7</td>\n <td>4.250000</td>\n </tr>\n <tr>\n <th>Orenmir</th>\n <td>29.70</td>\n <td>6</td>\n <td>4.950000</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n" }, { "alpha_fraction": 0.4790146052837372, "alphanum_fraction": 0.4863138794898987, "avg_line_length": 32.24242401123047, "blob_id": "cc6a012be63cc12855a76b2c8ee37e45c223b364", "content_id": "4e79260d83ea04fc8e309549e5d3a8317382f822", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1096, "license_type": "no_license", "max_line_length": 76, "num_lines": 33, "path": "/HW 13-14/samples_data.py", "repo_name": "thonagan-H/NW-DATAVISBOOTCAMP-HW", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport csv\n\ndf_samples = pd.read_csv(\"belly_button_biodiversity_samples.csv\")\n\n#Sample_Values list with Otu_Ids and corresponding values\ncols = df_samples.columns.tolist()\nsample_vals_list = []\n\nfor i in cols:\n otu_id_list = []\n otu_id_vals = []\n \n for j in range(len(df_samples[i].values)):\n \n if df_samples[i].values[j] > 0:\n \n otu_id_vals.append(df_samples[i].values[j])\n otu_id_list.append(df_samples[i].index[j] - 1)\n otu_dict = {\n i : otu_id_list,\n 'vals':otu_id_vals \n }\n temp_df = pd.DataFrame(data = otu_dict)\n temp_df = temp_df.sort_values(by=['vals'],ascending = False)\n \n otu_and_vals = {\n 'otu_ids':temp_df[i][0:10].tolist(),\n 'sample_values':temp_df['vals'][0:10].tolist()\n }\n final_dict ={i:otu_and_vals}\n sample_vals_list.append(final_dict)" }, { "alpha_fraction": 0.29648181796073914, "alphanum_fraction": 0.4712255299091339, "avg_line_length": 20.838422775268555, "blob_id": "9c2ae3fcad00078366e118c6f4c44f292b02ca6f", "content_id": "7575cbe7818a44b92d29f412338203893f7d3d4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 17169, "license_type": "no_license", "max_line_length": 99, "num_lines": 786, "path": "/HW 7/README.md", "repo_name": "thonagan-H/NW-DATAVISBOOTCAMP-HW", "src_encoding": "UTF-8", "text": "\n\n```python\n# Dependencies\nimport tweepy\nimport json\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib\nfrom datetime import datetime\n\n# Import and Initialize Sentiment Analyzer\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nanalyzer = SentimentIntensityAnalyzer()\n\n# Twitter API Keys\nconsumer_key = \"Ed4RNulN1lp7NbOooHa9STCoU\"\nconsumer_secret = \"P7cUJlmJpq0VaCY0Jg7COliwQqzK0qYEyUF9Y0idx4ujb3ZlW5\"\naccess_token = \"839621358724198402-dzdOsx2WWHrSuBwyNUiqXEnTivHozAZ\"\naccess_token_secret = \"dCZ80uNRbFDjxdU2EckmNiSckdoATach6Q8zb7YYYE5EW\"\n\n# Setup Tweepy API Authentication\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth, parser=tweepy.parsers.JSONParser())\n\n\n```\n\n\n```python\n# Target Search Term\ntarget_term = [\"@BBC\",\"@CBS\",\"@CNN\",\"@FoxNews\",\"@nytimes\"]\n\n# Lists to hold sentiments\nsentiment =[]\ncompound_list = []\npositive_list = []\nnegative_list = []\nneutral_list = []\nhandle = []\ncounter = 1\n\n# Grab 25 tweets\nfor i in target_term:\n public_tweets = api.user_timeline(i, count=100)\n\n # Loop through all tweets\n for tweet in public_tweets:\n\n # Run Vader Analysis on each tweet\n compound = analyzer.polarity_scores(tweet[\"text\"])[\"compound\"]\n pos = analyzer.polarity_scores(tweet[\"text\"])[\"pos\"]\n neu = analyzer.polarity_scores(tweet[\"text\"])[\"neu\"]\n neg = analyzer.polarity_scores(tweet[\"text\"])[\"neg\"]\n\n # Add each value to the appropriate array\n compound_list.append(compound)\n positive_list.append(pos)\n negative_list.append(neg)\n neutral_list.append(neu)\n handle.append(i)\n\n # Store the Average Sentiments\n sentiment.append({\"Date\": tweet[\"created_at\"],\n \"Handle\":i,\n \"Compound\": np.mean(compound_list),\n \"Positive\": np.mean(positive_list),\n \"Neutral\": np.mean(negative_list),\n \"Negative\": np.mean(neutral_list),\n \"Tweets Ago\": counter})\n \n counter = counter + 1\n \n \n \n \n```\n\n\n```python\nsentiments_pd = pd.DataFrame.from_dict(sentiment)\nsentiments_pd.to_csv(\"Dataframe.csv\")\nsentiments_pd\n```\n\n\n\n\n<div>\n<style scoped>\n .dataframe tbody tr th:only-of-type {\n vertical-align: middle;\n }\n\n .dataframe tbody tr th {\n vertical-align: top;\n }\n\n .dataframe thead th {\n text-align: right;\n }\n</style>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>Compound</th>\n <th>Date</th>\n <th>Handle</th>\n <th>Negative</th>\n <th>Neutral</th>\n <th>Positive</th>\n <th>Tweets Ago</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>0.000000</td>\n <td>Tue Mar 20 19:48:04 +0000 2018</td>\n <td>@BBC</td>\n <td>1.000000</td>\n <td>0.000000</td>\n <td>0.000000</td>\n <td>1</td>\n </tr>\n <tr>\n <th>1</th>\n <td>0.000000</td>\n <td>Tue Mar 20 19:03:04 +0000 2018</td>\n <td>@BBC</td>\n <td>1.000000</td>\n <td>0.000000</td>\n <td>0.000000</td>\n <td>2</td>\n </tr>\n <tr>\n <th>2</th>\n <td>-0.128633</td>\n <td>Tue Mar 20 18:33:01 +0000 2018</td>\n <td>@BBC</td>\n <td>0.922667</td>\n <td>0.053333</td>\n <td>0.023667</td>\n <td>3</td>\n </tr>\n <tr>\n <th>3</th>\n <td>-0.011475</td>\n <td>Tue Mar 20 17:33:03 +0000 2018</td>\n <td>@BBC</td>\n <td>0.876500</td>\n <td>0.065500</td>\n <td>0.057750</td>\n <td>4</td>\n </tr>\n <tr>\n <th>4</th>\n <td>-0.009180</td>\n <td>Tue Mar 20 17:03:01 +0000 2018</td>\n <td>@BBC</td>\n <td>0.901200</td>\n <td>0.052400</td>\n <td>0.046200</td>\n <td>5</td>\n </tr>\n <tr>\n <th>5</th>\n <td>-0.007650</td>\n <td>Tue Mar 20 16:05:04 +0000 2018</td>\n <td>@BBC</td>\n <td>0.917667</td>\n <td>0.043667</td>\n <td>0.038500</td>\n <td>6</td>\n </tr>\n <tr>\n <th>6</th>\n <td>-0.006557</td>\n <td>Tue Mar 20 15:33:03 +0000 2018</td>\n <td>@BBC</td>\n <td>0.929429</td>\n <td>0.037429</td>\n <td>0.033000</td>\n <td>7</td>\n </tr>\n <tr>\n <th>7</th>\n <td>0.045312</td>\n <td>Tue Mar 20 15:03:02 +0000 2018</td>\n <td>@BBC</td>\n <td>0.921750</td>\n <td>0.032750</td>\n <td>0.045375</td>\n <td>8</td>\n </tr>\n <tr>\n <th>8</th>\n <td>0.111044</td>\n <td>Tue Mar 20 14:24:06 +0000 2018</td>\n <td>@BBC</td>\n <td>0.901667</td>\n <td>0.029111</td>\n <td>0.069111</td>\n <td>9</td>\n </tr>\n <tr>\n <th>9</th>\n <td>0.099940</td>\n <td>Tue Mar 20 14:03:04 +0000 2018</td>\n <td>@BBC</td>\n <td>0.911500</td>\n <td>0.026200</td>\n <td>0.062200</td>\n <td>10</td>\n </tr>\n <tr>\n <th>10</th>\n <td>0.111173</td>\n <td>Tue Mar 20 13:16:25 +0000 2018</td>\n <td>@BBC</td>\n <td>0.908727</td>\n <td>0.023818</td>\n <td>0.067364</td>\n <td>11</td>\n </tr>\n <tr>\n <th>11</th>\n <td>0.068383</td>\n <td>Tue Mar 20 13:02:01 +0000 2018</td>\n <td>@BBC</td>\n <td>0.902833</td>\n <td>0.035333</td>\n <td>0.061750</td>\n <td>12</td>\n </tr>\n <tr>\n <th>12</th>\n <td>0.110154</td>\n <td>Tue Mar 20 11:03:23 +0000 2018</td>\n <td>@BBC</td>\n <td>0.896308</td>\n <td>0.032615</td>\n <td>0.071000</td>\n <td>13</td>\n </tr>\n <tr>\n <th>13</th>\n <td>0.056793</td>\n <td>Tue Mar 20 10:30:04 +0000 2018</td>\n <td>@BBC</td>\n <td>0.877714</td>\n <td>0.049643</td>\n <td>0.072571</td>\n <td>14</td>\n </tr>\n <tr>\n <th>14</th>\n <td>0.077287</td>\n <td>Tue Mar 20 10:04:02 +0000 2018</td>\n <td>@BBC</td>\n <td>0.874333</td>\n <td>0.046333</td>\n <td>0.079267</td>\n <td>15</td>\n </tr>\n <tr>\n <th>15</th>\n <td>0.072456</td>\n <td>Tue Mar 20 09:49:33 +0000 2018</td>\n <td>@BBC</td>\n <td>0.882188</td>\n <td>0.043438</td>\n <td>0.074313</td>\n <td>16</td>\n </tr>\n <tr>\n <th>16</th>\n <td>0.049476</td>\n <td>Tue Mar 20 09:49:23 +0000 2018</td>\n <td>@BBC</td>\n <td>0.870471</td>\n <td>0.052059</td>\n <td>0.077412</td>\n <td>17</td>\n </tr>\n <tr>\n <th>17</th>\n <td>0.060617</td>\n <td>Tue Mar 20 09:49:10 +0000 2018</td>\n <td>@BBC</td>\n <td>0.865444</td>\n <td>0.054000</td>\n <td>0.080500</td>\n <td>18</td>\n </tr>\n <tr>\n <th>18</th>\n <td>0.057426</td>\n <td>Tue Mar 20 09:49:02 +0000 2018</td>\n <td>@BBC</td>\n <td>0.872526</td>\n <td>0.051158</td>\n <td>0.076263</td>\n <td>19</td>\n </tr>\n <tr>\n <th>19</th>\n <td>0.079250</td>\n <td>Tue Mar 20 09:32:02 +0000 2018</td>\n <td>@BBC</td>\n <td>0.869600</td>\n <td>0.048600</td>\n <td>0.081750</td>\n <td>20</td>\n </tr>\n <tr>\n <th>20</th>\n <td>0.075476</td>\n <td>Tue Mar 20 09:03:04 +0000 2018</td>\n <td>@BBC</td>\n <td>0.875810</td>\n <td>0.046286</td>\n <td>0.077857</td>\n <td>21</td>\n </tr>\n <tr>\n <th>21</th>\n <td>0.072045</td>\n <td>Tue Mar 20 08:25:06 +0000 2018</td>\n <td>@BBC</td>\n <td>0.881455</td>\n <td>0.044182</td>\n <td>0.074318</td>\n <td>22</td>\n </tr>\n <tr>\n <th>22</th>\n <td>0.068913</td>\n <td>Tue Mar 20 08:03:03 +0000 2018</td>\n <td>@BBC</td>\n <td>0.886609</td>\n <td>0.042261</td>\n <td>0.071087</td>\n <td>23</td>\n </tr>\n <tr>\n <th>23</th>\n <td>0.050133</td>\n <td>Mon Mar 19 19:33:04 +0000 2018</td>\n <td>@BBC</td>\n <td>0.886750</td>\n <td>0.045083</td>\n <td>0.068125</td>\n <td>24</td>\n </tr>\n <tr>\n <th>24</th>\n <td>0.054252</td>\n <td>Mon Mar 19 18:33:05 +0000 2018</td>\n <td>@BBC</td>\n <td>0.879640</td>\n <td>0.047920</td>\n <td>0.072400</td>\n <td>25</td>\n </tr>\n <tr>\n <th>25</th>\n <td>0.048215</td>\n <td>Mon Mar 19 18:03:01 +0000 2018</td>\n <td>@BBC</td>\n <td>0.881192</td>\n <td>0.049154</td>\n <td>0.069615</td>\n <td>26</td>\n </tr>\n <tr>\n <th>26</th>\n <td>0.046430</td>\n <td>Mon Mar 19 17:30:08 +0000 2018</td>\n <td>@BBC</td>\n <td>0.885593</td>\n <td>0.047333</td>\n <td>0.067037</td>\n <td>27</td>\n </tr>\n <tr>\n <th>27</th>\n <td>0.019429</td>\n <td>Mon Mar 19 17:00:05 +0000 2018</td>\n <td>@BBC</td>\n <td>0.869750</td>\n <td>0.060429</td>\n <td>0.069786</td>\n <td>28</td>\n </tr>\n <tr>\n <th>28</th>\n <td>0.018759</td>\n <td>Mon Mar 19 16:33:29 +0000 2018</td>\n <td>@BBC</td>\n <td>0.874241</td>\n <td>0.058345</td>\n <td>0.067379</td>\n <td>29</td>\n </tr>\n <tr>\n <th>29</th>\n <td>0.018133</td>\n <td>Mon Mar 19 15:02:02 +0000 2018</td>\n <td>@BBC</td>\n <td>0.878433</td>\n <td>0.056400</td>\n <td>0.065133</td>\n <td>30</td>\n </tr>\n <tr>\n <th>...</th>\n <td>...</td>\n <td>...</td>\n <td>...</td>\n <td>...</td>\n <td>...</td>\n <td>...</td>\n <td>...</td>\n </tr>\n <tr>\n <th>470</th>\n <td>0.070662</td>\n <td>Tue Mar 20 13:00:11 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.861911</td>\n <td>0.055985</td>\n <td>0.082091</td>\n <td>471</td>\n </tr>\n <tr>\n <th>471</th>\n <td>0.070033</td>\n <td>Tue Mar 20 12:45:04 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.861801</td>\n <td>0.056106</td>\n <td>0.082081</td>\n <td>472</td>\n </tr>\n <tr>\n <th>472</th>\n <td>0.069885</td>\n <td>Tue Mar 20 12:28:03 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862093</td>\n <td>0.055987</td>\n <td>0.081907</td>\n <td>473</td>\n </tr>\n <tr>\n <th>473</th>\n <td>0.069738</td>\n <td>Tue Mar 20 12:15:08 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862384</td>\n <td>0.055869</td>\n <td>0.081734</td>\n <td>474</td>\n </tr>\n <tr>\n <th>474</th>\n <td>0.069591</td>\n <td>Tue Mar 20 12:00:06 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862674</td>\n <td>0.055752</td>\n <td>0.081562</td>\n <td>475</td>\n </tr>\n <tr>\n <th>475</th>\n <td>0.069970</td>\n <td>Tue Mar 20 11:50:08 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862729</td>\n <td>0.055634</td>\n <td>0.081624</td>\n <td>476</td>\n </tr>\n <tr>\n <th>476</th>\n <td>0.070127</td>\n <td>Tue Mar 20 11:39:04 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862524</td>\n <td>0.055738</td>\n <td>0.081725</td>\n <td>477</td>\n </tr>\n <tr>\n <th>477</th>\n <td>0.071196</td>\n <td>Tue Mar 20 11:30:07 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862186</td>\n <td>0.055772</td>\n <td>0.082029</td>\n <td>478</td>\n </tr>\n <tr>\n <th>478</th>\n <td>0.072040</td>\n <td>Tue Mar 20 11:20:08 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862073</td>\n <td>0.055656</td>\n <td>0.082259</td>\n <td>479</td>\n </tr>\n <tr>\n <th>479</th>\n <td>0.072506</td>\n <td>Tue Mar 20 11:11:05 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862108</td>\n <td>0.055540</td>\n <td>0.082340</td>\n <td>480</td>\n </tr>\n <tr>\n <th>480</th>\n <td>0.073149</td>\n <td>Tue Mar 20 11:00:04 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862156</td>\n <td>0.055424</td>\n <td>0.082407</td>\n <td>481</td>\n </tr>\n <tr>\n <th>481</th>\n <td>0.073872</td>\n <td>Tue Mar 20 10:44:03 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862187</td>\n <td>0.055309</td>\n <td>0.082492</td>\n <td>482</td>\n </tr>\n <tr>\n <th>482</th>\n <td>0.073719</td>\n <td>Tue Mar 20 10:36:06 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862472</td>\n <td>0.055195</td>\n <td>0.082321</td>\n <td>483</td>\n </tr>\n <tr>\n <th>483</th>\n <td>0.073567</td>\n <td>Tue Mar 20 10:14:01 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862756</td>\n <td>0.055081</td>\n <td>0.082151</td>\n <td>484</td>\n </tr>\n <tr>\n <th>484</th>\n <td>0.072207</td>\n <td>Tue Mar 20 10:00:07 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862662</td>\n <td>0.055344</td>\n <td>0.081981</td>\n <td>485</td>\n </tr>\n <tr>\n <th>485</th>\n <td>0.072058</td>\n <td>Tue Mar 20 09:45:09 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862944</td>\n <td>0.055230</td>\n <td>0.081813</td>\n <td>486</td>\n </tr>\n <tr>\n <th>486</th>\n <td>0.070896</td>\n <td>Tue Mar 20 09:30:14 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862930</td>\n <td>0.055413</td>\n <td>0.081645</td>\n <td>487</td>\n </tr>\n <tr>\n <th>487</th>\n <td>0.071311</td>\n <td>Tue Mar 20 09:15:06 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862906</td>\n <td>0.055299</td>\n <td>0.081783</td>\n <td>488</td>\n </tr>\n <tr>\n <th>488</th>\n <td>0.071165</td>\n <td>Tue Mar 20 09:00:18 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.863186</td>\n <td>0.055186</td>\n <td>0.081616</td>\n <td>489</td>\n </tr>\n <tr>\n <th>489</th>\n <td>0.071433</td>\n <td>Tue Mar 20 08:45:06 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.863047</td>\n <td>0.055073</td>\n <td>0.081867</td>\n <td>490</td>\n </tr>\n <tr>\n <th>490</th>\n <td>0.071287</td>\n <td>Tue Mar 20 08:30:12 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.863326</td>\n <td>0.054961</td>\n <td>0.081701</td>\n <td>491</td>\n </tr>\n <tr>\n <th>491</th>\n <td>0.072146</td>\n <td>Tue Mar 20 08:15:04 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.863181</td>\n <td>0.054850</td>\n <td>0.081957</td>\n <td>492</td>\n </tr>\n <tr>\n <th>492</th>\n <td>0.070784</td>\n <td>Tue Mar 20 08:02:02 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.863043</td>\n <td>0.055154</td>\n <td>0.081791</td>\n <td>493</td>\n </tr>\n <tr>\n <th>493</th>\n <td>0.069787</td>\n <td>Tue Mar 20 07:47:03 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.863081</td>\n <td>0.055281</td>\n <td>0.081626</td>\n <td>494</td>\n </tr>\n <tr>\n <th>494</th>\n <td>0.069646</td>\n <td>Tue Mar 20 07:32:03 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.863358</td>\n <td>0.055170</td>\n <td>0.081461</td>\n <td>495</td>\n </tr>\n <tr>\n <th>495</th>\n <td>0.070630</td>\n <td>Tue Mar 20 07:17:04 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.863204</td>\n <td>0.055058</td>\n <td>0.081726</td>\n <td>496</td>\n </tr>\n <tr>\n <th>496</th>\n <td>0.071720</td>\n <td>Tue Mar 20 07:07:42 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862704</td>\n <td>0.054948</td>\n <td>0.082336</td>\n <td>497</td>\n </tr>\n <tr>\n <th>497</th>\n <td>0.071576</td>\n <td>Tue Mar 20 07:02:05 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.862980</td>\n <td>0.054837</td>\n <td>0.082171</td>\n <td>498</td>\n </tr>\n <tr>\n <th>498</th>\n <td>0.071432</td>\n <td>Tue Mar 20 06:33:04 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.863255</td>\n <td>0.054727</td>\n <td>0.082006</td>\n <td>499</td>\n </tr>\n <tr>\n <th>499</th>\n <td>0.070409</td>\n <td>Tue Mar 20 06:18:45 +0000 2018</td>\n <td>@nytimes</td>\n <td>0.863040</td>\n <td>0.055106</td>\n <td>0.081842</td>\n <td>500</td>\n </tr>\n </tbody>\n</table>\n<p>500 rows × 7 columns</p>\n</div>\n\n\n\n\n```python\nfor user in target_term:\n dataframe = sentiments_pd.loc[sentiments_pd[\"Handle\"] == user]\n plt.scatter(dataframe[\"Tweets Ago\"],dataframe[\"Compound\"],label = user)\n\nplt.legend(bbox_to_anchor = (1,1))\nplt.grid()\n#plt.xlim(1,-1)\nplt.savefig('Analysis_1.png')\nplt.show()\n```\n\n\n![png](output_3_0.png)\n\n\n\n```python\nsentiments_pd.groupby('Handle')[\"Compound\"].sum()\n```\n\n\n\n\n Handle\n @BBC 6.493245\n @CBS 19.286886\n @CNN 16.263189\n @FoxNews 12.138717\n @nytimes 8.059501\n Name: Compound, dtype: float64\n\n\n\n\n```python\n\nsentiments_pd.groupby('Handle')[\"Compound\"].sum().plot.bar(x='Tweets Ago', \n y='Compound',width = 1.0, title=\"title\")\n\nplt.title(\"Overall Sentiment of Media Tweets (11/5/2017)\")\nplt.xlabel(\"News Organizations\")\nplt.ylabel(\"Tweet Polarity\")\nplt.savefig(\"Overall Sentiment of Media Tweets\")\nplt.ylim(-20,20)\nplt.savefig(\"Analysis_2.png\")\nplt.show()\n\n```\n\n\n![png](output_5_0.png)\n\n" }, { "alpha_fraction": 0.7910447716712952, "alphanum_fraction": 0.7910447716712952, "avg_line_length": 75.57142639160156, "blob_id": "50e3755d5b0fde4f2c8f8733762043c905126753", "content_id": "2410adf777e8d4b979d03909fb2ed2ded2a5ee7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 536, "license_type": "no_license", "max_line_length": 137, "num_lines": 7, "path": "/HW 5/NOTES.txt", "repo_name": "thonagan-H/NW-DATAVISBOOTCAMP-HW", "src_encoding": "UTF-8", "text": "Regarding the bubble plot:\n I was able to accurately generate the bubbble plot however I was unable to change the legend color to match the bubbble color.\n I also believe that bubble plots are not the best way to represent the data. The data appears too clustered and is difficult to analyze\n given the overlapping colors. I feel that using a bar chart can provide the same result with better visualization.\n \n Regarding the pie charts:\n I was able to generate the chart, but was unable to combine two wedges into one single wedge.\n" }, { "alpha_fraction": 0.5416666865348816, "alphanum_fraction": 0.5726807117462158, "avg_line_length": 22.53333282470703, "blob_id": "0857e53e3af6adc2ed4e44fdf9739bb14f8090c6", "content_id": "55bec250c8722a2b43e4e934f974133d5ae4845e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7416, "license_type": "no_license", "max_line_length": 1197, "num_lines": 315, "path": "/HW 6/README .md", "repo_name": "thonagan-H/NW-DATAVISBOOTCAMP-HW", "src_encoding": "UTF-8", "text": "\n\n```python\nimport csv\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport requests\nfrom citipy import citipy\nimport openweathermapy as ow\n\nfrom config import api_key\n\n```\n\n\n```python\n #PSEUDOCODE\n\n#create an array of cities based on lat and long\n #generate random coordnates - check\n #use citipy to generate nearest city - check\n #make sure cities are unique\n#loop through array\n #in the loop, make an api call to each city and append data to a list:\n #put weather data - lat, temp, humidity, clouds, wind speed into separate lists\n#create dataframe with weather data and city name\n#plot data from dataframe\n```\n\n\n```python\n#create an array of cities based on lat and long\n #generate random coordnates - check\ncoord = []\ntup = ()\nfor limit in range(1000):\n lat, long = np.random.uniform(-180,180), np.random.uniform(-90, 90)\n tup = (lat,long)\n coord.append(tup)\n\n```\n\n\n```python\n#use citipy to generate nearest city - check\nempty = []\nfor i in range(0,len(coord)):\n city = citipy.nearest_city(coord[i][0], coord[i][1])\n empty.append(city.city_name)\n\n#Make sure cities are unique \ncity_list = []\nfor j in empty:\n if j not in city_list:\n city_list.append(j)\n else:\n city = citipy.nearest_city(np.random.uniform(-180,180), np.random.uniform(-90, 90))\n city_new = city.city_name\n empty.append(city_new)\n \n#Check if cities are unique:\ncity_set = set(empty)\nif len(city_set) == len(city_list):\n print(\"Cities are unique\")\n\n```\n\n Cities are unique\n \n\n\n```python\n#Do the api call:\nsettings = {\"units\": \"metric\", \"appid\": api_key}\nweather_data = []\nnot_found = []\n\n#Loop through the city list and catch for 404 errors for cities that don't have weather data\nfor city in city_list:\n if len(weather_data) > 700:\n break\n else:\n try:\n weather_data.append([ow.get_current(city, **settings)]) \n except Exception as err:\n not_found.append(city)\n continue\nprint(\"The following cities could not be found: \\n\")\nprint(not_found)\n```\n\n The following cities could not be found: \n \n ['bengkulu', 'barentsburg', 'illoqqortoormiut', 'karaul', 'belushya guba', 'warqla', 'taolanaro', 'berbera', 'bantry', 'urumqi', 'amderma', 'mouzakion', 'tsihombe', 'taltal', 'solovetskiy', 'marcona', 'louisbourg', 'attawapiskat', 'koyilandi', 'olafsvik', 'tumannyy', 'kosya', 'grand river south east', 'korla', 'barawe', 'kachikau', 'kemijarvi', 'chissamba', 'tres lagoas', 'saint quentin', 'zhovtneve', 'balykshi', 'chigorodo', 'vedaranniyam', 'kytlym', 'aflu', 'labrea', 'maarianhamina', 'longlac', 'polikastron', 'kalavrita', 'zachagansk', 'tunduru', 'ciras', 'vicuna', 'kashi', 'achisay', 'bur gabo', 'zmiyiv', 'toliary', 'formoso do araguaia', 'leghorn', 'borama', 'machali', 'acarau', 'raga', 'santa eulalia del rio', 'rolim de moura', 'el reten', 'khokholskiy', 'el faiyum', 'bossembele', 'aberystwyth', 'westpunt', 'irbil', 'umzimvubu', 'doctor pedro p. pena', 'stornoway', 'krasnoselkup', 'araguacu', 'ipora', 'rudbar', 'tsienyane', 'varzea alegre', 'sitio novo do tocantins', 'malwan', 'andenes', 'talah', 'bolshoy tsaryn', 'bargal', 'saryshagan', 'tambopata', 'mahaicony', 'mwaya', 'kargil', 'burica', 'sento se', 'yakshur-bodya', 'hunza', 'vestbygda', 'fianga', 'tome-acu', 'tingrela']\n \n\n\n```python\n#Create Dataframe to hold Weather Data:\ndata_list = []\nnames = []\nfor item in weather_data:\n for response in item:\n data = ( response['main']['temp'], response['main']['humidity'], response['wind']['speed'],\n response['clouds']['all'], response['coord']['lat'], response['coord']['lon']) \n name = (response['name'])\n names.append(name)\n data_list.append(data)\n\n\n#put weather data - lat, temp, humidity, clouds, wind speed into separate lists\nweather_data_df = pd.DataFrame(data_list)\ncolumn_names = [\"Temp\",\"Humidity\",\"Wind Speed\",\"Cloudiness(%)\", \"Latitude\", \"Longitude\"]\nweather_data_df = pd.DataFrame(data_list, index = names , columns=column_names)\n\n```\n\n\n```python\nx = weather_data_df['Latitude']\nweather_data_df.to_csv('Weather_Data.csv')\nweather_data_df.head(10)\n```\n\n\n\n\n<div>\n<style scoped>\n .dataframe tbody tr th:only-of-type {\n vertical-align: middle;\n }\n\n .dataframe tbody tr th {\n vertical-align: top;\n }\n\n .dataframe thead th {\n text-align: right;\n }\n</style>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>Temp</th>\n <th>Humidity</th>\n <th>Wind Speed</th>\n <th>Cloudiness(%)</th>\n <th>Latitude</th>\n <th>Longitude</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>Narsaq</th>\n <td>-7.00</td>\n <td>44</td>\n <td>3.10</td>\n <td>0</td>\n <td>60.91</td>\n <td>-46.05</td>\n </tr>\n <tr>\n <th>Ipixuna</th>\n <td>22.00</td>\n <td>94</td>\n <td>3.10</td>\n <td>75</td>\n <td>-1.76</td>\n <td>-48.80</td>\n </tr>\n <tr>\n <th>Njombe</th>\n <td>16.20</td>\n <td>99</td>\n <td>0.88</td>\n <td>80</td>\n <td>-9.34</td>\n <td>34.77</td>\n </tr>\n <tr>\n <th>Qandala</th>\n <td>13.80</td>\n <td>100</td>\n <td>0.43</td>\n <td>8</td>\n <td>11.47</td>\n <td>49.87</td>\n </tr>\n <tr>\n <th>Bredasdorp</th>\n <td>17.00</td>\n <td>88</td>\n <td>3.10</td>\n <td>92</td>\n <td>-34.53</td>\n <td>20.04</td>\n </tr>\n <tr>\n <th>Tasiilaq</th>\n <td>-9.00</td>\n <td>43</td>\n <td>1.00</td>\n <td>12</td>\n <td>65.61</td>\n <td>-37.64</td>\n </tr>\n <tr>\n <th>Shelburne</th>\n <td>-4.01</td>\n <td>73</td>\n <td>2.60</td>\n <td>1</td>\n <td>44.08</td>\n <td>-80.20</td>\n </tr>\n <tr>\n <th>Qaanaaq</th>\n <td>-23.56</td>\n <td>100</td>\n <td>0.43</td>\n <td>36</td>\n <td>77.48</td>\n <td>-69.36</td>\n </tr>\n <tr>\n <th>Dikson</th>\n <td>-21.31</td>\n <td>100</td>\n <td>12.78</td>\n <td>48</td>\n <td>73.51</td>\n <td>80.55</td>\n </tr>\n <tr>\n <th>Ushuaia</th>\n <td>6.00</td>\n <td>75</td>\n <td>5.70</td>\n <td>40</td>\n <td>-54.81</td>\n <td>-68.31</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\n\n```python\n#TEMP VS LAT\ny_t = weather_data_df[\"Temp\"]\nplt.plot(x,y_t,'mo')\nplt.xlabel(\"Latitude\")\nplt.ylabel(\"Temp(C)\")\nplt.title(\"Temp(C) vs Lat\")\nplt.grid()\nplt.savefig(\"Temp vs Lat\")\nplt.show()\n```\n\n\n![png](output_7_0.png)\n\n\n\n```python\n#HUMIDITY VS LAT\ny_h = weather_data_df[\"Humidity\"]\nplt.plot(x,y_h,'bo')\nplt.xlabel(\"Latitude\")\nplt.ylabel(\"Humidity(%)\")\nplt.title(\"Humidity(%) vs Lat\")\nplt.grid()\nplt.savefig(\"Humidity vs Lat\")\nplt.show()\n```\n\n\n![png](output_8_0.png)\n\n\n\n```python\n#WIND SPEED VS LAT\ny_ws = weather_data_df[\"Wind Speed\"]\nplt.plot(x,y_ws,'ro')\nplt.xlabel(\"Latitude\")\nplt.ylabel(\"Wind Speed(mph)\")\nplt.title(\"Wind Speed(mph) vs Lat\")\nplt.grid()\nplt.savefig(\"Wind Speed vs Lat\")\nplt.show()\n```\n\n\n![png](output_9_0.png)\n\n\n\n```python\n#CLOUDINESS VS LAT\ny_c = weather_data_df[\"Cloudiness(%)\"]\nplt.plot(x,y_c,'go')\nplt.xlabel(\"Latitude\")\nplt.ylabel(\"Cloudiness(%)\")\nplt.title(\"Cloudiness(%) vs Lat\")\nplt.grid()\nplt.savefig(\"Cloudiness vs Lat\")\nplt.show()\n```\n\n\n![png](output_10_0.png)\n\n" }, { "alpha_fraction": 0.6283524632453918, "alphanum_fraction": 0.6321839094161987, "avg_line_length": 34.75862121582031, "blob_id": "50cd1c5511d02939e90b5bbd9c022409a19a0555", "content_id": "854bb46dd4cf017f08103111c2bfbba72801129e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1044, "license_type": "no_license", "max_line_length": 99, "num_lines": 29, "path": "/HW 13-14/biodiversity.py", "repo_name": "thonagan-H/NW-DATAVISBOOTCAMP-HW", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport csv\n\ndf_samples = pd.read_csv(\"belly_button_biodiversity_samples.csv\")\ndf_otu_id = pd.read_csv(\"belly_button_biodiversity_otu_id.csv\")\ndf_met_csv = pd.read_csv(\"Belly_Button_Biodiversity_Metadata.csv\")\ndf_met = pd.read_csv(\"metadata_columns.csv\")\ndf_met_csv_2 = df_met_csv.set_index(df_met_csv['SAMPLEID'])\n\n#List of Names\nid_list = df_samples.columns[1:].tolist()\n\n#List of OTU Descriptions\notu_descr = df_otu_id['lowest_taxonomic_unit_found'].tolist()\n\nlist_of_dicts_metadata = [df_met_csv_2.loc[x].to_dict() for x in df_met_csv_2['SAMPLEID'].tolist()]\n\nmetadata_samples = []\nfor i in list_of_dicts_metadata:\n filtered_dict = {k:v for (k,v) in i.items()\n if ('AGE' in k) or ('BBTYPE' in k)\n or('ETHNICITY' in k) or ('GENDER' in k)\n or('LOCATION' in k) or ('SAMPLEID' in k)} \n metadata_samples.append(filtered_dict)\n\nfor i in metadata_samples:\n i['AGE'] = i['AGE'].item()\n i['SAMPLEID'] = i['SAMPLEID'].item()\n \n\n\n" }, { "alpha_fraction": 0.520799994468689, "alphanum_fraction": 0.5426666736602783, "avg_line_length": 28.25806427001953, "blob_id": "bf3e5e923486db83a1adf0348f4fb300d58de5d3", "content_id": "fbf925b73612aaf56f561bb81b4c38d1e3b918a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3750, "license_type": "no_license", "max_line_length": 117, "num_lines": 124, "path": "/HW 14-15/app.js", "repo_name": "thonagan-H/NW-DATAVISBOOTCAMP-HW", "src_encoding": "UTF-8", "text": "// Chart Params\r\nvar svgWidth = 960;\r\nvar svgHeight = 500;\r\n\r\nvar margin = { top: 20, right: 40, bottom: 60, left: 100 };\r\n\r\nvar width = svgWidth - margin.left - margin.right;\r\nvar height = svgHeight - margin.top - margin.bottom;\r\n\r\n// Create an SVG wrapper, append an SVG group that will hold our chart, and shift the latter by left and top margins.\r\nvar svg = d3\r\n .select(\"body\")\r\n .append(\"svg\")\r\n .attr(\"width\", svgWidth)\r\n .attr(\"height\", svgHeight);\r\n\r\nvar chartGroup = svg.append(\"g\")\r\n .attr(\"transform\", `translate(${margin.left}, ${margin.top})`);\r\n\r\n// Import data from an external CSV file\r\nd3.csv(\"combined_data_25_34.csv\", function(error, csvData) {\r\n if (error) throw error;\r\n \r\n console.log(csvData);\r\n console.log([csvData]);\r\n\r\n csvData.forEach(function (data) {\r\n data.edu_percent = +data.edu_percent;\r\n data.obesity_percent = +data.obesity_percent;\r\n });\r\n \r\n // Create scaling functions\r\n var xScale = d3.scaleLinear()\r\n .domain([0,d3.max(csvData, d => d.edu_percent)+2])\r\n .range([0, width]);\r\n \r\n var yScale = d3.scaleLinear()\r\n .domain([d3.min(csvData, d => d.obesity_percent)-2,d3.max(csvData, d => d.obesity_percent)+2])\r\n // d3.extent(csvData, d => d.obesity_percent_65_plus))\r\n .range([height, 0]);\r\n \r\n \r\n // Create axis functions\r\n var bottomAxis = d3.axisBottom(xScale)\r\n var leftAxis = d3.axisLeft(yScale);\r\n\r\n \r\n // Add x-axis\r\n chartGroup.append(\"g\")\r\n .attr(\"transform\", `translate(0, ${height})`)\r\n .call(bottomAxis);\r\n \r\n // Add y-axis to the left side of the display\r\n chartGroup.append(\"g\")\r\n .call(leftAxis);\r\n \r\n // Step 5: Create Circles \r\n var circlesGroup = chartGroup.selectAll(\"circle\")\r\n .data(csvData)\r\n .enter()\r\n .append(\"circle\")\r\n .attr(\"class\", \"dot\")\r\n .attr(\"cx\", d => xScale(d.edu_percent))\r\n .attr(\"cy\", d => yScale(d.obesity_percent))\r\n .attr(\"r\", \"5\")\r\n .attr(\"fill\", \"red\")\r\n .attr(\"opacity\", \"1\")\r\n \r\n // Create axes labels\r\n chartGroup.append(\"text\")\r\n .attr(\"transform\", \"rotate(-90)\")\r\n .attr(\"y\", 0 - margin.left + 40)\r\n .attr(\"x\", 0 - (height / 2))\r\n .attr(\"dy\", \"1em\")\r\n .attr(\"class\", \"axisText\")\r\n .text(\"Ages 25-34 Obesity %\");\r\n\r\n chartGroup.append(\"text\")\r\n .attr(\"transform\", `translate(${width/2}, ${height + margin.top + 30})`)\r\n .attr(\"class\", \"axisText\")\r\n .text(\"Ages 25-34 Education %\");\r\n \r\n // // Step 6: Initialize tool tip\r\n var toolTip = d3.tip()\r\n .attr(\"class\", \"tooltip\")\r\n .offset([80, -60])\r\n .html(function (d) {\r\n return (`${d.State}<br>Education: ${d.edu_percent} <br>Obesity: ${d.obesity_percent}%`);\r\n });\r\n \r\n // Step 7: Create tooltip in the chart\r\n chartGroup.call(toolTip);\r\n\r\n // Step 8: Create event listeners to display and hide the tooltip\r\n circlesGroup.on(\"mouseover\", function (data) {\r\n toolTip.show(data);\r\n })\r\n // onmouseout event\r\n .on(\"mouseout\", function (data, index) {\r\n toolTip.hide(data);\r\n });\r\n \r\n // Legend\r\n var legend = chartGroup.append(\"g\")\r\n .attr(\"class\", \"legend\")\r\n \r\n\r\n // draw legend colored rectangles\r\n legend.append(\"circle\")\r\n .attr(\"cx\", width - 5)\r\n .attr(\"cy\", height - 410)\r\n .attr(\"r\", 5)\r\n .style(\"fill\", 'red')\r\n .style('stroke','black')\r\n\r\n // draw legend text\r\n legend.append(\"text\")\r\n .attr(\"x\", width - 16)\r\n .attr(\"y\", 9)\r\n .attr(\"dy\", \".35em\")\r\n .style(\"text-anchor\", \"end\")\r\n .text('obesity vs education in 25-34 year olds')\r\n\r\n });" }, { "alpha_fraction": 0.6594594717025757, "alphanum_fraction": 0.6778378486633301, "avg_line_length": 23.263158798217773, "blob_id": "c6b8a9dd8fce2ada4ba844746725b7d662e48e56", "content_id": "e2c1e56315bea9f630b4cb9ffe52accf38224b26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 925, "license_type": "no_license", "max_line_length": 59, "num_lines": 38, "path": "/HW 11-12/app.py", "repo_name": "thonagan-H/NW-DATAVISBOOTCAMP-HW", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, jsonify, redirect\nfrom flask_pymongo import PyMongo\nimport mission_to_mars\n\n\napp = Flask(__name__)\n\nmongo = PyMongo(app)\n\n\[email protected](\"/\")\ndef index():\n\tnews_title_text = mongo.db.news.find()\n\tpic_of_day = mongo.db.pic_of_day.find()\n\tmars_tweets = mongo.db.tweets.find()\n\timg_dict = mongo.db.imgs.find()\n\treturn render_template(\"index.html\", listings=listings)\n\[email protected](\"/clear\")\ndef clear():\n\tresult_1 = mongo.db.news.delete_many({})\n\tresult_2 = mongo.db.pic_of_day.delete_many({})\n\tresult_3 = mongo.db.tweets.delete_many({})\n\tresult_4 = mongo.db.imigs.delete_many({})\n\treturn redirect(\"http://127.0.0.1:5000/\", code=302)\n\[email protected](\"/scrape\")\ndef scrape():\n\tnews_title_text = mongo.db.news\n\tpic_of_day = mongo.db.pic_of_day\n\tmars_tweets = mongo.db.tweets\n\timg_dict = mongo.db.imgs\n\tmars_data = mission_to_mars.scrape()\n\t\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n\n\n" }, { "alpha_fraction": 0.6244487762451172, "alphanum_fraction": 0.6313081979751587, "avg_line_length": 34.18965530395508, "blob_id": "0f8fcad5c8340512d66ef8ce10506ec1aed3799d", "content_id": "373147d9af1b299fae3f59592ccd0980b2e8f4a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4082, "license_type": "no_license", "max_line_length": 168, "num_lines": 116, "path": "/HW 11-12/mission_to_mars.py", "repo_name": "thonagan-H/NW-DATAVISBOOTCAMP-HW", "src_encoding": "UTF-8", "text": "#Dependencies\nfrom splinter import Browser\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\nfrom selenium import webdriver\nfrom flask import (Flask, render_template, jsonify, redirect, )\nimport pymongo\n\n\n\n\ndef scrape():\n # Establish Mongo Connections:\n conn = 'mongodb://localhost:27017'\n client = pymongo.MongoClient(conn)\n #Create Mars Database\n mars_db = client.mars_data\n #Create Collections:\n collection_news = mars_db.news #provide collection of mars news\n collection_pic_of_day = mars_db.pic_of_day #provide collection of mars pic of day url\n collection_tweets = mars_db.tweets #provides collection of tweets\n collection_imgs = mars_db.imgs #Provides collection of img url and tile\n \n #Create Scraper\n pretty_print = None\n soups = None\n browsers = None\n def scraper(link):\n global pretty_print\n global browsers\n browsers = webdriver.Chrome('chromedriver.exe')\n browsers.get(link)\n htmls = browsers.page_source\n global soups\n soups = bs(htmls, \"html.parser\")\n pretty_print = soups.body.prettify()\n return pretty_print,soups,browsers\n\n # Scrape Mars Website\n url_mars_press = \"https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&category=19%2C165%2C184%2C204&blank_scope=Latest\"\n scraper(url_mars_press)\n print(soups.body.prettify())\n \n # Get titles and paragraph text from mars website\n headings_res = soups.find_all('div', class_='content_title')\n para_res = soups.find_all('div', class_='rollover_description_inner')\n for i in range(len(headings_res)):\n news_title_text = {\n 'title':headings_res[i].text,\n 'text':para_res[i].text\n }\n collection_news.insert_one(news_title_text)\n\n #USE SPLINTER TO GET IMG URL\n def init_browser():\n # @NOTE: Replace the path with your actual path to the chromedriver\n executable_path = {\"executable_path\": \"D:\\Downloads\\chromedriver.exe\"}\n return Browser(\"chrome\", **executable_path, headless=False)\n\n\n # Get URL for Pic of the Day\n brow = init_browser()\n mars_img_url = \"https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars\"\n brow.visit(mars_img_url)\n brow.click_link_by_partial_text('FULL IMAGE')\n imgs = brow.find_by_tag('img')\n for i in range(len(imgs)):\n if imgs[i].has_class('fancybox-image') == True:\n img_of_the_day = imgs[i]._element.get_attribute('src')\n pic_of_day = {\n 'url':img_of_the_day\n }\n collection_pic_of_day.insert_one(pic_of_day) \n \n\n # Scrape Mars Twitter:\n url_tweets = \"https://twitter.com/marswxreport?lang=en\"\n scraper(url_tweets)\n print(pretty_print)\n\n # Get all Mars Weather Tweets\n tweets = soups.find_all('p', class_='TweetTextSize TweetTextSize--normal js-tweet-text tweet-text')\n for i in range(len(tweets)):\n if 'http' not in tweets[i].text:\n mars_weather.append((tweets[i]).text)\n mars_tweets = {\n 'tweet':tweets[i].text\n }\n collection_tweets.insert_one(mars_tweets)\n\n #Mars Images\n brow_images = init_browser()\n img_site = \"https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars\"\n brow_images.visit(img_site)\n\n # Get a list of all the titles for the hemispheres\n tag_list = []\n tags = brow_images.find_by_tag('h3')\n for i in tags:\n tag_list.append(i.text)\n tag_list\n \n # Get img title and url using a loop\n for i in range(len(tag_list)):\n brow_images.click_link_by_partial_text(tag_list[i])\n link_to_get = brow_images.find_link_by_text('Sample')\n img_title = brow_images.find_by_tag('h2')\n img_dict = {\n 'title':img_title.text,\n 'img_url':link_to_get['href']\n }\n collection_imgs.insert_one(img_dict)\n brow_images.back()\n \n \n return news_title_text,pic_of_day,mars_tweets,img_dict\n" } ]
16
alvis1029/scanner
https://github.com/alvis1029/scanner
aef16a8cca2d566dcbf6141db834129525749739
7119c9810256edfde78f466108dea1dc882a366c
b4b6738e5cfe2d42cbc1916607729c97d1136ba7
refs/heads/master
2023-07-11T07:13:02.745215
2021-08-26T08:32:35
2021-08-26T08:32:35
358,221,204
0
2
null
null
null
null
null
[ { "alpha_fraction": 0.49699312448501587, "alphanum_fraction": 0.5354381203651428, "avg_line_length": 31.760562896728516, "blob_id": "b844a13fd6122c1c793f628ae809d2966c8aa50d", "content_id": "85c1f3c71c53b00f0b9061890f2555c84d3533e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4656, "license_type": "no_license", "max_line_length": 140, "num_lines": 142, "path": "/src/scanner/src/2D_gaussian.py", "repo_name": "alvis1029/scanner", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n\nimport rospy\nimport std_msgs.msg\nimport detection_msgs.msg\nfrom std_msgs.msg import Float64, Int8\n\nimport numpy as np\nfrom math import sqrt\nfrom matplotlib import cm\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nmod_var = 1.0\nmin = 100.0\nprev_min = 100.0\npassby = 0\nadd_var = 0.01\ncounter = 0\n\nclass SetMaxSpeed:\n def __init__(self, max_speed_pub, det_pub, distance_pub, modify_var_pub):\n self.max_speed_pub = max_speed_pub\n self.det_pub = det_pub\n self.distance_pub = distance_pub\n self.modify_var_pub = modify_var_pub\n\n def symmetric_gaussian(self, pos, mu, Sigma):\n \"\"\"Return the multivariate Gaussian distribution on array pos.\"\"\"\n\n n = mu.shape[0]\n Sigma_det = np.linalg.det(Sigma)\n Sigma_inv = np.linalg.inv(Sigma)\n N = np.sqrt((2*np.pi)**n * Sigma_det)\n # This einsum call calculates (x-mu)T.Sigma-1.(x-mu) in a vectorized\n # way across all the input variables.\n fac = np.einsum('...k,kl,...l->...', pos-mu, Sigma_inv, pos-mu)\n\n return np.exp(-fac / 2) / N\n\n def social_speed(self, dx, dy, MAX_SPEED):\n x = np.arange(-3, 3, 0.1)\n y = np.arange(-3, 3, 0.1)\n X, Y = np.meshgrid(x, y)\n\n # Mean vector and covariance matrix\n mu = np.array([0.0, 0.0])\n Sigma = np.array([[ 0.5, 0.0 ], [ 0.0, 0.5 ]])\n\n # Pack X and Y into a single 3-dimensional array\n pos = np.empty(X.shape + (2,))\n pos[:, :, 0] = X\n pos[:, :, 1] = Y\n\n # The distribution on the variables X, Y packed into pos.\n Z = self.symmetric_gaussian(pos, mu, Sigma)\n\n # fig = plt.figure()\n # ax = fig.gca(projection='3d')\n # ax.plot_surface(X, Y, Z, rstride=3, cstride=3, linewidth=1, antialiased=True, cmap=cm.viridis)\n # plt.contour(X, Y, Z)\n # plt.show()\n\n global mod_var\n global passby\n global add_var\n\n if passby == 0:\n if 1.0 - Z[29+dx, 29+dy] / Z[29, 29] < 0.99 :\n if mod_var - (1.0 - Z[29+dx, 29+dy] / Z[29, 29]) > 0.033 :\n mod_var = 1.0 - Z[29+dx, 29+dy] / Z[29, 29] + 0.02\n else :\n mod_var = 1.0 - Z[29+dx, 29+dy] / Z[29, 29]\n else :\n if mod_var == 1.0:\n mod_var = 1.0\n elif mod_var > 0.04:\n mod_var = mod_var - 0.04\n\n if passby == 1 and mod_var <= 1.0:\n mod_var = mod_var + add_var/12\n\n final_max_speed = mod_var * MAX_SPEED\n # rospy.logwarn(\"modify velocity to %lf\", final_max_speed)\n self.max_speed_pub.publish(final_max_speed)\n self.modify_var_pub.publish(mod_var)\n\n def get_distance_callback(self, msg):\n global min\n global prev_min\n global passby\n global add_var\n global counter\n target = -1\n \n if len(msg.dets_list) != 0 :\n for i in range(len(msg.dets_list)) :\n min = msg.dets_list[i].x * msg.dets_list[i].x + msg.dets_list[i].y * msg.dets_list[i].y\n target = i\n \n if target != -1 :\n if min > prev_min :\n min = min - 0.05\n \n self.social_speed(int(msg.dets_list[target].x/0.2), int(msg.dets_list[target].y/0.2), 0.4)\n else :\n if min == prev_min and min > 0.5 and passby == 0:\n min = min - 0.2\n\n if min <= 0.5:\n passby = 1\n\n self.social_speed(30, 30, 0.4)\n\n if passby == 1 and min < 40:\n min = min + add_var\n\n if counter/3 == 0: \n add_var = add_var + 0.06\n elif counter/3 == 1:\n add_var = add_var + 0.07\n else:\n add_var = add_var + 0.03\n\n counter = counter + 1\n\n self.det_pub.publish(len(msg.dets_list)) \n self.distance_pub.publish(sqrt(min))\n prev_min = min\n\ndef main():\n rospy.init_node(\"Setting_Max_Speed\")\n max_speed_pub = rospy.Publisher(\"/navigation_controller/max_speed\", Float64, queue_size=10)\n det_pub = rospy.Publisher(\"/people/num\", Int8, queue_size=10)\n distance_pub = rospy.Publisher(\"/people/distance\", Float64, queue_size=10)\n modify_var_pub = rospy.Publisher(\"/modify_variable\", Float64, queue_size=10)\n modifier = SetMaxSpeed(max_speed_pub, det_pub, distance_pub, modify_var_pub)\n sub = rospy.Subscriber(\"/scan_person_clustering_front_node/det3d_result\", detection_msgs.msg.Det3DArray, modifier.get_distance_callback)\n rospy.spin()\n\nif __name__ == '__main__':\n main()\n " }, { "alpha_fraction": 0.602150559425354, "alphanum_fraction": 0.6256109476089478, "avg_line_length": 29.117647171020508, "blob_id": "15fef025cb0175a31fa461bee6ae5386972687f2", "content_id": "fa275e3fdc39dd9b93f5915662c98f364c7ad629", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1023, "license_type": "no_license", "max_line_length": 100, "num_lines": 34, "path": "/src/yolov4/pytorch-master/test_msg.py", "repo_name": "alvis1029/scanner", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport rospy\nimport os\nimport sys\nimport numpy as np\nfrom detection_msgs.msg import Detection2D, BBox2D\nros_py27_path = '/opt/ros/' + os.getenv(\"ROS_DISTRO\") + '/lib/python2.7/dist-packages'\nif ros_py27_path in sys.path:\n sys.path.remove(ros_py27_path)\nimport cv2\nfrom cv_bridge import CvBridge\nbridge = CvBridge()\n\ndef callback(msg):\n if len(msg.boxes) != 0:\n img = bridge.imgmsg_to_cv2(msg.result_image, \"rgb8\")\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n cv2.imshow(\"test\", img)\n cv2.waitKey(1)\n\n for i in range(len(msg.boxes)):\n print(\"Target Name = \", msg.boxes[i].class_name)\n print(\"x = \", msg.boxes[i].center.x)\n print(\"y = \", msg.boxes[i].center.y)\n else:\n print(\"No target detected !!!!!\\n\")\n\n print(\"\\n\")\n\nif __name__ == '__main__':\n sub_img = rospy.Subscriber(\"/DetectedImgNode/det2D_result\", Detection2D, callback, queue_size=1)\n rospy.init_node('test_node', anonymous=False)\n rospy.spin()" }, { "alpha_fraction": 0.5892884731292725, "alphanum_fraction": 0.6048967242240906, "avg_line_length": 39.339508056640625, "blob_id": "6eb5c888d6488abd3c7f828408b9692e8a1073fa", "content_id": "6be032aca995fd8a4e4ec7767cf3808306a273e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6535, "license_type": "no_license", "max_line_length": 127, "num_lines": 162, "path": "/src/yolov4/pytorch-master/demo.py", "repo_name": "alvis1029/scanner", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n# -*- coding: utf-8 -*-\n'''\n@Time : 20/04/25 15:49\n@Author : huguanghao\n@File : demo.py\n@Noice :\n@Modificattion :\n @Author :\n @Time :\n @Detail :\n'''\n\n# import sys\n# import time\n# from PIL import Image, ImageDraw\n# from models.tiny_yolo import TinyYoloNet\nfrom tool.utils import *\nfrom tool.torch_utils import *\nfrom tool.darknet2pytorch import Darknet\nimport argparse\nimport os\nimport sys\nimport math\nimport rospy\nfrom sensor_msgs.msg import Image as ROSImage\nfrom detection_msgs.msg import Detection2D, BBox2D\nfrom detection_msgs.srv import Detection2DTrig, Detection2DTrigResponse\nfrom cv_bridge import CvBridge, CvBridgeError\nif '/opt/ros/kinetic/lib/python2.7/dist-packages' in sys.path:\n sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')\nimport cv2\n\n\n\"\"\"hyper parameters\"\"\"\nuse_cuda = True\nbridge = CvBridge()\n# INTEREST_CLASSES = [\"green_milk\", \"black_milk\", \"oolong_milk\"]\nINTEREST_CLASSES = [\"Soda\", \"Coke\", \"PinkSoda\", \"Lemonade\", \"MineralWater\"]\n\nclass DetectedImgNode(object):\n def __init__(self, cfgfile, weightfile):\n self.m = Darknet(cfgfile)\n self.m.print_network()\n self.m.load_weights(weightfile)\n print('Loading weights from %s... Done!' % (weightfile))\n\n if use_cuda:\n self.m.cuda()\n\n self.pub_msg = rospy.Publisher(\"~det2d_result\", Detection2D, queue_size=1)\n self.sub_img = rospy.Subscriber(\"/camera1/color/image_raw\", ROSImage, self.img_callback, queue_size=1)\n self.detection_srv = rospy.Service(\"~yolo_detect\", Detection2DTrig, self.srv_callback)\n\n def srv_callback(self, req):\n try:\n cv_image = bridge.imgmsg_to_cv2(req.image, \"rgb8\")\n except CvBridgeError as e:\n print(e)\n return\n\n num_classes = self.m.num_classes\n if num_classes == 20:\n namesfile = os.path.join(os.path.dirname(__file__), './data/voc.names')\n elif num_classes == 80:\n namesfile = os.path.join(os.path.dirname(__file__), './data/coco.names')\n else:\n namesfile = os.path.join(os.path.dirname(__file__), './data/obj_bottle.names')\n class_names = load_class_names(namesfile)\n\n img_sized = cv2.resize(cv_image, (self.m.width, self.m.height))\n boxes_batch = do_detect(self.m, img_sized, 0.5, 0.2, use_cuda)\n\n detection_msg = Detection2D()\n detection_msg.header.stamp = rospy.Time.now()\n detection_msg.header.frame_id = req.image.header.frame_id\n\n # Batch size != 1\n if len(boxes_batch) != 1:\n print(\"Batch size != 1, cannot handle it\")\n exit(-1)\n boxes = boxes_batch[0]\n\n for index, box in enumerate(boxes):\n bbox_msg = BBox2D()\n bbox_msg.center.x = math.floor(box[0] * req.image.width)\n bbox_msg.center.y = math.floor(box[1] * req.image.height)\n bbox_msg.size_x = math.floor(box[2] * req.image.width)\n bbox_msg.size_y = math.floor(box[3] * req.image.height)\n bbox_msg.id = box[6]\n bbox_msg.score = box[5]\n bbox_msg.class_name = class_names[bbox_msg.id]\n detection_msg.boxes.append(bbox_msg)\n \n result_img = plot_boxes_cv2(cv_image, boxes, savename=None, class_names=class_names, interest_classes=INTEREST_CLASSES)\n # result_img = plot_boxes_cv2(cv_image, boxes, savename=None, class_names=class_names)\n detection_msg.result_image = bridge.cv2_to_imgmsg(result_img, \"rgb8\")\n\n # print('return {} detection results'.format(len(boxes)))\n return Detection2DTrigResponse(result=detection_msg)\n\n def img_callback(self, msg):\n try:\n imgfile = bridge.imgmsg_to_cv2(msg, \"rgb8\")\n except CvBridgeError as e:\n print(e)\n return\n\n num_classes = self.m.num_classes\n if num_classes == 20:\n namesfile = os.path.join(os.path.dirname(__file__), './data/voc.names')\n elif num_classes == 80:\n namesfile = os.path.join(os.path.dirname(__file__), './data/coco.names')\n else:\n namesfile = os.path.join(os.path.dirname(__file__), './data/obj_bottle.names')\n class_names = load_class_names(namesfile)\n\n sized = cv2.resize(imgfile, (self.m.width, self.m.height))\n\n for i in range(2):\n start = time.time()\n boxes = do_detect(self.m, sized, 0.4, 0.3, use_cuda)\n finish = time.time()\n # if i == 1:\n # print('\\nPredicted in %f seconds.\\n' % (finish - start))\n # print('=====================================================')\n\n detection_msg = Detection2D()\n detection_msg.header.stamp = rospy.Time.now()\n detection_msg.header.frame_id = msg.header.frame_id\n\n for index, box in enumerate(boxes[0]):\n bbox_msg = BBox2D()\n bbox_msg.center.x = math.floor(box[0] * msg.width)\n bbox_msg.center.y = math.floor(box[1] * msg.height)\n bbox_msg.size_x = math.floor(box[2] * msg.width)\n bbox_msg.size_y = math.floor(box[3] * msg.height)\n bbox_msg.id = box[6]\n bbox_msg.score = box[5]\n bbox_msg.class_name = class_names[bbox_msg.id]\n detection_msg.boxes.append(bbox_msg)\n\n result_img = plot_boxes_cv2(sized, boxes[0], savename=None, class_names=class_names, interest_classes=INTEREST_CLASSES)\n # result_img = plot_boxes_cv2(imgfile, boxes[0], savename=None, class_names=class_names)\n detection_msg.result_image = bridge.cv2_to_imgmsg(result_img, encoding=\"rgb8\")\n # self.pub_img.publish(bridge.cv2_to_imgmsg(result_img, encoding=\"rgb8\"))\n self.pub_msg.publish(detection_msg)\n\nif __name__ == '__main__':\n #rospy.loginfo(\"Use yolov4 model\")\n\n # weightfile = os.path.join(os.path.dirname(__file__), \"./weights/yolov4-tiny.weights\")\n # cfgfile = os.path.join(os.path.dirname(__file__), \"./cfg/yolov4-tiny.cfg\")\n # weightfile = os.path.join(os.path.dirname(__file__), \"./weights/milktea/yolov4-tiny-obj_6000.weights\")\n # cfgfile = os.path.join(os.path.dirname(__file__), \"./cfg/yolov4-tiny-obj.cfg\")\n weightfile = os.path.join(os.path.dirname(__file__), \"./weights/yolov4-bottle_10000.weights\")\n cfgfile = os.path.join(os.path.dirname(__file__), \"./cfg/yolo-obj.cfg\")\n\n rospy.init_node('DetectedImgNode', anonymous=False) \n node = DetectedImgNode(cfgfile, weightfile)\n rospy.spin()\n" }, { "alpha_fraction": 0.6477272510528564, "alphanum_fraction": 0.75, "avg_line_length": 28.66666603088379, "blob_id": "38eb77d0c42921246798f82bb3d04eae1260ce04", "content_id": "85aff3023e80b988a9e97d80dce4c2aaf758a3a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 88, "license_type": "no_license", "max_line_length": 69, "num_lines": 3, "path": "/Dockerfile/docker_build.sh", "repo_name": "alvis1029/scanner", "src_encoding": "UTF-8", "text": "#!/usr/bin/env sh\n\ndocker build -t alvis1029/mars-docker:cuda10.0 -f Dockerfile-cuda10 ." }, { "alpha_fraction": 0.5982749462127686, "alphanum_fraction": 0.6076842546463013, "avg_line_length": 38.04081726074219, "blob_id": "f962bc0a5eb2f29f95bd90f95f49e50551abb003", "content_id": "54938df60dd59315caae25d635e90c3c42721baa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3826, "license_type": "no_license", "max_line_length": 131, "num_lines": 98, "path": "/src/scanner/src/pointcloud2xyz.cpp", "repo_name": "alvis1029/scanner", "src_encoding": "UTF-8", "text": "#include <iostream>\n\n#include <ros/ros.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <std_msgs/Float32MultiArray.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <std_msgs/Int16MultiArray.h>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/Point.h>\n#include <tf/transform_broadcaster.h>\n#include <detection_msgs/BBox2D.h>\n#include <detection_msgs/Detection2D.h>\n#include <detection_msgs/Det3D.h>\n#include <detection_msgs/Det3DArray.h>\n#include <message_filters/subscriber.h>\n#include <message_filters/time_synchronizer.h>\n\nros::Publisher pub_xyz;\npcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz_out (new pcl::PointCloud<pcl::PointXYZ>);\nsensor_msgs::PointCloud2 save_cloud;\n\nvoid cloud_cb (const sensor_msgs::PointCloud2 cloud_in)\n{\n pcl::fromROSMsg (cloud_in, *cloud_xyz_out);\n save_cloud = cloud_in;\n}\n\nvoid box_cb (const detection_msgs::Detection2D input)\n{\n detection_msgs::Det3DArray position_array;\n detection_msgs::Det3D item_position;\n bool flag = true;\n\n for(int i=0; i<input.boxes.size(); i++)\n {\n int x = input.boxes[i].center.x;\n int y = input.boxes[i].center.y;\n int index = x + y * cloud_xyz_out->width;\n std::cout<<\"x = \"<<x<<std::endl;\n std::cout<<\"y = \"<<y<<std::endl;\n std::cout<<\"cloud_msg_width = \"<<cloud_xyz_out->width<<std::endl;\n std::cout<<\"cloud_msg_height = \"<<cloud_xyz_out->height<<std::endl;\n std::cout<<i<<\" cloud_point_size = \"<<cloud_xyz_out->points.size()<<std::endl;\n std::cout<<\"index = \"<<index<<std::endl;\n \n if(isnan(cloud_xyz_out->points[index].x) && isnan(cloud_xyz_out->points[index].y) && isnan(cloud_xyz_out->points[index].z))\n flag = false;\n else\n {\n float x3Ddepth = cloud_xyz_out->points[index].x;\n float y3Ddepth = cloud_xyz_out->points[index].y;\n float z3Ddepth = cloud_xyz_out->points[index].z;\n item_position.x = z3Ddepth;\n item_position.y = -x3Ddepth;\n item_position.z = -y3Ddepth; \n item_position.class_name = input.boxes[i].class_name;\n item_position.class_id = input.boxes[i].id;\n position_array.dets_list.push_back(item_position);\n position_array.header = input.header;\n position_array.pointcloud = save_cloud;\n\n // tf_broadcaster\n // static tf::TransformBroadcaster br;\n // tf::Transform transform;\n // transform.setOrigin(tf::Vector3(item_position.position.x,item_position.position.y,item_position.position.z));\n // tf::Quaternion q;\n // q.setEuler(0.0,0.0,0.0);\n // br.sendTransform(tf::StampedTransform(transform, ros::Time::now(),\"rs_camera_link\", \"item_link\"));\n }\n }\n\n if(flag)\n pub_xyz.publish(position_array);\n else\n std::cout<<\"No data receive!!!!\"<<std::endl;\n\n for(int i=0; i<position_array.dets_list.size(); i++)\n {\n std::cout<<position_array.dets_list[i].class_name<<std::endl;\n std::cout<<\"x = \"<<position_array.dets_list[i].x<<std::endl; \n std::cout<<\"y = \"<<position_array.dets_list[i].y<<std::endl; \n std::cout<<\"z = \"<<position_array.dets_list[i].z<<std::endl;\n std::cout<<\"=========================================================\"<<std::endl<<std::endl; \n } \n}\n\nint main (int argc, char** argv)\n{\n ros::init (argc, argv, \"pointcloud2xyz\");\n ros::NodeHandle nh;\n ros::Subscriber sub_cloud =nh.subscribe(\"/scan_pointcloud_filtered\", 1, cloud_cb);\n ros::Subscriber sub_box =nh.subscribe(\"/DetectedImgNode/det2D_result\", 1, box_cb);\n pub_xyz = nh.advertise<detection_msgs::Det3DArray> (\"object_detection/item_position\", 1);\n ros::spin ();\n return 0;\n}\n" }, { "alpha_fraction": 0.6651982665061951, "alphanum_fraction": 0.691629946231842, "avg_line_length": 44.400001525878906, "blob_id": "b5fb20ceaf6de47b6283fe0e9323817d840ab839", "content_id": "8fc47398304a6370031ce438c6ca9e1e49629744", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 227, "license_type": "no_license", "max_line_length": 68, "num_lines": 5, "path": "/compile_py36.sh", "repo_name": "alvis1029/scanner", "src_encoding": "UTF-8", "text": "catkin_make -j3 --cmake-args \\\n -DCMAKE_BUILD_TYPE=Release \\\n -DPYTHON_EXECUTABLE=/usr/bin/python3 \\\n -DPYTHON_INCLUDE_DIR=/usr/include/python3.6m \\\n -DPYTHON_LIBRARY=/usr/lib/$(uname -i)-linux-gnu/libpython3.6m.so\n" }, { "alpha_fraction": 0.48750001192092896, "alphanum_fraction": 0.5375000238418579, "avg_line_length": 25.77777862548828, "blob_id": "bee71e4679cade08d8951b1fae0e34364a1d0c64", "content_id": "57cba3916c14385f4d41c50ae8f699ceea9588a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 240, "license_type": "no_license", "max_line_length": 48, "num_lines": 9, "path": "/src/yolov4/pytorch-master/to_train_txt.py", "repo_name": "alvis1029/scanner", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n\nfor i in range(0, 479, 1):\n f1 = open(\"./tea0_addr/\"+str(i)+\".txt\", \"r\")\n lines = f1.readlines()\n f2 = open(\"./data/tea0/cfg/train.txt\", \"a\")\n\n for j in range(len(lines)):\n f2.write(\"%s\" %lines[j])" }, { "alpha_fraction": 0.6799362897872925, "alphanum_fraction": 0.7018312215805054, "avg_line_length": 32.06578826904297, "blob_id": "28436a35c5c02dc688af7ada4eada4c5b4c44b01", "content_id": "414d5ec32232403f0d848496575d9a972eab598d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2512, "license_type": "no_license", "max_line_length": 108, "num_lines": 76, "path": "/src/scanner/src/scan_person_back_node.cpp", "repo_name": "alvis1029/scanner", "src_encoding": "UTF-8", "text": "#include <iostream>\n\n// ROS\n#include <ros/ros.h>\n#include <sensor_msgs/LaserScan.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <laser_geometry/laser_geometry.h>\n\n// PCL\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl_ros/transforms.h>\n#include <pcl/filters/passthrough.h>\n#include <pcl/filters/crop_box.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/filters/radius_outlier_removal.h>\n\nusing namespace std;\n\ntypedef pcl::PointCloud<pcl::PointXYZ> PointCloudXYZ;\ntypedef pcl::PointCloud<pcl::PointXYZ>::Ptr PointCloudXYZPtr;\ntypedef pcl::PointCloud<pcl::PointXYZRGB> PointCloudXYZRGB;\ntypedef pcl::PointCloud<pcl::PointXYZRGB>::Ptr PointCloudXYZRGBPtr;\n\n\nros::Publisher pub_combined_image;\n\nvoid scan_callback(const sensor_msgs::PointCloud2 cloud_msg)\n{\n // ROS PointCloud2 -> PCL Pointcloud\n PointCloudXYZPtr cloud_raw(new PointCloudXYZ);\n pcl::fromROSMsg(cloud_msg, *cloud_raw);\n std::vector<int> indices;\n pcl::removeNaNFromPointCloud(*cloud_raw, *cloud_raw, indices);\n\n pcl::CropBox<pcl::PointXYZ> box_filter_;\n box_filter_.setMax(Eigen::Vector4f(3.0, 5.0, 5.0, 1.0)); //3.0, 1.0, 3.0, 1.0\n box_filter_.setMin(Eigen::Vector4f(-3.0, -1.2, 0.0, 1.0)); //-3.0, -1.2, 0, 1.0\n box_filter_.setKeepOrganized(false);\n box_filter_.setNegative(false);\n box_filter_.setInputCloud(cloud_raw);\n box_filter_.filter(*cloud_raw);\n //cout << cloud_raw->points.size()<< endl;\n\n pcl::VoxelGrid<pcl::PointXYZ> sor;\n PointCloudXYZPtr cloud_filtered(new PointCloudXYZ);\n sor.setInputCloud (cloud_raw);\n sor.setLeafSize (0.05f, 0.05f, 0.05f);\n sor.filter (*cloud_filtered);\n //cout << cloud_filtered->points.size()<< endl;\n\n // Remove outlier\n pcl::RadiusOutlierRemoval<pcl::PointXYZ> outrem;\n PointCloudXYZPtr cloud_out(new PointCloudXYZ);\n outrem.setInputCloud(cloud_filtered);\n outrem.setRadiusSearch(0.2);\n outrem.setMinNeighborsInRadius(30);\n outrem.filter(*(cloud_out));\n\n sensor_msgs::PointCloud2 output;\n pcl::toROSMsg(*cloud_out, output);\n pub_combined_image.publish(output);\n}\n\nint main(int argc, char **argv) \n{\n ros::init(argc, argv, \"scan_person_back_filter_node\");\n ros::NodeHandle nh;\n // ROS related\n pub_combined_image = nh.advertise<sensor_msgs::PointCloud2>(\"/scan_person_back_pointcloud_filtered\", 1);\n ros::Subscriber scan_sub = nh.subscribe(\"/camera2/depth_registered/points\", 1, scan_callback);\n\n ros::spin();\n return 0;\n}" }, { "alpha_fraction": 0.5954737663269043, "alphanum_fraction": 0.6148571968078613, "avg_line_length": 37.11198425292969, "blob_id": "fc8d7ac4238b727e4e5aeda7bff96e12f5850204", "content_id": "01ca7df92fac88509dcd00cbf30862154ebeac95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 19398, "license_type": "no_license", "max_line_length": 138, "num_lines": 509, "path": "/src/scanner/src/person_clustering.cpp", "repo_name": "alvis1029/scanner", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <time.h>\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n\n// ROS\n#include <ros/ros.h>\n#include <sensor_msgs/Image.h>\n#include <sensor_msgs/CameraInfo.h>\n#include <sensor_msgs/image_encodings.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <geometry_msgs/Point.h>\n#include <cv_bridge/cv_bridge.h>\n#include <visualization_msgs/Marker.h>\n#include <visualization_msgs/MarkerArray.h>\n\n// Custom msg & srv\n#include <detection_msgs/Detection2DTrig.h>\n#include <detection_msgs/Det3D.h>\n#include <detection_msgs/Det3DArray.h>\n\n// Message filter\n#include <message_filters/subscriber.h>\n#include <message_filters/synchronizer.h>\n#include <message_filters/sync_policies/approximate_time.h>\n#include <message_filters/time_synchronizer.h>\n\n// Eigen\n#include <Eigen/Dense>\n\n// OpenCV\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\n// TF\n#include <tf/transform_listener.h>\n#include <tf/transform_datatypes.h>\n\n// PCL\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/common/common.h>\n#include <pcl/common/centroid.h> // Centroid\n#include <pcl/kdtree/kdtree.h>\n#include <pcl/segmentation/extract_clusters.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl_conversions/pcl_conversions.h> // ros2pcl\n#include <pcl/filters/radius_outlier_removal.h> // RemoveOutlier\n#include <pcl/filters/statistical_outlier_removal.h>\n#include <pcl_ros/transforms.h>\n#include <pcl/search/impl/search.hpp>\n\nusing namespace std;\nusing namespace cv;\nint count_runtime = 0;\ntypedef message_filters::sync_policies::ApproximateTime<cv_bridge::CvImage, sensor_msgs::PointCloud2> MySyncPolicy;\ntypedef message_filters::Synchronizer<MySyncPolicy> MySynchronizer;\n\ntypedef pcl::PointCloud<pcl::PointXYZ> PointCloudXYZ;\ntypedef pcl::PointCloud<pcl::PointXYZ>::Ptr PointCloudXYZPtr;\ntypedef pcl::PointCloud<pcl::PointXYZRGB> PointCloudXYZRGB;\ntypedef pcl::PointCloud<pcl::PointXYZRGB>::Ptr PointCloudXYZRGBPtr;\n\n// Just for color words display\nstatic const string COLOR_RED = \"\\e[0;31m\";\nstatic const string COLOR_GREEN = \"\\e[0;32m\";\nstatic const string COLOR_YELLOW = \"\\e[0;33m\"; \nstatic const string COLOR_NC = \"\\e[0m\";\n\nstatic const int kNumOfInterestClass = 1;\nstatic const string kInterestClassNames[kNumOfInterestClass] = {\"person\"};\n\n\ntemplate <typename T, typename A>\nint arg_max(std::vector<T, A> const& vec) \n{\n return static_cast<int>(std::distance(vec.begin(), max_element(vec.begin(), vec.end())));\n}\n\ntemplate <typename T, typename A>\nint arg_min(std::vector<T, A> const& vec) \n{\n return static_cast<int>(std::distance(vec.begin(), min_element(vec.begin(), vec.end())));\n}\n\nclass ObjInfo \n{\npublic:\n ObjInfo()\n {\n cloud = PointCloudXYZPtr(new PointCloudXYZ);\n radius = 0.0;\n }\n detection_msgs::BBox2D box;\n PointCloudXYZPtr cloud;\n geometry_msgs::Point location;\n double radius;\n};\n\nclass ScanImageCombineNode \n{\npublic:\n ScanImageCombineNode(ros::NodeHandle nh, ros::NodeHandle pnh);\n void img_scan_cb(const cv_bridge::CvImage::ConstPtr &cv_ptr, const sensor_msgs::PointCloud2ConstPtr &cloud_raw_ptr);\n void separate_outlier_points(PointCloudXYZPtr cloud_in, PointCloudXYZPtr cloud_out);\n bool is_interest_class(string class_name);\n cv::Point2d point_pointcloud2pixel(double x_from_camera, double y_from_camera, double z_from_camera);\n\n // Transformation\n cv::Mat K_;\n cv::Mat D_;\n\n // ROS related\n ros::NodeHandle nh_, pnh_;\n tf::TransformListener tf_listener_;\n ros::Publisher pub_combined_image_;\n ros::Publisher pub_marker_array_;\n ros::Publisher pub_colored_pc_;\n ros::Publisher pub_detection3d_;\n ros::ServiceClient yolov4_detect_; // ROS Service client\n\n // Message filters\n message_filters::Subscriber<sensor_msgs::PointCloud2> scan_sub_;\n message_filters::Subscriber<cv_bridge::CvImage> image_sub_;\n boost::shared_ptr<MySynchronizer> sync_;\n\n // Object list\n std::vector<ObjInfo> obj_list;\n};\n\nScanImageCombineNode::ScanImageCombineNode(ros::NodeHandle nh, ros::NodeHandle pnh): nh_(nh), pnh_(pnh)\n{\n // ROS parameters\n string scan_topic;\n string img_topic;\n string caminfo_topic;\n string yolo_srv_name = \"DetectedPersonImgNode/yolo_detect\";\n ros::param::param<string>(\"~scan_topic\", scan_topic, \"/scan_person_pointcloud_filtered\");\n ros::param::param<string>(\"~img_topic\", img_topic, \"/camera3/color/image_raw\"); \n ros::param::param<string>(\"~caminfo_topic\", caminfo_topic, \"/camera3/color/camera_info\"); \n\n // ROS publisher & subscriber & message filter\n pub_combined_image_ = nh.advertise<sensor_msgs::Image>(\"/scan_person_clustering_node/debug_reprojection\", 1);\n pub_marker_array_ = nh.advertise<visualization_msgs::MarkerArray>(\"/scan_person_clustering_node/obj_marker\", 1);\n pub_colored_pc_ = nh.advertise<sensor_msgs::PointCloud2>(\"/scan_person_clustering_node/colored_pc\", 1);\n pub_detection3d_ = nh.advertise<detection_msgs::Det3DArray>(\"/scan_person_clustering_node/det3d_result\", 1);\n scan_sub_.subscribe(nh_, scan_topic, 1);\n image_sub_.subscribe(nh_, img_topic, 1);\n sync_.reset(new MySynchronizer(MySyncPolicy(10), image_sub_, scan_sub_));\n sync_->registerCallback(boost::bind(&ScanImageCombineNode::img_scan_cb, this, _1, _2));\n \n\n // ROS service client\n ROS_INFO_STREAM(\"Wait for yolo detection service in 30 seconds...\");\n if(!ros::service::waitForService(yolo_srv_name, ros::Duration(30.0))) \n {\n ROS_ERROR(\"Cannot get the detection service: %s. Aborting...\", yolo_srv_name.c_str());\n exit(-1);\n }\n yolov4_detect_ = nh_.serviceClient<detection_msgs::Detection2DTrig>(yolo_srv_name);\n\n // Prepare intrinsic matrix\n boost::shared_ptr<sensor_msgs::CameraInfo const> caminfo_ptr;\n double fx, fy, cx, cy;\n double k1, k2, p1, p2;\n ROS_INFO_STREAM(\"Wait for camera_info message in 10 seconds\");\n caminfo_ptr = ros::topic::waitForMessage<sensor_msgs::CameraInfo>(caminfo_topic, ros::Duration(10.0));\n if(caminfo_ptr != NULL)\n { \n fx = caminfo_ptr->P[0];\n fy = caminfo_ptr->P[5];\n cx = caminfo_ptr->P[2];\n cy = caminfo_ptr->P[6];\n\n k1 = caminfo_ptr->D[0];\n k2 = caminfo_ptr->D[1];\n p1 = caminfo_ptr->D[2];\n p2 = caminfo_ptr->D[3];\n\n }\n else \n {\n ROS_INFO_STREAM(\"No camera_info received, use default values\");\n fx = 612.3729858398438;\n fy = 612.6065063476562;\n cx = 323.61614990234375;\n cy = 238.90309143066406;\n\n k1 = -0.0556167;\n k2 = 0.0649698;\n p1 = -0.000873693;\n p2 = -0.000543307;\n }\n K_ = (Mat_<double>(3, 3) << fx, 0., cx, 0., fy, cy, 0., 0., 1.);\n D_ = (Mat_<double>(5, 1) << k1, k2, p1, p2, 0.0);\n\n cout << COLOR_GREEN << ros::this_node::getName() << \" is ready.\" << COLOR_NC << endl;\n}\n\nvoid ScanImageCombineNode::separate_outlier_points(PointCloudXYZPtr cloud_in, PointCloudXYZPtr cloud_out) \n{\n // Euclidean Cluster Extraction\n pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>);\n tree->setInputCloud(cloud_in);\n std::vector<pcl::PointIndices> cluster_indices;\n pcl::EuclideanClusterExtraction<pcl::PointXYZ> euler_extractor;\n euler_extractor.setClusterTolerance(0.6); //0.3 //0.035\n euler_extractor.setMinClusterSize(1); //1\n euler_extractor.setMaxClusterSize(10000); // need to check the max pointcloud size of each object {person 5000}\n euler_extractor.setSearchMethod(tree);\n euler_extractor.setInputCloud(cloud_in);\n euler_extractor.extract(cluster_indices);\n\n // Find the cloud cluster which is closest to ego\n int idx_proper_cloud = 0;\n std::vector<float> candidates;\n for(int i = 0; i < cluster_indices.size(); i++) \n {\n Eigen::Vector3f centroid;\n centroid << 0, 0, 0;\n for(int j = 0; j < cluster_indices[i].indices.size(); j++) \n {\n centroid[0] += cloud_in->points[cluster_indices[i].indices[j]].x;\n centroid[1] += cloud_in->points[cluster_indices[i].indices[j]].y;\n centroid[2] += cloud_in->points[cluster_indices[i].indices[j]].z;\n }\n centroid /= cluster_indices[i].indices.size();\n candidates.push_back(centroid.norm());\n }\n \n idx_proper_cloud = arg_min(candidates);\n \n pcl::PointIndices::Ptr inliers_ptr(new pcl::PointIndices(cluster_indices[idx_proper_cloud]));\n PointCloudXYZPtr cloud_extracted(new PointCloudXYZ);\n pcl::ExtractIndices<pcl::PointXYZ> extractor;\n extractor.setInputCloud(cloud_in);\n extractor.setIndices(inliers_ptr);\n extractor.setNegative(false);\n extractor.filter(*cloud_extracted);\n\n // Remove outlier\n pcl::RadiusOutlierRemoval<pcl::PointXYZ> outrem;\n outrem.setInputCloud(cloud_extracted);\n outrem.setRadiusSearch(0.55); //0.2 0.035\n outrem.setMinNeighborsInRadius(2); //2\n outrem.filter(*(cloud_out));\n\n pcl::copyPointCloud(*cloud_in, *cloud_out); \n}\n\nbool ScanImageCombineNode::is_interest_class(string class_name)\n{\n for(int i = 0; i < kNumOfInterestClass; i++) \n {\n if(strcmp(class_name.c_str(), kInterestClassNames[i].c_str()) == 0)\n return true;\n }\n return false;\n}\n\ncv::Point2d ScanImageCombineNode::point_pointcloud2pixel(double x_from_camera, double y_from_camera, double z_from_camera) \n{\n // Transform to camera frame\n tf::Vector3 pt_camframe(x_from_camera, y_from_camera, z_from_camera); \n\n if(pt_camframe.getZ() <= 0.0) // points behind ego\n return cv::Point2d(-1, -1);\n \n // Normalization: z --> 1\n pt_camframe.setX(pt_camframe.getX() / pt_camframe.getZ());\n pt_camframe.setY(pt_camframe.getY() / pt_camframe.getZ());\n pt_camframe.setZ(1.0);\n\n // Trasform to pixel frame\n cv::Mat uv = K_ * (cv::Mat_<double>(3, 1) << pt_camframe.getX(), pt_camframe.getY(), pt_camframe.getZ());\n cv::Point2d pt_pixelframe(uv.at<double>(0, 0), uv.at<double>(1, 0));\n\n return pt_pixelframe;\n}\n\nvoid ScanImageCombineNode::img_scan_cb(const cv_bridge::CvImage::ConstPtr &cv_ptr, const sensor_msgs::PointCloud2ConstPtr &cloud_raw_ptr)\n{\n // Object list init\n obj_list.clear();\n visualization_msgs::MarkerArray marker_array;\n // 2D bounding box detection service\n detection_msgs::Detection2DTrig srv;\n srv.request.image = *(cv_ptr->toImageMsg());\n if(!yolov4_detect_.call(srv))\n {\n ROS_ERROR(\"Failed to call service\");\n return;\n }\n\n // Collect all interest classes to obj_list\n std::vector<detection_msgs::BBox2D> boxes = srv.response.result.boxes;\n\n for(int i = 0; i < boxes.size(); i++) \n {\n if(is_interest_class(boxes[i].class_name)) \n {\n ObjInfo obj_info;\n obj_info.box = boxes[i];\n // Skip the boxes which are too closed\n bool flag_too_closed = false;\n\n obj_list.push_back(obj_info);\n \n }\n }\n\n // Reconstruct undistorted cvimage from detection result image\n cv::Mat cvimage;\n cv_bridge::CvImagePtr detected_cv_ptr = cv_bridge::toCvCopy(srv.response.result.result_image);\n cv::undistort(detected_cv_ptr->image, cvimage, K_, D_);\n\n // Convert pointcloud: ROS PointCloud2 --> PCL PointCloudXYZ\n PointCloudXYZPtr cloud_msg(new PointCloudXYZ); \n pcl::fromROSMsg(*cloud_raw_ptr, *cloud_msg);\n\n // Color pointcloud to visaulize detected points\n PointCloudXYZRGBPtr cloud_colored(new PointCloudXYZRGB);\n // Convert laserscan points to pixel points\n std::vector<cv::Point2d> pts_uv;\n // cout<<\"cloud_msg->points.size = \"<<cloud_msg->points.size()<<endl;\n \n for (int i = 0; i < cloud_msg->points.size(); i++) \n {\n cv::Point2d pt_uv = point_pointcloud2pixel(cloud_msg->points[i].x, cloud_msg->points[i].y, cloud_msg->points[i].z); \n if(pt_uv.x == -1 && pt_uv.y == -1)\n continue;\n pts_uv.push_back(pt_uv);\n // Connect relationship between valid laserscan points to interest classes\n for(int j = 0; j < obj_list.size(); j++) \n {\n float diff_x = fabs((float)(pt_uv.x - obj_list[j].box.center.x));\n float diff_y = fabs((float)(pt_uv.y - obj_list[j].box.center.y));\n if(diff_x < obj_list[j].box.size_x / 4 && diff_y < obj_list[j].box.size_y / 4)\n obj_list[j].cloud->points.push_back(cloud_msg->points[i]); \n // Note that the pointcloud would be registered repeatly, so need to filter it later.\n } \n }\n // cout<<\"Point cloud size\"<<obj_list[0].cloud->points.size()<<endl;\n // Custom message\n detection_msgs::Det3DArray detection_array;\n\n // Remove outlier for each object cloud\n for(int i = 0; i < obj_list.size(); i++) \n {\n if(obj_list[i].cloud->points.size() > 1)\n {\n cout<<\"Object \"<<i<<\"'s pc size is: \"<<obj_list[i].cloud->points.size()<<endl;\n // Clustering and outlier removing\n \n separate_outlier_points(obj_list[i].cloud, obj_list[i].cloud);\n if(obj_list[i].cloud->points.size() < 1)\n continue;\n \n // Merge raw detected points with color to visualization\n if(pub_colored_pc_.getNumSubscribers() > 0) \n {\n int color_r = (rand() % 5) * 60;\n int color_g = (rand() % 5) * 60;\n int color_b = (rand() % 5) * 60;\n PointCloudXYZRGBPtr tmp_cloud(new PointCloudXYZRGB);\n pcl::copyPointCloud(*(obj_list[i].cloud), *tmp_cloud);\n for(auto& point: *tmp_cloud) \n {\n point.r = color_r;\n point.g = color_g;\n point.b = color_b;\n }\n *cloud_colored += *tmp_cloud;\n }\n\n // Find the center of each object\n pcl::PointXYZ min_point, max_point;\n Eigen::Vector3f center(0, 0, 0);\n int count;\n\n for(count=0; count<obj_list[i].cloud->points.size(); count++)\n {\n center[0] += obj_list[i].cloud->points[count].x;\n center[1] += obj_list[i].cloud->points[count].y;\n center[2] += obj_list[i].cloud->points[count].z;\n }\n center[0] /= count;\n center[1] /= count;\n center[2] /= count;\n\n // pcl::getMinMax3D(*(obj_list[i].cloud), min_point, max_point);\n // center = (min_point.getVector3fMap() + max_point.getVector3fMap()) / 2.0;\n obj_list[i].location.x = center[0];\n obj_list[i].location.y = center[1];\n obj_list[i].location.z = center[2];\n double tmp_r1 = sqrt(pow(max_point.x - center[0], 2) + pow(max_point.y - center[1], 2));\n double tmp_r2 = sqrt(pow(min_point.x - center[0], 2) + pow(min_point.y - center[1], 2));\n obj_list[i].radius = std::max(tmp_r1, tmp_r2);\n\n\n // Pack the custom ros package\n detection_msgs::Det3D det_msg;\n det_msg.x = obj_list[i].location.z;\n det_msg.y = -obj_list[i].location.x;\n det_msg.z = -obj_list[i].location.y;\n det_msg.yaw = 0;\n det_msg.radius = obj_list[i].radius;\n det_msg.confidence = obj_list[i].box.score;\n det_msg.class_name = obj_list[i].box.class_name;\n det_msg.class_id = obj_list[i].box.id;\n detection_array.dets_list.push_back(det_msg);\n \n // Visualization\n visualization_msgs::Marker marker;\n marker.header.frame_id = cloud_raw_ptr->header.frame_id;\n marker.header.stamp = ros::Time();\n marker.ns = \"detection_result\";\n marker.id = i;\n marker.type = visualization_msgs::Marker::CUBE;\n marker.lifetime = ros::Duration(0.2);\n // marker.lifetime = ros::Duration(10.0);\n marker.action = visualization_msgs::Marker::ADD;\n marker.pose.position.x = obj_list[i].location.x;\n marker.pose.position.y = obj_list[i].location.y;\n marker.pose.position.z = obj_list[i].location.z;\n marker.pose.orientation.x = 0.0;\n marker.pose.orientation.y = 0.0;\n marker.pose.orientation.z = 0.0;\n marker.pose.orientation.w = 1.0;\n double distance =sqrt(obj_list[i].location.x*obj_list[i].location.x+obj_list[i].location.z*obj_list[i].location.z);\n \n // cout<< \"d:\" << distance << endl;\n // cout<< \"x:\" << obj_list[i].location.x << endl;\n // cout<< \"z:\" << obj_list[i].location.z << endl;\n // marker.scale.x = marker.scale.y = obj_list[i].radius * 2;\n marker.scale.x = 0.4;\n marker.scale.y = 1.2;\n marker.scale.z = 0.4;\n marker.color.a = 1.0;\n marker.color.g = 1.0;\n marker_array.markers.push_back(marker);\n }\n // TODO: deal with the objects which has no matched points\n }\n\n // Publish visualization topics\n if(pub_marker_array_.getNumSubscribers() > 0)\n if(count_runtime < 50)\n pub_marker_array_.publish(marker_array);\n if(pub_colored_pc_.getNumSubscribers() > 0) \n {\n sensor_msgs::PointCloud2 colored_cloud_msg;\n pcl::toROSMsg(*cloud_colored, colored_cloud_msg);\n colored_cloud_msg.header.frame_id = \"camera3_color_optical_frame\";\n // colored_cloud_msg.header.frame_id = \"base_link\";\n if(count_runtime < 50)\n pub_colored_pc_.publish(colored_cloud_msg);\n }\n if(pub_combined_image_.getNumSubscribers() > 0)\n {\n // Draw points in images\n for (int j = 0; j < pts_uv.size(); ++j)\n cv::circle(cvimage, pts_uv[j], 1, Scalar(0, 255, 0), 1);\n cv_bridge::CvImage result_image(cv_ptr->header, \"rgb8\", cvimage);\n if(count_runtime < 50)\n pub_combined_image_.publish(result_image.toImageMsg());\n }\n\n // Publish detection result\n if(pub_detection3d_.getNumSubscribers() > 0) \n {\n detection_array.header.frame_id = cloud_raw_ptr->header.frame_id;\n detection_array.header.stamp = ros::Time::now();\n detection_array.pointcloud = *cloud_raw_ptr;\n if(count_runtime < 50)\n pub_detection3d_.publish(detection_array);\n }\n\n for(int k=0; k<detection_array.dets_list.size(); k++)\n {\n cout<<detection_array.dets_list[k].class_name<<endl;\n cout<<\"It's x is : \"<<detection_array.dets_list[k].x<<endl;\n cout<<\"It's y is : \"<<detection_array.dets_list[k].y<<endl;\n cout<<\"It's depth is : \"<<detection_array.dets_list[k].z<<endl<<endl;\n }\n // cout<<\"Size : \"<<count_runtime<<endl;\n // count_runtime++ ;\n // Show object infomation\n // if(obj_list.size() > 0)\n // {\n // cout << \"Prediction result:\" << endl;\n // for(int i = 0; i < obj_list.size(); i++) \n // cout << obj_list[i].box.class_name << \", cloud size: \" << obj_list[i].cloud->points.size() << endl; \n // cout << \"\\n===================\" << endl;\n // }\n}\n\n\nint main(int argc, char **argv) \n{\n ros::init(argc, argv, \"scan_person_clustering_node\");\n ros::NodeHandle nh, pnh(\"~\");\n ScanImageCombineNode node(nh, pnh);\n ros::spin();\n return 0;\n}" } ]
9