diff --git "a/070.jsonl" "b/070.jsonl" new file mode 100644--- /dev/null +++ "b/070.jsonl" @@ -0,0 +1,457 @@ +{"seq_id": "24901137481", "text": "\"\"\"Helpers for slackchannel2pdf.\"\"\"\n\nimport html\nimport json\nimport logging\nfrom pathlib import Path\n\nlogger = logging.getLogger(__name__)\n\n\ndef transform_encoding(text: str) -> str:\n \"\"\"adjust encoding to latin-1 and transform HTML entities\"\"\"\n text2 = html.unescape(text)\n text2 = text2.encode(\"utf-8\", \"replace\").decode(\"utf-8\")\n text2 = text2.replace(\"\\t\", \" \")\n return text2\n\n\ndef read_array_from_json_file(filepath: Path, quiet=False) -> list:\n \"\"\"reads a json file and returns its contents as array\"\"\"\n my_file = filepath.parent / (filepath.name + \".json\")\n if not my_file.is_file:\n if quiet is False:\n logger.warning(\"file does not exist: %s\", filepath)\n arr = []\n else:\n try:\n with my_file.open(\"r\", encoding=\"utf-8\") as file:\n arr = json.load(file)\n except IOError:\n if quiet is False:\n logger.warning(\"failed to read from %s: \", my_file, exc_info=True)\n arr = []\n\n return arr\n\n\ndef write_array_to_json_file(arr, filepath: Path) -> None:\n \"\"\"writes array to a json file\"\"\"\n my_file = filepath.parent / (filepath.name + \".json\")\n logger.info(\"Writing file: %s\", filepath)\n try:\n with my_file.open(\"w\", encoding=\"utf-8\") as file:\n json.dump(arr, file, sort_keys=True, indent=4, ensure_ascii=False)\n except IOError:\n logger.error(\"failed to write to %s\", my_file, exc_info=True)\n", "repo_name": "ErikKalkoken/slackchannel2pdf", "sub_path": "slackchannel2pdf/helpers.py", "file_name": "helpers.py", "file_ext": "py", "file_size_in_byte": 1461, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 78, "dataset": "github-code", "pt": "48", "api": [{"api_name": "logging.getLogger", "line_number": 8, "usage_type": "call"}, {"api_name": "html.unescape", "line_number": 13, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 19, "usage_type": "name"}, {"api_name": "json.load", "line_number": 29, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 38, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 44, "usage_type": "call"}]} +{"seq_id": "12839626650", "text": "from django.urls import path\n\nfrom . import views\nfrom .views import SubjectListView, NewSubjectView, TeacherListView, NewTeacherView\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('subject', SubjectListView.as_view(), name='subject-list'),\n path('subject/new', NewSubjectView.as_view(), name='subject-new'),\n path('teacher', TeacherListView.as_view(), name='teacher-list'),\n path('teacher//detail', views.teacher_detail, name='teacher'),\n path('teacher/new', NewTeacherView.as_view(), name='teacher-new'), \n path('group', views.group, name='group-list'),\n path('group//detail', views.group_detail, name='group'), \n path('student', views.student_detail, name='student'),\n]", "repo_name": "RomanArtemenko/lesson11", "sub_path": "class_app/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 743, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "views.index", "line_number": 7, "usage_type": "attribute"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "views.SubjectListView.as_view", "line_number": 8, "usage_type": "call"}, {"api_name": "views.SubjectListView", "line_number": 8, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "views.NewSubjectView.as_view", "line_number": 9, "usage_type": "call"}, {"api_name": "views.NewSubjectView", "line_number": 9, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "views.TeacherListView.as_view", "line_number": 10, "usage_type": "call"}, {"api_name": "views.TeacherListView", "line_number": 10, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "views.teacher_detail", "line_number": 11, "usage_type": "attribute"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "views.NewTeacherView.as_view", "line_number": 12, "usage_type": "call"}, {"api_name": "views.NewTeacherView", "line_number": 12, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 13, "usage_type": "call"}, {"api_name": "views.group", "line_number": 13, "usage_type": "attribute"}, {"api_name": "django.urls.path", "line_number": 14, "usage_type": "call"}, {"api_name": "views.group_detail", "line_number": 14, "usage_type": "attribute"}, {"api_name": "django.urls.path", "line_number": 15, "usage_type": "call"}, {"api_name": "views.student_detail", "line_number": 15, "usage_type": "attribute"}]} +{"seq_id": "29580613001", "text": "# -*- coding:utf-8 -*-\nfrom flask_wtf import Form\nfrom wtforms import StringField, IntegerField, BooleanField, FileField, DecimalField, DateTimeField, SelectField, TextField,validators\nfrom wtforms.validators import DataRequired, regexp\nfrom app.models.Account import Account\n\n\nclass AccountForm(Form):\n \"\"\"帐目信息\n \n 其他和发票有关的表单都放在这个文件中\n 注意,新版本的 WTForm 用 StringField 替代了 TextField,其他变化和 API 请查阅文档\n \"\"\"\n# bill_id = IntegerField(u'账单编号')\n funder = StringField(u'出资人')\n transaction_money = DecimalField(u'交易金额')\n currency = SelectField(u'币种', choices=Account.get_currencies())\n enter_money = DecimalField(u'入账金额')\n enter_date = DateTimeField(u'记账日', format='%Y-%m-%d')\n card_no = StringField(u'卡号后四位', [validators.length(max=4)])\n trade_abstract = StringField(u'交易摘要')\n transaction_place = StringField(u'交易地点')\n is_submit = BooleanField(u'是否需要报销')\n# status_index = SelectField(u'发票抵冲账单的记录', coerce=int, choices=Account.get_status())\n \n", "repo_name": "tobarisystem/tobari", "sub_path": "app/forms/account.py", "file_name": "account.py", "file_ext": "py", "file_size_in_byte": 1166, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "flask_wtf.Form", "line_number": 8, "usage_type": "name"}, {"api_name": "wtforms.StringField", "line_number": 15, "usage_type": "call"}, {"api_name": "wtforms.DecimalField", "line_number": 16, "usage_type": "call"}, {"api_name": "wtforms.SelectField", "line_number": 17, "usage_type": "call"}, {"api_name": "app.models.Account.Account.get_currencies", "line_number": 17, "usage_type": "call"}, {"api_name": "app.models.Account.Account", "line_number": 17, "usage_type": "name"}, {"api_name": "wtforms.DecimalField", "line_number": 18, "usage_type": "call"}, {"api_name": "wtforms.DateTimeField", "line_number": 19, "usage_type": "call"}, {"api_name": "wtforms.StringField", "line_number": 20, "usage_type": "call"}, {"api_name": "wtforms.validators.length", "line_number": 20, "usage_type": "call"}, {"api_name": "wtforms.validators", "line_number": 20, "usage_type": "name"}, {"api_name": "wtforms.StringField", "line_number": 21, "usage_type": "call"}, {"api_name": "wtforms.StringField", "line_number": 22, "usage_type": "call"}, {"api_name": "wtforms.BooleanField", "line_number": 23, "usage_type": "call"}]} +{"seq_id": "8016072043", "text": "import json\n\nfrom utils.sqs import get_queue\n\n\ndef make_message_body(\n first_name,\n last_name,\n email,\n username,\n):\n return json.dumps(\n {\n \"first_name\": first_name,\n \"last_name\": last_name,\n \"email\": email,\n \"username\": username,\n }\n )\n\n\ndef main():\n print(\"Sign in\")\n\n first_name = input(\"First name: \") or \"Felipe\"\n last_name = input(\"Last name: \") or \"Conceicao\"\n email = input(\"Email: \") or \"felipe.conceicao@contaazul.com\"\n username = input(\"Username: \") or \"felipe.conceicao\"\n\n queue = get_queue(\"poc-practices\")\n queue.send_message(\n MessageBody=make_message_body(first_name, last_name, email, username)\n )\n\n\nif __name__ == \"__main__\":\n main()\n", "repo_name": "felipeflamarion/sqs-practices", "sub_path": "dispatcher.py", "file_name": "dispatcher.py", "file_ext": "py", "file_size_in_byte": 763, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "json.dumps", "line_number": 12, "usage_type": "call"}, {"api_name": "utils.sqs.get_queue", "line_number": 30, "usage_type": "call"}]} +{"seq_id": "41305615526", "text": "from django.urls import include, re_path,path\nfrom sindhudurga import views\n\nurlpatterns = [\n re_path(r'^$', views.HomePageView.as_view(), name='home'), # Notice the URL has been named\n re_path(r'^about/$', views.AboutPageView.as_view(), name='about'),\n re_path(r'^data/$', views.DataPageView.as_view(), name='data'),\n re_path(r'^contactus/$', views.ContactUsPageView.as_view(), name='contactus'),\n path('staticstring', views.PlainText,name='staticstring'),\n path('form', views.FormView,name='form'),\n path('myclass_list', views.SelectMyClass,name='list'),\n]", "repo_name": "gitsangramdesai/django001", "sub_path": "mahafort/sindhudurga/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 579, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "django.urls.re_path", "line_number": 5, "usage_type": "call"}, {"api_name": "sindhudurga.views.HomePageView.as_view", "line_number": 5, "usage_type": "call"}, {"api_name": "sindhudurga.views.HomePageView", "line_number": 5, "usage_type": "attribute"}, {"api_name": "sindhudurga.views", "line_number": 5, "usage_type": "name"}, {"api_name": "django.urls.re_path", "line_number": 6, "usage_type": "call"}, {"api_name": "sindhudurga.views.AboutPageView.as_view", "line_number": 6, "usage_type": "call"}, {"api_name": "sindhudurga.views.AboutPageView", "line_number": 6, "usage_type": "attribute"}, {"api_name": "sindhudurga.views", "line_number": 6, "usage_type": "name"}, {"api_name": "django.urls.re_path", "line_number": 7, "usage_type": "call"}, {"api_name": "sindhudurga.views.DataPageView.as_view", "line_number": 7, "usage_type": "call"}, {"api_name": "sindhudurga.views.DataPageView", "line_number": 7, "usage_type": "attribute"}, {"api_name": "sindhudurga.views", "line_number": 7, "usage_type": "name"}, {"api_name": "django.urls.re_path", "line_number": 8, "usage_type": "call"}, {"api_name": "sindhudurga.views.ContactUsPageView.as_view", "line_number": 8, "usage_type": "call"}, {"api_name": "sindhudurga.views.ContactUsPageView", "line_number": 8, "usage_type": "attribute"}, {"api_name": "sindhudurga.views", "line_number": 8, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "sindhudurga.views.PlainText", "line_number": 9, "usage_type": "attribute"}, {"api_name": "sindhudurga.views", "line_number": 9, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "sindhudurga.views.FormView", "line_number": 10, "usage_type": "attribute"}, {"api_name": "sindhudurga.views", "line_number": 10, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "sindhudurga.views.SelectMyClass", "line_number": 11, "usage_type": "attribute"}, {"api_name": "sindhudurga.views", "line_number": 11, "usage_type": "name"}]} +{"seq_id": "30985121326", "text": "import cv2 as cv\r\nimport numpy as np \r\nimport pyautogui\r\npyautogui.FAILSAFE = False\r\n\r\ncap = cv.VideoCapture(0) \r\nwhile(1): \r\n \r\n _, frame = cap.read() \r\n \r\n hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV) \r\n lower_green = np.array([19,109,57]) \r\n upper_green = np.array([255,255,255]) \r\n #parametro para cor verde detectada\r\n \r\n mask = cv.inRange(hsv, lower_green, upper_green) \r\n res = cv.bitwise_and(frame,frame, mask= mask) \r\n gray = cv.cvtColor(res, cv.COLOR_BGR2GRAY)\r\n _, borda = cv.threshold(gray, 3, 255, cv.THRESH_BINARY)\r\n \r\n \r\n contornos, _ = cv.findContours(\r\n borda, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)\r\n\r\n for contorno in contornos:\r\n \r\n area = cv.contourArea(contorno)\r\n \r\n if area > 800:\r\n (x, y, w, h) = cv.boundingRect(contorno)\r\n #cv.drawContours(frame, contorno, -1, (255,0,0), 2)\r\n cv.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 1)\r\n cv.putText(\r\n frame,\r\n str(f\"x: {x} y: {y}\"),\r\n (x, y-20),\r\n cv.FONT_HERSHEY_SIMPLEX,\r\n 1, 1\r\n )\r\n pyautogui.moveTo(100, 100, 2, pyautogui.easeOutQuad)\r\n print(\"cor verde\")\r\n #movimetação do mouse quando encontra a cor verde\r\n else:\r\n print(\"cor diferente\")\r\n #pyautogui.drag(30, 0, 2, button='right') \r\n pyautogui.click(1000,0,2,button='right')\r\n #movimentação do mouse botão direito quando encontra uma cor diferente\r\n break\r\n\r\n\r\n\r\n #cv.imshow(\"result mask\", borda)\r\n \r\n \r\n \r\n \r\n k = cv.waitKey(5) & 0xFF\r\n if k == 27: \r\n break\r\n\r\n cv.imshow('frame',frame) \r\n cv.imshow('mask',mask) \r\n cv.imshow('res',res) \r\n\r\n\r\ncv.destroyAllWindows() \r\ncap.release() \r\n\r\n\r\n", "repo_name": "thayafalk/Capture_computacaografica_Python", "sub_path": "web.py", "file_name": "web.py", "file_ext": "py", "file_size_in_byte": 1865, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "pyautogui.FAILSAFE", "line_number": 4, "usage_type": "attribute"}, {"api_name": "cv2.VideoCapture", "line_number": 6, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 11, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2HSV", "line_number": 11, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 13, "usage_type": "call"}, {"api_name": "cv2.inRange", "line_number": 16, "usage_type": "call"}, {"api_name": "cv2.bitwise_and", "line_number": 17, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 18, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 18, "usage_type": "attribute"}, {"api_name": "cv2.threshold", "line_number": 19, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 19, "usage_type": "attribute"}, {"api_name": "cv2.findContours", "line_number": 22, "usage_type": "call"}, {"api_name": "cv2.RETR_LIST", "line_number": 23, "usage_type": "attribute"}, {"api_name": "cv2.CHAIN_APPROX_SIMPLE", "line_number": 23, "usage_type": "attribute"}, {"api_name": "cv2.contourArea", "line_number": 27, "usage_type": "call"}, {"api_name": "cv2.boundingRect", "line_number": 30, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 32, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 37, "usage_type": "attribute"}, {"api_name": "pyautogui.moveTo", "line_number": 40, "usage_type": "call"}, {"api_name": "pyautogui.easeOutQuad", "line_number": 40, "usage_type": "attribute"}, {"api_name": "pyautogui.click", "line_number": 46, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 57, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 61, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 62, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 63, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 66, "usage_type": "call"}]} +{"seq_id": "1961484539", "text": "import datetime\n\nfrom django.contrib.auth import get_user_model\nfrom django.db import models\n\nfrom petstagram.accounts.models import PetstagramUser\n\nUserModel = get_user_model()\n\n\nclass Pet(models.Model):\n NAME_MAX_LENGTH = 30\n\n CAT = 'Cat'\n DOG = 'Dog'\n BUNNY = 'Bunny'\n PARROT = 'Parrot'\n FISH = 'Fish'\n OTHER = 'Other'\n\n ANIMAL_TYPES = (\n CAT,\n DOG,\n BUNNY,\n PARROT,\n FISH,\n OTHER,\n )\n\n name = models.CharField(\n max_length=NAME_MAX_LENGTH,\n )\n\n type = models.CharField(\n max_length=max(len(t) for t in ANIMAL_TYPES),\n choices=((t, t) for t in ANIMAL_TYPES),\n )\n\n date_of_birth = models.DateField(\n null=True,\n blank=True,\n )\n\n user = models.ForeignKey(\n UserModel,\n on_delete=models.CASCADE,\n )\n\n @property\n def age(self):\n return datetime.datetime.now().year - self.date_of_birth.year\n\n def __str__(self):\n return f\"{self.name} the {self.type}\"\n\n class Meta:\n unique_together = ('user', 'name')\n\n\nclass PetPhoto(models.Model):\n photo = models.ImageField(\n validators=(\n\n ),\n )\n\n description = models.TextField(\n null=True,\n blank=True,\n )\n\n publication_date = models.DateTimeField(\n auto_now_add=True,\n )\n\n likes = models.IntegerField(\n default=0,\n )\n\n tagged_pets = models.ManyToManyField(\n Pet,\n )\n\n user = models.ForeignKey(\n UserModel,\n on_delete=models.CASCADE,\n )\n", "repo_name": "vesselindoychev/Python-Web-Basics", "sub_path": "WorkShop/petstagram/petstagram/main/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 1549, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "django.contrib.auth.get_user_model", "line_number": 8, "usage_type": "call"}, {"api_name": "django.db.models.Model", "line_number": 11, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 11, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 30, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 30, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 34, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 34, "usage_type": "name"}, {"api_name": "django.db.models.DateField", "line_number": 39, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 39, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 44, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 44, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 46, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 46, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 51, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 51, "usage_type": "attribute"}, {"api_name": "django.db.models.Model", "line_number": 60, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 60, "usage_type": "name"}, {"api_name": "django.db.models.ImageField", "line_number": 61, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 61, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 67, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 67, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 72, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 72, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 76, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 76, "usage_type": "name"}, {"api_name": "django.db.models.ManyToManyField", "line_number": 80, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 80, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 84, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 84, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 86, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 86, "usage_type": "name"}]} +{"seq_id": "42100257812", "text": "import sys\ntry:\n import numpy as np\nexcept ImportError:\n print(\"This version REQUIRES numpy\")\n sys.exit(1)\n#\n# The \"Vitale\" property: The first two digits are divisible by 2, the\n# first 3 digits are divisible by 4 and so on. \n#\n# Numpy version: If numpy has 128bit uInts (or Ints) then this would\n# work, with 64 bit ints, it starts failing in the teens\n#\n# http://www.blog.republicofmath.com/the-number-3608528850368400786036725/\n#\n# Start with the even two digit numbers less than 100\n#\n\ntry:\n vitale_dtype = np.int128\nexcept AttributeError:\n vitale_dtype = np.int64\n pass\n\ndef vitaleproperty(n):\n if n == 2:\n return np.arange(10, 99, 2, dtype=vitale_dtype)\n else:\n res = vitaleproperty(n - 1)\n res = 10 * res[:, np.newaxis] + np.arange(10)\n assert np.all(res > 0)\n return res[np.where(res % n == 0)]\n\nif __name__ == \"__main__\":\n n = 2\n nvnums = []\n while True:\n try:\n vitale_n = vitaleproperty(n)\n except AssertionError:\n print(\"Overflow likely for n=%d, INCOMPLETE!!!\" % n)\n break\n pass\n if (vitale_n.size != 0):\n nvnums.append(len(vitale_n))\n n = n + 1\n else:\n break\n\n try:\n import matplotlib.pyplot as plt\n plt.plot(nvnums, 'ro', markersize=5)\n plt.ylim([0, max(nvnums) * 1.1])\n plt.xlim([0, n+3])\n plt.show()\n except ImportError:\n print(nvnums)\n\n", "repo_name": "ianabc/vitale", "sub_path": "vitale-numpy.py", "file_name": "vitale-numpy.py", "file_ext": "py", "file_size_in_byte": 1476, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "sys.exit", "line_number": 6, "usage_type": "call"}, {"api_name": "numpy.int128", "line_number": 20, "usage_type": "attribute"}, {"api_name": "numpy.int64", "line_number": 22, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 30, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 53, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 53, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}]} +{"seq_id": "42139168579", "text": "from skimage import io\nimport daisy\nimport glob\nimport numpy as np\nimport os\nimport sys\n\nvoxel_size = daisy.Coordinate((60, 56, 56))\n# raw_dir = '/nrs/funke/sheridana/zebrafish_nuclei/130201zf142_XY_56.4x56.4x60.0/'\n# out_file = '/nrs/funke/sheridana/zebrafish_nuclei/130201zf142.zarr'\n\nraw_dir = sys.argv[1]\nout_file = '/nrs/funke/sheridana/zebrafish_nuclei/gt_data.zarr'\n\ndef get_total_roi(image_dir):\n\n files = []\n\n for f in os.listdir(image_dir):\n\n print('Appending %s to list' %f)\n\n files.append(os.path.join(image_dir, f))\n\n section_numbers = sorted([ int(f.split('/')[-1][0:5]) for f in files ])\n\n begin = min(section_numbers)\n end = max(section_numbers) + 1\n\n shape_yx = np.array(io.imread(files[0])).shape\n\n roi = daisy.Roi(\n (0, 0, 0),\n voxel_size*(end - begin, shape_yx[0], shape_yx[1]))\n\n print(\"Total ROI: %s\" % roi)\n\n return roi, begin\n\ndef fill_section(ds, image_dir, block, image_index_offset=0):\n\n # 0-based image index\n image_index = block.read_roi.get_offset()[0]/ds.voxel_size[0]\n image_index += image_index_offset\n\n image_file = os.path.join(\n image_dir,\n \"%05d.png\" % image_index)\n\n print(\"Copying section %d...\" % image_index)\n\n try:\n ds[block.write_roi] = np.array(io.imread(image_file))[np.newaxis,:]\n except IOError:\n print(\"Skipping section %d, image file does not exist.\" % image_index)\n pass\n\nif __name__ == \"__main__\":\n\n total_roi, image_index_offset = get_total_roi(raw_dir)\n\n raw_ds = daisy.prepare_ds(\n out_file,\n 'volumes/%s/labels/neuron_ids'%sys.argv[2],\n total_roi=total_roi,\n voxel_size=voxel_size,\n write_size=voxel_size*(1, 256, 256),\n dtype=np.uint64)\n\n section_roi = daisy.Roi(\n (0, 0, 0),\n (voxel_size[0],) + total_roi.get_shape()[1:])\n\n print(\"Copying in chunks of %s\" % section_roi)\n\n daisy.run_blockwise(\n total_roi=total_roi,\n read_roi=section_roi,\n write_roi=section_roi,\n process_function=lambda b: fill_section(\n raw_ds,\n raw_dir,\n b,\n image_index_offset),\n num_workers=40)\n", "repo_name": "funkelab/lsd_experiments", "sub_path": "scripts/data_consolidation/convert_zfish_gt.py", "file_name": "convert_zfish_gt.py", "file_ext": "py", "file_size_in_byte": 2185, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "48", "api": [{"api_name": "daisy.Coordinate", "line_number": 8, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 12, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 30, "usage_type": "call"}, {"api_name": "skimage.io.imread", "line_number": 30, "usage_type": "call"}, {"api_name": "skimage.io", "line_number": 30, "usage_type": "name"}, {"api_name": "daisy.Roi", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path", "line_number": 46, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 53, "usage_type": "call"}, {"api_name": "skimage.io.imread", "line_number": 53, "usage_type": "call"}, {"api_name": "skimage.io", "line_number": 53, "usage_type": "name"}, {"api_name": "numpy.newaxis", "line_number": 53, "usage_type": "attribute"}, {"api_name": "daisy.prepare_ds", "line_number": 62, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 64, "usage_type": "attribute"}, {"api_name": "numpy.uint64", "line_number": 68, "usage_type": "attribute"}, {"api_name": "daisy.Roi", "line_number": 70, "usage_type": "call"}, {"api_name": "daisy.run_blockwise", "line_number": 76, "usage_type": "call"}]} +{"seq_id": "12064968585", "text": "\"\"\" Transport stream probe utility \"\"\"\nimport os\nimport time\nimport av\nfrom av import VideoFrame, AudioFrame\nfrom audiobuffer import AudioBuffer\nfrom videobuffer import VideoBuffer\nfrom prometheus import Prometheus\nfrom logger import log\nfrom benchmark import Benchmarker\n\n\nDEFAULT_VIDEO_URL = 'http://simula.frikanalen.no:9094/frikanalen.ts'\nPROMETHEUS_PORT = 8000\n# Generates a trace-ts-probe.json that can be opened in about:tracing or https://ui.perfetto.dev/\nBENCHMARK = False\n# Use threading.\nDO_THREADING = False\n# Interval between analysis\nVIDEO_PROBE_INTERVAL = 5\nAUDIO_PROBE_INTERVAL = 5\n\n# Benchmark tuning\nBENCHMARK_STOP_FRAME = -1\nif BENCHMARK:\n BENCHMARK_STOP_FRAME = 100\nif BENCHMARK:\n VIDEO_PROBE_INTERVAL = 1\n AUDIO_PROBE_INTERVAL = 1\n\n# MPEG-2 transport stream URL\nurl = os.environ.get('VIDEO_URL', None)\nif url is None:\n url = DEFAULT_VIDEO_URL\n log.warning(\"No video URL specified, using default: %s\" % url)\n\n# Create buffers\naudio_buffer = AudioBuffer()\nvideo_buffer = VideoBuffer()\n\n\n# Start Prometheus HTTP server\nprom = Prometheus()\nprom.listen(PROMETHEUS_PORT)\n\n\ndef run():\n bench = Benchmarker(BENCHMARK)\n smp = bench.sample_begin(\"Warmup\")\n log.info(\"Opening stream: %s\" % url)\n stream = av.open(url)\n if DO_THREADING:\n stream.streams.video[0].thread_type = \"AUTO\"\n log.info(\"Stream is open\")\n smp.end()\n # Bookkeeping\n local_video_frame_count = 0 # Used by benchmark to track frame\n video_interval_counter = 0 # Used to track intervals\n audio_interval_counter = 0\n # Start the clock (for benchmarking)\n START_TIME = time.time()\n while True:\n frame_smp = bench.sample_begin(\"Frame\")\n frame_decode_smp = bench.sample_begin(\"Frame-Decode\")\n frame_iter = iter(stream.decode())\n try:\n frame = next(frame_iter)\n frame_decode_smp.end()\n if isinstance(frame, VideoFrame):\n prom.video_frame_count.inc()\n local_video_frame_count += 1\n\n video_interval_counter += 1\n if VIDEO_PROBE_INTERVAL == video_interval_counter:\n #\n video_analysis_smp = bench.sample_begin(\"Video-Analysis\")\n # Add frame\n video_buffer.append(frame)\n avg_brightness = video_buffer.avg_brightness\n motion = video_buffer.motion\n prom.video_brightness_gauge.set(avg_brightness)\n prom.motion_gauge.set(motion)\n video_interval_counter = 0\n video_analysis_smp.end()\n if BENCHMARK:\n motion *= 1000\n avg_brightness *= 1000\n print(f\"Motion: {motion:12.3f} Brightness: {avg_brightness:12.3f}\")\n bench.add_metric_sample(\"video\", \"motion\", motion)\n bench.add_metric_sample(\"video\", \"brightness\", avg_brightness)\n\n elif isinstance(frame, AudioFrame):\n audio_buffer.append(frame)\n audio_interval_counter += 1\n if AUDIO_PROBE_INTERVAL == audio_interval_counter:\n audio_analysis_smp = bench.sample_begin(\"Audio-Analysis\")\n lufs = audio_buffer.lufs()\n dbfs = audio_buffer.dbfs(0)\n prom.audio_amplitude_lufs_gauge.set(lufs)\n prom.audio_amplitude_dbfs_gauge.set(dbfs)\n audio_interval_counter = 0\n audio_analysis_smp.end()\n bench.add_metric_sample(\"audio\", \"lufs\", lufs)\n bench.add_metric_sample(\"audio\", \"dbfs\", dbfs)\n\n if BENCHMARK:\n if local_video_frame_count == BENCHMARK_STOP_FRAME:\n dt = time.time() - START_TIME\n avg = dt / local_video_frame_count * 1000;\n print(f\"Average: {avg:.3}ms\")\n break\n except av.AVError as e:\n frame_decode_smp.end()\n log.error(e)\n prom.decode_error_count.inc()\n reopen_smp = bench.sample_begin(\"Re-open\")\n stream = av.open(url)\n reopen_smp.end()\n\n except KeyboardInterrupt:\n log.info(\"Keyboard interrupt\")\n break\n frame_smp.end()\n bench.report(\"trace-ts-probe\")\n\nrun()\n", "repo_name": "Frikanalen/ts-probe", "sub_path": "ts_probe.py", "file_name": "ts_probe.py", "file_ext": "py", "file_size_in_byte": 4421, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "48", "api": [{"api_name": "os.environ.get", "line_number": 32, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 32, "usage_type": "attribute"}, {"api_name": "logger.log.warning", "line_number": 35, "usage_type": "call"}, {"api_name": "logger.log", "line_number": 35, "usage_type": "name"}, {"api_name": "audiobuffer.AudioBuffer", "line_number": 38, "usage_type": "call"}, {"api_name": "videobuffer.VideoBuffer", "line_number": 39, "usage_type": "call"}, {"api_name": "prometheus.Prometheus", "line_number": 43, "usage_type": "call"}, {"api_name": "benchmark.Benchmarker", "line_number": 48, "usage_type": "call"}, {"api_name": "logger.log.info", "line_number": 50, "usage_type": "call"}, {"api_name": "logger.log", "line_number": 50, "usage_type": "name"}, {"api_name": "av.open", "line_number": 51, "usage_type": "call"}, {"api_name": "logger.log.info", "line_number": 54, "usage_type": "call"}, {"api_name": "logger.log", "line_number": 54, "usage_type": "name"}, {"api_name": "time.time", "line_number": 61, "usage_type": "call"}, {"api_name": "av.VideoFrame", "line_number": 69, "usage_type": "argument"}, {"api_name": "av.AudioFrame", "line_number": 92, "usage_type": "argument"}, {"api_name": "time.time", "line_number": 108, "usage_type": "call"}, {"api_name": "av.AVError", "line_number": 112, "usage_type": "attribute"}, {"api_name": "logger.log.error", "line_number": 114, "usage_type": "call"}, {"api_name": "logger.log", "line_number": 114, "usage_type": "name"}, {"api_name": "av.open", "line_number": 117, "usage_type": "call"}, {"api_name": "logger.log.info", "line_number": 121, "usage_type": "call"}, {"api_name": "logger.log", "line_number": 121, "usage_type": "name"}]} +{"seq_id": "15544722990", "text": "\"\"\"\ncomm_frontend_opts.py -- Common-used frontend options.\n\nExisting argument parsers::\n\n\"\"\"\n\n__all__ = (\n \"FrontendOptSpec\",\n \"FrontendOptSpecs\"\n)\n\nimport argparse\n\nfrom labw_utils.commonutils.stdlib_helper.argparse_helper import ArgumentParserWithEnhancedFormatHelp\nfrom labw_utils.devutils.decorators import copy_doc\nfrom labw_utils.typing_importer import Dict, Any, Mapping, Tuple, Iterable\n\n\nclass FrontendOptSpec:\n \"\"\"\n Class for Frontend option specification\n \"\"\"\n _args: Tuple[Any, ...]\n _kwargs: Mapping[str, Any]\n\n @copy_doc(argparse.ArgumentParser.add_argument)\n def __init__(self, *args, **kwargs):\n self._args = args\n self._kwargs = kwargs\n\n def patch(\n self,\n parser: argparse.ArgumentParser,\n **update_kwargs\n ) -> argparse.ArgumentParser:\n \"\"\"\n Patch argument parser.\n\n :param parser: Destination parser.\n :param update_kwargs: Keyword arguments used to override existing configurations.\n :return: Patched argument parser.\n \"\"\"\n kwargs = dict(self._kwargs)\n kwargs.update(update_kwargs)\n parser.add_argument(*self._args, **kwargs)\n return parser\n\n @property\n def name(self) -> str:\n \"\"\"Unique name of the option\"\"\"\n return self._args[0]\n\n\nclass FrontendOptSpecs:\n _inner_dict: Dict[str, FrontendOptSpec] = {}\n\n @staticmethod\n def add(opt_spec: FrontendOptSpec):\n FrontendOptSpecs._inner_dict[opt_spec.name] = opt_spec\n\n @staticmethod\n def patch(\n parser: argparse.ArgumentParser,\n name: str, **update_kwargs\n ):\n return FrontendOptSpecs._inner_dict[name].patch(parser=parser, **update_kwargs)\n\n @staticmethod\n def names() -> Iterable[str]:\n return iter(FrontendOptSpecs._inner_dict.keys())\n\n\nFrontendOptSpecs.add(FrontendOptSpec(\n '-f',\n '--fasta',\n required=True,\n help=\"Path to input reference genome sequence in FASTA format. Can be compressed.\",\n nargs='?',\n type=str,\n action='store'\n))\n\nFrontendOptSpecs.add(FrontendOptSpec(\n '-g', '--gtf',\n required=True,\n help=\"Path to input genomic annotation in GTF format. Can be compressed.\",\n nargs='?',\n type=str,\n action='store'\n))\n\nFrontendOptSpecs.add(FrontendOptSpec(\n \"-s\", \"--sam\",\n required=True,\n help=\"Path to input alignment file in SAM/BAM format\",\n nargs='?',\n type=str,\n action='store'\n))\n\n_parser = ArgumentParserWithEnhancedFormatHelp()\nfor _name in FrontendOptSpecs.names():\n _parser = FrontendOptSpecs.patch(_parser, _name)\n\n__doc__ += \"\\n\" + \"\\n\".join(\" \" + ln for ln in _parser.format_help().splitlines()) + \"\\n\"\n", "repo_name": "WanluLiuLab/labw_utils", "sub_path": "src/labw_utils/bioutils/comm_frontend_opts.py", "file_name": "comm_frontend_opts.py", "file_ext": "py", "file_size_in_byte": 2696, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "labw_utils.typing_importer.Tuple", "line_number": 24, "usage_type": "name"}, {"api_name": "labw_utils.typing_importer.Any", "line_number": 24, "usage_type": "name"}, {"api_name": "labw_utils.typing_importer.Mapping", "line_number": 25, "usage_type": "name"}, {"api_name": "labw_utils.typing_importer.Any", "line_number": 25, "usage_type": "name"}, {"api_name": "labw_utils.devutils.decorators.copy_doc", "line_number": 27, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 27, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 34, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 36, "usage_type": "attribute"}, {"api_name": "labw_utils.typing_importer.Dict", "line_number": 56, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 64, "usage_type": "attribute"}, {"api_name": "labw_utils.typing_importer.Iterable", "line_number": 70, "usage_type": "name"}, {"api_name": "labw_utils.commonutils.stdlib_helper.argparse_helper.ArgumentParserWithEnhancedFormatHelp", "line_number": 102, "usage_type": "call"}]} +{"seq_id": "26761899257", "text": "import cv2\nimport mediapipe as mp\nimport time\n\ncap = cv2.VideoCapture(1)\n\nmpHands = mp.solutions.hands\nhands = mpHands.Hands()\nmpDraw = mp.solutions.drawing_utils\n\nprevTime = 0\ncurrTime = 0\n\nwhile True:\n success, img = cap.read()\n imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n results = hands.process(imgRGB)\n\n if results.multi_hand_landmarks:\n for handLms in results.multi_hand_landmarks:\n # to get index for each point in hand\n for id, lm in enumerate(handLms.landmark):\n # to convert point on X-Y plane into pixels by multiplying wiht height and width of screen\n height, width, channels = img.shape\n # cx, cy points on the plane X and Y\n cx, cy = int(lm.x * width), int(lm.y * height)\n if id == 4:\n cv2.circle(img, (cx, cy), 15, (255, 0, 255), cv2.FILLED)\n # to draw points and connections on hand\n mpDraw.draw_landmarks(img, handLms, mpHands.HAND_CONNECTIONS)\n\n currTime = time.time()\n fps = 1 / (currTime - prevTime)\n prevTime = currTime\n\n # to display fps, convert into string, position, font, scale, color, height\n cv2.putText(\n img,\n str(int(fps)),\n (10, 70),\n cv2.FONT_HERSHEY_PLAIN,\n 3,\n (255, 0, 255),\n 3,\n )\n\n cv2.imshow(\"Image\", img)\n cv2.waitKey(1)\n", "repo_name": "Luvjeet/Volume-Control-Through-Gesture", "sub_path": "handTrackinMinimum.py", "file_name": "handTrackinMinimum.py", "file_ext": "py", "file_size_in_byte": 1394, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "cv2.VideoCapture", "line_number": 5, "usage_type": "call"}, {"api_name": "mediapipe.solutions", "line_number": 7, "usage_type": "attribute"}, {"api_name": "mediapipe.solutions", "line_number": 9, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 16, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 16, "usage_type": "attribute"}, {"api_name": "cv2.circle", "line_number": 28, "usage_type": "call"}, {"api_name": "cv2.FILLED", "line_number": 28, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 32, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 37, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_PLAIN", "line_number": 41, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 47, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 48, "usage_type": "call"}]} +{"seq_id": "42969840513", "text": "\nimport pytest\n\nimport astrodata\nimport astrodata.testing\nimport gemini_instruments\n\nfilename = 'N20190120S0287.fits'\n\n\n@pytest.fixture()\ndef ad():\n path = astrodata.testing.download_from_archive(filename)\n return astrodata.open(path)\n\n\n@pytest.mark.xfail(reason=\"AstroFaker changes the AstroData factory\")\n@pytest.mark.dragons_remote_data\ndef test_is_right_type(ad):\n assert type(ad) == gemini_instruments.niri.adclass.AstroDataNiri\n\n\n@pytest.mark.dragons_remote_data\ndef test_is_right_instance(ad):\n # YES, this *can* be different from test_is_right_type. Metaclasses!\n assert isinstance(ad, gemini_instruments.niri.adclass.AstroDataNiri)\n\n\n@pytest.mark.dragons_remote_data\ndef test_extension_data_shape(ad):\n assert ad[0].data.shape == (1024, 1024)\n\n\n@pytest.mark.dragons_remote_data\ndef test_tags(ad):\n tags = ad.tags\n expected = {'RAW', 'GEMINI', 'NORTH', 'SIDEREAL', 'UNPREPARED',\n 'IMAGE', 'NIRI'}\n assert expected.issubset(tags)\n\n\n@pytest.mark.dragons_remote_data\ndef test_can_return_instrument(ad):\n assert ad.phu['INSTRUME'] == 'NIRI'\n assert ad.instrument() == ad.phu['INSTRUME']\n\n\n@pytest.mark.dragons_remote_data\ndef test_can_return_ad_length(ad):\n assert len(ad) == 1\n\n\n@pytest.mark.dragons_remote_data\ndef test_slice_range(ad):\n metadata = ('SCI', 2), ('SCI', 3)\n slc = ad[1:]\n assert len(slc) == 0\n for ext, md in zip(slc, metadata):\n assert (ext.hdr['EXTNAME'], ext.hdr['EXTVER']) == md\n\n\n@pytest.mark.dragons_remote_data\ndef test_read_a_keyword_from_hdr(ad):\n try:\n assert ad.hdr['CCDNAME'] == 'NIRI'\n except KeyError:\n # KeyError only accepted if it's because headers out of range\n assert len(ad) == 1\n\n\ndef test_ra_dec_from_text(astrofaker):\n ad = astrofaker.create('NIRI', ['SPECT'],\n extra_keywords={'RA': '03:48:30.113',\n 'DEC': '+24:20:43.00',\n 'DATE-OBS': '2021-01-01T12:00:00.000'}\n )\n assert ad.target_ra() == pytest.approx(57.12547083333333)\n assert ad.target_dec() == pytest.approx(24.345277777777778)\n\n from astropy import units as u\n\n", "repo_name": "GeminiDRSoftware/DRAGONS", "sub_path": "gemini_instruments/niri/tests/test_niri.py", "file_name": "test_niri.py", "file_ext": "py", "file_size_in_byte": 2210, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 27, "dataset": "github-code", "pt": "48", "api": [{"api_name": "astrodata.testing.download_from_archive", "line_number": 13, "usage_type": "call"}, {"api_name": "astrodata.testing", "line_number": 13, "usage_type": "attribute"}, {"api_name": "astrodata.open", "line_number": 14, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 11, "usage_type": "call"}, {"api_name": "gemini_instruments.niri", "line_number": 20, "usage_type": "attribute"}, {"api_name": "pytest.mark.xfail", "line_number": 17, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 17, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 18, "usage_type": "attribute"}, {"api_name": "gemini_instruments.niri", "line_number": 26, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 23, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 29, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 34, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 42, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 48, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 53, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 62, "usage_type": "attribute"}, {"api_name": "pytest.approx", "line_number": 77, "usage_type": "call"}, {"api_name": "pytest.approx", "line_number": 78, "usage_type": "call"}]} +{"seq_id": "27656335011", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom typing import Dict, Iterator, List, Optional, Union, Literal, Tuple\nimport os\nimport json\nimport pickle\n\nimport numpy as np\nfrom hyperopt import hp\nfrom sklearn.gaussian_process.kernels import (\n ConstantKernel,\n RBF\n)\n\n\nclass BaseKernelConfig:\n def __init__(self, N_RBF: int = 0,\n sigma_RBF: List[float] = None,\n sigma_RBF_bounds: List[Tuple[float, float]] = None):\n self.N_RBF = N_RBF\n self.sigma_RBF = sigma_RBF\n self.sigma_RBF_bounds = sigma_RBF_bounds\n self.kernel = self._get_rbf_kernel()[0]\n\n def get_kernel_dict(self, X: np.ndarray, X_labels: np.ndarray) -> Dict:\n K = self.kernel(X)\n return {\n 'X': X_labels,\n 'K': K,\n 'theta': self.kernel.theta\n }\n\n def _update_kernel(self):\n self.kernel = self._get_rbf_kernel()[0]\n\n def _get_rbf_kernel(self) -> List:\n if self.N_RBF != 0:\n if len(self.sigma_RBF) != 1 and len(self.sigma_RBF) != self.N_RBF:\n raise RuntimeError('features_mol and hyperparameters must be the'\n ' same length')\n add_kernel = RBF(length_scale=self.sigma_RBF,\n length_scale_bounds=self.sigma_RBF_bounds)\n # ConstantKernel(1.0, (1e-3, 1e3)) * \\\n return [add_kernel]\n else:\n return [None]\n\n # functions for Bayesian optimization of hyperparameters.\n def get_space(self):\n SPACE = dict()\n if self.sigma_RBF is not None:\n for i in range(len(self.sigma_RBF)):\n hp_key = 'RBF:%d:' % i\n hp_ = self._get_hp(hp_key, [self.sigma_RBF[i],\n self.sigma_RBF_bounds[i]])\n if hp_ is not None:\n SPACE[hp_key] = hp_\n return SPACE\n\n def update_from_space(self, hyperdict: Dict[str, Union[int, float]]):\n for key, value in hyperdict.items():\n n, term, microterm = key.split(':')\n # RBF kernels\n if n == 'RBF':\n n_rbf = int(term)\n self.sigma_RBF[n_rbf] = value\n self._update_kernel()\n\n @staticmethod\n def _get_hp(key, value):\n if value[1] == 'fixed':\n return None\n elif value[0] in ['Additive', 'Tensorproduct']:\n return hp.choice(key, value[1])\n elif len(value) == 2:\n return hp.uniform(key, low=value[1][0], high=value[1][1])\n elif len(value) == 3:\n return hp.quniform(key, low=value[1][0], high=value[1][1],\n q=value[2])\n else:\n raise RuntimeError('.')\n\n # save functions.\n def save_hyperparameters(self, path: str):\n if self.sigma_RBF is not None:\n rbf = {\n 'sigma_RBF': self.sigma_RBF,\n 'sigma_RBF_bounds': self.sigma_RBF_bounds\n }\n open(os.path.join(path, 'sigma_RBF.json'), 'w').write(\n json.dumps(rbf, indent=1, sort_keys=False))\n\n def save_kernel_matrix(self, path: str, X: np.ndarray, X_labels: List[str]):\n \"\"\"Save kernel.pkl file that used for preCalc kernels.\"\"\"\n kernel_dict = self.get_kernel_dict(X, X_labels)\n kernel_pkl = os.path.join(path, 'kernel.pkl')\n pickle.dump(kernel_dict, open(kernel_pkl, 'wb'), protocol=4)\n", "repo_name": "Xiangyan93/ALMS", "sub_path": "alms/ml/mgk/kernels/BaseKernelConfig.py", "file_name": "BaseKernelConfig.py", "file_ext": "py", "file_size_in_byte": 3440, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "48", "api": [{"api_name": "typing.List", "line_number": 18, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 19, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 19, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 25, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 25, "usage_type": "name"}, {"api_name": "sklearn.gaussian_process.kernels.RBF", "line_number": 41, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 36, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 60, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 60, "usage_type": "name"}, {"api_name": "hyperopt.hp.choice", "line_number": 74, "usage_type": "call"}, {"api_name": "hyperopt.hp", "line_number": 74, "usage_type": "name"}, {"api_name": "hyperopt.hp.uniform", "line_number": 76, "usage_type": "call"}, {"api_name": "hyperopt.hp", "line_number": 76, "usage_type": "name"}, {"api_name": "hyperopt.hp.quniform", "line_number": 78, "usage_type": "call"}, {"api_name": "hyperopt.hp", "line_number": 78, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 90, "usage_type": "call"}, {"api_name": "os.path", "line_number": 90, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 93, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 93, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 96, "usage_type": "call"}, {"api_name": "os.path", "line_number": 96, "usage_type": "attribute"}, {"api_name": "pickle.dump", "line_number": 97, "usage_type": "call"}]} +{"seq_id": "71463239187", "text": "import json\n\nfrom datetime import datetime\n\nfrom django.db import models\nfrom apps.base.models import DescriptiveModel\nfrom apps.base.models import Parameter\nfrom apps.base.models import SoftDeleteTSModel\nfrom apps.core.models import Indicator\nfrom apps.core.models import Program\nfrom apps.core.models import Subject\n\nindicator_values = json.loads(Parameter.objects.get(code='score').value)\nMIN_INDICATOR_VALUE = int(indicator_values['min'])\nMAX_INDICATOR_VALUE = int(indicator_values['max'])\n\nclass Survey(SoftDeleteTSModel, DescriptiveModel):\n checksum = models.CharField(blank=True, max_length=100)\n indicator = models.ManyToManyField(Indicator)\n subject = models.ForeignKey(Subject, on_delete=models.CASCADE,)\n\n class Meta:\n verbose_name = 'encuesta'\n\n\nclass Period(SoftDeleteTSModel, DescriptiveModel):\n checksum = models.CharField(blank=True, max_length=100)\n start_date = models.DateField()\n end_date = models.DateField()\n program = models.ForeignKey(Program, on_delete=models.CASCADE,)\n\n class Meta:\n verbose_name = 'periodo'\n\n def __str__(self):\n return '{0} {1}'.format(self.name, self.program)\n\n @property\n def is_active(self):\n start_date = self.start_date\n end_date = self.end_date\n now = datetime.now().date()\n return start_date <= now <= end_date\n\n @property\n def is_past(self):\n end_date = self.end_date\n now = datetime.now().date()\n return end_date < now\n\n @property\n def is_future(self):\n start_date = self.start_date\n now = datetime.now().date()\n return now < start_date\n\n @property\n def time_status(self):\n if self.is_active:\n return 'active'\n elif self.is_past:\n return 'past'\n elif self.is_future:\n return 'future'\n else:\n return None\n\n @property\n def courses(self):\n from apps.term.models import Course\n return Course.objects.filter(period=self)\n\n @classmethod\n def all_active(cls):\n now = datetime.now().date()\n return Period.objects.filter(\n start_date__lte=now,\n end_date__gte=now,\n )\n\n @classmethod\n def all_past(cls):\n now = datetime.now().date()\n return Period.objects.filter(\n end_date__lt=now,\n )\n\n @classmethod\n def all_future(cls):\n now = datetime.now().date()\n return Period.objects.filter(\n start_date__gt=now,\n )\n\n @property\n def len_total_values(self):\n len_total_values = 0\n for c in self.courses:\n len_total_values += c.len_total_values\n return len_total_values\n\n @property\n def total_evaluated_values(self):\n from apps.term.models import FinalIndicatorEvaluation\n return FinalIndicatorEvaluation.objects.filter(\n course__in=self.courses,\n ).values_list('value', flat=True)\n\n @property\n def progress_level(self):\n len_total_evaluated_values = len(self.total_evaluated_values)\n len_total_values = self.len_total_values\n return float(len_total_evaluated_values)/len_total_values if len_total_values > 0 else None\n\n @property\n def goal_level(self):\n len_total_evaluated_values = len(self.total_evaluated_values)\n sum_total_evaluated_values = sum(self.total_evaluated_values)\n\n max_total_evaluated_values = len_total_evaluated_values * (MAX_INDICATOR_VALUE - MIN_INDICATOR_VALUE)\n\n return float(sum_total_evaluated_values)/max_total_evaluated_values if max_total_evaluated_values > 0 else None\n\n @classmethod\n def all_json(\n cls,\n time_status='active', # 'active', 'past', 'future', 'all' # Ok \n programs=None,\n p_periods=None,\n # campus=None,\n # teachers=None,\n # students=None,\n # subjects=None,\n # skills=None,\n # skills_groups=None,\n # progress_level_not_none=None, # None (all), True, False\n # progress_level_less_than=None,\n # progress_level_greater_than=None,\n # progress_level_less_or_equal_than=None,\n # progress_level_greater_or_equal_than=None,\n # goal_level_not_none=None, # None (all), True, False\n # goal_level_less_than=None,\n # goal_level_greater_than=None,\n # goal_level_less_or_equal_than=None,\n # goal_level_greater_or_equal_than=None,\n order_by=None,\n show_skills=False,\n show_skills_groups=False,\n as_json=False,\n ):\n periods = Period.objects.all().distinct()\n\n if p_periods is not None:\n if type(p_periods) is not list:\n p_periods = [p_periods]\n if len(p_periods) > 0:\n periods = periods.filter(id__in=[p.id for p in p_periods])\n elif time_status != 'all':\n if time_status == 'active':\n periods = Period.all_active()\n elif time_status == 'past':\n periods = Period.all_past()\n elif time_status == 'future':\n periods = Period.all_future()\n\n if programs is not None:\n if type(programs) is not list:\n programs = [programs]\n if len(programs) > 0:\n periods = periods.filter(program__in=programs)\n\n # if subjects is not None:\n # if type(subjects) is not list:\n # subjects = [subjects]\n # if len(subjects) > 0:\n # courses = courses.filter(subject__in=subjects)\n\n # if campus is not None:\n # if type(campus) is not list:\n # campus = [campus]\n # if len(campus) > 0:\n # courses = courses.filter(campus__in=campus)\n\n # if skills is not None:\n # if type(skills) is not list:\n # skills = [skills]\n # if len(skills) > 0:\n # courses = courses.filter(survey__indicator__skill__in=skills)\n\n # if skills_groups is not None:\n # if type(skills_groups) is not list:\n # skills_groups = [skills_groups]\n # if len(skills_groups) > 0:\n # courses = courses.filter(survey__indicator__skill__skill_group__in=skills_groups)\n\n # if teachers is not None:\n # if type(teachers) is not list:\n # teachers = [teachers]\n # if len(teachers) > 0:\n # courses = courses.filter(teachers__in=teachers)\n\n # if students is not None:\n # if type(students) is not list:\n # students = [students]\n # if len(students) > 0:\n # courses = courses.filter(students__in=students)\n\n # if progress_level_not_none is not None:\n # if progress_level_not_none:\n # courses = [c for c in courses if c.progress_level is not None] \n # else:\n # courses = [c for c in courses if c.progress_level is None] \n\n # if progress_level_less_than is not None:\n # courses = [c for c in courses if c.progress_level is not None and c.progress_level < progress_level_less_than] \n\n # if progress_level_greater_than is not None:\n # courses = [c for c in courses if c.progress_level is not None and c.progress_level > progress_level_greater_than] \n\n # if progress_level_less_or_equal_than is not None:\n # courses = [c for c in courses if c.progress_level is not None and c.progress_level <= progress_level_less_or_equal_than] \n\n # if progress_level_greater_or_equal_than is not None:\n # courses = [c for c in courses if c.progress_level is not None and c.progress_level >= progress_level_greater_or_equal_than] \n\n # if goal_level_not_none is not None:\n # if goal_level_not_none:\n # courses = [c for c in courses if c.goal_level is not None] \n # else:\n # courses = [c for c in courses if c.goal_level is None] \n\n # if goal_level_less_than is not None:\n # courses = [c for c in courses if c.goal_level is not None and c.goal_level < goal_level_less_than] \n\n # if goal_level_greater_than is not None:\n # courses = [c for c in courses if c.goal_level is not None and c.goal_level > goal_level_greater_than] \n\n # if goal_level_less_or_equal_than is not None:\n # courses = [c for c in courses if c.goal_level is not None and c.goal_level <= goal_level_less_or_equal_than] \n\n # if goal_level_greater_or_equal_than is not None:\n # courses = [c for c in courses if c.goal_level is not None and c.goal_level >= goal_level_greater_or_equal_than]\n\n result = []\n\n for p in periods:\n\n json_course = {\n 'id': p.id,\n 'name': p.name,\n 'code': p.code,\n 'start_date': p.start_date.strftime('%d/%m/%Y'),\n 'end_date': p.end_date.strftime('%d/%m/%Y'),\n 'program': p.program.name,\n 'time_status': p.time_status,\n 'progress_level': p.progress_level,\n 'goal_level': p.goal_level, \n }\n\n if show_skills:\n skills = []\n\n for s in c.skills:\n skills.append({\n 'name': s.name,\n 'code': s.code,\n 'group': s.skill_group.name,\n 'progress_level': c.progress_level_by_skill(s),\n 'goal_level': c.goal_level_by_skill(s), \n })\n\n json_course.update({ \n 'skills': skills, \n })\n\n if show_skills:\n skills_groups = []\n\n for s in c.skills_groups:\n skills_groups.append({\n 'name': s.name,\n 'code': s.code,\n 'skills': [sk.name for sk in c.get_skills_by_skills_group(s)],\n 'progress_level': c.progress_level_by_skills_group(s),\n 'goal_level': c.goal_level_by_skills_group(s), \n })\n\n json_course.update({ \n 'skills_groups': skills_groups, \n })\n\n result.append(json_course)\n\n if order_by is not None:\n reverse = '-' in order_by\n key = order_by.replace('-','')\n result.sort(key = lambda c: c[key] if c[key] is not None else 0, reverse=reverse)\n\n return json.dumps(result) if as_json else result\n\nclass Campus(SoftDeleteTSModel, DescriptiveModel):\n program = models.ManyToManyField(Program)\n\n class Meta:\n verbose_name = 'campus'\n verbose_name_plural = 'campus'\n", "repo_name": "claudioDcv/la-cosa-es-como-es-no-ma", "sub_path": "apps/business/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 10961, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "json.loads", "line_number": 13, "usage_type": "call"}, {"api_name": "apps.base.models.Parameter.objects.get", "line_number": 13, "usage_type": "call"}, {"api_name": "apps.base.models.Parameter.objects", "line_number": 13, "usage_type": "attribute"}, {"api_name": "apps.base.models.Parameter", "line_number": 13, "usage_type": "name"}, {"api_name": "apps.base.models.SoftDeleteTSModel", "line_number": 17, "usage_type": "name"}, {"api_name": "apps.base.models.DescriptiveModel", "line_number": 17, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 18, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 18, "usage_type": "name"}, {"api_name": "django.db.models.ManyToManyField", "line_number": 19, "usage_type": "call"}, {"api_name": "apps.core.models.Indicator", "line_number": 19, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 19, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 20, "usage_type": "call"}, {"api_name": "apps.core.models.Subject", "line_number": 20, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 20, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 20, "usage_type": "attribute"}, {"api_name": "apps.base.models.SoftDeleteTSModel", "line_number": 26, "usage_type": "name"}, {"api_name": "apps.base.models.DescriptiveModel", "line_number": 26, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 27, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 27, "usage_type": "name"}, {"api_name": "django.db.models.DateField", "line_number": 28, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 28, "usage_type": "name"}, {"api_name": "django.db.models.DateField", "line_number": 29, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 29, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 30, "usage_type": "call"}, {"api_name": "apps.core.models.Program", "line_number": 30, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 30, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 30, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 42, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 42, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 48, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 48, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 54, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 54, "usage_type": "name"}, {"api_name": "apps.term.models.Course.objects.filter", "line_number": 71, "usage_type": "call"}, {"api_name": "apps.term.models.Course.objects", "line_number": 71, "usage_type": "attribute"}, {"api_name": "apps.term.models.Course", "line_number": 71, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 75, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 75, "usage_type": "name"}, {"api_name": "{'Course': 'apps.term.models.Course'}.objects.filter", "line_number": 76, "usage_type": "call"}, {"api_name": "{'Course': 'apps.term.models.Course'}.objects", "line_number": 76, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 83, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 83, "usage_type": "name"}, {"api_name": "{'Course': 'apps.term.models.Course'}.objects.filter", "line_number": 84, "usage_type": "call"}, {"api_name": "{'Course': 'apps.term.models.Course'}.objects", "line_number": 84, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 90, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 90, "usage_type": "name"}, {"api_name": "{'Course': 'apps.term.models.Course'}.objects.filter", "line_number": 91, "usage_type": "call"}, {"api_name": "{'Course': 'apps.term.models.Course'}.objects", "line_number": 91, "usage_type": "attribute"}, {"api_name": "apps.term.models.FinalIndicatorEvaluation.objects.filter", "line_number": 105, "usage_type": "call"}, {"api_name": "apps.term.models.FinalIndicatorEvaluation.objects", "line_number": 105, "usage_type": "attribute"}, {"api_name": "apps.term.models.FinalIndicatorEvaluation", "line_number": 105, "usage_type": "name"}, {"api_name": "{'Course': 'apps.term.models.Course', 'FinalIndicatorEvaluation': 'apps.term.models.FinalIndicatorEvaluation'}.objects.all", "line_number": 151, "usage_type": "call"}, {"api_name": "{'Course': 'apps.term.models.Course', 'FinalIndicatorEvaluation': 'apps.term.models.FinalIndicatorEvaluation'}.objects", "line_number": 151, "usage_type": "attribute"}, {"api_name": "{'Course': 'apps.term.models.Course', 'FinalIndicatorEvaluation': 'apps.term.models.FinalIndicatorEvaluation'}.all_active", "line_number": 160, "usage_type": "call"}, {"api_name": "{'Course': 'apps.term.models.Course', 'FinalIndicatorEvaluation': 'apps.term.models.FinalIndicatorEvaluation'}.all_past", "line_number": 162, "usage_type": "call"}, {"api_name": "{'Course': 'apps.term.models.Course', 'FinalIndicatorEvaluation': 'apps.term.models.FinalIndicatorEvaluation'}.all_future", "line_number": 164, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 299, "usage_type": "call"}, {"api_name": "apps.base.models.SoftDeleteTSModel", "line_number": 301, "usage_type": "name"}, {"api_name": "apps.base.models.DescriptiveModel", "line_number": 301, "usage_type": "name"}, {"api_name": "django.db.models.ManyToManyField", "line_number": 302, "usage_type": "call"}, {"api_name": "apps.core.models.Program", "line_number": 302, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 302, "usage_type": "name"}]} +{"seq_id": "35942204824", "text": "import os\nimport re\nimport itertools\nimport nbformat\n\nNOTEBOOK_DIR = os.path.join(os.path.dirname(__file__), '..', 'notebooks')\n\nCHAPTERS = {\"00\": \"Preface\",\n \"01\": \"IPython: Beyond Normal Python\",\n \"02\": \"NumPy\",\n \"03\": \"Pandas\",\n \"04\": \"Matplotlib\",\n \"05\": \"Machine Learning\"}\n\nREG = re.compile(r'(\\d\\d)\\.(\\d\\d)-(.*)\\.ipynb')\n\n\ndef iter_notebooks():\n return sorted(nb for nb in os.listdir(NOTEBOOK_DIR) if REG.match(nb))\n\n\ndef get_notebook_title(nb_file):\n nb = nbformat.read(os.path.join(NOTEBOOK_DIR, nb_file), as_version=4)\n for cell in nb.cells:\n if cell.source.startswith('#'):\n return cell.source[1:].splitlines()[0].strip()\n\n\ndef gen_contents(directory=None):\n for nb in iter_notebooks():\n if directory:\n nb_url = os.path.join(directory, nb)\n else:\n nb_url = nb\n chapter, section, title = REG.match(nb).groups()\n title = get_notebook_title(nb)\n if section == '00':\n if chapter in ['00', '06']:\n yield '\\n### [{0}]({1})'.format(title, nb_url)\n else:\n yield '\\n### [{0}. {1}]({2})'.format(int(chapter),\n title, nb_url)\n else:\n yield \"- [{0}]({1})\".format(title, nb_url)\n\n\ndef print_contents(directory=None):\n print('\\n'.join(gen_contents(directory)))\n\n\nif __name__ == '__main__':\n print_contents()\n print('\\n', 70 * '#', '\\n')\n print_contents('http://nbviewer.jupyter.org/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/')\n", "repo_name": "jakevdp/PythonDataScienceHandbook", "sub_path": "tools/generate_contents.py", "file_name": "generate_contents.py", "file_ext": "py", "file_size_in_byte": 1621, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 40127, "dataset": "github-code", "pt": "48", "api": [{"api_name": "os.path.join", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 6, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 15, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 19, "usage_type": "call"}, {"api_name": "nbformat.read", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path", "line_number": 32, "usage_type": "attribute"}]} +{"seq_id": "10297829507", "text": "import os\nimport sys\n\nimport oneagent # SDK initialization functions\nimport oneagent.sdk as onesdk # All other SDK functions.\n\ntry: # Python 2 compatibility.\n input = raw_input #pylint:disable=redefined-builtin\nexcept NameError:\n pass\n\n\ngetsdk = oneagent.get_sdk # Just to make the code shorter.\n\n\ndef do_some_fancy_stuff(proc_number):\n sdk = getsdk()\n\n # Initially, the state in the child will be PRE_INITIALIZED (2).\n print('Agent fork state (child process before SDK call):', sdk.agent_fork_state)\n\n # The agent state in the child process should be ACTIVE (0).\n print('Agent state (child process #{}): {}'.format(proc_number, sdk.agent_state), flush=True)\n\n # After calling any SDK function but agent_fork_state,\n # the state in the child will be FULLY_INITIALIZED (3).\n # In this case the SDK function called was the agent_state property accessed above.\n print('Agent fork state (child process after SDK call):', sdk.agent_fork_state)\n\n print('Agent found:', sdk.agent_found)\n print('Agent is compatible:', sdk.agent_is_compatible)\n print('Agent version:', sdk.agent_version_string)\n\n # This call below will complete the OneAgent for Python SDK initialization and then it\n # will start the tracer for tracing the custom service\n with sdk.trace_custom_service('my_fancy_transaction', 'MyFancyService #{}'.format(proc_number)):\n print('do some fancy stuff')\n\ndef create_child_process(proc_number):\n pid = os.fork()\n if pid == 0:\n print('child #{} is running ...'.format(proc_number))\n do_some_fancy_stuff(proc_number)\n print('child #{} is exiting ...'.format(proc_number))\n sys.exit(0)\n\n return pid\n\ndef fork_children():\n print('now starting children ...', flush=True)\n pid_1 = create_child_process(1)\n pid_2 = create_child_process(2)\n\n print('waiting for child #1 ...', flush=True)\n os.waitpid(pid_1, 0)\n print('child #1 exited', flush=True)\n\n print('waiting for child #2 ...', flush=True)\n os.waitpid(pid_2, 0)\n print('child #2 exited', flush=True)\n\n print('all children exited', flush=True)\n\ndef main():\n # This gathers arguments prefixed with '--dt_' from sys.argv into the\n # returned list. See also the basic-sdk-sample.\n sdk_options = oneagent.sdkopts_from_commandline(remove=True)\n\n # Before using the SDK you have to initialize the OneAgent. In this scenario, we\n # initialize the SDK and prepare it for forking.\n #\n # Passing in the sdk_options is entirely optional and usually not required\n # as all settings will be automatically provided by the Dynatrace OneAgent\n # that is installed on the host.\n #\n # To activate the forking support add the optional 'forkable' parameter and set it to True.\n #\n # If you run this example on Windows then you'll get an \"Invalid Argument\" error back\n # because there's no forking support for Windows available.\n init_result = oneagent.initialize(sdk_options, forkable=True)\n try:\n if init_result.error is not None:\n print('Error during SDK initialization:', init_result.error)\n\n # While not by much, it is a bit faster to cache the result of\n # oneagent.get_sdk() instead of calling the function multiple times.\n sdk = getsdk()\n\n # The agent state is one of the integers in oneagent.sdk.AgentState.\n # Since we're using the 'forkable' mode the state will be TEMPORARILY_INACTIVE (1) on Linux.\n print('Agent state (parent process):', sdk.agent_state)\n\n # In the parent, the state will be PARENT_INITIALIZED (1).\n print('Agent fork state (parent process):', sdk.agent_fork_state)\n\n # The instance attribute 'agent_found' indicates whether an agent could be found or not.\n print('Agent found:', sdk.agent_found)\n\n # If an agent was found but it is incompatible with this version of the SDK for Python\n # then 'agent_is_compatible' would be set to false.\n print('Agent is compatible:', sdk.agent_is_compatible)\n\n # The agent version is a string holding both the OneAgent version and the\n # OneAgent SDK for C/C++ version separated by a '/'.\n print('Agent version:', sdk.agent_version_string)\n\n if init_result.error is None:\n fork_children()\n input('Now wait until the path appears in the UI ...')\n finally:\n shutdown_error = oneagent.shutdown()\n if shutdown_error:\n print('Error shutting down SDK:', shutdown_error)\n\nif __name__ == '__main__':\n main()\n", "repo_name": "Dynatrace/OneAgent-SDK-for-Python", "sub_path": "samples/fork-sdk-sample/fork_sdk_sample.py", "file_name": "fork_sdk_sample.py", "file_ext": "py", "file_size_in_byte": 4560, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 27, "dataset": "github-code", "pt": "48", "api": [{"api_name": "oneagent.get_sdk", "line_number": 13, "usage_type": "attribute"}, {"api_name": "os.fork", "line_number": 40, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 45, "usage_type": "call"}, {"api_name": "os.waitpid", "line_number": 55, "usage_type": "call"}, {"api_name": "os.waitpid", "line_number": 59, "usage_type": "call"}, {"api_name": "oneagent.sdkopts_from_commandline", "line_number": 67, "usage_type": "call"}, {"api_name": "oneagent.initialize", "line_number": 80, "usage_type": "call"}, {"api_name": "oneagent.shutdown", "line_number": 111, "usage_type": "call"}]} +{"seq_id": "22816635046", "text": "from collections import defaultdict\nimport sys, threading\n \ndef main():\n def solve():\n def dfs(node):\n nonlocal visited, balanced_trees\n if node in visited:\n return 0\n \n visited.add(node)\n if colors[node-1] == \"B\":\n curr = 1\n else:\n curr = -1\n\n res = 0\n for neighbour in neighbours[node]:\n res += dfs(neighbour)\n \n if res + curr == 0:\n balanced_trees += 1\n return res + curr\n \n \n neighbours = defaultdict(list)\n \n n = int(input())\n parents = list(map(int, input().split()))\n colors = [color for color in input()]\n \n for i in range(len(parents)):\n neighbours[parents[i]].append(i+2)\n \n visited = set()\n balanced_trees = 0\n dfs(1)\n print(balanced_trees)\n \n t = int(input())\n for _ in range(t):\n solve()\nsys.setrecursionlimit(1 << 30)\nthreading.stack_size(1 << 27)\n \nmain_thread = threading.Thread(target=main)\nmain_thread.start()\nmain_thread.join()", "repo_name": "mnhaqq/A2SV-problems", "sub_path": "week_24/contest/white_black_balanced_subtrees.py", "file_name": "white_black_balanced_subtrees.py", "file_ext": "py", "file_size_in_byte": 1127, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "collections.defaultdict", "line_number": 26, "usage_type": "call"}, {"api_name": "sys.setrecursionlimit", "line_number": 43, "usage_type": "call"}, {"api_name": "threading.stack_size", "line_number": 44, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 46, "usage_type": "call"}]} +{"seq_id": "24319882215", "text": "import tensorflow as tf\nimport numpy as np\n\n\n\n# Positional Encoding\n# https://kazemnejad.com/blog/transformer_architecture_positional_encoding/\n# PE(pos, 2i) = sin(pos / 10000 ^ (2i / d_model))\n# PE(pos, 2i+1) = con(pos / 10000 ^ (2i / d_model))\n\ndef get_angles(pos, i, model_dim):\n angle_rates = 1 / np.power(10000, (2*(i//2)) / np.float32(model_dim))\n return pos * angle_rates\n\n\ndef positional_encoding(pos, model_dim):\n angle_rads = get_angles(np.arange(pos)[:, np.newaxis], # pos, 1\n np.arange(model_dim)[np.newaxis, :], # 1, pos\n model_dim)\n angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])\n angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])\n\n pos_encoding = angle_rads[np.newaxis, ...]\n return tf.cast(pos_encoding, tf.float32)\n\n\n\nclass PositionalEncoding(tf.keras.layers.Layer):\n def __init__(self):\n super(PositionalEncoding, self).__init__()\n\n def get_angles(self, pos, i, d_model): # pos: (seq_length, 1) i: (1, d_model)\n angles = 1 / np.power(10000., (2 * (i // 2)) / np.float32(d_model))\n return pos * angles # (seq_length, d_model)\n\n def call(self, inputs):\n '''\n\n :param inputs: Embedding Ouput\n :return: Positional Encoding as the same size of embedding\n '''\n seq_length = inputs.shape.as_list()[-2]\n d_model = inputs.shape.as_list()[-1]\n\n angles = self.get_angles(np.arange(seq_length)[:, np.newaxis],\n np.arange(d_model)[np.newaxis, :],\n d_model)\n\n angles[:, 0::2] = np.sin(angles[:, 0::2])\n angles[:, 1::2] = np.cos(angles[:, 1::2])\n\n return tf.cast(angles[np.newaxis, ...], tf.float32) # (B, seq_length, d_model)\n\n\n\n\n\nif __name__ == '__main__':\n import matplotlib.pyplot as plt\n pe = PositionalEncoding()\n pe_result = pe(tf.random.uniform(shape=(2, 5, 10)))\n plt.matshow(pe_result.numpy().squeeze())\n plt.show()", "repo_name": "seunghwan1228/Transfomer-MachineTranslation", "sub_path": "models/pos_encoding.py", "file_name": "pos_encoding.py", "file_ext": "py", "file_size_in_byte": 2000, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "48", "api": [{"api_name": "numpy.power", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 17, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 18, "usage_type": "attribute"}, {"api_name": "numpy.sin", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 23, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 24, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 24, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 28, "usage_type": "attribute"}, {"api_name": "numpy.power", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 45, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 46, "usage_type": "attribute"}, {"api_name": "numpy.sin", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 50, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 52, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 52, "usage_type": "attribute"}, {"api_name": "tensorflow.random.uniform", "line_number": 61, "usage_type": "call"}, {"api_name": "tensorflow.random", "line_number": 61, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.matshow", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 63, "usage_type": "name"}]} +{"seq_id": "2979332123", "text": "from unittest.mock import MagicMock, PropertyMock, patch, call\nimport numpy as np\n\nfrom thunderq.cycles.native import Cycle\nfrom utils import init_runtime, init_fixed_sequence\n\nruntime = init_runtime()\ninit_fixed_sequence(runtime)\n\ntest_param1 = PropertyMock()\ntest_param2 = PropertyMock()\ntest_param3 = PropertyMock()\n\ntest_result = np.linspace(0, 99, 100)\n\n\ndef prepare_cycle():\n global test_param1, test_param2, test_param3\n cycle = MagicMock()\n test_param1 = PropertyMock()\n test_param2 = PropertyMock()\n test_param3 = PropertyMock()\n type(cycle).test_param1 = test_param1\n type(cycle).test_param2 = test_param2\n type(cycle).test_param3 = test_param3\n type(cycle).add_procedure = MagicMock()\n type(cycle).clear_procedures = MagicMock()\n type(cycle).run = MagicMock()\n type(cycle).run.side_effect = [{'test_result': v} for v in test_result]\n type(cycle).run_sequence = MagicMock()\n type(cycle).stop_sequence = MagicMock()\n\n return cycle\n\n\nclass TestSweep:\n def test_attr_getter(self):\n from thunderq.experiment import SweepExperiment\n\n class Obj1:\n word = \"Hello\"\n\n class Obj2:\n obj = Obj1()\n\n obj = Obj2()\n\n assert SweepExperiment.get_attribute_getter(obj, \"obj.word\")() == \"Hello\"\n\n def test_attr_setter(self):\n from thunderq.experiment import SweepExperiment\n\n class Obj1:\n word = \"Hello\"\n\n class Obj2:\n obj = Obj1()\n\n obj = Obj2()\n\n SweepExperiment.get_attribute_setter(obj, \"obj.word\")(\"World\")\n assert obj.obj.word == \"World\"\n\n def test_sweep_1d(self):\n from thunderq.experiment import Sweep1DExperiment\n cycle = prepare_cycle()\n sweep = Sweep1DExperiment(runtime, \"TestSweepBase\", cycle)\n sweep.sweep(scan_param=\"test_param1\",\n points=np.linspace(0, 5, 6),\n scan_param_unit=\"arb.\",\n result_name='test_result')\n\n test_param1.assert_has_calls(\n [call(0.), call(1.), call(2.), call(3.), call(4.), call(5.)])\n assert (sweep.results['test_result'] == test_result[:6]).all()\n\n def test_sweep_2d(self):\n import itertools\n from thunderq.experiment import Sweep2DExperiment\n cycle = prepare_cycle()\n sweep = Sweep2DExperiment(runtime, \"TestSweep2DBase\", cycle)\n fast_points = np.linspace(0, 5, 6)\n slow_points = np.linspace(10, 18, 9)\n sweep.sweep(fast_param=\"test_param1\",\n fast_param_points=fast_points,\n fast_param_unit=\"unit1\",\n slow_param=\"test_param2\",\n slow_param_points=slow_points,\n slow_param_unit=\"unit2\",\n result_name='test_result',\n result_unit=\"unit3\")\n\n test_param1.assert_has_calls(\n [call(v) for v in fast_points] * len(slow_points))\n test_param2.assert_has_calls(\n itertools.chain(*[[call(v)]*len(fast_points) for v in slow_points]))\n assert (sweep.results['test_result'].flatten() ==\n test_result[:len(fast_points)*len(slow_points)]).all()\n\n", "repo_name": "TerryGeng/ThunderQ", "sub_path": "tests/test_sweep.py", "file_name": "test_sweep.py", "file_ext": "py", "file_size_in_byte": 3189, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "48", "api": [{"api_name": "utils.init_runtime", "line_number": 7, "usage_type": "call"}, {"api_name": "utils.init_fixed_sequence", "line_number": 8, "usage_type": "call"}, {"api_name": "unittest.mock.PropertyMock", "line_number": 10, "usage_type": "call"}, {"api_name": "unittest.mock.PropertyMock", "line_number": 11, "usage_type": "call"}, {"api_name": "unittest.mock.PropertyMock", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 14, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 19, "usage_type": "call"}, {"api_name": "unittest.mock.PropertyMock", "line_number": 20, "usage_type": "call"}, {"api_name": "unittest.mock.PropertyMock", "line_number": 21, "usage_type": "call"}, {"api_name": "unittest.mock.PropertyMock", "line_number": 22, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 26, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 27, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 28, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 30, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 31, "usage_type": "call"}, {"api_name": "thunderq.experiment.SweepExperiment.get_attribute_getter", "line_number": 48, "usage_type": "call"}, {"api_name": "thunderq.experiment.SweepExperiment", "line_number": 48, "usage_type": "name"}, {"api_name": "thunderq.experiment.SweepExperiment.get_attribute_setter", "line_number": 61, "usage_type": "call"}, {"api_name": "thunderq.experiment.SweepExperiment", "line_number": 61, "usage_type": "name"}, {"api_name": "thunderq.experiment.Sweep1DExperiment", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 69, "usage_type": "call"}, {"api_name": "unittest.mock.call", "line_number": 74, "usage_type": "call"}, {"api_name": "thunderq.experiment.Sweep2DExperiment", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 83, "usage_type": "call"}, {"api_name": "unittest.mock.call", "line_number": 94, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 96, "usage_type": "call"}, {"api_name": "unittest.mock.call", "line_number": 96, "usage_type": "call"}]} +{"seq_id": "25171366893", "text": "import pygame\r\nfrom random import randint\r\n\r\n\r\nclass Stars(pygame.sprite.Sprite):\r\n\r\n def __init__(self, game):\r\n super().__init__()\r\n self.game = game\r\n self.image = pygame.image.load(\"Images/Stars.png\")\r\n self.rect = self.image.get_rect()\r\n self.rect.x = 0 + randint(0, 1000)\r\n self.rect.y = 0 + randint(10, 575)\r\n\r\n def remove(self):\r\n self.rect = self.image.get_rect()\r\n self.rect.x = 0 + randint(0, 1000)\r\n self.rect.y = 0 + randint(10, 575)\r\n\r\n def collision(self):\r\n if self.game.check_collision(self, self.game.all_players):\r\n self.remove()\r\n # self.game.player.heal_sapin\r\n", "repo_name": "Gaetan-c/SoloSapin", "sub_path": "stars.py", "file_name": "stars.py", "file_ext": "py", "file_size_in_byte": 682, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "pygame.sprite", "line_number": 5, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 10, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 10, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 12, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 13, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 17, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 18, "usage_type": "call"}]} +{"seq_id": "73359533584", "text": "# coding: utf-8\nfrom PIL import Image, ImageDraw, ImageFont\nbase = Image.new(\"L\",(100,50),\"white\")\n\nfnt = ImageFont.truetype('C:/Users/Junwha-PC/Documents/programming/2018-PW-MakerTon/asdf.ttf', 50)\nd = ImageDraw.Draw(base)\ntxt = \"안\"\n\nd.text((0,0), txt, fill='black', font=fnt)\nbase.convert(\"L\").show()\n# pixels = base.load()\n# print('const char pixels[] = {')\n# w, h = base.size \n# for y in range(h):\n# print('\\t'),\n# for x in range(w):\n# print(hex(pixels[x,y]), end = '')\n# print(',', end = '')\n# print()\n# print('};')\n\n", "repo_name": "junwha0511/2018-PW-MakerThon", "sub_path": "fontImage.py", "file_name": "fontImage.py", "file_ext": "py", "file_size_in_byte": 555, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "PIL.Image.new", "line_number": 3, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 3, "usage_type": "name"}, {"api_name": "PIL.ImageFont.truetype", "line_number": 5, "usage_type": "call"}, {"api_name": "PIL.ImageFont", "line_number": 5, "usage_type": "name"}, {"api_name": "PIL.ImageDraw.Draw", "line_number": 6, "usage_type": "call"}, {"api_name": "PIL.ImageDraw", "line_number": 6, "usage_type": "name"}]} +{"seq_id": "28231992324", "text": "\"\"\"empty message\n\nRevision ID: 2be60b01c844\nRevises: 1488d90762b2\nCreate Date: 2019-05-08 08:23:55.823878\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '2be60b01c844'\ndown_revision = '1488d90762b2'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('Account', sa.Column('admin', sa.Boolean(), server_default='False', nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('Account', 'admin')\n # ### end Alembic commands ###\n", "repo_name": "baldurfb/lokaverkefni-2019v", "sub_path": "migrations/versions/2be60b01c844_.py", "file_name": "2be60b01c844_.py", "file_ext": "py", "file_size_in_byte": 676, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "alembic.op.add_column", "line_number": 21, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 21, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 21, "usage_type": "call"}, {"api_name": "sqlalchemy.Boolean", "line_number": 21, "usage_type": "call"}, {"api_name": "alembic.op.drop_column", "line_number": 27, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 27, "usage_type": "name"}]} +{"seq_id": "29810503092", "text": "from kivy.app import App\nfrom kivy.uix.label import Label\nfrom kivy.uix.button import Button\nfrom kivy.uix.checkbox import CheckBox\nfrom kivy.uix.boxlayout import BoxLayout\n\n\nclass MainApp(App):\n def build(self):\n layout = BoxLayout(orientation =\"vertical\")\n label = Label(text=x,\n size_hint=(.5, .5),\n pos_hint={'center_x': .5, 'center_y': .5})\n layout.add_widget(label)\n label2 = Label(text=\"hello assem\",\n size_hint=(.1, .1),\n pos_hint={'center_x': .1, 'center_y': .2})\n layout.add_widget(label2)\n # layout.clear_widgets()\n button = Button(text='Hello world', size_hint=(.1, .1),\n pos_hint={'x': .1, 'y': .1})\n\n layout.add_widget(button)\n button2 = Button(text='Hello world', size_hint=(.1, .1),\n pos_hint={'x': .1, 'y': .1})\n\n layout.add_widget(button2)\n\n return layout\n\n\nif __name__ == '__main__':\n app = MainApp()\n app.run()\n", "repo_name": "ahmedelarabykhaled/machine-learning-weather-forecasting", "sub_path": "tariningMobile.py", "file_name": "tariningMobile.py", "file_ext": "py", "file_size_in_byte": 1050, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "kivy.app.App", "line_number": 8, "usage_type": "name"}, {"api_name": "kivy.uix.boxlayout.BoxLayout", "line_number": 10, "usage_type": "call"}, {"api_name": "kivy.uix.label.Label", "line_number": 11, "usage_type": "call"}, {"api_name": "kivy.uix.label.Label", "line_number": 15, "usage_type": "call"}, {"api_name": "kivy.uix.button.Button", "line_number": 20, "usage_type": "call"}, {"api_name": "kivy.uix.button.Button", "line_number": 24, "usage_type": "call"}]} +{"seq_id": "40289443959", "text": "from urllib.parse import quote\n\nimport pymysql\nfrom pyquery import PyQuery as pq\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nKEYWORD = 'ipad'\nMAX_PAGE = 3\n# 设置缓存和禁用图片加载的功能\nSERVICE_ARGS = ['--load-images=false', '--disk-cache=true']\n# 使用phantomjs打开\ndriver = webdriver.PhantomJS(\n executable_path=r\"D:\\Python\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe\", service_args=SERVICE_ARGS)\n# driver = webdriver.PhantomJS(service_args=SERVICE_ARGS)\n# driver = webdriver.Chrome()\n\nwait = WebDriverWait(driver, 10)\nproducts = []\n\n\ndef index_page(page):\n \"\"\"\n 抓取索引页\n :param page: 页码\n \"\"\"\n print('正在爬取第', page, '页')\n try:\n url = 'https://s.taobao.com/search?q=' + quote(KEYWORD)\n driver.get(url)\n if page > 1:\n input = wait.until(\n EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-pager div.form > input')))\n submit = wait.until(\n EC.element_to_be_clickable((By.CSS_SELECTOR, '#mainsrp-pager div.form > span.btn.J_Submit')))\n input.clear()\n input.send_keys(page)\n submit.click()\n wait.until(\n EC.text_to_be_present_in_element((By.CSS_SELECTOR, '#mainsrp-pager li.item.active > span'), str(page)))\n wait.until(EC.presence_of_element_located(\n (By.CSS_SELECTOR, '.m-itemlist .items .item')))\n get_products()\n except TimeoutException:\n index_page(page)\n\n\ndef get_products():\n \"\"\"\n 提取商品数据\n \"\"\"\n html = driver.page_source\n doc = pq(html)\n # print('+++++++++++++++++++++++++++doc+++++++++++++++++++++', doc)\n items = doc('#mainsrp-itemlist .items .item').items()\n # print(\"itemsType\\n\",type(items))\n\n for item in items:\n # print(\"itemType\\n\",type(item))\n # print(\"===============item===============\",item)\n product = {\n 'image': item.find('.pic .img').attr('data-src'),\n 'price': item.find('.price').text(),\n 'deal': item.find('.deal-cnt').text(),\n 'title': item.find('.title').text(),\n 'shop': item.find('.shop').text(),\n 'location': item.find('.location').text()\n }\n products.append(product)\n # print(len(products))\n # print(products)\n save_to_mysql(products)\n\n\ndef save_to_mysql(products):\n # print('连接到mysql服务器...')\n mydb = pymysql.connect(host='localhost', user='root',\n passwd='123456', db='spider', port=3306, charset='utf8')\n cursor = mydb.cursor()\n # print('连接上了!')\n cursor.execute(\"DROP TABLE IF EXISTS taoBaoData\")\n createTableSql = \"\"\"CREATE TABLE taoBaoData (\n id int NOT NULL,\n title CHAR(100),\n price CHAR(10),\n deal CHAR(20),\n shop CHAR(50),\n location CHAR(30),\n image CHAR(200)\n )\n \"\"\"\n cursor.execute(createTableSql)\n i = 0\n for product in products:\n i = i + 1\n cursor.execute(\n 'insert into taoBaoData (id,title, price, deal,shop, location,image) VALUES (\"{0}\", \"{1}\", \"{2}\", \"{3}\", \"{4}\",\"{5}\",\"{6}\");'.format(\n i, product[\"title\"], product[\"price\"], product[\n \"deal\"], product[\"shop\"], product[\"location\"],\n product[\"image\"]))\n\n # data=(product[\"title\"], product[\"price\"], product[\"deal\"],\n # product[\"shop\"], product[\"location\"], product[\"image\"])\n print(\"==========第{}条数据插入成功============\".format(i))\n mydb.commit()\n mydb.close()\n\n\ndef main():\n \"\"\"\n 遍历每一页\n \"\"\"\n\n for i in range(1, MAX_PAGE + 1):\n index_page(i)\n print(\"插入完成\")\n driver.close()\n\n\nif __name__ == '__main__':\n main()\n", "repo_name": "isscal/mypycode", "sub_path": "connerMysql.py", "file_name": "connerMysql.py", "file_ext": "py", "file_size_in_byte": 4007, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "selenium.webdriver.PhantomJS", "line_number": 16, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 16, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.wait.WebDriverWait", "line_number": 21, "usage_type": "call"}, {"api_name": "urllib.parse.quote", "line_number": 32, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions.presence_of_element_located", "line_number": 36, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 36, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CSS_SELECTOR", "line_number": 36, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 36, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.expected_conditions.element_to_be_clickable", "line_number": 38, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 38, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CSS_SELECTOR", "line_number": 38, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 38, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.expected_conditions.text_to_be_present_in_element", "line_number": 43, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 43, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CSS_SELECTOR", "line_number": 43, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 43, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.expected_conditions.presence_of_element_located", "line_number": 44, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 44, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CSS_SELECTOR", "line_number": 45, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 45, "usage_type": "name"}, {"api_name": "selenium.common.exceptions.TimeoutException", "line_number": 47, "usage_type": "name"}, {"api_name": "pyquery.PyQuery", "line_number": 56, "usage_type": "call"}, {"api_name": "pymysql.connect", "line_number": 80, "usage_type": "call"}]} +{"seq_id": "33120141967", "text": "#!/usr/bin/python3\n\nfrom kafka import KafkaConsumer\nfrom subprocess import call\nfrom zkstate import ZKState\nimport traceback\nimport socket\nimport time\nimport os\n\ntopic=\"video_curation_sched\"\ngroupid=\"curaters\"\nclientid=socket.gethostname()\n\nkkhost=os.environ[\"KKHOST\"]\nvdhost=os.environ[\"VDHOST\"]\ndbhost=os.environ[\"DBHOST\"]\n\nwhile True:\n try:\n c=KafkaConsumer(topic,bootstrap_servers=kkhost,\n client_id=clientid, group_id=groupid, auto_offset_reset=\"earliest\",\n api_version=(0,10))\n\n for msg in c:\n mode,clip_name=msg.value.decode('utf-8').split(\",\")\n zk=ZKState(\"/state/\"+clip_name,mode)\n if not zk.processed():\n if zk.process_start():\n\n print(\"Processing \"+clip_name+\":\"+mode+\"...\", flush=True)\n while True:\n print(\"Downloading \"+clip_name, flush=True)\n sts=call([\"/usr/bin/wget\",\"-O\",clip_name,vdhost+\"/mp4/\"+clip_name])\n if sts==0: break\n time.sleep(1)\n\n call([\"/opt/gstreamer_gva/metaData_extract\",\"-i\",clip_name,\"-n\",\"-x\",mode,\"-a\",dbhost,\"-l\"])\n os.remove(clip_name)\n zk.process_end()\n zk.close()\n\n except:\n print(traceback.format_exc(), flush=True)\n", "repo_name": "OpenVisualCloud/Video-Curation-Sample", "sub_path": "ingest/ingest.py", "file_name": "ingest.py", "file_ext": "py", "file_size_in_byte": 1355, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 19, "dataset": "github-code", "pt": "48", "api": [{"api_name": "socket.gethostname", "line_number": 13, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 16, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 17, "usage_type": "attribute"}, {"api_name": "kafka.KafkaConsumer", "line_number": 21, "usage_type": "call"}, {"api_name": "zkstate.ZKState", "line_number": 27, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 34, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 36, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 38, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 39, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 44, "usage_type": "call"}]} +{"seq_id": "11111046242", "text": "import numpy as np\nfrom matplotlib import cm\nfrom torchvision import utils\n\n\ndef visualize_kernels(tensor, ch=0, allkernels=False, nrow=8, padding=1):\n tensor = tensor.detach().cpu()\n if tensor.ndim == 2:\n tensor = tensor.unsqueeze(0).unsqueeze(1)\n n, c, w, h = tensor.shape\n\n grayscale = False\n\n if allkernels:\n tensor = tensor.view(n * c, -1, w, h)\n elif c != 3:\n tensor = tensor[:, ch, :, :].unsqueeze(dim=1)\n grayscale = True\n\n grid = utils.make_grid(tensor, nrow=nrow, normalize=True, padding=padding)\n grid = grid.numpy().transpose((1, 2, 0))\n\n if grayscale:\n grid = grid[:, :, 0]\n grid = cm.Spectral_r(grid)[..., :3]\n return grid\n", "repo_name": "fagp/sinkhorn-rebasin", "sub_path": "examples/utils/visualization.py", "file_name": "visualization.py", "file_ext": "py", "file_size_in_byte": 709, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "48", "api": [{"api_name": "torchvision.utils.make_grid", "line_number": 20, "usage_type": "call"}, {"api_name": "torchvision.utils", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.cm.Spectral_r", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.cm", "line_number": 25, "usage_type": "name"}]} +{"seq_id": "4440050537", "text": "import argparse\nimport bisect\nfrom collections import defaultdict\nimport datetime\nfrom math import pi\n\nimport bokeh.plotting as bokeh_plotting # import figure, output_file, show, ColumnDataSource\nimport bokeh.models as bokeh_models # import HoverTool, DatetimeTickFormatter\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-i\", \"--interval\", default=5, type=int, help=\"time intervals in minutes; defaults to 5 minutes\")\nrequired = parser.add_argument_group('Required')\nrequired.add_argument(\"-f\", \"--file\", type=str, required=True, help=\"datafile\")\nrequired.add_argument(\"-s\", \"--start\", type=str, required=True, help=\"start date; YYYY-mm-dd\")\nrequired.add_argument(\"-e\", \"--end\", type=str, required=True, help=\"end date; YYYY-mm-dd\")\n\n\nclass Data(object):\n\n def __init__(self, data_file, start_date, end_date, interval):\n self.data_file = data_file\n self.start_time = datetime.datetime.strptime('{} 06:00:00'.format(start_date), '%Y-%m-%d %H:%M:%S')\n self.end_time = datetime.datetime.strptime('{} 06:00:00'.format(end_date), '%Y-%m-%d %H:%M:%S')\n self.interval = interval or 5\n\n @property\n def log_entries(self):\n logs = []\n with open('{}'.format(self.data_file), 'r') as f:\n for line in f:\n logs.append(line) # .split('|')[1].strip())\n return logs\n\n @property\n def time_slots(self):\n time_slots = [str(self.start_time)]\n next_time = self.start_time + datetime.timedelta(minutes=self.interval)\n while next_time < self.end_time:\n time_slots.append(str(next_time))\n next_time = next_time + datetime.timedelta(minutes=self.interval)\n return time_slots\n\n def group_log_entries(self):\n groups = defaultdict(lambda: defaultdict(list))\n slots = self.time_slots\n for slot in slots:\n groups[slot]['time'] = slot\n for log in self.log_entries:\n idx = bisect.bisect_left(slots, log)\n groups[slots[idx - 1]]['logs'].append(log)\n return groups\n\n def add_stats_to_groups(self, groups):\n for group in groups:\n groups[group]['count'] = len(groups[group]['logs'])\n groups[group]['avg_per_min'] = groups[group]['count'] / self.interval\n groups[group]['avg_per_second'] = groups[group]['count'] / (self.interval * 60)\n return groups\n\n def get_data(self):\n groups = self.group_log_entries()\n data = self.add_stats_to_groups(groups)\n points = []\n for key in sorted(groups.keys()):\n amount = groups[key]['count']\n date = (datetime.datetime.strptime(key, '%Y-%m-%d %H:%M:%S') - datetime.timedelta(hours=6))\n points.append({\n 'x': date,\n 'y': amount,\n 'time': '{}'.format(date),\n 'count': amount,\n 'avg_per_min': groups[key]['avg_per_min'],\n 'avg_per_sec': groups[key]['avg_per_second'],\n })\n return points\n\n def print_data(self, data):\n print('TOTALS: Files Processed: {}'.format(len(logs)))\n print('{:^19} {:^5} {:^7} {:^7}'.format('Time', 'Count', 'Avg/min', 'Avg/sec'))\n for datum in data:\n print('{} {:>5} {:>7} {:>7.3f}'.format(\n datum['time'],\n datum['count'],\n datum['avg_per_min'],\n datum['avg_per_second'],\n ))\n\n\nclass Graph(object):\n\n def __init__(self, data, interval=5, out_file='graph.html'):\n self.data = data\n self.interval = interval\n self.chart = self.create_chart()\n bokeh_plotting.output_file(out_file)\n\n @property\n def source(self):\n return bokeh_plotting.ColumnDataSource(\n data=dict(\n x=[datum['x'] for datum in self.data],\n y=[datum['y'] for datum in self.data],\n time=[datum['time'] for datum in self.data],\n count=[datum['count'] for datum in self.data],\n )\n )\n\n @property\n def hover(self):\n return bokeh_models.HoverTool(\n names=['points'],\n tooltips=[\n ('Time', '@time'),\n ('Count', '@count'),\n ]\n )\n\n def create_plot(self):\n plot = bokeh_plotting.figure(\n width=1000,\n height=500,\n title='Files per {} minutes'.format(self.interval),\n x_axis_label='Time (UTC)',\n x_axis_type='datetime',\n y_axis_label='Fileprocesslog Count',\n )\n plot.add_tools(self.hover)\n plot.xaxis.formatter=bokeh_models.DatetimeTickFormatter(\n minutes=[\"%H:%M\"],\n hours=[\"%H:%M\"],\n days=[\"%Y-%m-%d\"],\n )\n plot.xaxis.major_label_orientation = pi/4\n return plot\n\n def create_line_graph(self, plot):\n plot.line(\n 'x',\n 'y',\n source=self.source,\n line_width=1,\n color='gray'\n )\n return plot\n\n def create_circle_graph(self, plot):\n plot.circle(\n 'x',\n 'y',\n name='points',\n source=self.source,\n line_color='olive',\n legend='Files Processed'\n )\n return plot\n\n def create_chart(self):\n plot = self.create_plot()\n plot = self.create_line_graph(plot)\n plot = self.create_circle_graph(plot)\n return plot\n\n def output_chart(self):\n bokeh_plotting.show(self.chart)\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n data = Data(args.file, args.start, args.end, args.interval).get_data()\n chart = Graph(data, interval=args.interval)\n chart.output_chart()\n", "repo_name": "voidnologo/bokeh_graph", "sub_path": "gen_chart.py", "file_name": "gen_chart.py", "file_ext": "py", "file_size_in_byte": 5796, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 11, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 23, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 23, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 24, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 24, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 38, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 41, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 45, "usage_type": "call"}, {"api_name": "bisect.bisect_left", "line_number": 50, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 67, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 67, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 67, "usage_type": "call"}, {"api_name": "bokeh.plotting.output_file", "line_number": 96, "usage_type": "call"}, {"api_name": "bokeh.plotting", "line_number": 96, "usage_type": "name"}, {"api_name": "bokeh.plotting.ColumnDataSource", "line_number": 100, "usage_type": "call"}, {"api_name": "bokeh.plotting", "line_number": 100, "usage_type": "name"}, {"api_name": "bokeh.models.HoverTool", "line_number": 111, "usage_type": "call"}, {"api_name": "bokeh.models", "line_number": 111, "usage_type": "name"}, {"api_name": "bokeh.plotting.figure", "line_number": 120, "usage_type": "call"}, {"api_name": "bokeh.plotting", "line_number": 120, "usage_type": "name"}, {"api_name": "bokeh.models.DatetimeTickFormatter", "line_number": 129, "usage_type": "call"}, {"api_name": "bokeh.models", "line_number": 129, "usage_type": "name"}, {"api_name": "math.pi", "line_number": 134, "usage_type": "name"}, {"api_name": "bokeh.plotting.show", "line_number": 165, "usage_type": "call"}, {"api_name": "bokeh.plotting", "line_number": 165, "usage_type": "name"}]} +{"seq_id": "73892317585", "text": "import boto3\nfrom pprint import pprint\nimport json\ntrust_relationship_policy = {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": { \"AWS\": \"arn:aws:iam::##############:user/####\" },\n \"Action\": \"sts:AssumeRole\",\n }\n\n ]\n\n}\n\niam = boto3.client(\"iam\")\niam.create_role(\n RoleName = \"my_s3_role\",\n AssumeRolePolicyDocument = json.dumps(trust_relationship_policy)\n)\nresponse = iam.list_policies()\nArn = response['Policies'][0]['Arn']\nresponse = iam.attach_role_policy(\n RoleName = \"my_s3_role\",\n PolicyArn = Arn\n)\npprint(response)\n\n", "repo_name": "HarryChen1995/AWS", "sub_path": "iam/add_iam_role.py", "file_name": "add_iam_role.py", "file_ext": "py", "file_size_in_byte": 626, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "boto3.client", "line_number": 17, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 20, "usage_type": "call"}, {"api_name": "pprint.pprint", "line_number": 28, "usage_type": "call"}]} +{"seq_id": "17759252123", "text": "# SERVER SETUP\nfrom fastapi import FastAPI\nfrom fastapi.responses import HTMLResponse\nfrom fastapi.staticfiles import StaticFiles\nimport uvicorn\n\nfrom api.EaseMyTrip import Auth\n# from api.EaseMyTrip import EaseMyTrip\n\n\n# GENERAL IMPORTS\nimport os\nimport colorama\nimport requests\nfrom pathlib import Path\n\nimport modulex as mx\n\n# INITIALIZE\ncolorama.init()\napp = FastAPI()\n\n\n@app.get(\"/\",response_class=HTMLResponse)\nasync def home():\n return mx.fread('./dev/index.html')\n\n\n@app.get(\"/api\")\ndef apihome():\n return {\"Hello\": 'This the the home of api Router '}\n\n\n@app.get('/api/fs')\ndef get_flights(src,dst,fromdate):\n url = \"https://stagingapi.easemytrip.com/Flight.svc/json/FlightSearch\"\n data = {\n \"Adults\": \"1\",\n \"Childs\": \"0\",\n \"Infants\": \"0\",\n **Auth.test,\n \"TraceId\": \"\",\n \"EngineID\": [\n \"0\",\n \"1\",\n \"5\",\n \"6\",\n \"7\",\n \"10\",\n \"11\",\n ],\n \"FlightSearchDetails\": [\n {\n \"BeginDate\": fromdate,\n \"Origin\": src,\n \"Destination\": dst,\n },\n ],\n \"TripType\": 1,\n \"Cabin\": 0\n }\n # print(mx.jdumps(data))\n r = requests.post(url, json=data)\n return r.json()\n # return {\"r.json()\",\"asdasd\"}\n\n\nif __name__ == \"__main__\":\n app.mount(\"/dev/\", StaticFiles(directory=Path(__file__).parent, html = True), name=\"site\")\n uvicorn.run('main:app', reload=True, workers=2)\n", "repo_name": "BinarySwami-10/WEB_LIPI_FBT", "sub_path": "www.fastholidayz.com/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1520, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "colorama.init", "line_number": 20, "usage_type": "call"}, {"api_name": "fastapi.FastAPI", "line_number": 21, "usage_type": "call"}, {"api_name": "modulex.fread", "line_number": 26, "usage_type": "call"}, {"api_name": "fastapi.responses.HTMLResponse", "line_number": 24, "usage_type": "name"}, {"api_name": "api.EaseMyTrip.Auth.test", "line_number": 41, "usage_type": "attribute"}, {"api_name": "api.EaseMyTrip.Auth", "line_number": 41, "usage_type": "name"}, {"api_name": "requests.post", "line_number": 63, "usage_type": "call"}, {"api_name": "fastapi.staticfiles.StaticFiles", "line_number": 69, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 69, "usage_type": "call"}, {"api_name": "uvicorn.run", "line_number": 70, "usage_type": "call"}]} +{"seq_id": "5460133577", "text": "import datetime\nimport random\nimport tempfile\nimport time\nimport uuid\nfrom datetime import datetime, timedelta\nimport numpy as np\nimport pytest\nimport requests\nfrom nomic import AtlasProject, atlas\n\n\ndef gen_random_datetime(min_year=1900, max_year=datetime.now().year):\n # generate a datetime in format yyyy-mm-dd hh:mm:ss.000000\n start = datetime(min_year, 1, 1, 00, 00, 00)\n years = max_year - min_year + 1\n end = start + timedelta(days=365 * years)\n return start + (end - start) * random.random()\n\n\ndef test_map_idless_embeddings():\n num_embeddings = 50\n embeddings = np.random.rand(num_embeddings, 512)\n\n response = atlas.map_embeddings(embeddings=embeddings)\n print(response)\n\n\ndef test_map_embeddings_with_errors():\n num_embeddings = 20\n embeddings = np.random.rand(num_embeddings, 10)\n\n # test nested dictionaries\n with pytest.raises(Exception):\n data = [{'key': {'nested_key': 'nested_value'}} for i in range(len(embeddings))]\n response = atlas.map_embeddings(\n embeddings=embeddings, data=data, name='UNITTEST1', is_public=True, reset_project_if_exists=True\n )\n\n # test underscore\n with pytest.raises(Exception):\n data = [{'__hello': {'hello'}} for i in range(len(embeddings))]\n response = atlas.map_embeddings(\n embeddings=embeddings, data=data, name='UNITTEST1', is_public=True, reset_project_if_exists=True\n )\n\n # test to long ids\n with pytest.raises(Exception):\n data = [{'id': str(uuid.uuid4()) + 'a'} for i in range(len(embeddings))]\n response = atlas.map_embeddings(\n embeddings=embeddings,\n data=data,\n name='UNITTEST1',\n id_field='id',\n is_public=True,\n reset_project_if_exists=True,\n )\n\n\ndef test_map_embeddings():\n num_embeddings = 20\n embeddings = np.random.rand(num_embeddings, 10)\n data = [{'field': str(uuid.uuid4()), 'id': str(uuid.uuid4())} for i in range(len(embeddings))]\n\n project = atlas.map_embeddings(\n embeddings=embeddings,\n name='UNITTEST1',\n id_field='id',\n data=data,\n is_public=True,\n reset_project_if_exists=True,\n )\n\n map = project.get_map(name='UNITTEST1')\n\n time.sleep(10)\n with tempfile.TemporaryDirectory() as td:\n retrieved_embeddings = map.download_embeddings(td)\n\n assert project.total_datums == num_embeddings\n\n project = AtlasProject(name='UNITTEST1')\n map = project.get_map(name='UNITTEST1')\n\n project.create_index(name='My new index')\n with project.wait_for_project_lock():\n neighbors, _ = map.vector_search(queries=np.random.rand(1, 10), k=2)\n assert len(neighbors[0]) == 2\n\n for map in project.projections:\n assert map.map_link\n\n map.tag(ids=[data[0]['id']], tags=['my_tag'])\n\n assert len(map.get_tags()['my_tag']) == 1\n\n map.remove_tags(ids=[data[0]['id']], tags=['my_tag'])\n\n assert 'my_tag' not in map.get_tags()\n\n project.delete()\n\n\ndef test_date_metadata():\n num_embeddings = 20\n embeddings = np.random.rand(num_embeddings, 10)\n data = [{'my_date': datetime.datetime(2022, 1, i),\n 'my_random_date': gen_random_datetime()} for i in range(1, len(embeddings) + 1)]\n\n project = atlas.map_embeddings(\n embeddings=embeddings, name='test_date_metadata', data=data, is_public=True, reset_project_if_exists=True\n )\n\n assert project.id\n\n project.delete()\n\n # put an invalid iso timestamp after the first valid isotimestamp , make sure the client fails\n with pytest.raises(Exception):\n data[1]['my_date'] = data[1]['my_date'] + 'asdf'\n project = atlas.map_embeddings(\n embeddings=embeddings,\n name='UNITTEST1',\n id_field='id',\n data=data,\n is_public=True,\n reset_project_if_exists=True,\n )\n\n\ndef test_map_text_errors():\n # no indexed field\n with pytest.raises(Exception):\n project = atlas.map_text(\n data=[{'key': 'a'}],\n indexed_field='text',\n is_public=True,\n name='test_map_text_errors',\n description='test map description',\n reset_project_if_exists=True,\n )\n\n\ndef test_map_embedding_progressive():\n num_embeddings = 100\n embeddings = np.random.rand(num_embeddings, 10)\n data = [{'field': str(uuid.uuid4()), 'id': str(uuid.uuid4()), 'upload': 0.0} for i in range(len(embeddings))]\n\n project = atlas.map_embeddings(\n embeddings=embeddings,\n name='test_map_embedding_progressive',\n id_field='id',\n data=data,\n is_public=True,\n build_topic_model=False,\n reset_project_if_exists=True,\n )\n\n embeddings = np.random.rand(num_embeddings, 10) + np.ones(shape=(num_embeddings, 10))\n data = [{'field': str(uuid.uuid4()), 'id': str(uuid.uuid4()), 'upload': 1.0} for i in range(len(embeddings))]\n\n current_project = AtlasProject(name=project.name)\n\n with current_project.wait_for_project_lock():\n project = atlas.map_embeddings(\n embeddings=embeddings,\n name=current_project.name,\n colorable_fields=['upload'],\n id_field='id',\n data=data,\n build_topic_model=False,\n is_public=True,\n add_datums_if_exists=True,\n )\n with pytest.raises(Exception):\n # Try adding a bad field.\n with current_project.wait_for_project_lock():\n data = [{'invalid_field': str(uuid.uuid4()), 'id': str(uuid.uuid4()), 'upload': 1.0} for i in\n range(len(embeddings))]\n\n current_project = AtlasProject(name=project.name)\n\n with current_project.wait_for_project_lock():\n project = atlas.map_embeddings(\n embeddings=embeddings,\n name=current_project.name,\n colorable_fields=['upload'],\n id_field='id',\n data=data,\n build_topic_model=False,\n is_public=True,\n add_datums_if_exists=True,\n )\n\n current_project.delete()\n\n\ndef test_topics():\n num_embeddings = 100\n embeddings = np.random.rand(num_embeddings, 10)\n texts = ['foo', 'bar', 'baz', 'bat']\n data = [{'field': str(uuid.uuid4()), 'id': str(uuid.uuid4()), 'upload': 0.0, 'text': texts[i % 4]}\n for i in range(len(embeddings))]\n\n p = atlas.map_embeddings(\n embeddings=embeddings,\n name='test_topics',\n id_field='id',\n data=data,\n is_public=True,\n build_topic_model=True,\n topic_label_field='text',\n reset_project_if_exists=True,\n )\n\n with p.wait_for_project_lock():\n assert len(p.maps[0].get_topic_data()) > 0\n\n q = np.random.random((3, 10))\n assert len(p.maps[0].vector_search_topics(q, depth=1, k=3)['topics']) == 3\n p.delete()\n\n\nwords = [\n 'foo', 'bar', 'baz', 'bat',\n 'glorp', 'gloop', 'glib', 'glub',\n 'florp', 'floop', 'flib', 'flub',\n 'blorp', 'bloop', 'blib', 'blub',\n 'slorp', 'sloop', 'slib', 'slub',\n 'clorp', 'cloop', 'clib', 'club',\n 'plorp', 'ploop', 'plib', 'plub',\n 'zlorp', 'zloop', 'zlib', 'zlub',\n 'xlorp', 'xloop', 'xlib', 'xlub',\n 'vlorp', 'vloop', 'vlib', 'vlub',\n 'nlorp', 'nloop', 'nlib', 'nlub',\n 'mlorp', 'mloop', 'mlib', 'mlub'\n]\n\n\ndef test_interactive_workflow():\n p = AtlasProject(name='UNITTEST1',\n modality='text',\n unique_id_field='id',\n reset_project_if_exists=True\n )\n\n p.add_text(data=[{'text': random.choice(words), 'id': i} for i in range(100)])\n\n p.create_index(name='UNITTEST1',\n indexed_field='text',\n build_topic_model=True\n )\n\n assert p.total_datums == 100\n\n # Test ability to add more data to a project and have the ids coerced.\n with p.wait_for_project_lock():\n p.add_text(data=[{'text': random.choice(words), 'id': i} for i in range(100, 200)])\n p.create_index(name='UNITTEST1',\n indexed_field='text',\n build_topic_model=True\n )\n assert p.total_datums == 200\n\n with p.wait_for_project_lock():\n p.delete()\n\n\ndef test_weird_inputs():\n \"\"\"\n Check that null and empty strings do not block an index build.\n \"\"\"\n p = AtlasProject(\n name='test_weird_inputs',\n modality='text',\n unique_id_field='id',\n reset_project_if_exists=True\n )\n\n elements = []\n for i in range(20):\n if i % 3 == 0 and i % 5 == 0:\n elements.append({'text': 'fizzbuzz', 'id': str(i)})\n elif i % 3 == 0:\n elements.append({'text': 'fizz', 'id': str(i)})\n elif i % 5 == 0:\n elements.append({'text': 'buzz', 'id': str(i)})\n elif i % 7 == 0:\n elements.append({'text': None, 'id': str(i)})\n elif i % 2 == 0:\n elements.append({'text': '', 'id': str(i)})\n else:\n elements.append({'text': 'foo', 'id': str(i)})\n p.add_text(data=elements)\n p.create_index(\n name='test_weird_inputs',\n indexed_field='text',\n build_topic_model=True\n )\n with p.wait_for_project_lock():\n assert True", "repo_name": "qmeng222/MovieVista", "sub_path": "env/lib/python3.10/site-packages/nomic/tests/test_atlas_client.py", "file_name": "test_atlas_client.py", "file_ext": "py", "file_size_in_byte": 9409, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "datetime.datetime.now", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 13, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 15, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 17, "usage_type": "call"}, {"api_name": "random.random", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 23, "usage_type": "attribute"}, {"api_name": "nomic.atlas.map_embeddings", "line_number": 25, "usage_type": "call"}, {"api_name": "nomic.atlas", "line_number": 25, "usage_type": "name"}, {"api_name": "numpy.random.rand", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 31, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 34, "usage_type": "call"}, {"api_name": "nomic.atlas.map_embeddings", "line_number": 36, "usage_type": "call"}, {"api_name": "nomic.atlas", "line_number": 36, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 41, "usage_type": "call"}, {"api_name": "nomic.atlas.map_embeddings", "line_number": 43, "usage_type": "call"}, {"api_name": "nomic.atlas", "line_number": 43, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 48, "usage_type": "call"}, {"api_name": "uuid.uuid4", "line_number": 49, "usage_type": "call"}, {"api_name": "nomic.atlas.map_embeddings", "line_number": 50, "usage_type": "call"}, {"api_name": "nomic.atlas", "line_number": 50, "usage_type": "name"}, {"api_name": "numpy.random.rand", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 62, "usage_type": "attribute"}, {"api_name": "uuid.uuid4", "line_number": 63, "usage_type": "call"}, {"api_name": "nomic.atlas.map_embeddings", "line_number": 65, "usage_type": "call"}, {"api_name": "nomic.atlas", "line_number": 65, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 76, "usage_type": "call"}, {"api_name": "tempfile.TemporaryDirectory", "line_number": 77, "usage_type": "call"}, {"api_name": "nomic.AtlasProject", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 87, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 106, "usage_type": "attribute"}, {"api_name": "datetime.datetime.datetime", "line_number": 107, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 107, "usage_type": "name"}, {"api_name": "nomic.atlas.map_embeddings", "line_number": 110, "usage_type": "call"}, {"api_name": "nomic.atlas", "line_number": 110, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 119, "usage_type": "call"}, {"api_name": "nomic.atlas.map_embeddings", "line_number": 121, "usage_type": "call"}, {"api_name": "nomic.atlas", "line_number": 121, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 133, "usage_type": "call"}, {"api_name": "nomic.atlas.map_text", "line_number": 134, "usage_type": "call"}, {"api_name": "nomic.atlas", "line_number": 134, "usage_type": "name"}, {"api_name": "numpy.random.rand", "line_number": 146, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 146, "usage_type": "attribute"}, {"api_name": "uuid.uuid4", "line_number": 147, "usage_type": "call"}, {"api_name": "nomic.atlas.map_embeddings", "line_number": 149, "usage_type": "call"}, {"api_name": "nomic.atlas", "line_number": 149, "usage_type": "name"}, {"api_name": "numpy.random.rand", "line_number": 159, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 159, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 159, "usage_type": "call"}, {"api_name": "uuid.uuid4", "line_number": 160, "usage_type": "call"}, {"api_name": "nomic.AtlasProject", "line_number": 162, "usage_type": "call"}, {"api_name": "nomic.atlas.map_embeddings", "line_number": 165, "usage_type": "call"}, {"api_name": "nomic.atlas", "line_number": 165, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 175, "usage_type": "call"}, {"api_name": "uuid.uuid4", "line_number": 178, "usage_type": "call"}, {"api_name": "nomic.AtlasProject", "line_number": 181, "usage_type": "call"}, {"api_name": "nomic.atlas.map_embeddings", "line_number": 184, "usage_type": "call"}, {"api_name": "nomic.atlas", "line_number": 184, "usage_type": "name"}, {"api_name": "numpy.random.rand", "line_number": 200, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 200, "usage_type": "attribute"}, {"api_name": "uuid.uuid4", "line_number": 202, "usage_type": "call"}, {"api_name": "nomic.atlas.map_embeddings", "line_number": 205, "usage_type": "call"}, {"api_name": "nomic.atlas", "line_number": 205, "usage_type": "name"}, {"api_name": "numpy.random.random", "line_number": 219, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 219, "usage_type": "attribute"}, {"api_name": "nomic.AtlasProject", "line_number": 241, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 247, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 258, "usage_type": "call"}, {"api_name": "nomic.AtlasProject", "line_number": 273, "usage_type": "call"}]} +{"seq_id": "9922319104", "text": "import argparse\nfrom textbox import run_textbox\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--model', '-m', type=str, default='BART', help='name of models')\n parser.add_argument('--dataset', '-d', type=str, default='samsum', help='name of datasets')\n parser.add_argument('--config_files', type=str, nargs='*', default=list(), help='config files')\n\n args, _ = parser.parse_known_args()\n\n run_textbox(model=args.model, dataset=args.dataset, config_file_list=args.config_files, config_dict={})\n", "repo_name": "RUCAIBox/TextBox", "sub_path": "run_textbox.py", "file_name": "run_textbox.py", "file_ext": "py", "file_size_in_byte": 551, "program_lang": "python", "lang": "fa", "doc_type": "code", "stars": 1031, "dataset": "github-code", "pt": "48", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 5, "usage_type": "call"}, {"api_name": "textbox.run_textbox", "line_number": 12, "usage_type": "call"}]} +{"seq_id": "31818927024", "text": "from __future__ import print_function\n\nimport argparse\nimport os.path\nimport distutils.util\n\nclass ComLine():\n\t'Class for implementing command line options'\n\n\n\tdef __init__(self, args):\n\t\tparser = argparse.ArgumentParser()\n\t\tparser._action_groups.pop()\n\t\trequired = parser.add_argument_group('required arguments')\n\t\toptional = parser.add_argument_group('optional arguments')\n\t\topt_admix = parser.add_argument_group('Admixture optional arguments')\n\t\topt_plink = parser.add_argument_group('plink optional arguments')\n\t\topt_vcf = parser.add_argument_group('VCFtools optional arguments')\n\t\trequired.add_argument(\"-m\", \"--popmap\",\n\t\t\t\t\t\t\tdest='popmap',\n\t\t\t\t\t\t\trequired=True,\n\t\t\t\t\t\t\thelp=\"Specify a tab-delimited population map (sample -> population)\"\n\t\t)\n\t\trequired.add_argument(\"-v\", \"--vcf\",\n\t\t\t\t\t\t\tdest='vcf',\n\t\t\t\t\t\t\trequired=True,\n\t\t\t\t\t\t\thelp=\"Specify a vcf file for input.\"\n\t\t)\n\t\topt_admix.add_argument(\"-k\", \"--minK\",\n\t\t\t\t\t\t\tdest='minK',\n\t\t\t\t\t\t\ttype=int,\n\t\t\t\t\t\t\tdefault=1,\n\t\t\t\t\t\t\thelp=\"minimum K value.\"\n\t\t)\n\t\topt_admix.add_argument(\"-K\", \"--maxK\",\n\t\t\t\t\t\t\tdest='maxK',\n\t\t\t\t\t\t\ttype=int,\n\t\t\t\t\t\t\tdefault=20,\n\t\t\t\t\t\t\thelp=\"maximum K value.\"\n\t\t)\n\t\topt_vcf.add_argument(\"-M\", \"--mac\",\n\t\t\t\t\tdest='mac',\n\t\t\t\t\ttype=int,\n\t\t\t\t\tdefault=0,\n\t\t\t\t\thelp=\"Enter the minimum count for the minor allele filter.\"\n\t\t)\n\n\t\topt_vcf.add_argument(\"-a\", \"--maf\",\n\t\t\t\t\t\t\tdest='maf',\n\t\t\t\t\t\t\ttype=float,\n\t\t\t\t\t\t\tdefault=0.0,\n\t\t\t\t\t\t\thelp=\"Enter the minimum frequency for the minor allele filter.\"\n\t\t)\n\t\toptional.add_argument(\"-n\", \"--np\",\n\t\t\t\t\t\t\tdest='np',\n\t\t\t\t\t\t\ttype=int,\n\t\t\t\t\t\t\tdefault=1,\n\t\t\t\t\t\t\thelp=\"Number of processors.\"\n\t\t)\n\t\topt_vcf.add_argument(\"-t\", \"--thin\",\n\t\t\t\t\t\t\tdest='thin',\n\t\t\t\t\t\t\ttype=int,\n\t\t\t\t\t\t\tdefault=0,\n\t\t\t\t\t\t\thelp=\"Use VCFtools to thin out loci falling within the specified proximity to one another.\"\n\t\t)\n\t\topt_vcf.add_argument(\"-r\", \"--remove\",\n\t\t\t\t\t\t\tdest='remove',\n\t\t\t\t\t\t\thelp=\"Specify a file of blacklisted individuals to have VCFtools remove from the analysis.\"\n\t\t)\n\t\topt_vcf.add_argument(\"-C\", \"--indcov\",\n\t\t\t\t\t\t\tdest='indcov',\n\t\t\t\t\t\t\ttype=float,\n\t\t\t\t\t\t\tdefault=0.9,\n\t\t\t\t\t\t\thelp=\"Specify the maximum allowable missing data per individual\"\n\t\t)\n\t\topt_vcf.add_argument(\"-S\", \"--snpcov\",\n\t\t\t\t\t\t\tdest='snpcov',\n\t\t\t\t\t\t\ttype=float,\n\t\t\t\t\t\t\tdefault=0.1,\n\t\t\t\t\t\t\thelp=\"Specify the allowable proportion of missing data per SNP. 0 allows sites that are completely missing and 1 indicates no missing data allowed.\"\n\t\t)\n\t\topt_admix.add_argument(\"-c\", \"--cv\",\n\t\t\t\t\t\t\tdest='cv',\n\t\t\t\t\t\t\ttype=int,\n\t\t\t\t\t\t\tdefault=20,\n\t\t\t\t\t\t\thelp=\"Specify the cross-validation number for admixture program\"\n\t\t)\n\t\topt_admix.add_argument(\"-R\", \"--rep\",\n\t\t\t\t\t\t\tdest='rep',\n\t\t\t\t\t\t\ttype=int,\n\t\t\t\t\t\t\tdefault=20,\n\t\t\t\t\t\t\thelp=\"Number of replicates per K.\"\n\t\t)\n\t\topt_vcf.add_argument(\"-b\", \"--bi\",\n\t\t\t\t\t\t\tdest='bi',\n\t\t\t\t\t\t\taction='store_true',\n\t\t\t\t\t\t\thelp=\"Turn off filter for biallelic SNPs.\"\n\t\t)\n\n\t\tself.args = parser.parse_args()\n\n\t\t#check if files exist\n\t\tself.exists( self.args.popmap )\n\t\tself.exists( self.args.vcf )\n\t\tif self.args.remove:\n\t\t\tself.exists( self.args.remove )\n\n\n\n\tdef exists(self, filename):\n\t\tif( os.path.isfile(filename) != True ):\n\t\t\tprint(filename, \"does not exist\")\n\t\t\tprint(\"Exiting program...\")\n\t\t\tprint(\"\")\n\t\t\traise SystemExit\n", "repo_name": "Canales-AguirreCB/admixturePipeline", "sub_path": "comline.py", "file_name": "comline.py", "file_ext": "py", "file_size_in_byte": 3207, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "48", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path.path.isfile", "line_number": 111, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 111, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 111, "usage_type": "name"}]} +{"seq_id": "20963935055", "text": "from collections import deque\n\nclass Solution:\n\n def __init__(self):\n self.paranthesis_map = {\n \"(\": \")\",\n \"[\": \"]\",\n \"{\": \"}\"\n }\n self.stack = deque()\n\n def isValid(self, s: str) -> bool:\n all_keys = self.paranthesis_map.keys()\n for char in s:\n if char in all_keys or len(self.stack) == 0:\n self.stack.append(char)\n else:\n last_ele = self.stack.pop()\n if self.paranthesis_map.get(last_ele) != char:\n return False\n \n if len(self.stack) > 0:\n return False\n\n return True\n\n\nif __name__ == \"__main__\":\n\ts = Solution()\n\tprint(s.isValid(\"([])\"))\t\n", "repo_name": "nagavenkateshgavini/coding_practice", "sub_path": "stacks/valid_paranthesis.py", "file_name": "valid_paranthesis.py", "file_ext": "py", "file_size_in_byte": 733, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "collections.deque", "line_number": 11, "usage_type": "call"}]} +{"seq_id": "21455462680", "text": "from picamera import PiCamera\nfrom gpiozero import LED, Button\nfrom time import sleep\n\nprint(\"Cerebro: Testing Camera ...\")\n\n# This assumes its a Pi platform\ncamera = PiCamera()\n\ncamera.rotation = 180\n\ncamera.start_preview()\n#camera.start_recording('/home/pi/Desktop/video.h264')\n\nsleep(5)\n\nimage_path='/tmp/project_cerebro/media/test_camera.jpg'\ncamera.capture(image_path)\n\n#camera.stop_recording()\ncamera.stop_preview()\n\nprint(\"Image is now captured and available in: %s\" % image_path)\n\nprint(\"Now, trying the green led ...\")\nled=LED(27)\nled.on()\nsleep(5)\nled.off()\n\nprint(\"Now, trying the yellow led ...\")\nled=LED(26)\nled.on()\nsleep(5)\nled.off()\n\nprint(\"finished led testing!\")\n\nprint(\"Now, trying the green button for 10 secs ...\")\nled=LED(27)\nbutton=Button(17)\nbutton.when_pressed=led.on\nbutton.when_released=led.off\nsleep(10)\nprint(\"green button/led testing completed.\")\n\nprint(\"Now, trying the yellow button for 10 secs ...\")\nled=LED(26)\nbutton=Button(16)\nbutton.when_pressed=led.on\nbutton.when_released=led.off\nsleep(10)\nprint(\"yellow button/led testing completed.\")\n\nprint(\"finished led testing!\")\n", "repo_name": "aws-samples/aws-builders-fair-projects", "sub_path": "reinvent-2019/connected-photo-booth/py_client/cerebro_test_camera_led.py", "file_name": "cerebro_test_camera_led.py", "file_ext": "py", "file_size_in_byte": 1107, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 85, "dataset": "github-code", "pt": "48", "api": [{"api_name": "picamera.PiCamera", "line_number": 8, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 15, "usage_type": "call"}, {"api_name": "gpiozero.LED", "line_number": 26, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 28, "usage_type": "call"}, {"api_name": "gpiozero.LED", "line_number": 32, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 34, "usage_type": "call"}, {"api_name": "gpiozero.LED", "line_number": 40, "usage_type": "call"}, {"api_name": "gpiozero.Button", "line_number": 41, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 44, "usage_type": "call"}, {"api_name": "gpiozero.LED", "line_number": 48, "usage_type": "call"}, {"api_name": "gpiozero.Button", "line_number": 49, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 52, "usage_type": "call"}]} +{"seq_id": "10099466220", "text": "import subprocess\n\nfrom debtcollector import removals\nimport netaddr\nfrom neutron_lib.api import validators\nfrom neutron_lib import constants as neutron_lib_constants\nfrom oslo_log import log\nfrom tempest.common.utils import net_utils\nfrom tempest.common import waiters\nfrom tempest.lib.common.utils import data_utils\nfrom tempest.lib.common.utils import test_utils\nfrom tempest.lib import exceptions as lib_exc\n\nfrom neutron_tempest_plugin.api import base as base_api\nfrom neutron_tempest_plugin.common import ssh\nfrom neutron_tempest_plugin import config\nfrom neutron_tempest_plugin.scenario import constants\n\nCONF = config.CONF\n\nLOG = log.getLogger(__name__)\n\n\nclass BaseTempestTestCase(base_api.BaseNetworkTest):\n\n def create_server(self, flavor_ref, image_ref, key_name, networks,\n **kwargs):\n \"\"\"Create a server using tempest lib\n\n All the parameters are the ones used in Compute API\n * - Kwargs that require admin privileges\n\n Args:\n flavor_ref(str): The flavor of the server to be provisioned.\n image_ref(str): The image of the server to be provisioned.\n key_name(str): SSH key to to be used to connect to the\n provisioned server.\n networks(list): List of dictionaries where each represent\n an interface to be attached to the server. For network\n it should be {'uuid': network_uuid} and for port it should\n be {'port': port_uuid}\n kwargs:\n name(str): Name of the server to be provisioned.\n security_groups(list): List of dictionaries where\n the keys is 'name' and the value is the name of\n the security group. If it's not passed the default\n security group will be used.\n availability_zone(str)*: The availability zone that\n the instance will be in.\n You can request a specific az without actually creating one,\n Just pass 'X:Y' where X is the default availability\n zone, and Y is the compute host name.\n \"\"\"\n\n kwargs.setdefault('name', data_utils.rand_name('server-test'))\n\n # We cannot use setdefault() here because caller could have passed\n # security_groups=None and we don't want to pass None to\n # client.create_server()\n if not kwargs.get('security_groups'):\n kwargs['security_groups'] = [{'name': 'default'}]\n\n client = self.os_primary.servers_client\n if kwargs.get('availability_zone'):\n client = self.os_admin.servers_client\n\n server = client.create_server(\n flavorRef=flavor_ref,\n imageRef=image_ref,\n key_name=key_name,\n networks=networks,\n **kwargs)\n\n self.addCleanup(test_utils.call_and_ignore_notfound_exc,\n waiters.wait_for_server_termination,\n client,\n server['server']['id'])\n self.addCleanup(test_utils.call_and_ignore_notfound_exc,\n client.delete_server,\n server['server']['id'])\n return server\n\n @classmethod\n def create_secgroup_rules(cls, rule_list, secgroup_id=None,\n client=None):\n client = client or cls.os_primary.network_client\n if not secgroup_id:\n sgs = client.list_security_groups()['security_groups']\n for sg in sgs:\n if sg['name'] == constants.DEFAULT_SECURITY_GROUP:\n secgroup_id = sg['id']\n break\n\n for rule in rule_list:\n direction = rule.pop('direction')\n client.create_security_group_rule(\n direction=direction,\n security_group_id=secgroup_id,\n **rule)\n\n @classmethod\n def create_loginable_secgroup_rule(cls, secgroup_id=None,\n client=None):\n \"\"\"This rule is intended to permit inbound ssh\n\n Allowing ssh traffic traffic from all sources, so no group_id is\n provided.\n Setting a group_id would only permit traffic from ports\n belonging to the same security group.\n \"\"\"\n return cls.create_security_group_rule(\n security_group_id=secgroup_id,\n client=client,\n protocol=neutron_lib_constants.PROTO_NAME_TCP,\n direction=neutron_lib_constants.INGRESS_DIRECTION,\n port_range_min=22,\n port_range_max=22)\n\n @classmethod\n def create_pingable_secgroup_rule(cls, secgroup_id=None,\n client=None):\n \"\"\"This rule is intended to permit inbound ping\n\n \"\"\"\n return cls.create_security_group_rule(\n security_group_id=secgroup_id, client=client,\n protocol=neutron_lib_constants.PROTO_NAME_ICMP,\n direction=neutron_lib_constants.INGRESS_DIRECTION)\n\n @classmethod\n def create_router_by_client(cls, is_admin=False, **kwargs):\n kwargs.update({'router_name': data_utils.rand_name('router'),\n 'admin_state_up': True,\n 'external_network_id': CONF.network.public_network_id})\n if not is_admin:\n router = cls.create_router(**kwargs)\n else:\n router = cls.create_admin_router(**kwargs)\n LOG.debug(\"Created router %s\", router['name'])\n cls.routers.append(router)\n return router\n\n @removals.remove(version='Stein',\n message=\"Please use create_floatingip method instead of \"\n \"create_and_associate_floatingip.\")\n def create_and_associate_floatingip(self, port_id, client=None):\n client = client or self.os_primary.network_client\n return self.create_floatingip(port_id=port_id, client=client)\n\n def create_interface(cls, server_id, port_id, client=None):\n client = client or cls.os_primary.interfaces_client\n body = client.create_interface(server_id, port_id=port_id)\n return body['interfaceAttachment']\n\n def delete_interface(cls, server_id, port_id, client=None):\n client = client or cls.os_primary.interfaces_client\n client.delete_interface(server_id, port_id=port_id)\n\n def setup_network_and_server(\n self, router=None, server_name=None, network=None, **kwargs):\n \"\"\"Create network resources and a server.\n\n Creating a network, subnet, router, keypair, security group\n and a server.\n \"\"\"\n self.network = network or self.create_network()\n LOG.debug(\"Created network %s\", self.network['name'])\n self.subnet = self.create_subnet(self.network)\n LOG.debug(\"Created subnet %s\", self.subnet['id'])\n\n secgroup = self.os_primary.network_client.create_security_group(\n name=data_utils.rand_name('secgroup'))\n LOG.debug(\"Created security group %s\",\n secgroup['security_group']['name'])\n self.security_groups.append(secgroup['security_group'])\n if not router:\n router = self.create_router_by_client(**kwargs)\n self.create_router_interface(router['id'], self.subnet['id'])\n self.keypair = self.create_keypair()\n self.create_loginable_secgroup_rule(\n secgroup_id=secgroup['security_group']['id'])\n\n server_kwargs = {\n 'flavor_ref': CONF.compute.flavor_ref,\n 'image_ref': CONF.compute.image_ref,\n 'key_name': self.keypair['name'],\n 'networks': [{'uuid': self.network['id']}],\n 'security_groups': [{'name': secgroup['security_group']['name']}],\n }\n if server_name is not None:\n server_kwargs['name'] = server_name\n\n self.server = self.create_server(**server_kwargs)\n self.wait_for_server_active(self.server['server'])\n self.port = self.client.list_ports(network_id=self.network['id'],\n device_id=self.server[\n 'server']['id'])['ports'][0]\n self.fip = self.create_floatingip(port=self.port)\n\n def check_connectivity(self, host, ssh_user, ssh_key, servers=None):\n ssh_client = ssh.Client(host, ssh_user, pkey=ssh_key)\n try:\n ssh_client.test_connection_auth()\n except lib_exc.SSHTimeout as ssh_e:\n LOG.debug(ssh_e)\n self._log_console_output(servers)\n raise\n\n def _log_console_output(self, servers=None):\n if not CONF.compute_feature_enabled.console_output:\n LOG.debug('Console output not supported, cannot log')\n return\n if not servers:\n servers = self.os_primary.servers_client.list_servers()\n servers = servers['servers']\n for server in servers:\n try:\n console_output = (\n self.os_primary.servers_client.get_console_output(\n server['id'])['output'])\n LOG.debug('Console output for %s\\nbody=\\n%s',\n server['id'], console_output)\n except lib_exc.NotFound:\n LOG.debug(\"Server %s disappeared(deleted) while looking \"\n \"for the console log\", server['id'])\n\n def _check_remote_connectivity(self, source, dest, should_succeed=True,\n nic=None, mtu=None, fragmentation=True,\n timeout=None):\n \"\"\"check ping server via source ssh connection\n\n :param source: RemoteClient: an ssh connection from which to ping\n :param dest: and IP to ping against\n :param should_succeed: boolean should ping succeed or not\n :param nic: specific network interface to ping from\n :param mtu: mtu size for the packet to be sent\n :param fragmentation: Flag for packet fragmentation\n :returns: boolean -- should_succeed == ping\n :returns: ping is false if ping failed\n \"\"\"\n def ping_host(source, host, count=CONF.validation.ping_count,\n size=CONF.validation.ping_size, nic=None, mtu=None,\n fragmentation=True):\n IP_VERSION_4 = neutron_lib_constants.IP_VERSION_4\n IP_VERSION_6 = neutron_lib_constants.IP_VERSION_6\n\n # Use 'ping6' for IPv6 addresses, 'ping' for IPv4 and hostnames\n ip_version = (\n IP_VERSION_6 if netaddr.valid_ipv6(host) else IP_VERSION_4)\n cmd = (\n 'ping6' if ip_version == IP_VERSION_6 else 'ping')\n if nic:\n cmd = 'sudo {cmd} -I {nic}'.format(cmd=cmd, nic=nic)\n if mtu:\n if not fragmentation:\n cmd += ' -M do'\n size = str(net_utils.get_ping_payload_size(\n mtu=mtu, ip_version=ip_version))\n cmd += ' -c{0} -w{0} -s{1} {2}'.format(count, size, host)\n return source.exec_command(cmd)\n\n def ping_remote():\n try:\n result = ping_host(source, dest, nic=nic, mtu=mtu,\n fragmentation=fragmentation)\n\n except lib_exc.SSHExecCommandFailed:\n LOG.warning('Failed to ping IP: %s via a ssh connection '\n 'from: %s.', dest, source.host)\n return not should_succeed\n LOG.debug('ping result: %s', result)\n\n if validators.validate_ip_address(dest) is None:\n # Assert that the return traffic was from the correct\n # source address.\n from_source = 'from %s' % dest\n self.assertIn(from_source, result)\n return should_succeed\n\n return test_utils.call_until_true(\n ping_remote, timeout or CONF.validation.ping_timeout, 1)\n\n def check_remote_connectivity(self, source, dest, should_succeed=True,\n nic=None, mtu=None, fragmentation=True,\n servers=None, timeout=None):\n try:\n self.assertTrue(self._check_remote_connectivity(\n source, dest, should_succeed, nic, mtu, fragmentation,\n timeout=timeout))\n except lib_exc.SSHTimeout as ssh_e:\n LOG.debug(ssh_e)\n self._log_console_output(servers)\n raise\n except AssertionError:\n self._log_console_output(servers)\n raise\n\n def ping_ip_address(self, ip_address, should_succeed=True,\n ping_timeout=None, mtu=None):\n # the code is taken from tempest/scenario/manager.py in tempest git\n timeout = ping_timeout or CONF.validation.ping_timeout\n cmd = ['ping', '-c1', '-w1']\n\n if mtu:\n cmd += [\n # don't fragment\n '-M', 'do',\n # ping receives just the size of ICMP payload\n '-s', str(net_utils.get_ping_payload_size(mtu, 4))\n ]\n cmd.append(ip_address)\n\n def ping():\n proc = subprocess.Popen(cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n proc.communicate()\n\n return (proc.returncode == 0) == should_succeed\n\n caller = test_utils.find_test_caller()\n LOG.debug('%(caller)s begins to ping %(ip)s in %(timeout)s sec and the'\n ' expected result is %(should_succeed)s', {\n 'caller': caller, 'ip': ip_address, 'timeout': timeout,\n 'should_succeed':\n 'reachable' if should_succeed else 'unreachable'\n })\n result = test_utils.call_until_true(ping, timeout, 1)\n\n # To make sure ping_ip_address called by test works\n # as expected.\n self.assertTrue(result)\n\n LOG.debug('%(caller)s finishes ping %(ip)s in %(timeout)s sec and the '\n 'ping result is %(result)s', {\n 'caller': caller, 'ip': ip_address, 'timeout': timeout,\n 'result': 'expected' if result else 'unexpected'\n })\n return result\n\n def wait_for_server_status(self, server, status, client=None, **kwargs):\n \"\"\"Waits for a server to reach a given status.\n\n :param server: mapping having schema {'id': }\n :param status: string status to wait for (es: 'ACTIVE')\n :param clien: servers client (self.os_primary.servers_client as\n default value)\n \"\"\"\n\n client = client or self.os_primary.servers_client\n waiters.wait_for_server_status(client, server['id'], status, **kwargs)\n\n def wait_for_server_active(self, server, client=None):\n \"\"\"Waits for a server to reach active status.\n\n :param server: mapping having schema {'id': }\n :param clien: servers client (self.os_primary.servers_client as\n default value)\n \"\"\"\n self.wait_for_server_status(\n server, constants.SERVER_STATUS_ACTIVE, client)\n", "repo_name": "sonaproject/neutron-tempest-plugin", "sub_path": "neutron_tempest_plugin/scenario/base.py", "file_name": "base.py", "file_ext": "py", "file_size_in_byte": 15239, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "neutron_tempest_plugin.config.CONF", "line_number": 19, "usage_type": "attribute"}, {"api_name": "neutron_tempest_plugin.config", "line_number": 19, "usage_type": "name"}, {"api_name": "oslo_log.log.getLogger", "line_number": 21, "usage_type": "call"}, {"api_name": "oslo_log.log", "line_number": 21, "usage_type": "name"}, {"api_name": "neutron_tempest_plugin.api.base.BaseNetworkTest", "line_number": 24, "usage_type": "attribute"}, {"api_name": "neutron_tempest_plugin.api.base", "line_number": 24, "usage_type": "name"}, {"api_name": "tempest.lib.common.utils.data_utils.rand_name", "line_number": 55, "usage_type": "call"}, {"api_name": "tempest.lib.common.utils.data_utils", "line_number": 55, "usage_type": "name"}, {"api_name": "tempest.lib.common.utils.test_utils.call_and_ignore_notfound_exc", "line_number": 74, "usage_type": "attribute"}, {"api_name": "tempest.lib.common.utils.test_utils", "line_number": 74, "usage_type": "name"}, {"api_name": "tempest.common.waiters.wait_for_server_termination", "line_number": 75, "usage_type": "attribute"}, {"api_name": "tempest.common.waiters", "line_number": 75, "usage_type": "name"}, {"api_name": "tempest.lib.common.utils.test_utils.call_and_ignore_notfound_exc", "line_number": 78, "usage_type": "attribute"}, {"api_name": "tempest.lib.common.utils.test_utils", "line_number": 78, "usage_type": "name"}, {"api_name": "neutron_tempest_plugin.scenario.constants.DEFAULT_SECURITY_GROUP", "line_number": 90, "usage_type": "attribute"}, {"api_name": "neutron_tempest_plugin.scenario.constants", "line_number": 90, "usage_type": "name"}, {"api_name": "neutron_lib.constants.PROTO_NAME_TCP", "line_number": 114, "usage_type": "attribute"}, {"api_name": "neutron_lib.constants", "line_number": 114, "usage_type": "name"}, {"api_name": "neutron_lib.constants.INGRESS_DIRECTION", "line_number": 115, "usage_type": "attribute"}, {"api_name": "neutron_lib.constants", "line_number": 115, "usage_type": "name"}, {"api_name": "neutron_lib.constants.PROTO_NAME_ICMP", "line_number": 127, "usage_type": "attribute"}, {"api_name": "neutron_lib.constants", "line_number": 127, "usage_type": "name"}, {"api_name": "neutron_lib.constants.INGRESS_DIRECTION", "line_number": 128, "usage_type": "attribute"}, {"api_name": "neutron_lib.constants", "line_number": 128, "usage_type": "name"}, {"api_name": "tempest.lib.common.utils.data_utils.rand_name", "line_number": 132, "usage_type": "call"}, {"api_name": "tempest.lib.common.utils.data_utils", "line_number": 132, "usage_type": "name"}, {"api_name": "debtcollector.removals.remove", "line_number": 143, "usage_type": "call"}, {"api_name": "debtcollector.removals", "line_number": 143, "usage_type": "name"}, {"api_name": "tempest.lib.common.utils.data_utils.rand_name", "line_number": 172, "usage_type": "call"}, {"api_name": "tempest.lib.common.utils.data_utils", "line_number": 172, "usage_type": "name"}, {"api_name": "neutron_tempest_plugin.common.ssh.Client", "line_number": 201, "usage_type": "call"}, {"api_name": "neutron_tempest_plugin.common.ssh", "line_number": 201, "usage_type": "name"}, {"api_name": "tempest.lib.exceptions.SSHTimeout", "line_number": 204, "usage_type": "attribute"}, {"api_name": "tempest.lib.exceptions", "line_number": 204, "usage_type": "name"}, {"api_name": "tempest.lib.exceptions.NotFound", "line_number": 223, "usage_type": "attribute"}, {"api_name": "tempest.lib.exceptions", "line_number": 223, "usage_type": "name"}, {"api_name": "neutron_lib.constants.IP_VERSION_4", "line_number": 244, "usage_type": "attribute"}, {"api_name": "neutron_lib.constants", "line_number": 244, "usage_type": "name"}, {"api_name": "neutron_lib.constants.IP_VERSION_6", "line_number": 245, "usage_type": "attribute"}, {"api_name": "neutron_lib.constants", "line_number": 245, "usage_type": "name"}, {"api_name": "netaddr.valid_ipv6", "line_number": 249, "usage_type": "call"}, {"api_name": "tempest.common.utils.net_utils.get_ping_payload_size", "line_number": 257, "usage_type": "call"}, {"api_name": "tempest.common.utils.net_utils", "line_number": 257, "usage_type": "name"}, {"api_name": "tempest.lib.exceptions.SSHExecCommandFailed", "line_number": 267, "usage_type": "attribute"}, {"api_name": "tempest.lib.exceptions", "line_number": 267, "usage_type": "name"}, {"api_name": "neutron_lib.api.validators.validate_ip_address", "line_number": 273, "usage_type": "call"}, {"api_name": "neutron_lib.api.validators", "line_number": 273, "usage_type": "name"}, {"api_name": "tempest.lib.common.utils.test_utils.call_until_true", "line_number": 280, "usage_type": "call"}, {"api_name": "tempest.lib.common.utils.test_utils", "line_number": 280, "usage_type": "name"}, {"api_name": "tempest.lib.exceptions.SSHTimeout", "line_number": 290, "usage_type": "attribute"}, {"api_name": "tempest.lib.exceptions", "line_number": 290, "usage_type": "name"}, {"api_name": "tempest.common.utils.net_utils.get_ping_payload_size", "line_number": 309, "usage_type": "call"}, {"api_name": "tempest.common.utils.net_utils", "line_number": 309, "usage_type": "name"}, {"api_name": "subprocess.Popen", "line_number": 314, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 315, "usage_type": "attribute"}, {"api_name": "subprocess.PIPE", "line_number": 316, "usage_type": "attribute"}, {"api_name": "tempest.lib.common.utils.test_utils.find_test_caller", "line_number": 321, "usage_type": "call"}, {"api_name": "tempest.lib.common.utils.test_utils", "line_number": 321, "usage_type": "name"}, {"api_name": "tempest.lib.common.utils.test_utils.call_until_true", "line_number": 328, "usage_type": "call"}, {"api_name": "tempest.lib.common.utils.test_utils", "line_number": 328, "usage_type": "name"}, {"api_name": "tempest.common.waiters.wait_for_server_status", "line_number": 351, "usage_type": "call"}, {"api_name": "tempest.common.waiters", "line_number": 351, "usage_type": "name"}, {"api_name": "neutron_tempest_plugin.scenario.constants.SERVER_STATUS_ACTIVE", "line_number": 361, "usage_type": "attribute"}, {"api_name": "neutron_tempest_plugin.scenario.constants", "line_number": 361, "usage_type": "name"}]} +{"seq_id": "3050716652", "text": "from rest_framework import serializers\nfrom invadeapp.models import Champions, MatchData\n\nclass ChampionSerializer(serializers.ModelSerializer):\n class Meta:\n fields = (\n 'key', \n 'name', \n 'attack', \n 'defense', \n 'magic',\n 'difficulty', \n 'hp', \n 'hpperlevel', \n 'mp', \n 'mpperlevel', \n 'movespeed', \n 'armor', \n 'armorperlevel', \n 'spellblock', \n 'spellblockperlevel',\n 'attackrange', \n 'hpregen', \n 'hpregenperlevel', \n 'mpregen', \n 'mpregenperlevel',\n 'crit', \n 'critperlevel', \n 'attackdamage', \n 'attackdamageperlevel', \n 'attackspeedperlevel', \n 'attackspeed', \n 'image'\n )\n model = Champions\n\nclass MatchDataSerializer(serializers.ModelSerializer):\n class Meta:\n fields = (\n 'summoner_name_match',\n 'team_id', \n 'champion_id', \n 'spell1_id',\n 'spell2_id'\n )\n model = MatchData\n", "repo_name": "notvert/invade", "sub_path": "api/serializers.py", "file_name": "serializers.py", "file_ext": "py", "file_size_in_byte": 1187, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 4, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 4, "usage_type": "name"}, {"api_name": "invadeapp.models.Champions", "line_number": 35, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 37, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 37, "usage_type": "name"}, {"api_name": "invadeapp.models.MatchData", "line_number": 46, "usage_type": "name"}]} +{"seq_id": "8019784182", "text": "from aiogram import Bot\nfrom aiogram.dispatcher.filters import CommandObject\nfrom aiogram.types import Message\n\nfrom database.contexts import ContestContext, ContestMemberContext, MemberContext\nfrom misc.utils.contest import choose_the_winners\n\n\nasync def command_start_deeplink(message: Message,\n command: CommandObject,\n bot: Bot,\n contest_db: ContestContext,\n contest_members_db: ContestMemberContext,\n member_db: MemberContext):\n try:\n deeplink_name, arg2 = command.args.split('_', maxsplit=1)\n except ValueError:\n return await message.answer(text=f'Ошибка. Пожайлуста, не играйтесь с диплинком ;)')\n\n if deeplink_name == 'join-contest': # пример использования: handlers/channel/contest/callbacks/base.py, 23 line\n contest_db_id = int(arg2)\n\n member_data = await member_db.get_or_create_and_get(message.from_user)\n contest_data = await contest_db.get_by_db_id(contest_db_id)\n\n await contest_members_db.add(contest_db_id, member_data.id)\n await message.reply('Вы успешно зарегистрировались.')\n\n if contest_data.end_count:\n if contest_data.end_count <= await contest_members_db.count(contest_db_id):\n await choose_the_winners(bot, contest_db, contest_members_db, member_db, contest_db_id)\n\n # elif deeplink_name == 'еще какие-нибудь диплинки':\n else:\n return await message.answer(text=f'Ошибка. Такого диплинка не существует.')\n", "repo_name": "Like6po/for_raffle_bot", "sub_path": "app/handlers/private/start/deeplink.py", "file_name": "deeplink.py", "file_ext": "py", "file_size_in_byte": 1732, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "48", "api": [{"api_name": "aiogram.types.Message", "line_number": 9, "usage_type": "name"}, {"api_name": "aiogram.dispatcher.filters.CommandObject", "line_number": 10, "usage_type": "name"}, {"api_name": "aiogram.Bot", "line_number": 11, "usage_type": "name"}, {"api_name": "database.contexts.ContestContext", "line_number": 12, "usage_type": "name"}, {"api_name": "database.contexts.ContestMemberContext", "line_number": 13, "usage_type": "name"}, {"api_name": "database.contexts.MemberContext", "line_number": 14, "usage_type": "name"}, {"api_name": "misc.utils.contest.choose_the_winners", "line_number": 31, "usage_type": "call"}]} +{"seq_id": "34258988372", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('accounts', '0018_auto_20151113_0106'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='UserConnection',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('token', models.UUIDField(default=uuid.uuid4, unique=True, editable=False)),\n ('referrer_path', models.CharField(null=True, max_length=255)),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, null=True)),\n ],\n ),\n ]\n", "repo_name": "aeud/sing", "sub_path": "apps/accounts/migrations/0019_userconnection.py", "file_name": "0019_userconnection.py", "file_ext": "py", "file_size_in_byte": 783, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "django.db.migrations.Migration", "line_number": 9, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 9, "usage_type": "name"}, {"api_name": "django.db.migrations.CreateModel", "line_number": 16, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 16, "usage_type": "name"}, {"api_name": "django.db.models.AutoField", "line_number": 19, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 19, "usage_type": "name"}, {"api_name": "django.db.models.UUIDField", "line_number": 20, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 20, "usage_type": "name"}, {"api_name": "uuid.uuid4", "line_number": 20, "usage_type": "attribute"}, {"api_name": "django.db.models.CharField", "line_number": 21, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 21, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 22, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 22, "usage_type": "name"}, {"api_name": "django.conf.settings.AUTH_USER_MODEL", "line_number": 22, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 22, "usage_type": "name"}]} +{"seq_id": "31748925300", "text": "from IPython.core.interactiveshell import InteractiveShell\r\nInteractiveShell.ast_node_interactivity = \"all\"\r\nimport numpy as np, pandas as pd\r\nfrom datetime import datetime\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nfrom sklearn.preprocessing import StandardScaler,MinMaxScaler,MaxAbsScaler,RobustScaler\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.preprocessing import OneHotEncoder\r\nfrom sklearn.cluster import KMeans\r\nimport math\r\nimport requests\r\nimport json\r\nfrom pandas.io.json import json_normalize\r\nimport os\r\nimport webbrowser\r\nimport folium\r\nfrom folium import plugins\r\n\r\n\r\n \r\n\"\"\"\r\nName: caculatemean\r\n\r\nFunction: Switch data with labeled datas in oneHotencoded data and calculate mean in each column\r\n\r\nParameter: dataset,labeled array\r\n\r\nReturn: name of column, mean of column\r\n\r\nCondition: \r\n -dataset should be OneHotEncoded\r\n -dataset should contain only OneHotEncoded columns\r\n -labeled should be array of clusteing labeled data\r\n -labeled and dataset should be same size \r\n\"\"\" \r\ndef calculatemean(dataset,labeled):\r\n for i in range(len(dataset)):\r\n index_tmp = dataset.index[dataset[col[i]] == 1]\r\n dataset.iloc[index_tmp, i] = labeled[index_tmp].tolist()\r\n sum_dataset=np.zeros(25,dtype=object)\r\n for i in range(len(dataset)):\r\n index_tmp = dataset.index[dataset[col[i]]!=0]\r\n sum_dataset[i] = sum_dataset[i]+dataset.iloc[index_tmp, i]\r\n tmp_array_name=np.zeros(25,dtype=object)\r\n tmp_array_size=np.zeros(25,dtype=object)\r\n for i in range(len(sum_dataset)):\r\n tmp_array_name[i]=sum_dataset[i].name\r\n tmp_array_size[i]=sum_dataset[i].sum()/sum_dataset[i].size\r\n return tmp_array_name,tmp_array_size\r\n\r\n\r\n\"\"\"\r\nName: points_array\r\n\r\nFunction: match target to the array\r\n\r\nParameter: points(given jsonResult['features'][x]['geometry']['coordinates'][0])\r\n\r\nReturn: gathered array\r\n\"\"\" \r\ndef points_array(points):\r\n\r\n final_points = []\r\n\r\n for x in range(0, len(points)):\r\n\r\n if len(points[x]) == 2:\r\n final_points.append(points[x])\r\n else:\r\n target = points[x]\r\n for y in range(0, len(target)):\r\n final_points.append(target[y])\r\n\r\n return final_points\r\n\r\n\r\n\"\"\"\r\nName: cal\r\n\r\nFunction: bubblesort\r\n\r\nParameter: temparray\r\n\r\nReturn: temparray(bubblesorted array)\r\n\r\nCondition: \r\n -array should be numeric\r\n\r\n\"\"\"\r\ndef cal(temparray):\r\n for i in range(len(temparray)):\r\n for j in range(len(temparray)-i-1):\r\n if temparray[j]>temparray[j+1]:\r\n temp=temparray[j]\r\n temparray[j]=temparray[j+1]\r\n temparray[j+1]=temp\r\n return temparray\r\n\r\n\r\n# Visualize optimized k values\r\ndef visualizeElbowMethod(model, x):\r\n visualizer = KElbowVisualizer(model, k=(1, 10))\r\n visualizer.fit(x.values)\r\n visualizer.show()\r\n\r\n \r\n\"\"\"\r\nName: compare\r\n\r\nFunction: ordering(we use this after using cal above. needs to match the bubblesorted data into original data)\r\n\r\nParameter: tmp1, tmp2(both data)\r\n\r\nReturn: resultarray(ordered array)\r\n\r\nConditions: \r\n -tmp1 and tmp2 should be same size\r\n -array should be numeric\r\n\"\"\"\r\ndef compare(tmp1,tmp2):\r\n resultarray=np.zeros(len(tmp1))\r\n for i in range(len(tmp1)):\r\n for j in range(len(tmp1)):\r\n if tmp1[i]==tmp2[j]:\r\n resultarray[i]=j\r\n continue\r\n return resultarray \r\n\r\n\r\n\"\"\"\r\nName: setting\r\n\r\nFucntion: split data in 4 groups\r\n\r\nParameter: tmp(data)\r\n\r\nConditions:\r\n -tmp is the data bigger than size 4\r\n\"\"\"\r\ndef setting(tmp):\r\n sizenum=round(len(tmp)/4)\r\n for i in range(len(tmp)):\r\n if tmp[i]= 37.426026]\r\n target_df = pd.merge(temp_seoulmap,center_locations2, how = 'left', on = 'NAME')\r\n target_df = target_df.dropna(axis=0, subset=['X','Y'])\r\n \r\n m=folium.Map(location=[37.562225, 126.978555], tiles=\"OpenStreetMap\", zoom_start=11)\r\n\r\n m.choropleth(\r\n geo_data=state_geo2,\r\n name='미세먼지 위험군',\r\n data=temp_seoulmap,\r\n columns=['NAME', 'VALUE'],\r\n key_on='feature.properties.name',\r\n fill_color='Blues',\r\n fill_opacity=0.7,\r\n line_opacity=0.3,\r\n color = 'gray',\r\n legend_name = 'income'\r\n )\r\n\r\n for i in range(0,len(target_df)):\r\n latitude = target_df.iloc[i]['Y']\r\n longitude = target_df.iloc[i]['X']\r\n location=(latitude, longitude)\r\n\r\n if target_df.iloc[i]['NAME'] in ['서초구','강남구'] :\r\n color = 'white'\r\n else:\r\n color = '#3186cc'\r\n\r\n folium.CircleMarker(location, radius=10,color=color,fill_color=color,fill_opacity = 0.1, opacity=0.0, popup=target_df.iloc[i]['NAME'] + \"\\n\" + str(int(round(target_df.iloc[i]['VALUE']/10000,0))) + \"만원\").add_to(m)\r\n\r\n\r\n folium.LayerControl(collapsed=False).add_to(m)\r\n\r\n # Save to html\r\n m.save('kr_incode.html')\r\n return m\r\n", "repo_name": "yerinOneul/Seoul_air_pollution", "sub_path": "ordering,mapping.py", "file_name": "ordering,mapping.py", "file_ext": "py", "file_size_in_byte": 7218, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "IPython.core.interactiveshell.InteractiveShell.ast_node_interactivity", "line_number": 2, "usage_type": "attribute"}, {"api_name": "IPython.core.interactiveshell.InteractiveShell", "line_number": 2, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 123, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 172, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 173, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 184, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 201, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 202, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 203, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 207, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 210, "usage_type": "call"}, {"api_name": "folium.Map", "line_number": 213, "usage_type": "call"}, {"api_name": "folium.CircleMarker", "line_number": 238, "usage_type": "call"}, {"api_name": "folium.LayerControl", "line_number": 241, "usage_type": "call"}]} +{"seq_id": "41576423207", "text": "import os\nfrom os.path import expanduser\nfrom tkinter import *\nfrom collections import defaultdict\nimport git\nimport datetime\nfrom pprint import pprint\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ncommit_counts = defaultdict(list)\n\n\ndef find_git_folders(path):\n git_folders = []\n for root, dirs, files in os.walk(path):\n # skip node_modules\n if '.git' in dirs and 'node_modules' not in root:\n git_folders.append(os.path.join(root, '.git'))\n return git_folders\n \ndef get_commit_counts_by_user(repo_path, authors):\n repo = git.Repo(repo_path)\n try:\n commits = list(repo.iter_commits('HEAD'))\n except git.exc.GitCommandError:\n return\n for commit in commits:\n author = commit.author.name\n if(author not in authors):\n continue\n # date from unix timestamp\n timestam= commit.committed_date\n date = datetime.datetime.fromtimestamp(timestam).strftime('%Y-%m-%d')\n commit_counts[author].append(date)\n \n\n\ndef plot_data(dates):\n\n # x axis: dates\n # y axis: number of commits\n\n import matplotlib.pyplot as plt\n import numpy as np\n\n # sort dates\n dates = sorted(dates.items(), key=lambda x: x[0])\n\n # plot\n plt.plot([x[0] for x in dates], [x[1] for x in dates])\n\n # show a total of 30 dates on x axis\n plt.xticks(np.arange(0, len(dates), len(dates)/30))\n\n plt.xticks(rotation=90)\n plt.show()\n \n \ndef convert_data(data):\n \n # limit all values above 10 to 10 to get a more readable plot\n data = {k: min(v, 10) for k, v in data.items()}\n # Get the start and end dates from the data\n start_date = datetime.datetime.strptime(min(data.keys()), '%Y-%m-%d')\n end_date = datetime.datetime.strptime(max(data.keys()), '%Y-%m-%d')\n\n # Calculate the number of weeks between the start and end dates\n num_weeks = (end_date - start_date).days // 7 + 1\n\n # Create an array to hold the converted data\n converted_data = np.zeros((7, num_weeks), dtype=int)\n\n # Fill in the converted data\n for date_str, count in data.items():\n date = datetime.datetime.strptime(date_str, '%Y-%m-%d')\n week = (date - start_date).days // 7\n day = date.weekday()\n converted_data[day, week] = count\n\n return converted_data\n \n \ndef plot_squares(dates):\n data = convert_data(dict(dates))\n\n print(data)\n\n\n\n # Create a new figure and axes\n fig, ax = plt.subplots()\n\n # Plot the data as an image\n ax.imshow(data, cmap='Greens')\n\n\n start_date = datetime.datetime.strptime(min(dates.keys()), '%Y-%m-%d')\n end_date = datetime.datetime.strptime(max(dates.keys()), '%Y-%m-%d')\n # Calculate the number of weeks between the start and end dates\n weeks = (end_date - start_date).days // 7 + 1\n \n # show a few dates along x axis starting from the first date and ending with the last date\n # up to 40 dates\n # if there are less than 40 dates, show all of them\n ax.set_xticks(range(weeks)[::weeks//(40 if weeks > 40 else weeks)])\n ## print labels YYYY-MM-DD\n # formaat date to string\n ax.set_xticklabels([(start_date + datetime.timedelta(weeks=i)).strftime('%Y-%m-%d') for i in range(weeks)][::weeks//(40 if weeks > 40 else weeks)], rotation=90)\n \n ax.set_yticks(range(7))\n ax.set_yticklabels(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat','Sun' ])\n\n # make plot taller in y direction\n ax.set_aspect(1)\n\n # Show the plot\n plt.show()\n \n# start form home directory\nhome = expanduser(\"~\")\n\n\nhome_folders = os.listdir(home)\n# exclude hidden folders\nhome_folders = [folder for folder in home_folders if not folder.startswith('.')]\n# sort folders\nhome_folders.sort()\n\n\n\n\n\ndef submit():\n \n \n \n selected = []\n for i in range(len(var_list)):\n if var_list[i].get() == 1:\n selected.append(options[i])\n \n \n git_folders = []\n \n for i in selected:\n git_folders += find_git_folders(home + '/' + i)\n \n \n \n usernames = entry.get().split(\",\")\n \n \n root.destroy()\n\n print(\"Usernames:\", usernames)\n \n for git_folder in git_folders:\n get_commit_counts_by_user(git_folder, usernames)\n \n # conbine users Mats01-fer, Mats-01, Mats01 and ''Matej Butkovic' into one\n commit_counts['MatejSVE'] = commit_counts['Mats01-fer'] + commit_counts['Mats-01'] + commit_counts['Matej Butkovic'] + commit_counts['Mats01']\n\n # count how many time each date appears in the list of 'MatejSVE'\n dates = {}\n \n for date in commit_counts['MatejSVE']:\n dates[date] = dates.get(date, 0) + 1\n # map author to number of commits\n \n pprint('total distinct commit days: %d' % len(dates.keys()))\n plot_squares(dates)\n \n \n \n \n\n\nvar_list = []\nroot = Tk()\noptions = home_folders\n\n\nroot.title(\"Git activity\")\n\nframe = Frame(root)\nframe.pack(fill=BOTH, expand=1)\n\ncanvas = Canvas(frame)\ncanvas.pack(side=LEFT, fill=BOTH, expand=1)\n\n\nlabel = Label(frame, text=\"Enter comma-separated list of your usernames:\")\nlabel.pack()\n\nentry = Entry(frame)\nentry.pack()\n\n\n\nsubmit_button = Button(frame, text=\"Submit\", command=submit)\nsubmit_button.pack()\n\nscrollbar = Scrollbar(frame, orient=VERTICAL, command=canvas.yview)\nscrollbar.pack(side=RIGHT, fill=Y)\n\ncanvas.configure(yscrollcommand=scrollbar.set)\n\ninner_frame = Frame(canvas)\ncanvas.create_window((0, 0), window=inner_frame, anchor=\"nw\")\n\n\n\nfor option in options:\n var = IntVar()\n c = Checkbutton(inner_frame, text=option, variable=var, anchor=\"w\")\n c.pack(fill=X)\n var_list.append(var)\n\n\n\n\n\n\n\n\n\ndef on_configure(event):\n canvas.configure(scrollregion=canvas.bbox(\"all\"))\n\n\ncanvas.bind(\"\", on_configure)\nroot.mainloop()", "repo_name": "Mats01/git-squares", "sub_path": "gui.py", "file_name": "gui.py", "file_ext": "py", "file_size_in_byte": 5676, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "collections.defaultdict", "line_number": 12, "usage_type": "call"}, {"api_name": "os.walk", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "git.Repo", "line_number": 24, "usage_type": "call"}, {"api_name": "git.exc", "line_number": 27, "usage_type": "attribute"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 35, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 35, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 57, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 58, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 58, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 66, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 66, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 67, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 67, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 73, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 77, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 77, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 93, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 99, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 99, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 100, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 100, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 119, "usage_type": "name"}, {"api_name": "os.path.expanduser", "line_number": 122, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 125, "usage_type": "call"}, {"api_name": "pprint.pprint", "line_number": 172, "usage_type": "call"}]} +{"seq_id": "36422913199", "text": "import time\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport matplotlib.cm as cm\r\n\r\n'''def f(x):\r\n return np.sin(x)+0.5*x\r\n\r\nx_plt = np.arange(-5, 5, 0.1)\r\ny_plt = [f(x) for x in x_plt]\r\n\r\nplt.xlabel('x')\r\nplt.ylabel('y')\r\n\r\nx1 = 3\r\nx2 = -4\r\nx3 = 2\r\nN = 200\r\ndelta = 0.01\r\n\r\nplt.ion()\r\nfig, ax = plt.subplots()\r\nax.grid(True)\r\n\r\nax.plot(x_plt, y_plt)\r\npoint1 = ax.scatter(x1, f(x1), c='red')\r\npoint2 = ax.scatter(x2, f(x2), c='red')\r\npoint3 = ax.scatter(x3, f(x3), c='red')\r\n\r\n\r\nmn = 10\r\nfor i in range(N):\r\n lmd = 1/min(i+1, mn)\r\n x1 = x1 - lmd*(f(x1+delta)-f(x1-delta))/(2*delta)\r\n x2 = x2 - lmd*(f(x2+delta)-f(x2-delta))/(2*delta)\r\n x3 = x3 - lmd*(f(x3+delta)-f(x3-delta))/(2*delta)\r\n point1.set_offsets([x1, f(x1)])\r\n point2.set_offsets([x2, f(x2)])\r\n point3.set_offsets([x3, f(x3)])\r\n fig.canvas.draw()\r\n fig.canvas.flush_events()\r\n time.sleep(0.02)'''\r\n\r\n'''plt.ioff()\r\nprint(xx)\r\nax.scatter(xx, f(xx), c='blue')\r\nplt.show()'''\r\n\r\ndef f(a, b):\r\n return a**2/4+b**2/9\r\n\r\nx_plt = np.arange(-5, 5, 0.1)\r\ny_plt = np.arange(-5, 5, 0.1)\r\nx_plt, y_plt = np.meshgrid(x_plt, y_plt)\r\nz_plt = x_plt**2/4 + y_plt**2/9\r\n\r\nx1 = 7\r\ny1 = 6\r\nx2 = -9\r\ny2 = -3\r\nx3 = 5\r\ny3 = -7\r\nN = 200\r\ndelta = 0.01\r\n\r\nplt.ion()\r\nfig = plt.figure()\r\nax = fig.add_subplot(111, projection='3d')\r\n\r\nax.set_xlabel('x')\r\nax.set_ylabel('y')\r\nax.set_zlabel('z')\r\n\r\nax.view_init(20, 60)\r\n\r\nax.plot_surface(x_plt, y_plt, z_plt, color='b', alpha = 0.5)\r\n\r\nplt.show()\r\nd = 1\r\npoint1 = ax.scatter(x1, y1, f(x1, y1)+d, c='red')\r\npoint2 = ax.scatter(x2, y2, f(x2, y2)+d, c='red')\r\npoint3 = ax.scatter(x3, y3, f(x3, y3)+d, c='red')\r\n\r\n\r\nmn = 5\r\nfor i in range(N):\r\n lmd = 1/min(i+1, mn)\r\n x1 = x1 - lmd*(f(x1+delta,y1)-f(x1-delta, y1))/(2*delta)\r\n x2 = x2 - lmd*(f(x2+delta, y2)-f(x2-delta, y2))/(2*delta)\r\n x3 = x3 - lmd*(f(x3+delta, y3)-f(x3-delta, y3))/(2*delta)\r\n y1 = y1 - lmd * (f(y1 + delta, x1) - f(y1 - delta, x1)) / (2 * delta)\r\n y2 = y2 - lmd * (f(y2 + delta, x2) - f(y2 - delta, x2)) / (2 * delta)\r\n y3 = y3 - lmd * (f(y3 + delta, x3) - f(y3 - delta, x3)) / (2 * delta)\r\n point1.set_offsets([x1, y1])\r\n point1.set_3d_properties([f(x1, y1)+d],'z')\r\n point2.set_offsets([x2, y2])\r\n point2.set_3d_properties([f(x2, y2) + d], 'z')\r\n point3.set_offsets([x3, y3])\r\n point3.set_3d_properties([f(x3, y3) + d], 'z')\r\n fig.canvas.draw()\r\n fig.canvas.flush_events()\r\n time.sleep(0.01)", "repo_name": "Danich-One/VPD_projects", "sub_path": "ReferatVPD.py", "file_name": "ReferatVPD.py", "file_ext": "py", "file_size_in_byte": 2479, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "numpy.arange", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ion", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 79, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 79, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 103, "usage_type": "call"}]} +{"seq_id": "5045698659", "text": "from enum import Enum\n\nfrom tkinter import *\nimport tkinter as tk\nfrom tkinter import filedialog\n\nfrom .youtube_playlist import YoutubePlaylist\n\npad = {\"padx\": 30, \"pady\": 30}\n\nclass Action(Enum):\n BURN = 1\n SAVE = 2\n\nclass Language(Enum):\n ENGLISH = \"English\"\n RUSSIAN = \"русский\"\n\nclass App:\n def __init__(self):\n self.filename=None\n self.root = Tk()\n self.root.tk.call('tk', 'scaling', 10.0)\n self.root.option_add('*Font', 'Times 30')\n self.root.title(\"\")\n self.frame = LabelFrame(self.root, text=\"\", **pad)\n self.frame.pack(**pad)\n\n def create_app(self):\n self._add_languages()\n self._add_urls()\n self._add_actions()\n self._add_save_dir()\n self._add_submit()\n self._update_text()\n self.root.mainloop()\n\n###############\n### Actions ###\n###############\n def _take_action(self):\n self.status_bar = Label(self.frame,\n text=self.status_dl_text,\n bd=1,\n relief=SUNKEN,\n bg=\"yellow\")\n self.status_bar.grid(row=6, columnspan=2, sticky=W+E, **pad)\n\n if self.action_var.get() == Action.SAVE.value:\n song_format = \"mp3\"\n else:\n song_format = \"wav\"\n self.root.update_idletasks()\n self.root.update()\n pl = YoutubePlaylist([self.urls_entry.get().strip()], \"/tmp/yt\")\n filename = self.filename if self.file_shown else None\n pl.generate_audio_medium(save_path=self.filename,\n song_format=song_format)\n self.status_bar[\"text\"] = self.status_done_text\n self.status_bar[\"bg\"] = \"green\"\n self.root.update_idletasks()\n self.root.update()\n\n def _browse_files(self):\n kwargs = {\"initialdir\": \"/tmp/yt2\",\n \"title\": self.select_folder_text}\n self.filename = filedialog.askdirectory(**kwargs)\n self.file_label_entry.delete(0, END)\n self.file_label_entry.insert(0, self.filename)\n self.file_shown = True\n\n def _remove_browse_files(self):\n self.file_label_entry.grid_forget()\n self.file_button.grid_forget()\n self._update_text()\n self.file_shown = False\n\n def _add_browse_files(self, submit_text_update=True):\n self.file_label_entry.grid(row=3, column=1, **pad)\n self.file_button.grid(row=3, column=0, **pad)\n if submit_text_update:\n self._update_text()\n self.file_shown = True\n\n def _update_text(self, *args):\n self.root.title(self.root_text)\n self.frame[\"text\"] = self.root_text\n self.save_files_button[\"text\"] = self.save_files_text\n self.burn_cds_button[\"text\"] = self.burn_cds_text\n self.urls_label[\"text\"] = self.enter_url_text\n self.file_button[\"text\"] = self.select_folder_text\n self.submit[\"text\"] = self.submit_text\n\n##############\n### Format ###\n##############\n\n def _add_languages(self):\n self.language_var = StringVar()\n self.language_var.set(Language.ENGLISH.value)\n OptionMenu(self.frame,\n self.language_var,\n Language.ENGLISH.value,\n Language.RUSSIAN.value,\n command=self._update_text).grid(row=0, column=0, **pad)\n\n\n def _add_actions(self):\n self.action_var = IntVar()\n self.action_var.set(Action.SAVE.value)\n self.save_files_button = Radiobutton(self.frame,\n text=\"\",\n variable=self.action_var,\n value=Action.SAVE.value,\n command=self._add_browse_files\n )\n self.save_files_button.grid(row=0, column=1, sticky=\"W\", **pad)\n self.burn_cds_button = Radiobutton(self.frame,\n text=\"\",\n variable=self.action_var,\n value=Action.BURN.value,\n command=self._remove_browse_files\n )\n self.burn_cds_button.grid(row=1, column=1, stick=\"W\", **pad)\n\n\n def _add_urls(self):\n # URLs\n self.urls_label = Label(self.frame,\n text=self.enter_url_text,\n **pad)\n self.urls_entry = Entry(self.frame, width=50)\n #self.urls_entry.insert(0, (\"ex: https://www.youtube.com/\"\n # \"watch?v=jLtbFWJm9_M\"))\n\n self.urls_label.grid(row=2, column=0, **pad)\n self.urls_entry.grid(row=2, column=1, **pad)\n\n def _add_save_dir(self):\n self.file_label_entry = Entry(self.frame, width=50)\n self.file_button = Button(self.frame,\n text=self.select_folder_text,\n bd=1,\n command=self._browse_files)\n self._add_browse_files(submit_text_update=False)\n\n def _add_submit(self):\n # https://stackoverflow.com/a/1918054/8903959\n self.submit = Button(self.frame,\n text=self.submit_text,\n bd=1,\n #relief=SUNKEN,\n #anchor=E,\n command=self._take_action)\n self.submit.grid(row=4, column=0, columnspan=3, sticky=W+E, **pad)\n\n#############\n### Texts ###\n#############\n\n @property\n def submit_text(self):\n if self.action_var.get() == Action.SAVE.value:\n return self.select_folder_text\n else:\n return self.burn_cds_text\n\n @property\n def root_text(self):\n if self.language_var.get() == Language.ENGLISH.value:\n return \"Youtube Music\"\n elif self.language_var.get() == Language.RUSSIAN.value:\n return \"музыка на YouTube\"\n\n @property\n def select_folder_text(self):\n if self.language_var.get() == Language.ENGLISH.value:\n return \"Select save folder\"\n elif self.language_var.get() == Language.RUSSIAN.value:\n return \"выберите папку для сохранения\"\n\n @property\n def burn_cds_text(self):\n if self.language_var.get() == Language.ENGLISH.value:\n return \"Burn CD(s)\"\n elif self.language_var.get() == Language.RUSSIAN.value:\n return \"записывать компакт-диски\"\n\n @property\n def enter_url_text(self):\n if self.language_var.get() == Language.ENGLISH.value:\n return \"Enter (playlist) URL\"\n elif self.language_var.get() == Language.RUSSIAN.value:\n return \"Введите (плейлист) URL\"\n\n @property\n def save_files_text(self):\n if self.language_var.get() == Language.ENGLISH.value:\n return \"Save file(s)\"\n elif self.language_var.get() == Language.RUSSIAN.value:\n return \"Сохранить файлы\"\n\n @property\n def status_dl_text(self):\n if self.language_var.get() == Language.ENGLISH.value:\n return \"Downloading...\"\n elif self.language_var.get() == Language.RUSSIAN.value:\n return \"скачивание\"\n\n @property\n def status_done_text(self):\n if self.language_var.get() == Language.ENGLISH.value:\n return \"Done!\"\n elif self.language_var.get() == Language.RUSSIAN.value:\n return \"сделано!\"\n\n\n\n\"\"\"\nbutton = Button(root, text=\"click me\", padx=50, pady=50, command=myClick, fg=\"blue\", bg=\"red\")\nbutton.pack()\nroot.mainloop()\n\n# state disabled\n# grid forget\n\"\"\"\n", "repo_name": "jfuruness/lib_youtube_cd_burner", "sub_path": "lib_youtube_cd_burner/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 7856, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "48", "api": [{"api_name": "enum.Enum", "line_number": 11, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 15, "usage_type": "name"}, {"api_name": "youtube_playlist.YoutubePlaylist", "line_number": 55, "usage_type": "call"}, {"api_name": "tkinter.filedialog.askdirectory", "line_number": 67, "usage_type": "call"}, {"api_name": "tkinter.filedialog", "line_number": 67, "usage_type": "name"}]} +{"seq_id": "4312711380", "text": "import logging\nfrom django.conf import settings\nfrom django.core.management import BaseCommand\nfrom bot.models import TgUser\nfrom bot.tg.client import TgClient\nfrom bot.tg.dc import Message\nfrom goals.models import Goal, GoalCategory, BoardParticipant, Board\n\nlogging.basicConfig(format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", level=logging.INFO)\nlogger = logging.getLogger(__name__)\nlogger.info(\"start bot\")\n\nuser_states = {'state': {}}\ncat_id = []\nlogger.info(user_states)\nlogger.info(cat_id)\n\n\nclass Command(BaseCommand):\n help = \"run bot\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.tg_client = TgClient(settings.BOT_TOKEN)\n\n def handle(self, *args, **kwargs):\n offset = 0\n while True:\n res = self.tg_client.get_updates(offset=offset)\n for item in res.result:\n offset = item.update_id + 1\n self.handle_message(item.message)\n\n def handle_message(self, msg: Message):\n tg_user, created = TgUser.objects.get_or_create(user_ud=msg.from_.id, defaults={\"chat_id\": msg.chat.id,\n \"username\": msg.from_.username})\n if \"/start\" in msg.text:\n self.tg_client.send_message(\n msg.chat.id, \"Привет! {msg.chat.first_name}\\n\"\n 'Бот может обрабатывает следующие команды:\\n'\n '/board -> список досок\\n'\n '/category -> список категорий\\n'\n '/goals -> список целей\\n'\n '/create -> создать цель\\n'\n '/cancel -> отменить создание цели\\n')\n\n if tg_user.user:\n self.handle_verified_user(msg, tg_user)\n else:\n self.handle_user_without_verification(msg, tg_user)\n\n #\n def handle_user_without_verification(self, msg: Message, tg_user: TgUser):\n self.tg_client.send_message(\n msg.chat.id,\n 'Добро пожаловать!\\n'\n 'Для продолжения работы необходимо привязать\\n'\n 'Ваш аккаунт\\n',\n )\n tg_user.set_verification_code()\n tg_user.save(update_fields=[\"verification_code\"])\n self.tg_client.send_message(msg.chat.id, f\"Верификационный код: {tg_user.verification_code}\")\n\n def handle_verified_user(self, msg: Message, tg_user: TgUser):\n allowed_commands = ['/goals', '/create', '/cancel']\n\n if not msg.text:\n return\n if \"/start\" in msg.text:\n return\n if \"/board\" in msg.text:\n self.fetch_board(msg, tg_user)\n elif '/goal_category' in msg.text:\n self.fetch_category(msg, tg_user)\n elif '/goals' in msg.text:\n self.fetch_tasks(msg, tg_user)\n elif '/create' in msg.text:\n self.handle_categories(msg, tg_user)\n elif '/cancel' in msg.text:\n self.get_cancel(msg, tg_user)\n\n elif ('user' not in user_states['state']) and (msg.text not in allowed_commands):\n self.tg_client.send_message(tg_user.chat_id, 'Неизвестная команда')\n\n elif (msg.text not in allowed_commands) and (user_states['state']['user']) and (\n 'category' not in user_states['state']):\n category = self.handle_save_category(msg, tg_user)\n if category:\n user_states['state']['category'] = category\n self.tg_client.send_message(tg_user.chat_id,\n f'Выбрана категория:\\n {category}.\\nВведите заголовок цели')\n\n elif (msg.text not in allowed_commands) and (user_states['state']['user']) and (\n user_states['state']['category']) and ('goal_title' not in user_states['state']):\n user_states['state']['goal_title'] = msg.text\n logger.info(user_states)\n goal = Goal.objects.create(title=user_states['state']['goal_title'], user=user_states['state']['user'],\n category=user_states['state']['category'], )\n self.tg_client.send_message(tg_user.chat_id, f'Цель: {goal} создана в БД')\n del user_states['state']['user']\n del user_states['state']['msg_chat_id']\n del user_states['state']['category']\n del user_states['state']['goal_title']\n cat_id.clear()\n\n def fetch_board(self, msg: Message, tg_user: TgUser):\n boards = BoardParticipant.objects.filter(user=tg_user.user)\n # logger.info(boards)\n if boards:\n [self.tg_client.send_message(msg.chat.id, f\"Название: {item.board}\\n\") for item in boards]\n else:\n self.tg_client.send_message(msg.chat.id, \"У вас нет досок\")\n\n def fetch_category(self, msg: Message, tg_user: TgUser):\n resp_categories: list[str] = [\n f'{category.id} {category.title}'\n for category in GoalCategory.objects.filter(\n board__participants__user=tg_user.user_id, is_deleted=False)]\n if resp_categories:\n self.tg_client.send_message(msg.chat.id,\n \"Ваши категории\" + '\\n'.join(resp_categories))\n else:\n self.tg_client.send_message(msg.chat.id, 'У Вас нет ни одной категории!')\n\n def handle_categories(self, msg: Message, tg_user: TgUser):\n\n categories = GoalCategory.objects.filter(user=tg_user.user)\n if categories.count() > 0:\n cat_text = ''\n for cat in categories:\n cat_text += f'{cat.id}: {cat.title} \\n'\n cat_id.append(cat.id)\n self.tg_client.send_message(\n chat_id=tg_user.chat_id,\n text=f'Выберите номер категории для новой цели:\\n========================\\n{cat_text}'\n )\n if 'user' not in user_states['state']:\n user_states['state']['user'] = tg_user.user\n user_states['state']['msg_chat_id'] = tg_user.chat_id\n logger.info(user_states)\n else:\n self.tg_client.send_message(msg.chat.id, 'список категорий пуст')\n\n def fetch_tasks(self, msg: Message, tg_user: TgUser):\n\n goals = Goal.objects.filter(user=tg_user.user)\n if goals.count() > 0:\n [self.tg_client.send_message(tg_user.chat_id,\n f'Название: {goal.title},\\n'\n f'Категория: {goal.category},\\n'\n f'Статус: {goal.get_status_display()},\\n'\n f'Пользователь: {goal.user},\\n'\n f'Дедлайн {goal.due_date if goal.due_date else \"Нет\"} \\n') for goal in goals]\n else:\n self.tg_client.send_message(msg.chat.id, \"Список целей пуст\")\n\n @staticmethod\n def handle_save_category(msg: Message, tg_user: TgUser):\n category_id = int(msg.text)\n category_data = GoalCategory.objects.filter(user=tg_user.user).get(pk=category_id)\n return category_data\n\n def get_cancel(self, msg: Message, tg_user: TgUser):\n if 'user' in user_states['state']:\n del user_states['state']['user']\n del user_states['state']['msg_chat_id']\n\n if 'category' in user_states['state']:\n del user_states['state']['category']\n\n if 'goal_title' in user_states['state']:\n del user_states['state']['goal_title']\n self.tg_client.send_message(tg_user.chat_id, 'Операция отменена')\n", "repo_name": "yellow-carrot/ToDo_List", "sub_path": "bot/management/commands/runbot.py", "file_name": "runbot.py", "file_ext": "py", "file_size_in_byte": 8083, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "logging.basicConfig", "line_number": 9, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 9, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 10, "usage_type": "call"}, {"api_name": "django.core.management.BaseCommand", "line_number": 19, "usage_type": "name"}, {"api_name": "bot.tg.client.TgClient", "line_number": 24, "usage_type": "call"}, {"api_name": "django.conf.settings.BOT_TOKEN", "line_number": 24, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 24, "usage_type": "name"}, {"api_name": "bot.tg.dc.Message", "line_number": 34, "usage_type": "name"}, {"api_name": "bot.models.TgUser.objects.get_or_create", "line_number": 35, "usage_type": "call"}, {"api_name": "bot.models.TgUser.objects", "line_number": 35, "usage_type": "attribute"}, {"api_name": "bot.models.TgUser", "line_number": 35, "usage_type": "name"}, {"api_name": "bot.tg.dc.Message", "line_number": 53, "usage_type": "name"}, {"api_name": "bot.models.TgUser", "line_number": 53, "usage_type": "name"}, {"api_name": "bot.tg.dc.Message", "line_number": 64, "usage_type": "name"}, {"api_name": "bot.models.TgUser", "line_number": 64, "usage_type": "name"}, {"api_name": "goals.models.Goal.objects.create", "line_number": 97, "usage_type": "call"}, {"api_name": "goals.models.Goal.objects", "line_number": 97, "usage_type": "attribute"}, {"api_name": "goals.models.Goal", "line_number": 97, "usage_type": "name"}, {"api_name": "bot.tg.dc.Message", "line_number": 106, "usage_type": "name"}, {"api_name": "bot.models.TgUser", "line_number": 106, "usage_type": "name"}, {"api_name": "goals.models.BoardParticipant.objects.filter", "line_number": 107, "usage_type": "call"}, {"api_name": "goals.models.BoardParticipant.objects", "line_number": 107, "usage_type": "attribute"}, {"api_name": "goals.models.BoardParticipant", "line_number": 107, "usage_type": "name"}, {"api_name": "bot.tg.dc.Message", "line_number": 114, "usage_type": "name"}, {"api_name": "bot.models.TgUser", "line_number": 114, "usage_type": "name"}, {"api_name": "goals.models.GoalCategory.objects.filter", "line_number": 117, "usage_type": "call"}, {"api_name": "goals.models.GoalCategory.objects", "line_number": 117, "usage_type": "attribute"}, {"api_name": "goals.models.GoalCategory", "line_number": 117, "usage_type": "name"}, {"api_name": "bot.tg.dc.Message", "line_number": 125, "usage_type": "name"}, {"api_name": "bot.models.TgUser", "line_number": 125, "usage_type": "name"}, {"api_name": "goals.models.GoalCategory.objects.filter", "line_number": 127, "usage_type": "call"}, {"api_name": "goals.models.GoalCategory.objects", "line_number": 127, "usage_type": "attribute"}, {"api_name": "goals.models.GoalCategory", "line_number": 127, "usage_type": "name"}, {"api_name": "bot.tg.dc.Message", "line_number": 144, "usage_type": "name"}, {"api_name": "bot.models.TgUser", "line_number": 144, "usage_type": "name"}, {"api_name": "goals.models", "line_number": 146, "usage_type": "name"}, {"api_name": "goals.models.Goal.objects.filter", "line_number": 146, "usage_type": "call"}, {"api_name": "goals.models.Goal.objects", "line_number": 146, "usage_type": "attribute"}, {"api_name": "goals.models.Goal", "line_number": 146, "usage_type": "name"}, {"api_name": "goals.models.count", "line_number": 147, "usage_type": "call"}, {"api_name": "goals.models", "line_number": 147, "usage_type": "name"}, {"api_name": "goals.models", "line_number": 153, "usage_type": "name"}, {"api_name": "bot.tg.dc.Message", "line_number": 158, "usage_type": "name"}, {"api_name": "bot.models.TgUser", "line_number": 158, "usage_type": "name"}, {"api_name": "goals.models.GoalCategory.objects.filter", "line_number": 160, "usage_type": "call"}, {"api_name": "goals.models.GoalCategory.objects", "line_number": 160, "usage_type": "attribute"}, {"api_name": "goals.models.GoalCategory", "line_number": 160, "usage_type": "name"}, {"api_name": "bot.tg.dc.Message", "line_number": 163, "usage_type": "name"}, {"api_name": "bot.models.TgUser", "line_number": 163, "usage_type": "name"}]} +{"seq_id": "19626278755", "text": "from rudra.data_store.aws import AmazonS3\nfrom rudra.utils.helper import load_hyper_params\nfrom rudra.utils.validation import BQValidation\nfrom fractions import Fraction\nimport pandas as pd\nimport numpy as np\nimport hpfrec\nimport json\nimport logging\nimport ruamel.yaml\nfrom github import Github\n\nfrom src.config.path_constants import (PACKAGE_TO_ID_MAP, ID_TO_PACKAGE_MAP,\n MANIFEST_TO_ID_MAP, MANIFEST_PATH, HPF_MODEL_PATH, ECOSYSTEM,\n HYPERPARAMETERS_PATH, MODEL_VERSION)\nfrom src.config.cloud_constants import (AWS_S3_BUCKET_NAME, AWS_S3_SECRET_KEY_ID,\n AWS_S3_ACCESS_KEY_ID, GITHUB_TOKEN, DEPLOYMENT_PREFIX)\n\nlogging.basicConfig()\n_logger = logging.getLogger()\n_logger.setLevel(logging.INFO)\n\nbq_validator = BQValidation()\n\nUPSTREAM_REPO_NAME = 'openshiftio'\nFORK_REPO_NAME = 'developer-analytics-bot'\nPROJECT_NAME = 'saas-analytics'\nYAML_FILE_PATH = 'bay-services/f8a-pypi-insights.yaml'\n\n\ndef load_s3(): # pragma: no cover\n \"\"\"Create connection s3.\"\"\"\n s3_object = AmazonS3(bucket_name=AWS_S3_BUCKET_NAME,\n aws_access_key_id=AWS_S3_ACCESS_KEY_ID,\n aws_secret_access_key=AWS_S3_SECRET_KEY_ID)\n\n s3_object.connect()\n if s3_object.is_connected():\n _logger.info(\"S3 connection established for {} bucket\".format(AWS_S3_BUCKET_NAME))\n return s3_object\n\n raise Exception(\"S3 Connection Failed\")\n\n\ndef load_data(s3_client): # pragma: no cover\n \"\"\"Load data from s3 bucket.\"\"\"\n _logger.info(\"Reading Manifest file from {} path\".format(MANIFEST_PATH))\n raw_data_dict = s3_client.read_json_file(MANIFEST_PATH)\n if raw_data_dict is None:\n raise Exception(\"manifest.json not found\")\n _logger.info(\"Size of Raw Manifest file is: {}\".format(len(raw_data_dict)))\n return raw_data_dict\n\n\ndef make_user_item_df(manifest_dict, package_dict, user_input_stacks):\n \"\"\"Make user item dataframe.\"\"\"\n user_item_list = []\n set_input_stacks = {frozenset(x) for x in user_input_stacks}\n for manifest, user_id in manifest_dict.items():\n is_user_input_stack = manifest in set_input_stacks\n for package in manifest:\n item_id = package_dict[package]\n user_item_list.append(\n {\n \"UserId\": user_id,\n \"ItemId\": item_id,\n \"Count\": 1,\n \"is_user_input_stack\": is_user_input_stack\n }\n )\n return user_item_list\n\n\ndef generate_package_id_dict(manifest_list):\n \"\"\"Generate package id dictionary.\"\"\"\n package_id_dict = dict()\n id_package_dict = dict()\n count = 0\n for manifest in manifest_list:\n for package_name in manifest:\n if package_name not in package_id_dict:\n package_id_dict[package_name] = count\n id_package_dict[count] = package_name\n count += 1\n return package_id_dict, id_package_dict\n\n\ndef format_dict(package_id_dict, manifest_id_dict):\n \"\"\"Format the dictionaries.\"\"\"\n format_pkg_id_dict = {'ecosystem': ECOSYSTEM,\n 'package_list': package_id_dict\n }\n format_mnf_id_dict = {'ecosystem': ECOSYSTEM,\n 'manifest_list': manifest_id_dict\n }\n return format_pkg_id_dict, format_mnf_id_dict\n\n\ndef generate_manifest_id_dict(manifest_list):\n \"\"\"Generate manifest id dictionary.\"\"\"\n count = 0\n manifest_id_dict = dict()\n manifest_set = {frozenset(x) for x in manifest_list}\n _logger.info(\"Number of unique manifests are: {}\".format(len(manifest_set)))\n for manifest in manifest_set:\n manifest_id_dict[manifest] = count\n count += 1\n return manifest_id_dict\n\n\ndef run_recommender(train_df, latent_factors): # pragma: no cover\n \"\"\"Start the recommender.\"\"\"\n recommender = hpfrec.HPF(k=latent_factors, random_seed=123,\n ncores=-1, stop_crit='train-llk', verbose=True,\n reindex=False, stop_thr=0.000001, maxiter=3000)\n recommender.step_size = None\n _logger.warning(\"Model is training, Don't interrupt.\")\n recommender.fit(train_df)\n return recommender\n\n\ndef validate_manifest_data(manifest_list): # pragma: no cover\n \"\"\"Validate manifest packages with pypi.\"\"\"\n for idx, manifest in enumerate(manifest_list):\n filtered_manifest = bq_validator.validate_pypi(manifest)\n # Even the filtered manifest is of length 0, we don't care about that here.\n manifest_list[idx] = filtered_manifest\n\n\ndef preprocess_raw_data(raw_data_dict, lower_limit, upper_limit):\n \"\"\"Preprocess raw data.\"\"\"\n all_manifest_list = raw_data_dict.get('user_input_stack', []) \\\n + raw_data_dict.get('bigquery_data', [])\n _logger.info(\"Number of manifests collected = {}\".format(\n len(all_manifest_list)))\n validate_manifest_data(all_manifest_list)\n _logger.info(\"Manifest list now contains only packages from pypi\")\n trimmed_manifest_list = [\n manifest for manifest in all_manifest_list if lower_limit < len(manifest) < upper_limit]\n _logger.info(\"Number of trimmed manifest = {}\".format(\n len(trimmed_manifest_list)))\n package_id_dict, id_package_dict = generate_package_id_dict(trimmed_manifest_list)\n manifest_id_dict = generate_manifest_id_dict(trimmed_manifest_list)\n return package_id_dict, id_package_dict, manifest_id_dict\n\n\n# Calculating DataFrame according to fraction\ndef extra_df(frac, data_df, train_df):\n \"\"\"Calculate extra dataframe.\"\"\"\n remain_frac = float(\"%.2f\" % (0.80 - frac))\n len_df = len(data_df.index)\n no_rows = round(remain_frac * len_df)\n df_remain = pd.concat([data_df, train_df]).drop_duplicates(keep=False)\n df_remain_rand = df_remain.sample(frac=1)\n return df_remain_rand[:no_rows]\n\n\ndef train_test_split(data_df):\n \"\"\"Split for training and testing.\"\"\"\n user_input_df = data_df.loc[data_df['is_user_input_stack']]\n user_input_df = user_input_df.sample(frac=1)\n df_user = user_input_df.drop_duplicates(['UserId'])\n user_input_df = user_input_df.sample(frac=1)\n df_item = user_input_df.drop_duplicates(['ItemId'])\n train_df = pd.concat([df_user, df_item]).drop_duplicates()\n fraction = round(float(Fraction(len(train_df.index),\n len(user_input_df.index))), 2)\n\n if fraction < 0.80:\n df_ = extra_df(fraction, user_input_df, train_df)\n train_df = pd.concat([train_df, df_])\n test_df = pd.concat([user_input_df, train_df]).drop_duplicates(keep=False)\n test_df = test_df.drop(columns=['is_user_input_stack'])\n data_df = data_df.loc[~data_df['is_user_input_stack']]\n train_df = pd.concat([data_df, train_df])\n train_df = train_df.drop(columns=['is_user_input_stack'])\n _logger.info(\"Size of Training DF {} and Testing DF are: {}\".format(\n len(train_df), len(test_df)))\n return train_df, test_df\n\n\n# Calculating recall according to no of recommendations\ndef recall_at_m(m, test_df, recommender, user_count):\n \"\"\"Calculate recall at `m`.\"\"\"\n recall = []\n for i in range(user_count):\n x = np.array(test_df.loc[test_df.UserId.isin([i])].ItemId)\n rec_l = x.size\n recommendations = recommender.topN(user=i, n=m, exclude_seen=True)\n intersection_length = np.intersect1d(x, recommendations).size\n try:\n recall.append(intersection_length / rec_l)\n except ZeroDivisionError:\n pass\n return np.mean(recall)\n\n\ndef precision_at_m(m, test_df, recommender, user_count):\n \"\"\"Calculate precision at `m`.\"\"\"\n precision = []\n for i in range(user_count):\n x = np.array(test_df.loc[test_df.UserId.isin([i])].ItemId)\n recommendations = recommender.topN(user=i, n=m, exclude_seen=True)\n r_size = recommendations.size\n intersection_length = np.intersect1d(x, recommendations).size\n try:\n precision.append(intersection_length / r_size)\n except ZeroDivisionError:\n pass\n return np.mean(precision)\n\n\ndef precision_recall_at_m(m, test_df, recommender, user_item_df):\n \"\"\"Precision and recall at given `m`.\"\"\"\n user_count = user_item_df['UserId'].nunique()\n try:\n precision = precision_at_m(m, test_df, recommender, user_count)\n recall = recall_at_m(m, test_df, recommender, user_count)\n _logger.info(\"Precision {} and Recall are: {}\".format(\n precision, recall))\n return precision, recall\n except ValueError:\n pass\n\n\ndef save_model(s3_client, recommender): # pragma: no cover\n \"\"\"Save model on s3.\"\"\"\n try:\n status = s3_client.write_pickle_file(HPF_MODEL_PATH, recommender)\n _logger.info(\"Model has been saved {}.\".format(status))\n except Exception as exc:\n _logger.error(str(exc))\n\n\ndef save_dictionaries(s3_client, package_id_dict,\n id_package_dict, manifest_id_dict): # pragma: no cover\n \"\"\"Save the dictionaries for scoring.\"\"\"\n pkg_status = s3_client.write_json_file(PACKAGE_TO_ID_MAP,\n package_id_dict)\n id_status = s3_client.write_json_file(ID_TO_PACKAGE_MAP,\n id_package_dict)\n mnf_status = s3_client.write_pickle_file(MANIFEST_TO_ID_MAP,\n manifest_id_dict)\n\n if not (pkg_status and mnf_status and id_status):\n raise Exception(\"Unable to store data files for scoring\")\n\n logging.info(\"Saved dictionaries successfully\")\n\n\ndef save_hyperparams(s3_client, content_json):\n \"\"\"Save hyperparameters.\"\"\"\n status = s3_client.write_json_file(HYPERPARAMETERS_PATH, content_json)\n if not status:\n raise Exception(\"Unable to store hyperparameters file\")\n _logger.info(\"Hyperparameters saved\")\n\n\ndef save_obj(s3_client, trained_recommender, hyper_params,\n package_id_dict, id_package_dict, manifest_id_dict):\n \"\"\"Save the objects in s3 bucket.\"\"\"\n _logger.info(\"Trying to save the model.\")\n save_model(s3_client, trained_recommender)\n save_dictionaries(s3_client, package_id_dict, id_package_dict, manifest_id_dict)\n save_hyperparams(s3_client, hyper_params)\n\n\ndef build_hyperparams(lower_limit, upper_limit, latent_factor,\n precision_30, recall_30, precision_50, recall_50, deployment_type):\n \"\"\"Build hyper parameter object.\"\"\"\n return {\n \"deployment\": deployment_type,\n \"model_version\": MODEL_VERSION,\n \"minimum_length_of_manifest\": lower_limit,\n \"maximum_length_of_manifest\": upper_limit,\n \"latent_factor\": latent_factor,\n \"precision_at_30\": precision_30,\n \"recall_at_30\": recall_30,\n \"f1_score_at_30\": 2 * ((precision_30 * recall_30) / (precision_30 + recall_30)),\n \"precision_at_50\": precision_50,\n \"recall_at_50\": recall_50,\n \"f1_score_at_50\": 2 * ((precision_50 * recall_50) / (precision_50 + recall_50)),\n }\n\n\ndef get_deployed_model_version(yaml_dict, deployment_type):\n \"\"\"Read deployment yaml and return the deployed model verison.\"\"\"\n model_version = None\n environments = yaml_dict.get('services', [{}])[0].get('environments', [])\n for env in environments:\n if env.get('name', '') == deployment_type:\n model_version = env.get('parameters', {}).get('MODEL_VERSION', '')\n break\n\n if model_version is None:\n raise Exception(f'Model version could not be found for deployment {deployment_type}')\n\n _logger.info('Model version: %s for deployment: %s', model_version, deployment_type)\n return model_version\n\n\ndef update_yaml_data(yaml_dict, deployment_type, model_version, hyper_params):\n \"\"\"Update the yaml file for given deployment with model data and description as comments.\"\"\"\n environments = yaml_dict.get('services', [{}])[0].get('environments', [])\n hyper_params = {k: str(v) for k, v in hyper_params.items()}\n for index, env in enumerate(environments):\n if env.get('name', '') == deployment_type:\n yaml_dict['services'][0]['environments'][index]['comments'] = hyper_params\n yaml_dict['services'][0]['environments'][index]['parameters']['MODEL_VERSION'] = \\\n model_version\n break\n\n return ruamel.yaml.dump(yaml_dict, Dumper=ruamel.yaml.RoundTripDumper)\n\n\ndef build_hyper_params_message(hyper_params):\n \"\"\"Build hyper params data string used for PR description and in yaml comments.\"\"\"\n return '- Hyper parameters :: {}'.format(json.dumps(hyper_params, indent=4, sort_keys=True))\n\n\ndef format_body(body):\n \"\"\"Format PR body string to replace decorators.\"\"\"\n return body.replace('\"', '').replace('{', '').replace('}', '').replace(',', '')\n\n\ndef read_deployed_data(upstream_repo, s3_client, deployment_type):\n \"\"\"Read deployed data like yaml file, hyper params, model version.\"\"\"\n upstream_latest_commit_hash = upstream_repo.get_commits()[0].sha\n _logger.info('Upstream latest commit hash: %s', upstream_latest_commit_hash)\n\n contents = upstream_repo.get_contents(YAML_FILE_PATH, ref=upstream_latest_commit_hash)\n yaml_dict = ruamel.yaml.load(contents.decoded_content.decode('utf8'),\n ruamel.yaml.RoundTripLoader)\n\n deployed_version = get_deployed_model_version(yaml_dict, deployment_type)\n deployed_file_path = f'{deployed_version}/intermediate-model/hyperparameters.json'\n deployed_hyperparams = s3_client.read_json_file(deployed_file_path)\n if deployed_hyperparams is None:\n deployed_hyperparams = {}\n\n deployed_data = {\n 'version': deployed_version,\n 'hyperparams': deployed_hyperparams\n }\n yaml_data = {\n 'content_sha': contents.sha,\n 'dict': yaml_dict\n }\n\n return deployed_data, yaml_data, upstream_latest_commit_hash\n\n\ndef create_branch_and_update_yaml(deployment_type, deployed_data, yaml_data,\n hyper_params, latest_commit_hash):\n \"\"\"Create branch and update yaml content on fork repo.\"\"\"\n # Update yaml model version for the given deployment\n new_yaml_data = update_yaml_data(yaml_data['dict'], deployment_type,\n MODEL_VERSION, hyper_params)\n _logger.info('Modified yaml data, new length: %d', len(new_yaml_data))\n\n # Connect to fabric8 analytic repo & get latest commit hash\n f8a_repo = Github(GITHUB_TOKEN).get_repo(f'{FORK_REPO_NAME}/{PROJECT_NAME}')\n _logger.info('f8a fork repo: %s', f8a_repo)\n\n # Create a new branch on f8a repo\n branch_name = f'bump_f8a-pypi-insights_for_{deployment_type}_to_{MODEL_VERSION}'\n branch = f8a_repo.create_git_ref(f'refs/heads/{branch_name}', latest_commit_hash)\n _logger.info('Created new branch [%s] at [%s]', branch, latest_commit_hash)\n\n # Update the yaml content in branch on f8a repo\n commit_message = f'Bump up f8a-pypi-insights for {deployment_type} from ' \\\n f'{deployed_data[\"version\"]} to {MODEL_VERSION}'\n update = f8a_repo.update_file(YAML_FILE_PATH, commit_message, new_yaml_data,\n yaml_data['content_sha'], branch=f'refs/heads/{branch_name}')\n _logger.info('New yaml content hash %s', update['commit'].sha)\n\n return branch_name, commit_message\n\n\ndef create_git_pr(s3_client, hyper_params, deployment_type): # pragma: no cover\n \"\"\"Create a git PR automatically if recall_at_30 is higher than previous iteration.\"\"\"\n upstream_repo = Github(GITHUB_TOKEN).get_repo(f'{UPSTREAM_REPO_NAME}/{PROJECT_NAME}')\n deployed_data, yaml_data, latest_commit_hash = read_deployed_data(upstream_repo, s3_client,\n deployment_type)\n\n recall_at_30 = hyper_params['recall_at_30']\n deployed_recall_at_30 = deployed_data['hyperparams'].get('recall_at_30', 0.55)\n _logger.info('create_git_pr:: Deployed => Model %s, Recall %f Current => Model %s, Recall %f',\n deployed_data['version'], deployed_recall_at_30, MODEL_VERSION, recall_at_30)\n if recall_at_30 >= deployed_recall_at_30:\n promotion_creteria = 'current_recall_at_30 >= deployed_recall_at_30'\n\n params = hyper_params.copy()\n params.update({'promotion_criteria': str(promotion_creteria)})\n branch_name, commit_message = create_branch_and_update_yaml(deployment_type, deployed_data,\n yaml_data, params,\n latest_commit_hash)\n\n hyper_params_formated = build_hyper_params_message(hyper_params)\n prev_hyper_params_formated = build_hyper_params_message(deployed_data['hyperparams'])\n body = f'''Current deployed model details:\n- Model version :: `{deployed_data['version']}`\n{prev_hyper_params_formated}\n\nNew model details:\n- Model version :: `{MODEL_VERSION}`\n{hyper_params_formated}\n\nCriteria for promotion is `{promotion_creteria}`\n'''\n pr = upstream_repo.create_pull(title=commit_message, body=format_body(body),\n head=f'{FORK_REPO_NAME}:{branch_name}',\n base='refs/heads/master')\n _logger.info('Raised SAAS %s for review', pr)\n else:\n _logger.warn('Ignoring latest model %s as its recall %f is less than '\n 'existing model %s recall %f', MODEL_VERSION, recall_at_30,\n deployed_data['version'], deployed_recall_at_30)\n\n\ndef train_model():\n \"\"\"Training model.\"\"\"\n deployment_prefix_to_type_map = {\n 'STAGE': 'staging',\n 'PROD': 'production'\n }\n\n deployment_type = deployment_prefix_to_type_map.get(DEPLOYMENT_PREFIX.upper(), None)\n assert deployment_type is not None, f'Invalid DEPLOYMENT_PREFIX: {DEPLOYMENT_PREFIX}'\n\n s3_obj = load_s3()\n data = load_data(s3_obj)\n hyper_params = load_hyper_params() or {}\n lower_limit = int(hyper_params.get('lower_limit', 2))\n upper_limit = int(hyper_params.get('upper_limit', 100))\n latent_factors = int(hyper_params.get('latent_factor', 40))\n _logger.info(\"Deployment type {} Lower limit {}, Upper limit {} and latent factor {} are used.\"\n .format(DEPLOYMENT_PREFIX, lower_limit, upper_limit, latent_factors))\n package_id_dict, id_package_dict, manifest_id_dict = \\\n preprocess_raw_data(data.get('package_dict', {}), lower_limit, upper_limit)\n user_input_stacks = data.get('package_dict', {}).\\\n get('user_input_stack', [])\n user_item_list = make_user_item_df(manifest_id_dict, package_id_dict, user_input_stacks)\n user_item_df = pd.DataFrame(user_item_list)\n training_df, testing_df = train_test_split(user_item_df)\n format_pkg_id_dict, format_mnf_id_dict = format_dict(package_id_dict, manifest_id_dict)\n trained_recommender = run_recommender(training_df, latent_factors)\n precision_at_30, recall_at_30 = precision_recall_at_m(30, testing_df, trained_recommender,\n user_item_df)\n precision_at_50, recall_at_50 = precision_recall_at_m(50, testing_df, trained_recommender,\n user_item_df)\n try:\n hyper_params = build_hyperparams(lower_limit, upper_limit, latent_factors,\n precision_at_30, recall_at_30,\n precision_at_50, recall_at_50, deployment_type)\n save_obj(s3_obj, trained_recommender, hyper_params,\n format_pkg_id_dict, id_package_dict, format_mnf_id_dict)\n if GITHUB_TOKEN:\n create_git_pr(s3_obj, hyper_params, deployment_type)\n else:\n _logger.info('GITHUB_TOKEN is missing, cannot raise SAAS PR')\n except Exception as error:\n _logger.error(error)\n raise\n\n\nif __name__ == '__main__':\n train_model()\n", "repo_name": "fabric8-analytics/f8a-pypi-insights", "sub_path": "training/train.py", "file_name": "train.py", "file_ext": "py", "file_size_in_byte": 20071, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "48", "api": [{"api_name": "logging.basicConfig", "line_number": 19, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 20, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 21, "usage_type": "attribute"}, {"api_name": "rudra.utils.validation.BQValidation", "line_number": 23, "usage_type": "call"}, {"api_name": "rudra.data_store.aws.AmazonS3", "line_number": 33, "usage_type": "call"}, {"api_name": "src.config.cloud_constants.AWS_S3_BUCKET_NAME", "line_number": 33, "usage_type": "name"}, {"api_name": "src.config.cloud_constants.AWS_S3_ACCESS_KEY_ID", "line_number": 34, "usage_type": "name"}, {"api_name": "src.config.cloud_constants.AWS_S3_SECRET_KEY_ID", "line_number": 35, "usage_type": "name"}, {"api_name": "src.config.cloud_constants.AWS_S3_BUCKET_NAME", "line_number": 39, "usage_type": "argument"}, {"api_name": "src.config.path_constants.MANIFEST_PATH", "line_number": 47, "usage_type": "argument"}, {"api_name": "src.config.path_constants.MANIFEST_PATH", "line_number": 48, "usage_type": "argument"}, {"api_name": "src.config.path_constants.ECOSYSTEM", "line_number": 90, "usage_type": "name"}, {"api_name": "src.config.path_constants.ECOSYSTEM", "line_number": 93, "usage_type": "name"}, {"api_name": "hpfrec.HPF", "line_number": 113, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 153, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 165, "usage_type": "call"}, {"api_name": "fractions.Fraction", "line_number": 166, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 171, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 172, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 175, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 187, "usage_type": "call"}, {"api_name": "numpy.intersect1d", "line_number": 190, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 195, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 202, "usage_type": "call"}, {"api_name": "numpy.intersect1d", "line_number": 205, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 210, "usage_type": "call"}, {"api_name": "src.config.path_constants.HPF_MODEL_PATH", "line_number": 229, "usage_type": "argument"}, {"api_name": "src.config.path_constants.PACKAGE_TO_ID_MAP", "line_number": 238, "usage_type": "argument"}, {"api_name": "src.config.path_constants.ID_TO_PACKAGE_MAP", "line_number": 240, "usage_type": "argument"}, {"api_name": "src.config.path_constants.MANIFEST_TO_ID_MAP", "line_number": 242, "usage_type": "argument"}, {"api_name": "logging.info", "line_number": 248, "usage_type": "call"}, {"api_name": "src.config.path_constants.HYPERPARAMETERS_PATH", "line_number": 253, "usage_type": "argument"}, {"api_name": "src.config.path_constants.MODEL_VERSION", "line_number": 273, "usage_type": "name"}, {"api_name": "ruamel.yaml.yaml.dump", "line_number": 313, "usage_type": "call"}, {"api_name": "ruamel.yaml.yaml", "line_number": 313, "usage_type": "attribute"}, {"api_name": "ruamel.yaml", "line_number": 313, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 318, "usage_type": "call"}, {"api_name": "ruamel.yaml.yaml.load", "line_number": 332, "usage_type": "call"}, {"api_name": "ruamel.yaml.yaml", "line_number": 332, "usage_type": "attribute"}, {"api_name": "ruamel.yaml", "line_number": 332, "usage_type": "name"}, {"api_name": "ruamel.yaml.yaml", "line_number": 333, "usage_type": "attribute"}, {"api_name": "ruamel.yaml", "line_number": 333, "usage_type": "name"}, {"api_name": "src.config.path_constants.MODEL_VERSION", "line_number": 358, "usage_type": "argument"}, {"api_name": "github.Github", "line_number": 362, "usage_type": "call"}, {"api_name": "src.config.cloud_constants.GITHUB_TOKEN", "line_number": 362, "usage_type": "argument"}, {"api_name": "src.config.path_constants.MODEL_VERSION", "line_number": 366, "usage_type": "name"}, {"api_name": "src.config.path_constants.MODEL_VERSION", "line_number": 372, "usage_type": "name"}, {"api_name": "github.Github", "line_number": 382, "usage_type": "call"}, {"api_name": "src.config.cloud_constants.GITHUB_TOKEN", "line_number": 382, "usage_type": "argument"}, {"api_name": "src.config.path_constants.MODEL_VERSION", "line_number": 389, "usage_type": "argument"}, {"api_name": "src.config.path_constants.MODEL_VERSION", "line_number": 406, "usage_type": "name"}, {"api_name": "src.config.path_constants.MODEL_VERSION", "line_number": 417, "usage_type": "argument"}, {"api_name": "src.config.cloud_constants.DEPLOYMENT_PREFIX.upper", "line_number": 428, "usage_type": "call"}, {"api_name": "src.config.cloud_constants.DEPLOYMENT_PREFIX", "line_number": 428, "usage_type": "name"}, {"api_name": "src.config.cloud_constants.DEPLOYMENT_PREFIX", "line_number": 429, "usage_type": "name"}, {"api_name": "rudra.utils.helper.load_hyper_params", "line_number": 433, "usage_type": "call"}, {"api_name": "src.config.cloud_constants.DEPLOYMENT_PREFIX", "line_number": 438, "usage_type": "argument"}, {"api_name": "pandas.DataFrame", "line_number": 444, "usage_type": "call"}, {"api_name": "src.config.cloud_constants.GITHUB_TOKEN", "line_number": 458, "usage_type": "name"}]} +{"seq_id": "32889762230", "text": "import os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nfrom torchvision.transforms import Compose, ToTensor, Normalize, Resize, ToPILImage, PILToTensor\nfrom TransUnet.Data import image_dataset, create_df\nfrom torch.utils.data import DataLoader, Dataset\nfrom Unet.unet import U_net\n\n\ndef show(image, num_class):\n label_colors = np.array([\n (0, 0, 0), # unlabeled\n (128, 64, 128), # paved-area\n (130, 76, 0), # dirt\n (0, 102, 0), # grass\n (112, 103, 87), # gravel\n (28, 42, 168), # water\n (48, 41, 30), # rocks\n (0, 50, 89), # pool\n (107, 142, 35), # vegetation\n (70, 70, 70), # roof\n (102, 102, 156), # wall\n (254, 228, 12), # window\n (254, 148, 12), # door\n (190, 153, 153), # fence\n (153, 153, 153), # fence-pole\n (255, 22, 96), # person\n (102, 51, 0), # dog\n (9, 143, 150), # car\n (119, 11, 32), # bicycle\n (51, 51, 0), # tree\n (190, 250, 190), # bald-tree\n (112, 150, 146), # art-marker\n (2, 135, 115), # obstacle\n (255, 0, 0), # conflicting\n ])\n\n r = np.zeros_like(image).astype(np.uint8)\n g = np.zeros_like(image).astype(np.uint8)\n b = np.zeros_like(image).astype(np.uint8)\n\n for l in range(0, num_class):\n idx = image == l\n r[idx] = label_colors[l, 0]\n g[idx] = label_colors[l, 1]\n b[idx] = label_colors[l, 2]\n\n rgb = np.stack([r, g, b], axis=2)\n return rgb\n\n\nclass model_test:\n def __init__(self, model, path) -> None:\n self.test_model = model\n self.test_model.load_state_dict(torch.load(path))\n\n def process(self, x):\n # Input the image\n return self.test_model(x)\n\n\nif __name__ == '__main__':\n # The data\n df_list = create_df(image_path='../TransUnet/Image_2/val/val-org-img/',\n label_path='../TransUnet/Image_2/val/val-label-img/')\n test_set = image_dataset(image_path=r'../TransUnet/Image_2/val/val-org-img/',\n label_path=r'../TransUnet/Image_2/val/val-label-img/',\n x=df_list,\n mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n test_loader = DataLoader(test_set, batch_size=1, shuffle=False)\n\n # The model\n t_ = model_test(model=U_net(n_channels=3, n_classes=24), path=r'./result/unet_model.pth')\n\n # for i, (images, labels) in enumerate(test_loader):\n # predict = t_.process(images)\n # p = show(image=torch.argmax(predict[0, :, :, :], dim=0).detach().cpu().numpy(), num_class=24)\n # l = show(image=labels[0, :, :].detach().cpu().numpy(), num_class=24)\n # fig = plt.figure()\n # ax1 = plt.subplot(1, 2, 1)\n # ax1.imshow(p)\n # ax2 = plt.subplot(1, 2, 2)\n # ax2.imshow(l)\n # plt.tight_layout()\n # plt.show()\n # print(torch.argmax(predict[0, :, :, :], dim=0).shape)\n # print(torch.argmax(predict[0, :, :, :], dim=0), '\\n', labels[0, :, :])\n\n def read_image(img):\n transform_image = Compose([ToTensor(),\n Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n Resize((128, 256))])\n img = transform_image(cv2.imread(img)).unsqueeze(dim=0)\n return img\n\n\n # 测试\n image_t = read_image(r'../TransUnet/Image_2/val/val-org-img/' + df_list[0] + '.jpg')\n predict = t_.process(image_t)\n p = show(image=torch.argmax(predict[0, :, :, :], dim=0).detach().cpu().numpy(), num_class=24)\n plt.imshow(p)\n plt.show()\n", "repo_name": "1998-Chen/TransUnet", "sub_path": "Unet/test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 3655, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "48", "api": [{"api_name": "numpy.array", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 40, "usage_type": "attribute"}, {"api_name": "numpy.zeros_like", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 41, "usage_type": "attribute"}, {"api_name": "numpy.zeros_like", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 42, "usage_type": "attribute"}, {"api_name": "numpy.stack", "line_number": 50, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 57, "usage_type": "call"}, {"api_name": "TransUnet.Data.create_df", "line_number": 66, "usage_type": "call"}, {"api_name": "TransUnet.Data.image_dataset", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 72, "usage_type": "call"}, {"api_name": "Unet.unet.U_net", "line_number": 75, "usage_type": "call"}, {"api_name": "torchvision.transforms.Compose", "line_number": 92, "usage_type": "call"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 92, "usage_type": "call"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 93, "usage_type": "call"}, {"api_name": "torchvision.transforms.Resize", "line_number": 94, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 95, "usage_type": "call"}, {"api_name": "torch.argmax", "line_number": 102, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 103, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 103, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 104, "usage_type": "name"}]} +{"seq_id": "41871145135", "text": "import argparse\nimport collections\nimport json\nimport os\n\n\nerrors = collections.Counter()\n\nclass DidNotEval(ValueError):\n pass\n\nclass DidNotTrain(ValueError):\n pass\n\nclass NoModel(ValueError):\n pass\n\n\ndef main(args):\n with open(args.file_list) as f:\n file_list = f.read().strip().split('\\n')\n print('file_list', len(file_list))\n\n def readfile(path):\n eval_path, train_path = path.split()\n\n path = eval_path\n slurm_out = os.path.join(path, 'slurm.out')\n eval_json = os.path.join(path, 'train.aligned.txt.eval.json')\n flags_json = os.path.join(train_path, 'flags.json')\n\n if not os.path.exists(slurm_out):\n print('did not eval {} {}'.format(train_path, eval_path))\n raise DidNotEval('')\n\n if not os.path.exists(flags_json):\n print('did not train {} {}'.format(train_path, eval_path))\n raise DidNotTrain('')\n\n with open(flags_json) as f:\n train_flags = json.loads(f.read())\n\n eval_flags = None\n try:\n flags_json = os.path.join(eval_path, 'flags.json')\n with open(flags_json) as f:\n eval_flags = json.loads(f.read())\n except:\n\n with open(slurm_out) as f:\n for i, line in enumerate(f):\n if line.startswith('{'):\n if line[1] == \"'\":\n eval_flags = eval(line)\n else:\n eval_flags = json.loads(line.strip())\n break\n\n train_slurm = os.path.join(train_path, 'slurm.out')\n\n if eval_flags is None:\n print('nothing found', slurm_out, train_slurm)\n raise ValueError\n\n model_path = eval_flags['load']\n\n if not os.path.exists(model_path):\n print('no model {} {}'.format(train_path, eval_path))\n raise NoModel\n\n if os.path.exists(slurm_out) and not os.path.exists(eval_json):\n print('possible error {} {} {} {}'.format(slurm_out, eval_flags['hostname'], train_slurm, train_flags['hostname']))\n errors['train-{}'.format(train_flags['hostname'])] += 1\n errors['eval-{}'.format(eval_flags['hostname'])] += 1\n\n if not os.path.exists(eval_json):\n raise ValueError\n\n # read eval_json\n with open(eval_json) as f:\n o = json.loads(f.read())\n o['path'] = path\n o['train_flags'] = train_flags\n o['eval_flags'] = eval_flags\n return o\n\n def try_map(items, func):\n for x in items:\n try:\n yield func(x)\n except ValueError:\n continue\n\n def groupby(data):\n groups = collections.defaultdict(list)\n\n for ex in data:\n groups[ex['train_flags']['log_dir']].append(ex)\n\n return groups\n\n for k, v in sorted(errors.items(), key=lambda x: x[1]):\n print(k, v)\n\n data = [x for x in try_map(file_list, readfile)]\n for ex in data:\n recall = ex['Corpus Recall using spans for gold']['recall']\n ex['recall'] = recall\n\n groups = groupby(data)\n\n for group in sorted(groups.values(), key=lambda x: max(map(lambda x: x['recall'], x))):\n print(group[0]['train_flags']['log_dir'])\n for ex in sorted(group, key=lambda x: x['path']):\n print(ex['recall'], ex['path'])\n\n print('data', len(data), 'groups', len(groups))\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--file-list', default='eval_json.2021-11-05a.txt', type=str)\n args = parser.parse_args()\n\n print(args.__dict__)\n\n main(args)\n\n\n", "repo_name": "IBM/transition-amr-parser", "sub_path": "src/ibm_neural_aligner/gypsum/view_sweep.py", "file_name": "view_sweep.py", "file_ext": "py", "file_size_in_byte": 3692, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 216, "dataset": "github-code", "pt": "48", "api": [{"api_name": "collections.Counter", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path", "line_number": 28, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path", "line_number": 30, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path", "line_number": 32, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path", "line_number": 36, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 47, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 56, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path", "line_number": 59, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 67, "usage_type": "call"}, {"api_name": "os.path", "line_number": 67, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 71, "usage_type": "call"}, {"api_name": "os.path", "line_number": 71, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path", "line_number": 76, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 81, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 95, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 120, "usage_type": "call"}]} +{"seq_id": "74003709905", "text": "from datetime import datetime, timedelta as t\nfrom functions import parsing\nfrom pymongo import MongoClient\n\nclient = MongoClient('localhost', 27017)\ndb = client.dbtripin\n\nPLACE_TIME_INDEX_0 = t(hours=2)\nPLACE_TIME_INDEX_1 = t(hours=1)\nPLACE_TIME_INDEX_2 = t(hours=1)\n\nCONST_LUNCH_TIME = t(hours=12)\nCONST_DINNER_TIME = t(hours=18)\nCONST_CAFFE_TIME = t(hours=15)\nCONST_HOTEL_TIME = t(hours=21)\n\ndef schedule(places, places_info, start_day, start_time, dists, route, add_place_index):\n # 여행 경로 저장 변수\n total_route = []\n\n # 현재 장소\n current_index = 0\n current_point = route[current_index]\n\n # 현재 시간\n current_day = start_day\n current_time = start_time\n\n # 현재 위치 정보\n current_info = places_info[0]\n\n # 다음 위치\n next_index = current_index + 1\n next_point = route[next_index]\n\n #장소 추가 유무 변수 - 0: 추가안해도됨, 1: 추가해야됨\n lunch_bool, dinner_bool, caffe_bool, hotel_bool = add_place_index\n\n # 장소 추가 시점 변수\n lunch_time = current_day + CONST_LUNCH_TIME\n dinner_time = current_day + CONST_DINNER_TIME\n caffe_time = current_day + CONST_CAFFE_TIME\n hotel_time = current_day + CONST_HOTEL_TIME\n\n # 실재 여행 경로\n real_route = [0]\n # real_places = [places[0]]\n # real_info = [places_info[0]]\n\n # 다음으로 이동할 장소의 종류 - 0: 여행 장소, 1: 맛집, 2:카페, 3:숙소\n index = 0\n\n while 1:\n # 다음 이동 장소 판단\n if lunch_bool and current_time > lunch_time:\n index = 1\n elif dinner_bool and current_time > dinner_time:\n index = 1\n elif caffe_bool and current_time > caffe_time:\n index = 2\n elif hotel_bool and current_time > hotel_time:\n index = 3\n else: # index == 0:\n index = 0\n\n if index == 0:\n # 여행 장소 -> 여행 장소\n if current_info['index'] == 0:\n\n # 이동 시간\n move_time = dists[current_point][next_point]\n\n # 시간 업데이트\n current_time += t(minutes=move_time)\n print(current_time, ':', places[current_point], '->', places[next_point])\n temp_place = {\n 'time': current_time,\n 'doing': places[current_point] + '->' + places[next_point]\n }\n total_route.append(temp_place)\n\n # 추가한 장소 -> 여행 장소\n else:\n # 이동 시간\n duration = parsing.duration_minute(index, current_info['word'], 0, places[next_point], places_info)\n\n # 시간 업데이트\n current_time += t(minutes=duration)\n print(current_time, ':', current_info['name'], '->', places[next_point])\n temp_place = {\n 'time': current_time,\n 'doing': current_info['name'] + '->' + places[next_point]\n }\n total_route.append(temp_place)\n\n # 인덱스 수정\n current_index = next_index\n current_point = route[current_index]\n current_info = places_info[current_point]\n\n # 이동한 위치 저장\n real_route.append(current_point)\n # real_places.append(places[current_point])\n # real_info.append(current_info)\n\n # 다음 장소 이동\n if current_index < len(route) - 1:\n next_index = current_index + 1\n next_point = route[next_index]\n\n # 관광 시간 업데이트\n current_time += PLACE_TIME_INDEX_0\n print(current_time, ':', places[current_point], '관광')\n temp_place = {\n 'time': current_time,\n 'doing': places[current_point] + '관광'\n }\n total_route.append(temp_place)\n\n current_index += 1\n if current_index == len(route):\n # print('break :', current_index)\n break\n\n else:\n # 여행 장소 -> 추가한 장소\n if current_info['index'] == 0:\n # 추가한 장소\n add_place = parsing.parsing(index, places[current_point], places_info)\n\n # 이동 시간\n duration = parsing.duration_minute(0, places[current_point], index, add_place['word'], places_info)\n\n # 시간 업데이트\n current_time += t(minutes=duration)\n print(current_time, ':', places[current_point], '->', add_place['name'])\n temp_place = {\n 'time': current_time,\n 'doing': places[current_point] + '->' + add_place['name']\n }\n total_route.append(temp_place)\n\n # 추가한 장소 -> 추가한 장소\n else:\n\n # 이동할 추가한 장소\n add_place = parsing.parsing(index, places[current_point], places_info)\n\n # 이동 시간\n duration = parsing.duration_minute(current_info['index'], places[current_point], index,\n add_place['word'], places_info)\n\n # 시간 업데이트\n current_time += t(minutes=duration)\n print(current_time, ':', current_info['name'], '->', add_place['name'])\n temp_place = {\n 'time': current_time,\n 'doing': current_info['name'] + '->' + add_place['name']\n }\n total_route.append(temp_place)\n\n # 이동한 위치 저장\n add_point = len(places)\n current_info = add_place\n places.append(add_place['name'])\n real_route.append(add_point)\n\n # 소요 시간 업데이트\n if index == 1:\n current_time += PLACE_TIME_INDEX_1\n print(current_time, ': 식사 시간')\n temp_place = {\n 'time': current_time,\n 'doing': '식사 시간'\n }\n total_route.append(temp_place)\n\n if lunch_bool:\n lunch_bool = 0\n else:\n if dinner_bool:\n dinner_bool = 0\n elif index == 2:\n current_time += PLACE_TIME_INDEX_2\n print(current_time, ': 카페 시간')\n temp_place = {\n 'time': current_time,\n 'doing': '카페 시간'\n }\n total_route.append(temp_place)\n caffe_bool = 0\n elif index == 3:\n current_day += t(days=1)\n current_time = current_day + t(hours=10)\n lunch_time = current_day + CONST_LUNCH_TIME\n dinner_time = current_day + CONST_DINNER_TIME\n caffe_time = current_day + CONST_CAFFE_TIME\n hotel_time = current_day + CONST_HOTEL_TIME\n lunch_bool, dinner_bool, caffe_bool, hotel_bool = add_place_index\n print(current_time, ': 숙소 시간')\n temp_place = {\n 'time': current_time,\n 'doing': '숙소 시간'\n }\n total_route.append(temp_place)\n\n real_places = []\n for i in real_route:\n real_places.append(places[i])\n print('변경된 여행 경로 :', real_places)\n\n return total_route\n\n\n\n\n# t_places = ['서울역', '남산타워', '경복궁', '광화문']\n# t_places_info = [\n# {'id': '11630456', 'name': '서울역 경부선(고속철도)', 'x': '126.9706649', 'y': '37.5550333',\n# 'address': '서울특별시 중구 봉래동2가 122-21 서울역', 'word': '서울역', 'index': 0},\n# {'id': '38345004', 'name': '남산서울타워', 'x': '126.9882487', 'y': '37.5512164', 'address': '서울특별시 용산구 용산동2가 산1-3',\n# 'word': '남산타워', 'index': 0},\n# {'id': '11571707', 'name': '경복궁', 'x': '126.9770162', 'y': '37.5788407', 'address': '서울특별시 종로구 세종로 1-91',\n# 'word': '경복궁', 'index': 0},\n# {'id': '13161322', 'name': '광화문', 'x': '126.9768428', 'y': '37.5760260', 'address': '서울특별시 종로구 세종로 1-57',\n# 'word': '광화문', 'index': 0}]\n#\n# t_start_day = datetime(2022, 4, 14, 0, 0, 0)\n# t_start_time = t_start_day + t(hours=10)\n# t_dists = [[0, 53, 75, 66],\n# [63, 0, 68, 73],\n# [80, 65, 0, 40],\n# [60, 71, 43, 0]]\n# t_route = [0, 1, 2, 3, 0]\n#\n# add_place_index = [1, 1, 1, 1]\n#\n# schedule(t_places, t_places_info, t_start_day, t_start_time, t_dists, t_route, add_place_index)\n\n", "repo_name": "kimphysicsman/Travel_recommedation", "sub_path": "functions/schedule.py", "file_name": "schedule.py", "file_ext": "py", "file_size_in_byte": 8899, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "48", "api": [{"api_name": "pymongo.MongoClient", "line_number": 5, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 8, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 9, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 10, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 12, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 15, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 74, "usage_type": "call"}, {"api_name": "functions.parsing.duration_minute", "line_number": 85, "usage_type": "call"}, {"api_name": "functions.parsing", "line_number": 85, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 88, "usage_type": "call"}, {"api_name": "functions.parsing.parsing", "line_number": 129, "usage_type": "call"}, {"api_name": "functions.parsing", "line_number": 129, "usage_type": "name"}, {"api_name": "functions.parsing.duration_minute", "line_number": 132, "usage_type": "call"}, {"api_name": "functions.parsing", "line_number": 132, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 135, "usage_type": "call"}, {"api_name": "functions.parsing.parsing", "line_number": 147, "usage_type": "call"}, {"api_name": "functions.parsing", "line_number": 147, "usage_type": "name"}, {"api_name": "functions.parsing.duration_minute", "line_number": 150, "usage_type": "call"}, {"api_name": "functions.parsing", "line_number": 150, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 154, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 193, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 194, "usage_type": "call"}]} +{"seq_id": "20782422073", "text": "import matplotlib.pyplot as plt\nimport csv\n\nxFIFO = []\nyFIFO = []\n\nxLRU = []\nyLRU = []\n\nxRandom = []\nyRandom = []\n\nwith open('csvFIFO.csv','r') as csvFIFO, open('csvLRU.csv','r') as csvLRU, open('csvRandom.csv','r') as csvRandom:\n\tFIFOlines = csv.reader(csvFIFO, delimiter=',')\n\tfor row in FIFOlines:\n\t\txFIFO.append(row[0])\n\t\tyFIFO.append(row[1])\n\t\t\n\tLRUlines = csv.reader(csvLRU, delimiter=',')\n\tfor row in LRUlines:\n\t\txLRU.append(row[0])\n\t\tyLRU.append(row[1])\n\t\n\tRandomlines = csv.reader(csvRandom, delimiter=',')\n\tfor row in Randomlines:\n\t\txRandom.append(row[0])\n\t\tyRandom.append(row[1])\n\t\n# plot all the data\nplt.plot(xFIFO, yFIFO, color = 'blue', linestyle = 'solid', marker = 'o', label = \"FIFO\")\nplt.plot(xLRU, yLRU, color = 'green', linestyle = 'solid', marker = '*', label = \"LRU\")\nplt.plot(xRandom, yRandom, color = 'red', linestyle = 'solid', marker = '^', label = \"Random\")\n\nplt.xlabel('Frames')\nplt.ylabel('Page Faults')\nplt.show()", "repo_name": "ShahilPatel-IITDh/Operating-Systems", "sub_path": "Lab-8/AllPlot.py", "file_name": "AllPlot.py", "file_ext": "py", "file_size_in_byte": 944, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "csv.reader", "line_number": 14, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 19, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}]} +{"seq_id": "19627984365", "text": "\nfrom utils import Input, printResult\n\n# https://adventofcode.com/2020/day/3\n\ninput = Input(2020, 3).lines()\n\nm = [0] * 5\nfor y, line in enumerate(input):\n m[0] += line[y % len(line)] == '#'\n m[1] += line[(y * 3) % len(line)] == '#'\n m[2] += line[(y * 5) % len(line)] == '#'\n m[3] += line[(y * 7) % len(line)] == '#'\n m[4] += y%2 == 0 and line[y//2 % len(line)] == '#'\n\nprintResult(1, m[1])\nprintResult(2, m[0] * m[1] * m[2] * m[3] * m[4])\n", "repo_name": "Zefick/Advent-of-Code", "sub_path": "src/Python/2020/Day03.py", "file_name": "Day03.py", "file_ext": "py", "file_size_in_byte": 455, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "utils.Input", "line_number": 6, "usage_type": "call"}, {"api_name": "utils.printResult", "line_number": 16, "usage_type": "call"}, {"api_name": "utils.printResult", "line_number": 17, "usage_type": "call"}]} +{"seq_id": "31585144573", "text": "import pandas as pd\nfrom Bio import SeqIO\n\n\noperon_df = pd.read_csv(\"operon_df_filtered.csv\")\n\nwith open(\"final_filtered_mgyp_list.txt\", \"r\") as mgypfile:\n mgyp_list = [line.rstrip() for line in mgypfile]\n\n\noperon_df = operon_df.query(\"`Encapsulin MGYP` in @mgyp_list\")\noutfile = operon_df.to_csv(\"operon_df_filtered.csv\", index=False)\n\nall_cargos = []\nfor i in [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:\n all_cargos.extend(operon_df[f\"{i}\"].to_list())\n\nall_cargos = set(all_cargos)\n\n\nall_records = []\nfor record in SeqIO.parse(\"seqs/all_putative_cargo_proteins.fasta\", \"fasta\"):\n if str(record.id) in all_cargos:\n all_records.append(record)\n \n\noutfile = SeqIO.write(all_records, \"seqs/filtered_cargo_proteins.fasta\", \"fasta\")", "repo_name": "naailkhan28/encapsulin_metagenomics", "sub_path": "scripts/25_refilter_cargo_sequences.py", "file_name": "25_refilter_cargo_sequences.py", "file_ext": "py", "file_size_in_byte": 776, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "48", "api": [{"api_name": "pandas.read_csv", "line_number": 5, "usage_type": "call"}, {"api_name": "Bio.SeqIO.parse", "line_number": 22, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 22, "usage_type": "name"}, {"api_name": "Bio.SeqIO.write", "line_number": 27, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 27, "usage_type": "name"}]} +{"seq_id": "16690993861", "text": "import threading\nimport weakref\nfrom collections import namedtuple\n\nfrom ..utils import import_class_member\nfrom ...compat import six\nfrom ...utils import hashable\nfrom ...df import DataFrame\nfrom ...df.expr.collections import CollectionExpr, Expr, FilterPartitionCollectionExpr\nfrom ...df.expr.dynamic import DynamicMixin, DynamicCollectionExpr\nfrom ...utils import get_id\n\nexpr_output_registry = dict()\nshared_props_registry = dict()\n\n\nclass AlgoExprProxy(object):\n def __init__(self, expr):\n def _finalizer(_):\n if self._exec_id not in expr_output_registry:\n return\n if self._register_name in expr_output_registry[self._exec_id]:\n del expr_output_registry[self._exec_id][self._register_name]\n if len(expr_output_registry[self._exec_id]) == 0:\n del expr_output_registry[self._exec_id]\n if self._exec_id in shared_props_registry:\n del shared_props_registry[self._exec_id]\n\n self._ref = weakref.ref(expr, _finalizer)\n self._exec_id = expr._exec_id\n self._register_name = expr.register_name\n\n def __call__(self):\n return self._ref()\n\n def __getattr__(self, item):\n return getattr(self._ref(), item)\n\n\nclass AlgoExprMixin(Expr):\n _mixin_slots = '_exec_id', '_params', '_engine_kw', '_output_name', '_persist_kw', '_cases', \\\n '_table_callback', '_is_extra'\n _add_args_slots = False\n _algo = ''\n\n @staticmethod\n def cache_input(expr):\n if not isinstance(expr, Expr):\n return expr\n if isinstance(expr, FilterPartitionCollectionExpr) and isinstance(expr.input, DataFrame):\n return expr\n if isinstance(expr, AlgoExprMixin) and expr.executed:\n return expr\n return expr.cache(mem=False)\n\n def _register_name(self):\n return self._output_name\n\n register_name = property(fget=_register_name)\n\n def register_expr(self):\n if self._exec_id not in expr_output_registry:\n expr_output_registry[self._exec_id] = dict()\n expr_output_registry[self._exec_id][self.register_name] = AlgoExprProxy(self)\n shared_props_registry[self._exec_id] = dict()\n shared_props_registry[self._exec_id]['executed'] = False\n\n def uncache(self):\n pass\n\n def _get_executed(self):\n if self._exec_id not in shared_props_registry:\n return False\n return shared_props_registry[self._exec_id].get('executed', False)\n\n def _set_executed(self, value):\n if self._exec_id not in shared_props_registry:\n shared_props_registry[self._exec_id] = dict()\n shared_props_registry[self._exec_id]['executed'] = value\n if value and 'exec_lock' in shared_props_registry[self._exec_id]:\n exec_lock = shared_props_registry[self._exec_id]['exec_lock']\n exec_lock.release()\n\n executed = property(fget=lambda self: self._get_executed(),\n fset=lambda self, value: self._set_executed(value))\n\n def wait_execution(self):\n if self._exec_id not in shared_props_registry:\n shared_props_registry[self._exec_id] = dict()\n if 'exec_lock' not in shared_props_registry[self._exec_id]:\n exec_lock = threading.Lock()\n shared_props_registry[self._exec_id]['exec_lock'] = exec_lock\n else:\n exec_lock = shared_props_registry[self._exec_id]['exec_lock']\n if not self.executed:\n exec_lock.acquire()\n\n def convert_params(self, src_expr=None):\n params = dict((k, v) for k, v in six.iteritems(self._params) if k in self._exported)\n\n for name, exporter in six.iteritems(self._exporters):\n if src_expr is not None:\n params[name] = exporter(src_expr)\n if not params[name]:\n params[name] = exporter(self)\n\n for k, v in list(six.iteritems(params)):\n if v is None:\n params.pop(k)\n if isinstance(v, (list, tuple, set)) and len(v) == 0:\n params.pop(k)\n return params\n\n @property\n def persist_kw(self):\n if self._exec_id not in expr_output_registry:\n raise AttributeError\n if self.register_name not in expr_output_registry[self._exec_id]:\n raise AttributeError\n return expr_output_registry[self._exec_id][self.register_name]._persist_kw\n\n @persist_kw.setter\n def persist_kw(self, value):\n if self._exec_id not in expr_output_registry:\n raise AttributeError\n if self.register_name not in expr_output_registry[self._exec_id]:\n raise AttributeError\n expr_output_registry[self._exec_id][self.register_name]._persist_kw = value\n\n @property\n def shared_kw(self):\n if self._exec_id not in shared_props_registry:\n raise AttributeError\n return shared_props_registry[self._exec_id].get('shared_kw', dict())\n\n @shared_kw.setter\n def shared_kw(self, value):\n if self._exec_id not in shared_props_registry:\n raise AttributeError\n shared_props_registry[self._exec_id]['shared_kw'] = value\n\n def outputs(self):\n if getattr(self, '_exec_id', None) is None:\n return dict()\n out_dict = expr_output_registry.get(self._exec_id, dict())\n out_dict = dict((k, v()) for k, v in six.iteritems(out_dict))\n return dict((k, v) for k, v in six.iteritems(out_dict) if v is not None and not v.is_extra_expr)\n\n @property\n def is_extra_expr(self):\n return getattr(self, '_is_extra', False)\n\n\nclass AlgoCollectionExpr(AlgoExprMixin, CollectionExpr):\n _suffix = 'CollectionExpr'\n node_name = 'Algo'\n\n def _init(self, *args, **kwargs):\n register_expr = kwargs.pop('register_expr', False)\n\n p_args = [a.cache() if isinstance(a, Expr) else a for a in args]\n p_kw = dict((k, self.cache_input(v)) for k, v in six.iteritems(kwargs))\n\n absent_args = (a for a in self._args[len(args):] if a not in p_kw)\n for a in absent_args:\n p_kw[a] = None\n\n super(AlgoCollectionExpr, self)._init(*p_args, **p_kw)\n self.cache(False)\n\n if register_expr:\n self.register_expr()\n\n def accept(self, visitor):\n visitor.visit_algo(self)\n\n\nclass DynamicAlgoCollectionExpr(DynamicMixin, AlgoCollectionExpr):\n def __init__(self, *args, **kwargs):\n DynamicMixin.__init__(*args, **kwargs)\n AlgoCollectionExpr.__init__(*args, **kwargs)\n\n _project = DynamicCollectionExpr._project\n\n\nmetrics_tables = dict()\nmetrics_executed = dict()\n\n\nclass MetricsResultExpr(AlgoExprMixin, Expr):\n __slots__ = '_metrics_hash', '_result_callback'\n _suffix = 'ResultExpr'\n _non_table = True\n node_name = 'Metrics'\n\n def _init(self, *args, **kwargs):\n kwargs.pop('register_expr', False)\n\n p_args = [a.cache() if isinstance(a, Expr) else a for a in args]\n p_kw = dict((k, self.cache_input(v)) for k, v in six.iteritems(kwargs))\n\n absent_args = (a for a in self._args[len(args):] if a not in p_kw)\n for a in absent_args:\n p_kw[a] = None\n\n super(MetricsResultExpr, self)._init(*p_args, **p_kw)\n\n if getattr(self, '_metrics_hash', None) is None:\n param_hash = hash(frozenset(six.iteritems(hashable(self._params))))\n port_hash = hash(frozenset(self.get_input_hash(pt) for pt in self.input_ports))\n self._metrics_hash = hash((self.node_name, param_hash, port_hash))\n\n def get_input_hash(self, input_port):\n from .exporters import get_ml_input\n input_expr = get_ml_input(self, input_port.name)\n pid = get_id(input_expr) if input_expr else None\n return hash((input_port.name, pid))\n\n @property\n def tables_tuple(self):\n cls = type(self)\n if not hasattr(cls, '_tables_tuple'):\n cls._tables_tuple = namedtuple('_tables_tuple', [pt.name for pt in cls.output_ports])\n return cls._tables_tuple\n\n @property\n def calculator(self):\n cls = type(self)\n if not hasattr(cls, '_calculator'):\n cls._calculator = import_class_member(self.algo_meta['calculator'])\n return self._calculator\n\n def accept(self, visitor):\n visitor.visit_algo(self)\n\n def _get_executed(self):\n return metrics_executed.get(self._metrics_hash, False)\n\n def _set_executed(self, value):\n metrics_executed[self._metrics_hash] = value\n\n @property\n def tables(self):\n return metrics_tables.get(self._metrics_hash)\n\n @tables.setter\n def tables(self, value):\n if isinstance(value, dict):\n value = self.tables_tuple(**value)\n metrics_tables[self._metrics_hash] = value\n\n\ndef make_extra_expr(expr, name, schema, **kw):\n new_expr = expr.copy(clear_keys=['_id'], register_expr=True, _is_extra=True, _schema=schema,\n _output_name=name, **kw)\n new_expr.cache(False)\n return new_expr\n", "repo_name": "aliyun/aliyun-odps-python-sdk", "sub_path": "odps/ml/expr/core.py", "file_name": "core.py", "file_ext": "py", "file_size_in_byte": 9042, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 399, "dataset": "github-code", "pt": "48", "api": [{"api_name": "weakref.ref", "line_number": 29, "usage_type": "call"}, {"api_name": "df.expr.collections.Expr", "line_number": 40, "usage_type": "name"}, {"api_name": "df.expr.collections.Expr", "line_number": 48, "usage_type": "argument"}, {"api_name": "df.expr.collections.FilterPartitionCollectionExpr", "line_number": 50, "usage_type": "argument"}, {"api_name": "df.DataFrame", "line_number": 50, "usage_type": "argument"}, {"api_name": "threading.Lock", "line_number": 91, "usage_type": "call"}, {"api_name": "compat.six.iteritems", "line_number": 99, "usage_type": "call"}, {"api_name": "compat.six", "line_number": 99, "usage_type": "name"}, {"api_name": "compat.six.iteritems", "line_number": 101, "usage_type": "call"}, {"api_name": "compat.six", "line_number": 101, "usage_type": "name"}, {"api_name": "compat.six.iteritems", "line_number": 107, "usage_type": "call"}, {"api_name": "compat.six", "line_number": 107, "usage_type": "name"}, {"api_name": "compat.six.iteritems", "line_number": 146, "usage_type": "call"}, {"api_name": "compat.six", "line_number": 146, "usage_type": "name"}, {"api_name": "compat.six.iteritems", "line_number": 147, "usage_type": "call"}, {"api_name": "compat.six", "line_number": 147, "usage_type": "name"}, {"api_name": "df.expr.collections.CollectionExpr", "line_number": 154, "usage_type": "name"}, {"api_name": "df.expr.collections.Expr", "line_number": 161, "usage_type": "argument"}, {"api_name": "compat.six.iteritems", "line_number": 162, "usage_type": "call"}, {"api_name": "compat.six", "line_number": 162, "usage_type": "name"}, {"api_name": "df.expr.dynamic.DynamicMixin", "line_number": 178, "usage_type": "name"}, {"api_name": "df.expr.dynamic.DynamicMixin.__init__", "line_number": 180, "usage_type": "call"}, {"api_name": "df.expr.dynamic.DynamicMixin", "line_number": 180, "usage_type": "name"}, {"api_name": "df.expr.dynamic.DynamicCollectionExpr._project", "line_number": 183, "usage_type": "attribute"}, {"api_name": "df.expr.dynamic.DynamicCollectionExpr", "line_number": 183, "usage_type": "name"}, {"api_name": "df.expr.collections.Expr", "line_number": 190, "usage_type": "name"}, {"api_name": "df.expr.collections.Expr", "line_number": 199, "usage_type": "argument"}, {"api_name": "compat.six.iteritems", "line_number": 200, "usage_type": "call"}, {"api_name": "compat.six", "line_number": 200, "usage_type": "name"}, {"api_name": "compat.six.iteritems", "line_number": 209, "usage_type": "call"}, {"api_name": "compat.six", "line_number": 209, "usage_type": "name"}, {"api_name": "utils.hashable", "line_number": 209, "usage_type": "call"}, {"api_name": "exporters.get_ml_input", "line_number": 215, "usage_type": "call"}, {"api_name": "utils.get_id", "line_number": 216, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 223, "usage_type": "call"}, {"api_name": "utils.import_class_member", "line_number": 230, "usage_type": "call"}]} +{"seq_id": "39095266883", "text": "from sentence_transformers.evaluation import SentenceEvaluator\nfrom sentence_transformers.util import batch_to_device\nfrom sentence_transformers import SentenceTransformer\nfrom typing import List, Tuple, Dict\nimport torch\nimport numpy as np\nimport logging\nimport os\nimport csv\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass MSEEvaluatorFromDataFrame(SentenceEvaluator):\n \"\"\"\n Computes the mean squared error (x100) between the computed sentence embedding\n and some target sentence embedding.\n :param dataframe:\n It must have the following format. Rows contains different, parallel sentences. Columns are the respective language codes\n [{'en': 'My sentence', 'es': 'Sentence in Spanisch', 'fr': 'Sentence in French'...},\n {'en': 'My second sentence', ....]\n :param combinations:\n Must be of the format [('en', 'es'), ('en', 'fr'), ...]\n First entry in a tuple is the source language. The sentence in the respective language will be fetched from the dataframe and passed to the teacher model.\n Second entry in a tuple the the target language. Sentence will be fetched from the dataframe and passed to the student model\n \"\"\"\n def __init__(self, dataframe: List[Dict[str, str]], teacher_model: SentenceTransformer, combinations: List[Tuple[str, str]], batch_size: int = 8, name='', write_csv: bool = True):\n\n self.combinations = combinations\n self.name = name\n self.batch_size = batch_size\n\n\n if name:\n name = \"_\"+name\n\n self.csv_file = \"mse_evaluation\" + name + \"_results.csv\"\n self.csv_headers = [\"epoch\", \"steps\"]\n self.write_csv = write_csv\n self.data = {}\n\n logger.info(\"Compute teacher embeddings\")\n all_source_sentences = set()\n for src_lang, trg_lang in self.combinations:\n src_sentences = []\n trg_sentences = []\n\n for row in dataframe:\n if row[src_lang].strip() != \"\" and row[trg_lang].strip() != \"\":\n all_source_sentences.add(row[src_lang])\n src_sentences.append(row[src_lang])\n trg_sentences.append(row[trg_lang])\n\n self.data[(src_lang, trg_lang)] = (src_sentences, trg_sentences)\n self.csv_headers.append(\"{}-{}\".format(src_lang, trg_lang))\n\n all_source_sentences = list(all_source_sentences)\n all_src_embeddings = teacher_model.encode(all_source_sentences, batch_size=self.batch_size)\n self.teacher_embeddings = {sent: emb for sent, emb in zip(all_source_sentences, all_src_embeddings)}\n\n def __call__(self, model, output_path: str = None, epoch: int = -1, steps: int = -1):\n model.eval()\n\n mse_scores = []\n for src_lang, trg_lang in self.combinations:\n src_sentences, trg_sentences = self.data[(src_lang, trg_lang)]\n\n src_embeddings = np.asarray([self.teacher_embeddings[sent] for sent in src_sentences])\n trg_embeddings = np.asarray(model.encode(trg_sentences, batch_size=self.batch_size))\n\n mse = ((src_embeddings - trg_embeddings) ** 2).mean()\n mse *= 100\n mse_scores.append(mse)\n\n logger.info(\"MSE evaluation on {} dataset - {}-{}:\".format(self.name, src_lang, trg_lang))\n logger.info(\"MSE (*100):\\t{:4f}\".format(mse))\n\n if output_path is not None and self.write_csv:\n csv_path = os.path.join(output_path, self.csv_file)\n output_file_exists = os.path.isfile(csv_path)\n with open(csv_path, newline='', mode=\"a\" if output_file_exists else 'w', encoding=\"utf-8\") as f:\n writer = csv.writer(f)\n if not output_file_exists:\n writer.writerow(self.csv_headers)\n\n writer.writerow([epoch, steps]+mse_scores)\n\n return -np.mean(mse_scores) #Return negative score as SentenceTransformers maximizes the performance\n\n", "repo_name": "UKPLab/sentence-transformers", "sub_path": "sentence_transformers/evaluation/MSEEvaluatorFromDataFrame.py", "file_name": "MSEEvaluatorFromDataFrame.py", "file_ext": "py", "file_size_in_byte": 3940, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 12439, "dataset": "github-code", "pt": "48", "api": [{"api_name": "logging.getLogger", "line_number": 12, "usage_type": "call"}, {"api_name": "sentence_transformers.evaluation.SentenceEvaluator", "line_number": 15, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 28, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 28, "usage_type": "name"}, {"api_name": "sentence_transformers.SentenceTransformer", "line_number": 28, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 28, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 70, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 80, "usage_type": "call"}, {"api_name": "os.path", "line_number": 80, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 81, "usage_type": "call"}, {"api_name": "os.path", "line_number": 81, "usage_type": "attribute"}, {"api_name": "csv.writer", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 89, "usage_type": "call"}]} +{"seq_id": "72683143826", "text": "from flax import linen as nn\nfrom typing import (Any, Callable, Tuple, Optional)\nimport jax\nfrom flax.linen import compact\nfrom jax import lax, random, numpy as jnp\nimport numpy as np\nfrom functools import partial\nPRNGKey = Any\nShape = Tuple[int]\nDtype = Any\nArray = Any\n\nACT2FN = {\n \"gelu\": nn.gelu,\n \"relu\": nn.relu,\n \"silu\": nn.swish,\n \"swish\": nn.swish,\n \"gelu_new\": partial(nn.gelu, approximate=True),\n}\n\nclass FlaxBertEmbedding(nn.Module):\n \"\"\"\n Specify a new class for doing the embedding stuff as Flax's one use 'embedding' for the parameter name and PyTorch\n use 'weight'\n \"\"\"\n\n vocab_size: int\n hidden_size: int\n kernel_init_scale: float = 0.2\n emb_init: Callable[..., np.ndarray] = jax.nn.initializers.normal(stddev=kernel_init_scale)\n dtype: jnp.dtype = jnp.float32 # the dtype of the computation\n\n @nn.compact\n def __call__(self, inputs):\n embedding = self.param(\"weight\", self.emb_init, (self.vocab_size, self.hidden_size))\n return jnp.take(embedding, inputs, axis=0)\n\nclass FlaxBertEmbeddings(nn.Module):\n \"\"\"Construct the embeddings from word, position and token_type embeddings.\"\"\"\n\n vocab_size: int\n hidden_size: int\n type_vocab_size: int\n max_length: int\n kernel_init_scale: float = 0.2\n dropout_rate: float = 0.0\n dtype: jnp.dtype = jnp.float32 # the dtype of the computation\n\n @nn.compact\n def __call__(self, input_ids, token_type_ids, position_ids, attention_mask, deterministic: bool = True):\n\n # Embed\n w_emb = FlaxBertEmbedding(\n self.vocab_size,\n self.hidden_size,\n kernel_init_scale=self.kernel_init_scale,\n name=\"word_embeddings\",\n dtype=self.dtype,\n )(jnp.atleast_2d(input_ids.astype(\"i4\")))\n p_emb = FlaxBertEmbedding(\n self.max_length,\n self.hidden_size,\n kernel_init_scale=self.kernel_init_scale,\n name=\"position_embeddings\",\n dtype=self.dtype,\n )(jnp.atleast_2d(position_ids.astype(\"i4\")))\n t_emb = FlaxBertEmbedding(\n self.type_vocab_size,\n self.hidden_size,\n kernel_init_scale=self.kernel_init_scale,\n name=\"token_type_embeddings\",\n dtype=self.dtype,\n )(jnp.atleast_2d(token_type_ids.astype(\"i4\")))\n\n # Sum all embeddings\n summed_emb = w_emb + jnp.broadcast_to(p_emb, w_emb.shape) + t_emb\n\n # Layer Norm\n layer_norm = nn.LayerNorm(name=\"layer_norm\", dtype=self.dtype)(summed_emb)\n embeddings = nn.Dropout(rate=self.dropout_rate)(layer_norm, deterministic=deterministic)\n return embeddings\n\nclass FlaxBertAttention(nn.Module):\n num_heads: int\n head_size: int\n dropout_rate: float = 0.0\n kernel_init_scale: float = 0.2\n dtype: jnp.dtype = jnp.float32 # the dtype of the computation\n\n @nn.compact\n def __call__(self, hidden_states, attention_mask, deterministic: bool = True):\n # Attention mask comes in as attention_mask.shape == (*batch_sizes, kv_length)\n # FLAX expects: attention_mask.shape == (*batch_sizes, 1, 1, kv_length) such that it is broadcastable\n # with attn_weights.shape == (*batch_sizes, num_heads, q_length, kv_length)\n attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))\n self_att = SelfAttention(\n num_heads=self.num_heads,\n qkv_features=self.head_size,\n out_features = self.head_size,\n dropout_rate=self.dropout_rate,\n deterministic=deterministic,\n kernel_init=jax.nn.initializers.normal(self.kernel_init_scale, self.dtype),\n bias_init=jax.nn.initializers.zeros,\n name=\"self\",\n dtype=self.dtype,\n )(hidden_states, attention_mask)\n\n layer_norm = nn.LayerNorm(name=\"layer_norm\", dtype=self.dtype)(self_att + hidden_states)\n return layer_norm\n\nclass FlaxBertIntermediate(nn.Module):\n output_size: int\n hidden_act: str = \"gelu\"\n kernel_init_scale: float = 0.2\n dtype: jnp.dtype = jnp.float32 # the dtype of the computation\n\n @nn.compact\n def __call__(self, hidden_states):\n hidden_states = nn.Dense(\n features=self.output_size,\n kernel_init=jax.nn.initializers.normal(self.kernel_init_scale, self.dtype),\n name=\"dense\",\n dtype=self.dtype,\n )(hidden_states)\n hidden_states = ACT2FN[self.hidden_act](hidden_states)\n return hidden_states\n\n\nclass FlaxBertOutput(nn.Module):\n dropout_rate: float = 0.0\n kernel_init_scale: float = 0.2\n dtype: jnp.dtype = jnp.float32 # the dtype of the computation\n\n @nn.compact\n def __call__(self, intermediate_output, attention_output, deterministic: bool = True):\n hidden_states = nn.Dense(\n attention_output.shape[-1],\n kernel_init=jax.nn.initializers.normal(self.kernel_init_scale, self.dtype),\n name=\"dense\",\n dtype=self.dtype,\n )(intermediate_output)\n hidden_states = nn.Dropout(rate=self.dropout_rate)(hidden_states, deterministic=deterministic)\n hidden_states = nn.LayerNorm(name=\"layer_norm\", dtype=self.dtype)(hidden_states + attention_output)\n return hidden_states\n\nclass FlaxBertLayer(nn.Module):\n num_heads: int\n head_size: int\n intermediate_size: int\n hidden_act: str = \"gelu\"\n dropout_rate: float = 0.0\n kernel_init_scale: float = 0.2\n dtype: jnp.dtype = jnp.float32 # the dtype of the computation\n\n @nn.compact\n def __call__(self, hidden_states, attention_mask, deterministic: bool = True):\n attention = FlaxBertAttention(\n self.num_heads,\n self.head_size,\n kernel_init_scale=self.kernel_init_scale,\n dropout_rate=self.dropout_rate,\n name=\"attention\",\n dtype=self.dtype,\n )(hidden_states, attention_mask, deterministic=deterministic)\n intermediate = FlaxBertIntermediate(\n self.intermediate_size,\n kernel_init_scale=self.kernel_init_scale,\n hidden_act=self.hidden_act,\n name=\"intermediate\",\n dtype=self.dtype,\n )(attention)\n output = FlaxBertOutput(\n kernel_init_scale=self.kernel_init_scale, dropout_rate=self.dropout_rate, name=\"output\", dtype=self.dtype\n )(intermediate, attention, deterministic=deterministic)\n\n return output\n\nclass FlaxBertLayerCollection(nn.Module):\n \"\"\"\n Stores N BertLayer(s)\n \"\"\"\n\n num_layers: int\n num_heads: int\n head_size: int\n intermediate_size: int\n hidden_act: str = \"gelu\"\n dropout_rate: float = 0.0\n kernel_init_scale: float = 0.2\n dtype: jnp.dtype = jnp.float32 # the dtype of the computation\n\n @nn.compact\n def __call__(self, inputs, attention_mask, deterministic: bool = True):\n assert self.num_layers > 0, f\"num_layers should be >= 1, got ({self.num_layers})\"\n\n # Initialize input / output\n input_i = inputs\n\n # Forward over all encoders\n for i in range(self.num_layers):\n layer = FlaxBertLayer(\n self.num_heads,\n self.head_size,\n self.intermediate_size,\n kernel_init_scale=self.kernel_init_scale,\n dropout_rate=self.dropout_rate,\n hidden_act=self.hidden_act,\n name=f\"{i}\",\n dtype=self.dtype,\n )\n input_i = layer(input_i, attention_mask, deterministic=deterministic)\n return input_i\n\nclass FlaxBertEncoder(nn.Module):\n num_layers: int\n num_heads: int\n head_size: int\n intermediate_size: int\n hidden_act: str = \"gelu\"\n dropout_rate: float = 0.0\n kernel_init_scale: float = 0.2\n dtype: jnp.dtype = jnp.float32 # the dtype of the computation\n\n @nn.compact\n def __call__(self, hidden_states, attention_mask, deterministic: bool = True):\n layer = FlaxBertLayerCollection(\n self.num_layers,\n self.num_heads,\n self.head_size,\n self.intermediate_size,\n hidden_act=self.hidden_act,\n kernel_init_scale=self.kernel_init_scale,\n dropout_rate=self.dropout_rate,\n name=\"layer\",\n dtype=self.dtype,\n )(hidden_states, attention_mask, deterministic=deterministic)\n return layer\n\n\nclass FlaxBertPooler(nn.Module):\n kernel_init_scale: float = 0.2\n dtype: jnp.dtype = jnp.float32 # the dtype of the computation\n\n @nn.compact\n def __call__(self, hidden_states):\n cls_token = hidden_states[:, 0]\n out = nn.Dense(\n hidden_states.shape[-1],\n kernel_init=jax.nn.initializers.normal(self.kernel_init_scale, self.dtype),\n name=\"dense\",\n dtype=self.dtype,\n )(cls_token)\n return nn.tanh(out)\n\n\nclass FlaxBertPredictionHeadTransform(nn.Module):\n hidden_act: str = \"gelu\"\n dtype: jnp.dtype = jnp.float32\n\n @nn.compact\n def __call__(self, hidden_states):\n hidden_states = nn.Dense(hidden_states.shape[-1], name=\"dense\", dtype=self.dtype)(hidden_states)\n hidden_states = ACT2FN[self.hidden_act](hidden_states)\n return nn.LayerNorm(name=\"layer_norm\", dtype=self.dtype)(hidden_states)\n\n\nclass FlaxBertLMPredictionHead(nn.Module):\n vocab_size: int\n hidden_act: str = \"gelu\"\n dtype: jnp.dtype = jnp.float32\n\n @nn.compact\n def __call__(self, hidden_states):\n # TODO: The output weights are the same as the input embeddings, but there is\n # an output-only bias for each token.\n # Need a link between the two variables so that the bias is correctly\n # resized with `resize_token_embeddings`\n\n hidden_states = FlaxBertPredictionHeadTransform(\n name=\"transform\", hidden_act=self.hidden_act, dtype=self.dtype\n )(hidden_states)\n hidden_states = nn.Dense(self.vocab_size, name=\"decoder\", dtype=self.dtype)(hidden_states)\n return hidden_states\n\n\nclass FlaxBertOnlyMLMHead(nn.Module):\n vocab_size: int\n hidden_act: str = \"gelu\"\n dtype: jnp.dtype = jnp.float32\n\n @nn.compact\n def __call__(self, hidden_states):\n hidden_states = FlaxBertLMPredictionHead(\n vocab_size=self.vocab_size, hidden_act=self.hidden_act, name=\"predictions\", dtype=self.dtype\n )(hidden_states)\n return hidden_states\n\nclass FlaxBertModule(nn.Module):\n vocab_size: int\n hidden_size: int\n type_vocab_size: int\n max_length: int\n num_encoder_layers: int\n num_heads: int\n head_size: int\n intermediate_size: int\n hidden_act: str = \"gelu\"\n dropout_rate: float = 0.0\n kernel_init_scale: float = 0.2\n dtype: jnp.dtype = jnp.float32 # the dtype of the computation\n add_pooling_layer: bool = True\n\n @nn.compact\n def __call__(self, input_ids, attention_mask, token_type_ids, position_ids, deterministic: bool = True):\n\n # Embedding\n embeddings = FlaxBertEmbeddings(\n self.vocab_size,\n self.hidden_size,\n self.type_vocab_size,\n self.max_length,\n kernel_init_scale=self.kernel_init_scale,\n dropout_rate=self.dropout_rate,\n name=\"embeddings\",\n dtype=self.dtype,\n )(input_ids, token_type_ids, position_ids, attention_mask, deterministic=deterministic)\n\n # N stacked encoding layers\n encoder = FlaxBertEncoder(\n self.num_encoder_layers,\n self.num_heads,\n self.head_size,\n self.intermediate_size,\n kernel_init_scale=self.kernel_init_scale,\n dropout_rate=self.dropout_rate,\n hidden_act=self.hidden_act,\n name=\"encoder\",\n dtype=self.dtype,\n )(embeddings, attention_mask, deterministic=deterministic)\n\n if not self.add_pooling_layer:\n return encoder\n\n pooled = FlaxBertPooler(kernel_init_scale=self.kernel_init_scale, name=\"pooler\", dtype=self.dtype)(encoder)\n return encoder, pooled\n\nclass FlaxBertForMaskedLMModule(nn.Module):\n vocab_size: int\n hidden_size: int\n intermediate_size: int\n head_size: int\n num_heads: int\n num_encoder_layers: int\n type_vocab_size: int\n max_length: int\n hidden_act: str\n dropout_rate: float = 0.0\n dtype: jnp.dtype = jnp.float32\n\n @nn.compact\n def __call__(\n self, input_ids, attention_mask=None, token_type_ids=None, position_ids=None, deterministic: bool = True\n ):\n # Model\n encoder = FlaxBertModule(\n vocab_size=self.vocab_size,\n type_vocab_size=self.type_vocab_size,\n hidden_size=self.hidden_size,\n intermediate_size=self.intermediate_size,\n head_size=self.hidden_size,\n num_heads=self.num_heads,\n num_encoder_layers=self.num_encoder_layers,\n max_length=self.max_length,\n dropout_rate=self.dropout_rate,\n hidden_act=self.hidden_act,\n dtype=self.dtype,\n add_pooling_layer=False,\n name=\"bert\",\n )(input_ids, attention_mask, token_type_ids, position_ids, deterministic=deterministic)\n\n # Compute the prediction scores\n encoder = nn.Dropout(rate=self.dropout_rate)(encoder, deterministic=deterministic)\n logits = FlaxBertOnlyMLMHead(\n vocab_size=self.vocab_size, hidden_act=self.hidden_act, name=\"cls\", dtype=self.dtype\n )(encoder)\n\n return (logits,)\n\n\n\n\n\n\n\n\n# class TransformerEncoderBlock(nn.Module):\n# num_heads: int\n\n# This class only supports encoding operation now\nclass MultiHeadDotProductAttention(nn.Module):\n num_heads: int\n qkv_features: int\n out_features: int\n bias_init: Callable[[PRNGKey, Shape, Dtype], Array] = nn.initializers.zeros\n kernel_init: Callable[[PRNGKey, Shape, Dtype], Array] = nn.linear.default_kernel_init\n dtype: Dtype = jnp.float32\n dropout_rate: float = 0.\n deterministic: bool = False\n\n def setup(self):\n assert self.qkv_features % self.num_heads == 0\n head_dim = self.qkv_features // self.num_heads\n self.dense = partial(nn.DenseGeneral,\n axis=-1,\n features=(self.num_heads, head_dim),\n kernel_init=self.kernel_init,\n bias_init=self.bias_init,\n dtype=self.dtype,\n name=\"dense\"\n )\n\n def __call__(self, inputs_q: Array,inputs_kv: Array, mask: Optional[Array] = None):\n query = self.dense(name=\"query\")(inputs_q)\n key = self.dense(name=\"key\")(inputs_kv)\n value = self.dense(name=\"value\")(inputs_kv)\n if mask is not None:\n attention_bias = lax.select(mask>0,\n jnp.full(mask.shape,0).astype(self.dtype),\n jnp.full(mask.shape,-1e10).astype(self.dtype))\n else:\n attention_bias = None\n dropout_rng = None\n if not self.deterministic and self.dropout_rate > 0:\n dropout_rng = self.make_rng(\"dropout\")\n x = nn.attention.dot_product_attention(query, key, value,\n bias = attention_bias,\n dropout_rng = dropout_rng,\n dropout_rate = self.dropout_rate,\n deterministic = self.deterministic,\n dtype = self.dtype)\n output = nn.DenseGeneral(features = self.out_features,\n axis = (-2,-1),\n dtype = self.dtype,\n name = \"out\")(x)\n return output\n\n\n\nclass SelfAttention(MultiHeadDotProductAttention):\n @compact\n def __call__(self, inputs: Array, mask: Optional[Array] = None):\n return super().__call__(inputs,inputs,mask)\n\nclass InitEmbedding(nn.Module):\n vocab_size: int\n hidden_size: int\n emb_init: Callable[...,jnp.ndarray] = nn.initializers.normal()\n @compact\n def __call__(self, inputs):\n embeddings = self.param(\"weight\",self.emb_init,(self.vocab_size,self.hidden_size))\n return jnp.take(embeddings,inputs,0)\n\nclass FFNWithNorm(nn.Module):\n hidden_size: int\n act_fn: Optional = None\n @compact\n def __call__(self,inputs):\n act_fn = self.act_fn or nn.gelu\n middle = act_fn(nn.Dense(self.hidden_size,name=\"intermediate.dense\")(inputs))\n last = nn.Dense(inputs.shape[-1],name=\"output.dense\")(middle)\n return nn.LayerNorm(name=\"LayerNorm\")(inputs+last)\n\nfrom flax.linen import SelfAttention\n\nclass BertEncoderBlock(nn.Module):\n vocab_size: int\n hidden_size: int\n type_vocab_size: int\n max_length: int\n num_heads: int\n intermediate_size: int\n qkv_features: Optional[int] = None\n out_features: Optional[int] = None\n @compact\n def __call__(self, inputs, attention_mask):\n qkv_features = self.qkv_features or inputs.shape[-1]\n out_features = self.out_features or inputs.shape[-1]\n self_attn = SelfAttention(self.num_heads,qkv_features = qkv_features,out_features = out_features,name=\"attention\")(inputs,attention_mask)\n return FFNWithNorm(self.intermediate_size)(nn.LayerNorm(name=\"LayerNorm\")(self_attn+inputs))", "repo_name": "Cli212/flax-BERT", "sub_path": "layers.py", "file_name": "layers.py", "file_ext": "py", "file_size_in_byte": 17485, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "typing.Any", "line_number": 8, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 9, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 10, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 11, "usage_type": "name"}, {"api_name": "flax.linen.gelu", "line_number": 14, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 14, "usage_type": "name"}, {"api_name": "flax.linen.relu", "line_number": 15, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 15, "usage_type": "name"}, {"api_name": "flax.linen.swish", "line_number": 16, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 16, "usage_type": "name"}, {"api_name": "flax.linen.swish", "line_number": 17, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 17, "usage_type": "name"}, {"api_name": "functools.partial", "line_number": 18, "usage_type": "call"}, {"api_name": "flax.linen.gelu", "line_number": 18, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 18, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 21, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 21, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 30, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 30, "usage_type": "attribute"}, {"api_name": "jax.nn.initializers.normal", "line_number": 30, "usage_type": "call"}, {"api_name": "jax.nn", "line_number": 30, "usage_type": "attribute"}, {"api_name": "jax.numpy.dtype", "line_number": 31, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 31, "usage_type": "name"}, {"api_name": "jax.numpy.float32", "line_number": 31, "usage_type": "attribute"}, {"api_name": "jax.numpy.take", "line_number": 36, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 36, "usage_type": "name"}, {"api_name": "flax.linen.compact", "line_number": 33, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 33, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 38, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 38, "usage_type": "name"}, {"api_name": "jax.numpy.dtype", "line_number": 47, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 47, "usage_type": "name"}, {"api_name": "jax.numpy.float32", "line_number": 47, "usage_type": "attribute"}, {"api_name": "jax.numpy.atleast_2d", "line_number": 59, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 59, "usage_type": "name"}, {"api_name": "jax.numpy.atleast_2d", "line_number": 66, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 66, "usage_type": "name"}, {"api_name": "jax.numpy.atleast_2d", "line_number": 73, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 73, "usage_type": "name"}, {"api_name": "jax.numpy.broadcast_to", "line_number": 76, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 76, "usage_type": "name"}, {"api_name": "flax.linen.LayerNorm", "line_number": 79, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 79, "usage_type": "name"}, {"api_name": "flax.linen.Dropout", "line_number": 80, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 80, "usage_type": "name"}, {"api_name": "flax.linen.compact", "line_number": 49, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 49, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 83, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 83, "usage_type": "name"}, {"api_name": "jax.numpy.dtype", "line_number": 88, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 88, "usage_type": "name"}, {"api_name": "jax.numpy.float32", "line_number": 88, "usage_type": "attribute"}, {"api_name": "jax.numpy.expand_dims", "line_number": 95, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 95, "usage_type": "name"}, {"api_name": "jax.nn.initializers.normal", "line_number": 102, "usage_type": "call"}, {"api_name": "jax.nn", "line_number": 102, "usage_type": "attribute"}, {"api_name": "jax.nn", "line_number": 103, "usage_type": "attribute"}, {"api_name": "flax.linen.LayerNorm", "line_number": 108, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 108, "usage_type": "name"}, {"api_name": "flax.linen.compact", "line_number": 90, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 90, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 111, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 111, "usage_type": "name"}, {"api_name": "jax.numpy.dtype", "line_number": 115, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 115, "usage_type": "name"}, {"api_name": "jax.numpy.float32", "line_number": 115, "usage_type": "attribute"}, {"api_name": "flax.linen.Dense", "line_number": 119, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 119, "usage_type": "name"}, {"api_name": "jax.nn.initializers.normal", "line_number": 121, "usage_type": "call"}, {"api_name": "jax.nn", "line_number": 121, "usage_type": "attribute"}, {"api_name": "flax.linen.compact", "line_number": 117, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 117, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 129, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 129, "usage_type": "name"}, {"api_name": "jax.numpy.dtype", "line_number": 132, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 132, "usage_type": "name"}, {"api_name": "jax.numpy.float32", "line_number": 132, "usage_type": "attribute"}, {"api_name": "flax.linen.Dense", "line_number": 136, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 136, "usage_type": "name"}, {"api_name": "jax.nn.initializers.normal", "line_number": 138, "usage_type": "call"}, {"api_name": "jax.nn", "line_number": 138, "usage_type": "attribute"}, {"api_name": "flax.linen.Dropout", "line_number": 142, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 142, "usage_type": "name"}, {"api_name": "flax.linen.LayerNorm", "line_number": 143, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 143, "usage_type": "name"}, {"api_name": "flax.linen.compact", "line_number": 134, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 134, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 146, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 146, "usage_type": "name"}, {"api_name": "jax.numpy.dtype", "line_number": 153, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 153, "usage_type": "name"}, {"api_name": "jax.numpy.float32", "line_number": 153, "usage_type": "attribute"}, {"api_name": "flax.linen.compact", "line_number": 155, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 155, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 178, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 178, "usage_type": "name"}, {"api_name": "jax.numpy.dtype", "line_number": 190, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 190, "usage_type": "name"}, {"api_name": "jax.numpy.float32", "line_number": 190, "usage_type": "attribute"}, {"api_name": "flax.linen.compact", "line_number": 192, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 192, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 214, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 214, "usage_type": "name"}, {"api_name": "jax.numpy.dtype", "line_number": 222, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 222, "usage_type": "name"}, {"api_name": "jax.numpy.float32", "line_number": 222, "usage_type": "attribute"}, {"api_name": "flax.linen.compact", "line_number": 224, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 224, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 240, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 240, "usage_type": "name"}, {"api_name": "jax.numpy.dtype", "line_number": 242, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 242, "usage_type": "name"}, {"api_name": "jax.numpy.float32", "line_number": 242, "usage_type": "attribute"}, {"api_name": "flax.linen.Dense", "line_number": 247, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 247, "usage_type": "name"}, {"api_name": "jax.nn.initializers.normal", "line_number": 249, "usage_type": "call"}, {"api_name": "jax.nn", "line_number": 249, "usage_type": "attribute"}, {"api_name": "flax.linen.tanh", "line_number": 253, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 253, "usage_type": "name"}, {"api_name": "flax.linen.compact", "line_number": 244, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 244, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 256, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 256, "usage_type": "name"}, {"api_name": "jax.numpy.dtype", "line_number": 258, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 258, "usage_type": "name"}, {"api_name": "jax.numpy.float32", "line_number": 258, "usage_type": "attribute"}, {"api_name": "flax.linen.Dense", "line_number": 262, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 262, "usage_type": "name"}, {"api_name": "flax.linen.LayerNorm", "line_number": 264, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 264, "usage_type": "name"}, {"api_name": "flax.linen.compact", "line_number": 260, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 260, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 267, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 267, "usage_type": "name"}, {"api_name": "jax.numpy.dtype", "line_number": 270, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 270, "usage_type": "name"}, {"api_name": "jax.numpy.float32", "line_number": 270, "usage_type": "attribute"}, {"api_name": "flax.linen.Dense", "line_number": 282, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 282, "usage_type": "name"}, {"api_name": "flax.linen.compact", "line_number": 272, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 272, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 286, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 286, "usage_type": "name"}, {"api_name": "jax.numpy.dtype", "line_number": 289, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 289, "usage_type": "name"}, {"api_name": "jax.numpy.float32", "line_number": 289, "usage_type": "attribute"}, {"api_name": "flax.linen.compact", "line_number": 291, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 291, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 298, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 298, "usage_type": "name"}, {"api_name": "jax.numpy.dtype", "line_number": 310, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 310, "usage_type": "name"}, {"api_name": "jax.numpy.float32", "line_number": 310, "usage_type": "attribute"}, {"api_name": "flax.linen.compact", "line_number": 313, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 313, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 347, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 347, "usage_type": "name"}, {"api_name": "jax.numpy.dtype", "line_number": 358, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 358, "usage_type": "name"}, {"api_name": "jax.numpy.float32", "line_number": 358, "usage_type": "attribute"}, {"api_name": "flax.linen.Dropout", "line_number": 382, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 382, "usage_type": "name"}, {"api_name": "flax.linen.compact", "line_number": 360, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 360, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 400, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 400, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 404, "usage_type": "name"}, {"api_name": "flax.linen.initializers", "line_number": 404, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 404, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 405, "usage_type": "name"}, {"api_name": "flax.linen.linear", "line_number": 405, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 405, "usage_type": "name"}, {"api_name": "jax.numpy.float32", "line_number": 406, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 406, "usage_type": "name"}, {"api_name": "functools.partial", "line_number": 413, "usage_type": "call"}, {"api_name": "flax.linen.DenseGeneral", "line_number": 413, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 413, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 422, "usage_type": "name"}, {"api_name": "jax.lax.select", "line_number": 427, "usage_type": "call"}, {"api_name": "jax.lax", "line_number": 427, "usage_type": "name"}, {"api_name": "jax.numpy.full", "line_number": 428, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 428, "usage_type": "name"}, {"api_name": "jax.numpy.full", "line_number": 429, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 429, "usage_type": "name"}, {"api_name": "flax.linen.attention.dot_product_attention", "line_number": 435, "usage_type": "call"}, {"api_name": "flax.linen.attention", "line_number": 435, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 435, "usage_type": "name"}, {"api_name": "flax.linen.DenseGeneral", "line_number": 441, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 441, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 451, "usage_type": "name"}, {"api_name": "flax.linen.compact", "line_number": 450, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 454, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 454, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 457, "usage_type": "name"}, {"api_name": "jax.numpy.ndarray", "line_number": 457, "usage_type": "attribute"}, {"api_name": "jax.numpy", "line_number": 457, "usage_type": "name"}, {"api_name": "flax.linen.initializers.normal", "line_number": 457, "usage_type": "call"}, {"api_name": "flax.linen.initializers", "line_number": 457, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 457, "usage_type": "name"}, {"api_name": "jax.numpy.take", "line_number": 461, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 461, "usage_type": "name"}, {"api_name": "flax.linen.compact", "line_number": 458, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 463, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 463, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 465, "usage_type": "name"}, {"api_name": "flax.linen.gelu", "line_number": 468, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 468, "usage_type": "name"}, {"api_name": "flax.linen.Dense", "line_number": 469, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 469, "usage_type": "name"}, {"api_name": "flax.linen.Dense", "line_number": 470, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 470, "usage_type": "name"}, {"api_name": "flax.linen.LayerNorm", "line_number": 471, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 471, "usage_type": "name"}, {"api_name": "flax.linen.compact", "line_number": 466, "usage_type": "name"}, {"api_name": "flax.linen.Module", "line_number": 475, "usage_type": "attribute"}, {"api_name": "flax.linen", "line_number": 475, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 482, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 483, "usage_type": "name"}, {"api_name": "flax.linen.SelfAttention", "line_number": 488, "usage_type": "call"}, {"api_name": "flax.linen.LayerNorm", "line_number": 489, "usage_type": "call"}, {"api_name": "flax.linen", "line_number": 489, "usage_type": "name"}, {"api_name": "flax.linen.compact", "line_number": 484, "usage_type": "name"}]} +{"seq_id": "41160358361", "text": "from fastapi import FastAPI\n\nfrom core.routes.tweets import router as TweetRouter\n\napp = FastAPI()\n\napp.include_router(TweetRouter, tags=[\"Tweet\"], prefix=\"/tweets\")\n\n@app.get(\"/\", tags=[\"Root\"])\nasync def read_root():\n return {\"msg\": \"Hello World\"}\n", "repo_name": "Jeromeschmidt/Tweet-gen-fastAPI", "sub_path": "app/core/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 253, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "fastapi.FastAPI", "line_number": 5, "usage_type": "call"}, {"api_name": "core.routes.tweets.router", "line_number": 7, "usage_type": "argument"}]} +{"seq_id": "16933134290", "text": "# -*- coding: UTF-8 -*-\r\n# !/usr/bin/python\r\n# @time :2019/4/4 10:00\r\n# @author :Mo\r\n# @function :\r\n\r\n\r\nfrom conf.path_config import chicken_and_gossip_path\r\nfrom utils.text_tools import txtRead, txtWrite\r\nfrom conf.path_config import projectdir\r\nfrom fuzzywuzzy import process\r\nfrom fuzzywuzzy import fuzz\r\nimport pickle\r\nimport time\r\nimport re\r\n\r\n\r\ndef count_same_char(x1, x2):\r\n '''获取相同字符的个数'''\r\n res = []\r\n for x in x1:\r\n if x in x2:\r\n res.append(x)\r\n if res:\r\n return len(res)\r\n else:\r\n return 0\r\n\r\n\r\ndef fuzzy_re(user_input, collection):\r\n '''匹配方法, 效果不大好,只能匹配相同字数一样,或者字数比他多的那种,同义词或者是有一个词不一样,就没法区分开'''\r\n suggestions = []\r\n user_input = user_input.replace('.', '').replace('*', '').replace('?', '')\r\n\r\n collection_new = []\r\n len_user_input = len(user_input)\r\n for coll in collection: # 获取包含所有字符的,如果不包含,就返回错误\r\n count_coll = 0\r\n for i in range(len_user_input):\r\n if user_input[i] in coll:\r\n count_coll += 1\r\n if len_user_input == count_coll:\r\n collection_new.append(coll)\r\n if not collection_new:\r\n return None\r\n\r\n\r\n pattern = '.*?'.join(user_input) # Converts 'djm' to 'd.*?j.*?m'\r\n try:\r\n regex = re.compile(pattern) # Compiles a regex.\r\n except:\r\n gg = 0\r\n for item in collection_new:\r\n match = regex.search(item) # Checks if the current item matches the regex.\r\n if match:\r\n suggestions.append((len(match.group()), match.start(), item))\r\n return [x for _, _, x in sorted(suggestions)]\r\n\r\n\r\ndef fuzzy_fuzzywuzzy(fuzz, user_input, collection):\r\n '''编辑距离,速度比较慢,比起匹配方法,能够处理字符不一样的问题'''\r\n collection_new = []\r\n len_user_input = len(user_input)\r\n for coll in collection: # 获取包含一个字符的,如果不包含,就返回错误\r\n for i in range(len_user_input):\r\n if user_input[i] in coll:\r\n collection_new.append(coll)\r\n if not collection_new:\r\n return None\r\n collection_new = list(set(collection_new))\r\n\r\n same_char_list = []\r\n for collection_new_one in collection_new: # 获取相同字符串多的问题\r\n count_same_char_one = count_same_char(user_input, collection_new_one)\r\n same_char_list.append((collection_new_one, count_same_char_one))\r\n same_char_list.sort(key=lambda x: x[1], reverse=True)\r\n if len(same_char_list) >= 500:\r\n same_char_list = same_char_list[0: 500]\r\n\r\n result = process.extract(user_input, same_char_list, scorer=fuzz.token_set_ratio, limit=20)\r\n return result\r\n\r\n\r\ndef fuzzy_fuzzywuzzy_list(fuzz, user_input, qa_list, collection, topn=50):\r\n '''编辑距离,速度比较慢,比起匹配方法,能够处理字符不一样的问题'''\r\n\r\n start_time = time.time()\r\n # user_input_set = set([user_input_one for user_input_one in user_input])\r\n user_input_set = [user_input_one for user_input_one in user_input]\r\n\r\n\r\n same_char_list = []\r\n max_data = 0\r\n max_data_list = []\r\n count_collection_new_one = 0\r\n for collection_new_one in collection: # 获取相同字符串多的问题\r\n count_same_char_one = len([x for x in user_input_set if x in collection_new_one])\r\n\r\n if count_same_char_one > 0:\r\n same_char_list.append((count_collection_new_one, count_same_char_one))\r\n if count_same_char_one > max_data:\r\n max_data_list.append(count_same_char_one)\r\n max_data = count_same_char_one\r\n count_collection_new_one += 1\r\n\r\n end_time1 = time.time()\r\n list_max_count = []\r\n len_max_data_list = len(max_data_list)\r\n for x in range(len_max_data_list): # 获取前20排名\r\n for k,l in same_char_list:\r\n if l == max_data_list[len_max_data_list -1 - x]:\r\n list_max_count.append(qa_list[k]) #问答重这里取出来\r\n if len(list_max_count) >= 5000:\r\n list_max_count = list_max_count[0:5000]\r\n break\r\n\r\n end_time2 = time.time()\r\n\r\n # end_time1: 0.34090662002563477\r\n # end_time2: 0.4080846309661865\r\n\r\n # end_time1: 0.06417036056518555\r\n # end_time2: 0.08422374725341797\r\n\r\n # same_char_list.sort(key=lambda x: x[1], reverse=True)\r\n # if len(same_char_list) >= 20:\r\n # same_char_list = same_char_list[0: 20]\r\n\r\n result = process.extract(user_input, list_max_count, scorer=fuzz.token_set_ratio, limit=topn)\r\n end_time3 = time.time()\r\n\r\n # print('end_time1: ' + str(end_time1 - start_time))\r\n # print('end_time2: ' + str(end_time2 - start_time))\r\n # print('end_time3: ' + str(end_time3 - start_time))\r\n\r\n return result\r\n # [fuzz.WRatio, fuzz.QRatio,\r\n # fuzz.token_set_ratio, fuzz.token_sort_ratio,\r\n # fuzz.partial_token_set_ratio, fuzz.partial_token_sort_ratio,\r\n # fuzz.UWRatio, fuzz.UQRatio]\r\n\r\n\r\nif __name__ == '__main__':\r\n start_time = time.time()\r\n qa_list = txtRead(chicken_and_gossip_path)\r\n questions = [qa.strip().split(\"\\t\")[0] for qa in qa_list]\r\n print(\"read questions ok!\")\r\n sen = \"你谁呀\"\r\n # list_fuzzyfinder = fuzzyfinder(base_syn_one_split[1], qa_list)\r\n # list_fuzzyfinder = fuzzy_fuzzywuzzy(fuzz, base_syn_one_split[1], qa_list)\r\n print(\"你问: \" + \"你谁呀\")\r\n list_fuzzyfinder = fuzzy_fuzzywuzzy_list(fuzz, sen, qa_list, questions, topn=5)\r\n print(\"小姜机器人: \" + list_fuzzyfinder[0][0].split(\"\\t\")[1].strip())\r\n print(\"推荐结果: \")\r\n print(list_fuzzyfinder)\r\n\r\n while True:\r\n print(\"你问: \")\r\n ques = input()\r\n list_fuzzyfinder = fuzzy_fuzzywuzzy_list(fuzz, ques, qa_list, questions, topn=5)\r\n print(\"小姜机器人: \" + list_fuzzyfinder[0][0].split(\"\\t\")[1].strip())\r\n print(\"推荐结果: \")\r\n print(list_fuzzyfinder)\r\n", "repo_name": "yongzhuo/nlp_xiaojiang", "sub_path": "ChatBot/chatbot_search/chatbot_fuzzy.py", "file_name": "chatbot_fuzzy.py", "file_ext": "py", "file_size_in_byte": 6020, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1494, "dataset": "github-code", "pt": "48", "api": [{"api_name": "re.compile", "line_number": 50, "usage_type": "call"}, {"api_name": "fuzzywuzzy.process.extract", "line_number": 80, "usage_type": "call"}, {"api_name": "fuzzywuzzy.process", "line_number": 80, "usage_type": "name"}, {"api_name": "fuzzywuzzy.fuzz.token_set_ratio", "line_number": 80, "usage_type": "attribute"}, {"api_name": "fuzzywuzzy.fuzz", "line_number": 80, "usage_type": "name"}, {"api_name": "time.time", "line_number": 87, "usage_type": "call"}, {"api_name": "time.time", "line_number": 106, "usage_type": "call"}, {"api_name": "time.time", "line_number": 117, "usage_type": "call"}, {"api_name": "fuzzywuzzy.process.extract", "line_number": 129, "usage_type": "call"}, {"api_name": "fuzzywuzzy.process", "line_number": 129, "usage_type": "name"}, {"api_name": "fuzzywuzzy.fuzz.token_set_ratio", "line_number": 129, "usage_type": "attribute"}, {"api_name": "fuzzywuzzy.fuzz", "line_number": 129, "usage_type": "name"}, {"api_name": "time.time", "line_number": 130, "usage_type": "call"}, {"api_name": "time.time", "line_number": 144, "usage_type": "call"}, {"api_name": "utils.text_tools.txtRead", "line_number": 145, "usage_type": "call"}, {"api_name": "conf.path_config.chicken_and_gossip_path", "line_number": 145, "usage_type": "argument"}, {"api_name": "fuzzywuzzy.fuzz", "line_number": 152, "usage_type": "argument"}, {"api_name": "fuzzywuzzy.fuzz", "line_number": 160, "usage_type": "argument"}]} +{"seq_id": "13629152469", "text": "# (Attempt to) safely evaluate (some) python expressions.\n# See https://stackoverflow.com/a/9558001 for the base implementation.\n\nimport ast\nimport cmath\nimport math\nimport operator as op\nimport random\nimport resource\nimport time\nimport traceback\nimport types\n\nfrom cloudbot import hook\n\n\n# Limits on execution time and memory growth during expression evaluation, in\n# seconds and bytes.\nExpressionEvaluationTimeout = 1.0\nExpressionEvaluationMemoryLimit = 10 << 20\n\n\ndef safe_pow(a, b):\n if not isinstance(a, (int, float, complex)) or not isinstance(b, (int, float, complex)):\n raise Exception(\"unsupported operand type(s) for exponentiation\")\n # Determine whether the result will fit into 1024 bits. 710 =~ 1024*log(2)\n if abs(a) > 0 and b * math.log(abs(a)) > 710:\n raise Exception(\"result out of range evaluating exponentiation\")\n return op.pow(a, b)\n\n\ndef safe_factorial(a):\n # Determine whether the result will fit into 1024 bits. log2(171!) =~ 1024.\n if a >= 171:\n raise Exception(\"result out of range evaluating factorial\")\n return math.factorial(a)\n\n\ndef safe_mul(a, b):\n if (isinstance(a, str) and isinstance(b, int)) or (isinstance(a, int) and isinstance(b, str)):\n if len(a if isinstance(a, str) else b) * (b if isinstance(b, int) else a) > 400:\n raise Exception(\"result too large\")\n return op.mul(a, b)\n if not isinstance(a, (int, float, complex)) or not isinstance(b, (int, float, complex)):\n raise Exception(\"unsupported operand type(s) for multiplication\")\n # Determine whether the result will fit into 1024 bits. 710 =~ 1024*log(2)\n if abs(a) > 0 and abs(b) > 0 and math.log(abs(a)) + math.log(abs(b)) > 710:\n raise Exception(\"result out of range evaluating multiplication\")\n return op.mul(a, b)\n\n\ndef safe_lshift(a, b):\n if not isinstance(a, int) or not isinstance(b, int):\n raise Exception(\"unsupported operand type(s) for left shift\")\n # Determine whether the result will fit into 1024 bits\n if math.log(abs(a)) / math.log(2) + abs(b) > 1024:\n raise Exception(\"result out of range evaluating lshift\")\n return op.lshift(a, b)\n\n\ndef eval_expr(expr):\n e = ExpressionEvaluator()\n return e.eval_node(ast.parse(expr, mode='eval').body)\n\n\ndef safe_range(x, y=None, z=None):\n limit = 100000\n if z is not None:\n if z and (y - x) / z > limit:\n raise Exception(\"range() is capped to {:,d} steps\".format(limit))\n return range(x, y, z)\n elif y is not None:\n if (y - x) > limit:\n raise Exception(\"range() is capped to {:,d} steps\".format(limit))\n return range(x, y)\n else:\n if x > limit:\n raise Exception(\"range() is capped to {:,d} steps\".format(limit))\n return range(x)\n\noperators = {\n ast.Add: op.add,\n ast.Sub: op.sub,\n ast.Mult: safe_mul,\n ast.Div: op.truediv,\n\n ast.Mod: op.mod,\n ast.Pow: safe_pow,\n\n ast.BitXor: op.xor,\n ast.BitAnd: op.and_,\n ast.BitOr: op.or_,\n ast.Invert: op.invert,\n ast.LShift: safe_lshift,\n ast.RShift: op.rshift,\n\n ast.And: op.and_,\n ast.Or: op.or_,\n\n ast.USub: op.neg,\n ast.UAdd: op.pos,\n ast.Not: op.not_,\n\n ast.Eq: op.eq,\n ast.NotEq: op.ne,\n ast.Lt: op.lt,\n ast.LtE: op.le,\n ast.Gt: op.gt,\n ast.GtE: op.ge,\n ast.Is: op.is_,\n ast.IsNot: op.is_not,\n ast.In: lambda obj, seq: op.contains(seq, obj),\n ast.NotIn: lambda obj, seq: not(op.contains(seq, obj)),\n}\n\nallowed_stateless_functions = {\n # 9.2.1. Number-theoretic and representation functions\n \"abs\": abs,\n \"ceil\": math.ceil,\n \"copysign\": math.copysign,\n \"fabs\": math.fabs,\n \"factorial\": safe_factorial,\n \"floor\": math.floor,\n \"fmod\": math.fmod,\n \"frexp\": math.frexp,\n \"fsum\": math.fsum,\n \"isfinite\": math.isfinite,\n \"isinf\": math.isinf,\n \"isnan\": math.isnan,\n \"ldexp\": math.ldexp,\n \"modf\": math.modf,\n \"trunc\": math.trunc,\n\n # 9.2.2. Power and logarithmic functions\n \"exp\": math.exp,\n \"expm1\": math.expm1,\n \"log\": math.log,\n \"log1p\": math.log1p,\n \"log2\": math.log2,\n \"log10\": math.log10,\n \"pow\": safe_pow,\n \"sqrt\": math.sqrt,\n\n # 9.2.3. Trigonometric functions\n \"acos\": math.acos,\n \"asin\": math.asin,\n \"atan\": math.atan,\n \"atan2\": math.atan2,\n \"cos\": math.cos,\n \"hypot\": math.hypot,\n \"sin\": math.sin,\n \"tan\": math.tan,\n\n # 9.2.4. Angular conversion\n \"degrees\": math.degrees,\n \"radians\": math.radians,\n\n # 9.2.5. Hyperbolic functions\n \"acosh\": math.acosh,\n \"asinh\": math.asinh,\n \"atanh\": math.atanh,\n \"cosh\": math.cosh,\n \"sinh\": math.sinh,\n \"tanh\": math.tanh,\n\n # Math extras\n \"sec\": lambda x: 1 / math.cos(x),\n \"csc\": lambda x: 1 / math.sin(x),\n \"cot\": lambda x: 1 / math.tan(x),\n\n # 9.6. random\n \"random\": random.random,\n \"randint\": random.randint,\n \"randrange\": random.randrange,\n \"choice\": random.choice,\n \"sample\": random.sample,\n \"shuffle\": lambda x: random.sample(x, len(x)),\n\n # 2. Built-in functions. Some built-ins, e.g. list(), are resource-\n # limited. These are handled inside ExpressionEvaluator.\n \"bool\": bool,\n \"bin\": bin,\n \"complex\": complex,\n \"chr\": chr,\n \"dict\": dict,\n \"divmod\": divmod,\n \"enumerate\": enumerate,\n \"filter\": filter,\n \"float\": float,\n \"hex\": hex,\n \"int\": int,\n \"len\": len,\n \"max\": max,\n \"map\": map,\n \"min\": min,\n \"oct\": oct,\n \"ord\": ord,\n \"range\": safe_range,\n \"reversed\": reversed,\n \"round\": round,\n \"set\": set,\n \"slice\": slice,\n \"sorted\": sorted,\n \"str\": str,\n \"sum\": sum,\n \"type\": type,\n \"zip\": zip,\n}\n\nconstants = {\n \"e\": math.e,\n \"pi\": math.pi,\n\n \"True\": True,\n \"False\": False,\n}\n\nmodules = {\n \"cmath\": cmath,\n}\n\n\ndef attribute_allowed(value, attribute):\n allowed_type_methods = {\n complex: (\"conjugate\", \"imag\", \"real\"),\n dict: (\"clear\", \"copy\", \"get\", \"items\", \"keys\", \"pop\", \"popitem\", \"update\", \"values\"),\n float: (\"as_integer_ratio\", \"as_integer\", \"hex\", \"fromhex\"),\n int: (\"bit_length\"),\n list: (\"append\", \"extend\", \"insert\", \"remove\", \"pop\", \"clear\", \"index\", \"count\", \"sort\", \"reverse\", \"copy\"),\n set: (\"isdisjoint\", \"issubset\", \"issuperset\", \"union\", \"intersection\", \"difference\", \"symmetric_difference\"),\n str: (\"casefold\", \"capitalize\", \"endswith\", \"find\", \"isalnum\", \"isalpha\", \"isdecimal\", \"isdigit\", \"islower\", \"isnumeric\", \"isprintable\", \"isspace\", \"istitle\", \"isupper\", \"join\", \"lower\", \"replace\", \"rfind\", \"rindex\", \"rsplit\", \"rstrip\", \"split\", \"startswith\", \"strip\", \"swapcase\", \"title\", \"upper\"),\n }\n allowed_module_methods = {\n cmath: (\"phase\", \"polar\", \"rect\", \"exp\", \"log\", \"log10\", \"sqrt\", \"acos\", \"asin\", \"atan\", \"cos\", \"sin\", \"tan\", \"acosh\", \"asinh\", \"atanh\", \"cosh\", \"sinh\", \"tanh\", \"isinf\", \"isnan\", \"pi\", \"e\"),\n }\n if attribute in (\"count\", \"index\"):\n return True\n if isinstance(value, types.ModuleType) and value in allowed_module_methods:\n return attribute in allowed_module_methods[value]\n if type(value) in allowed_type_methods:\n return attribute in allowed_type_methods[type(value)]\n return False\n\n\nclass ExpressionEvaluator:\n def __init__(self):\n self.start_time = time.time()\n self.memory_usage = self.get_memory_usage()\n self.allowed_stateful_functions = {\n \"all\": self.safe_all,\n \"any\": self.safe_any,\n \"list\": self.safe_list,\n \"reduce\": self.safe_reduce,\n \"tuple\": self.safe_tuple,\n }\n\n def eval_generators(self, composition, generator_index, context, callback):\n generator = composition.generators[generator_index]\n iterable = generator.iter\n if_statements = generator.ifs\n is_deepest_generator = len(composition.generators) == generator_index + 1\n for i in self.eval_node(iterable, context):\n context = context.copy() if context else {}\n\n # FIXME: This is hacky. It assumes that the target is either a name or a shallow tuple.\n if isinstance(generator.target, ast.Name):\n context[generator.target.id] = i\n elif isinstance(generator.target, ast.Tuple):\n target_ids = list(map(lambda x: x.id, generator.target.elts))\n for x in range(0, len(target_ids)):\n context[target_ids[x]] = i[x]\n else:\n raise Exception(\"Unknown generator target {}\".format(generator.target))\n\n skip = False\n for condition in if_statements:\n if not self.eval_node(condition, context):\n skip = True\n break\n if skip:\n continue\n\n if is_deepest_generator:\n callback(composition, context)\n else:\n self.eval_generators(composition, generator_index + 1, context, callback)\n\n def safe_tuple(self, iterable):\n return tuple(self.safe_list(iterable))\n\n def safe_list(self, iterable):\n result = []\n for item in iterable:\n self.check_evaluation_exceeded_limits()\n result.append(item)\n return result\n\n def safe_all(self, iterable):\n result = []\n for item in iterable:\n self.check_evaluation_exceeded_limits()\n if not item:\n return False\n return True\n\n def safe_any(self, iterable):\n result = []\n for item in iterable:\n self.check_evaluation_exceeded_limits()\n if item:\n return True\n return False\n\n def safe_reduce(self, callback, iterable):\n iterator = iter(iterable)\n accumulator = next(iterator)\n for i, item in enumerate(iterable):\n self.check_evaluation_exceeded_limits()\n accumulator = callback(accumulator, item)\n return accumulator\n\n def check_evaluation_exceeded_limits(self):\n if time.time() - self.start_time > ExpressionEvaluationTimeout:\n raise Exception(\"timed out evaluating expression\")\n memory_usage = self.get_memory_usage()\n if memory_usage - self.memory_usage > ExpressionEvaluationMemoryLimit:\n raise Exception(\"memory threshold exceeded evaluating expression\")\n\n def get_memory_usage(self):\n return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * 1024\n\n def eval_node(self, node, context=None):\n self.check_evaluation_exceeded_limits()\n\n if isinstance(node, ast.Num):\n return node.n\n elif isinstance(node, ast.NameConstant):\n return node.value\n elif isinstance(node, ast.Str):\n return str(node.s)\n elif isinstance(node, ast.Tuple):\n return tuple(map(lambda x: self.eval_node(x, context), node.elts))\n elif isinstance(node, ast.List):\n return list(map(lambda x: self.eval_node(x, context), node.elts))\n elif isinstance(node, ast.Dict):\n result = dict()\n for key, value in zip(node.keys, node.values):\n result[self.eval_node(key, context)] = self.eval_node(value, context)\n return result\n elif isinstance(node, ast.Set):\n return set(map(lambda x: self.eval_node(x, context), node.elts))\n elif isinstance(node, ast.BoolOp):\n if type(node.op) == ast.And:\n result = self.eval_node(node.values[0], context)\n for i in range(1, len(node.values)):\n if not result:\n return result\n result = result and self.eval_node(node.values[i], context)\n return result\n assert(type(node.op) == ast.Or)\n result = self.eval_node(node.values[0], context)\n for i in range(1, len(node.values)):\n if result:\n return result\n result = result or self.eval_node(node.values[i], context)\n return result\n elif isinstance(node, ast.BinOp):\n return operators[type(node.op)](self.eval_node(node.left, context), self.eval_node(node.right, context))\n elif isinstance(node, ast.UnaryOp):\n return operators[type(node.op)](self.eval_node(node.operand, context))\n elif isinstance(node, ast.Call):\n function = self.eval_node(node.func, context)\n args = map(lambda x: self.eval_node(x, context), node.args)\n return function(*args)\n elif isinstance(node, ast.Compare):\n lhs = self.eval_node(node.left, context)\n result = True\n for i in range(len(node.ops)):\n rhs = self.eval_node(node.comparators[i], context)\n result &= operators[type(node.ops[i])](lhs, rhs)\n lhs = rhs\n return result\n elif isinstance(node, ast.Name):\n if node.id in constants:\n return constants[node.id]\n if context and node.id in context:\n return context[node.id]\n if node.id in self.allowed_stateful_functions:\n return self.allowed_stateful_functions[node.id]\n if node.id in allowed_stateless_functions:\n return allowed_stateless_functions[node.id]\n if node.id in modules:\n return modules[node.id]\n raise Exception(\"unknown identifier '{}'\".format(node.id))\n elif isinstance(node, ast.Lambda):\n def lambda_eval(*x):\n args = list(x)\n new_context = context.copy() if context else {}\n for i, arg in enumerate(node.args.args):\n if i < len(args):\n new_context[arg.arg] = args[i]\n else:\n new_context[arg.arg] = self.eval_node(node.args.defaults[i - len(args)], new_context)\n return self.eval_node(node.body, new_context)\n return lambda_eval\n elif isinstance(node, ast.Subscript):\n values = self.eval_node(node.value, context)\n indices = self.eval_node(node.slice, context)\n return values[indices]\n elif isinstance(node, ast.Index):\n return self.eval_node(node.value, context)\n elif isinstance(node, ast.Slice):\n start = self.eval_node(node.lower, context) if node.lower is not None else None\n stop = self.eval_node(node.upper, context) if node.upper is not None else None\n step = self.eval_node(node.step, context) if node.step is not None else None\n return slice(start, stop, step)\n elif isinstance(node, ast.Attribute):\n value = self.eval_node(node.value, context)\n attribute = node.attr\n if not attribute_allowed(value, attribute):\n raise Exception(\"unknown identifier '{}'\".format(node.attr))\n return getattr(value, attribute)\n elif isinstance(node, ast.IfExp):\n condition = self.eval_node(node.test, context)\n return self.eval_node(node.body if condition else node.orelse, context)\n elif isinstance(node, (ast.ListComp, ast.GeneratorExp)):\n result = []\n def array_callback(composition, context):\n result.append(self.eval_node(composition.elt, context))\n self.eval_generators(node, 0, context, array_callback)\n return result\n elif isinstance(node, ast.DictComp):\n result = {}\n def dict_callback(composition, context):\n result[self.eval_node(composition.key, context)] = self.eval_node(composition.value, context)\n self.eval_generators(node, 0, context, dict_callback)\n return result\n elif isinstance(node, ast.SetComp):\n result = set()\n def set_callback(composition, context):\n result.add(self.eval_node(composition.elt, context))\n self.eval_generators(node, 0, context, set_callback)\n return result\n else:\n raise Exception(\"unsupported AST node type {}\".format(node))\n\n\n@hook.command(\"calc\", \"eval\")\ndef on_message(reply, text):\n \"\"\"eval - evaluate a Python expression.\"\"\"\n try:\n result = eval_expr(text)\n result = str(result).replace(\"\\n\", \"\").replace(\"\\r\", \"\")\n\n if len(result) > 400:\n reply(\"Exception: result too large\")\n else:\n reply(result)\n except Exception as e:\n traceback.print_exc()\n reply(\"Exception: {}\".format(e))\n\n", "repo_name": "webvictim/CloudBot", "sub_path": "plugins/calc.py", "file_name": "calc.py", "file_ext": "py", "file_size_in_byte": 16656, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "48", "api": [{"api_name": "math.log", "line_number": 27, "usage_type": "call"}, {"api_name": "operator.pow", "line_number": 29, "usage_type": "call"}, {"api_name": "math.factorial", "line_number": 36, "usage_type": "call"}, {"api_name": "operator.mul", "line_number": 43, "usage_type": "call"}, {"api_name": "math.log", "line_number": 47, "usage_type": "call"}, {"api_name": "operator.mul", "line_number": 49, "usage_type": "call"}, {"api_name": "math.log", "line_number": 56, "usage_type": "call"}, {"api_name": "operator.lshift", "line_number": 58, "usage_type": "call"}, {"api_name": "ast.parse", "line_number": 63, "usage_type": "call"}, {"api_name": "ast.Add", "line_number": 82, "usage_type": "attribute"}, {"api_name": "ast.Sub", "line_number": 83, "usage_type": "attribute"}, {"api_name": "ast.Mult", "line_number": 84, "usage_type": "attribute"}, {"api_name": "ast.Div", "line_number": 85, "usage_type": "attribute"}, {"api_name": "ast.Mod", "line_number": 87, "usage_type": "attribute"}, {"api_name": "ast.Pow", "line_number": 88, "usage_type": "attribute"}, {"api_name": "ast.BitXor", "line_number": 90, "usage_type": "attribute"}, {"api_name": "ast.BitAnd", "line_number": 91, "usage_type": "attribute"}, {"api_name": "ast.BitOr", "line_number": 92, "usage_type": "attribute"}, {"api_name": "ast.Invert", "line_number": 93, "usage_type": "attribute"}, {"api_name": "ast.LShift", "line_number": 94, "usage_type": "attribute"}, {"api_name": "ast.RShift", "line_number": 95, "usage_type": "attribute"}, {"api_name": "ast.And", "line_number": 97, "usage_type": "attribute"}, {"api_name": "ast.Or", "line_number": 98, "usage_type": "attribute"}, {"api_name": "ast.USub", "line_number": 100, "usage_type": "attribute"}, {"api_name": "ast.UAdd", "line_number": 101, "usage_type": "attribute"}, {"api_name": "ast.Not", "line_number": 102, "usage_type": "attribute"}, {"api_name": "ast.Eq", "line_number": 104, "usage_type": "attribute"}, {"api_name": "ast.NotEq", "line_number": 105, "usage_type": "attribute"}, {"api_name": "ast.Lt", "line_number": 106, "usage_type": "attribute"}, {"api_name": "ast.LtE", "line_number": 107, "usage_type": "attribute"}, {"api_name": "ast.Gt", "line_number": 108, "usage_type": "attribute"}, {"api_name": "ast.GtE", "line_number": 109, "usage_type": "attribute"}, {"api_name": "ast.Is", "line_number": 110, "usage_type": "attribute"}, {"api_name": "ast.IsNot", "line_number": 111, "usage_type": "attribute"}, {"api_name": "ast.In", "line_number": 112, "usage_type": "attribute"}, {"api_name": "ast.NotIn", "line_number": 113, "usage_type": "attribute"}, {"api_name": "operator.add", "line_number": 82, "usage_type": "attribute"}, {"api_name": "operator.sub", "line_number": 83, "usage_type": "attribute"}, {"api_name": "operator.truediv", "line_number": 85, "usage_type": "attribute"}, {"api_name": "operator.mod", "line_number": 87, "usage_type": "attribute"}, {"api_name": "operator.xor", "line_number": 90, "usage_type": "attribute"}, {"api_name": "operator.and_", "line_number": 91, "usage_type": "attribute"}, {"api_name": "operator.or_", "line_number": 92, "usage_type": "attribute"}, {"api_name": "operator.invert", "line_number": 93, "usage_type": "attribute"}, {"api_name": "operator.rshift", "line_number": 95, "usage_type": "attribute"}, {"api_name": "operator.and_", "line_number": 97, "usage_type": "attribute"}, {"api_name": "operator.or_", "line_number": 98, "usage_type": "attribute"}, {"api_name": "operator.neg", "line_number": 100, "usage_type": "attribute"}, {"api_name": "operator.pos", "line_number": 101, "usage_type": "attribute"}, {"api_name": "operator.not_", "line_number": 102, "usage_type": "attribute"}, {"api_name": "operator.eq", "line_number": 104, "usage_type": "attribute"}, {"api_name": "operator.ne", "line_number": 105, "usage_type": "attribute"}, {"api_name": "operator.lt", "line_number": 106, "usage_type": "attribute"}, {"api_name": "operator.le", "line_number": 107, "usage_type": "attribute"}, {"api_name": "operator.gt", "line_number": 108, "usage_type": "attribute"}, {"api_name": "operator.ge", "line_number": 109, "usage_type": "attribute"}, {"api_name": "operator.is_", "line_number": 110, "usage_type": "attribute"}, {"api_name": "operator.is_not", "line_number": 111, "usage_type": "attribute"}, {"api_name": "operator.contains", "line_number": 112, "usage_type": "call"}, {"api_name": "operator.contains", "line_number": 113, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 119, "usage_type": "attribute"}, {"api_name": "math.copysign", "line_number": 120, "usage_type": "attribute"}, {"api_name": "math.fabs", "line_number": 121, "usage_type": "attribute"}, {"api_name": "math.floor", "line_number": 123, "usage_type": "attribute"}, {"api_name": "math.fmod", "line_number": 124, "usage_type": "attribute"}, {"api_name": "math.frexp", "line_number": 125, "usage_type": "attribute"}, {"api_name": "math.fsum", "line_number": 126, "usage_type": "attribute"}, {"api_name": "math.isfinite", "line_number": 127, "usage_type": "attribute"}, {"api_name": "math.isinf", "line_number": 128, "usage_type": "attribute"}, {"api_name": "math.isnan", "line_number": 129, "usage_type": "attribute"}, {"api_name": "math.ldexp", "line_number": 130, "usage_type": "attribute"}, {"api_name": "math.modf", "line_number": 131, "usage_type": "attribute"}, {"api_name": "math.trunc", "line_number": 132, "usage_type": "attribute"}, {"api_name": "math.exp", "line_number": 135, "usage_type": "attribute"}, {"api_name": "math.expm1", "line_number": 136, "usage_type": "attribute"}, {"api_name": "math.log", "line_number": 137, "usage_type": "attribute"}, {"api_name": "math.log1p", "line_number": 138, "usage_type": "attribute"}, {"api_name": "math.log2", "line_number": 139, "usage_type": "attribute"}, {"api_name": "math.log10", "line_number": 140, "usage_type": "attribute"}, {"api_name": "math.sqrt", "line_number": 142, "usage_type": "attribute"}, {"api_name": "math.acos", "line_number": 145, "usage_type": "attribute"}, {"api_name": "math.asin", "line_number": 146, "usage_type": "attribute"}, {"api_name": "math.atan", "line_number": 147, "usage_type": "attribute"}, {"api_name": "math.atan2", "line_number": 148, "usage_type": "attribute"}, {"api_name": "math.cos", "line_number": 149, "usage_type": "attribute"}, {"api_name": "math.hypot", "line_number": 150, "usage_type": "attribute"}, {"api_name": "math.sin", "line_number": 151, "usage_type": "attribute"}, {"api_name": "math.tan", "line_number": 152, "usage_type": "attribute"}, {"api_name": "math.degrees", "line_number": 155, "usage_type": "attribute"}, {"api_name": "math.radians", "line_number": 156, "usage_type": "attribute"}, {"api_name": "math.acosh", "line_number": 159, "usage_type": "attribute"}, {"api_name": "math.asinh", "line_number": 160, "usage_type": "attribute"}, {"api_name": "math.atanh", "line_number": 161, "usage_type": "attribute"}, {"api_name": "math.cosh", "line_number": 162, "usage_type": "attribute"}, {"api_name": "math.sinh", "line_number": 163, "usage_type": "attribute"}, {"api_name": "math.tanh", "line_number": 164, "usage_type": "attribute"}, {"api_name": "math.cos", "line_number": 167, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 168, "usage_type": "call"}, {"api_name": "math.tan", "line_number": 169, "usage_type": "call"}, {"api_name": "random.random", "line_number": 172, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 173, "usage_type": "attribute"}, {"api_name": "random.randrange", "line_number": 174, "usage_type": "attribute"}, {"api_name": "random.choice", "line_number": 175, "usage_type": "attribute"}, {"api_name": "random.sample", "line_number": 176, "usage_type": "attribute"}, {"api_name": "random.sample", "line_number": 177, "usage_type": "call"}, {"api_name": "math.e", "line_number": 211, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 212, "usage_type": "attribute"}, {"api_name": "types.ModuleType", "line_number": 238, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 247, "usage_type": "call"}, {"api_name": "ast.Name", "line_number": 266, "usage_type": "attribute"}, {"api_name": "ast.Tuple", "line_number": 268, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 323, "usage_type": "call"}, {"api_name": "resource.getrusage", "line_number": 330, "usage_type": "call"}, {"api_name": "resource.RUSAGE_SELF", "line_number": 330, "usage_type": "attribute"}, {"api_name": "ast.Num", "line_number": 335, "usage_type": "attribute"}, {"api_name": "ast.NameConstant", "line_number": 337, "usage_type": "attribute"}, {"api_name": "ast.Str", "line_number": 339, "usage_type": "attribute"}, {"api_name": "ast.Tuple", "line_number": 341, "usage_type": "attribute"}, {"api_name": "ast.List", "line_number": 343, "usage_type": "attribute"}, {"api_name": "ast.Dict", "line_number": 345, "usage_type": "attribute"}, {"api_name": "ast.Set", "line_number": 350, "usage_type": "attribute"}, {"api_name": "ast.BoolOp", "line_number": 352, "usage_type": "attribute"}, {"api_name": "ast.And", "line_number": 353, "usage_type": "attribute"}, {"api_name": "ast.Or", "line_number": 360, "usage_type": "attribute"}, {"api_name": "ast.BinOp", "line_number": 367, "usage_type": "attribute"}, {"api_name": "ast.UnaryOp", "line_number": 369, "usage_type": "attribute"}, {"api_name": "ast.Call", "line_number": 371, "usage_type": "attribute"}, {"api_name": "ast.Compare", "line_number": 375, "usage_type": "attribute"}, {"api_name": "ast.Name", "line_number": 383, "usage_type": "attribute"}, {"api_name": "ast.Lambda", "line_number": 395, "usage_type": "attribute"}, {"api_name": "ast.Subscript", "line_number": 406, "usage_type": "attribute"}, {"api_name": "ast.Index", "line_number": 410, "usage_type": "attribute"}, {"api_name": "ast.Slice", "line_number": 412, "usage_type": "attribute"}, {"api_name": "ast.Attribute", "line_number": 417, "usage_type": "attribute"}, {"api_name": "ast.IfExp", "line_number": 423, "usage_type": "attribute"}, {"api_name": "ast.ListComp", "line_number": 426, "usage_type": "attribute"}, {"api_name": "ast.GeneratorExp", "line_number": 426, "usage_type": "attribute"}, {"api_name": "ast.DictComp", "line_number": 432, "usage_type": "attribute"}, {"api_name": "ast.SetComp", "line_number": 438, "usage_type": "attribute"}, {"api_name": "traceback.print_exc", "line_number": 460, "usage_type": "call"}, {"api_name": "cloudbot.hook.command", "line_number": 448, "usage_type": "call"}, {"api_name": "cloudbot.hook", "line_number": 448, "usage_type": "name"}]} +{"seq_id": "25931038890", "text": "import pytest\nfrom unittest import mock\nfrom textwrap import dedent\nfrom dataclasses import asdict\n\n\nclass TestParseConfig:\n @pytest.fixture\n def target(self):\n from shimaenaga.config import parse_config\n\n return parse_config\n\n @pytest.fixture\n def toml(self):\n s = dedent(\n \"\"\"\\\n theme = \"simple\"\n [sitemeta]\n title = \"Site title\"\n author = \"your name\"\n language_code = \"en\"\n year_of_publication = 2020\n \"\"\"\n )\n return s\n\n def test_it(self, target, toml):\n with mock.patch(\"shimaenaga.config.read_file\", return_value=toml):\n result = target(\"path/to\")\n assert asdict(result) == {\n \"theme\": \"simple\",\n \"sitemeta\": {\n \"title\": \"Site title\",\n \"author\": \"your name\",\n \"language_code\": \"en\",\n \"year_of_publication\": 2020,\n },\n }\n", "repo_name": "kk6/shimaenaga", "sub_path": "tests/test_config.py", "file_name": "test_config.py", "file_ext": "py", "file_size_in_byte": 988, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "shimaenaga.config.parse_config", "line_number": 12, "usage_type": "name"}, {"api_name": "pytest.fixture", "line_number": 8, "usage_type": "attribute"}, {"api_name": "textwrap.dedent", "line_number": 16, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 14, "usage_type": "attribute"}, {"api_name": "unittest.mock.patch", "line_number": 29, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 29, "usage_type": "name"}, {"api_name": "dataclasses.asdict", "line_number": 31, "usage_type": "call"}]} +{"seq_id": "31308642100", "text": "from typing import Callable, List, Dict, Tuple, Optional, Union, Any\nimport abc\n\nfrom mlagents.torch_utils import torch, nn\n\nfrom mlagents_envs.base_env import ActionSpec, ObservationSpec, ObservationType\nfrom mlagents.trainers.torch_entities.action_model import ActionModel\nfrom mlagents.trainers.torch_entities.agent_action import AgentAction\nfrom mlagents.trainers.settings import NetworkSettings, EncoderType, ConditioningType\nfrom mlagents.trainers.torch_entities.utils import ModelUtils\nfrom mlagents.trainers.torch_entities.decoders import ValueHeads\nfrom mlagents.trainers.torch_entities.layers import LSTM, LinearEncoder\nfrom mlagents.trainers.torch_entities.encoders import VectorInput\nfrom mlagents.trainers.buffer import AgentBuffer\nfrom mlagents.trainers.trajectory import ObsUtil\nfrom mlagents.trainers.torch_entities.conditioning import ConditionalEncoder\nfrom mlagents.trainers.torch_entities.attention import (\n EntityEmbedding,\n ResidualSelfAttention,\n get_zero_entities_mask,\n)\nfrom mlagents.trainers.exception import UnityTrainerException\n\n\nActivationFunction = Callable[[torch.Tensor], torch.Tensor]\nEncoderFunction = Callable[\n [torch.Tensor, int, ActivationFunction, int, str, bool], torch.Tensor\n]\n\nEPSILON = 1e-7\n\n\nclass ObservationEncoder(nn.Module):\n ATTENTION_EMBEDDING_SIZE = 128 # The embedding size of attention is fixed\n\n def __init__(\n self,\n observation_specs: List[ObservationSpec],\n h_size: int,\n vis_encode_type: EncoderType,\n normalize: bool = False,\n ):\n \"\"\"\n Returns an ObservationEncoder that can process and encode a set of observations.\n Will use an RSA if needed for variable length observations.\n \"\"\"\n super().__init__()\n self.processors, self.embedding_sizes = ModelUtils.create_input_processors(\n observation_specs,\n h_size,\n vis_encode_type,\n self.ATTENTION_EMBEDDING_SIZE,\n normalize=normalize,\n )\n self.rsa, self.x_self_encoder = ModelUtils.create_residual_self_attention(\n self.processors, self.embedding_sizes, self.ATTENTION_EMBEDDING_SIZE\n )\n if self.rsa is not None:\n total_enc_size = sum(self.embedding_sizes) + self.ATTENTION_EMBEDDING_SIZE\n else:\n total_enc_size = sum(self.embedding_sizes)\n self.normalize = normalize\n self._total_enc_size = total_enc_size\n\n self._total_goal_enc_size = 0\n self._goal_processor_indices: List[int] = []\n for i in range(len(observation_specs)):\n if observation_specs[i].observation_type == ObservationType.GOAL_SIGNAL:\n self._total_goal_enc_size += self.embedding_sizes[i]\n self._goal_processor_indices.append(i)\n\n @property\n def total_enc_size(self) -> int:\n \"\"\"\n Returns the total encoding size for this ObservationEncoder.\n \"\"\"\n return self._total_enc_size\n\n @property\n def total_goal_enc_size(self) -> int:\n \"\"\"\n Returns the total goal encoding size for this ObservationEncoder.\n \"\"\"\n return self._total_goal_enc_size\n\n def update_normalization(self, buffer: AgentBuffer) -> None:\n obs = ObsUtil.from_buffer(buffer, len(self.processors))\n for vec_input, enc in zip(obs, self.processors):\n if isinstance(enc, VectorInput):\n enc.update_normalization(torch.as_tensor(vec_input.to_ndarray()))\n\n def copy_normalization(self, other_encoder: \"ObservationEncoder\") -> None:\n if self.normalize:\n for n1, n2 in zip(self.processors, other_encoder.processors):\n if isinstance(n1, VectorInput) and isinstance(n2, VectorInput):\n n1.copy_normalization(n2)\n\n def forward(self, inputs: List[torch.Tensor]) -> torch.Tensor:\n \"\"\"\n Encode observations using a list of processors and an RSA.\n :param inputs: List of Tensors corresponding to a set of obs.\n \"\"\"\n encodes = []\n var_len_processor_inputs: List[Tuple[nn.Module, torch.Tensor]] = []\n\n for idx, processor in enumerate(self.processors):\n if not isinstance(processor, EntityEmbedding):\n # The input can be encoded without having to process other inputs\n obs_input = inputs[idx]\n processed_obs = processor(obs_input)\n encodes.append(processed_obs)\n else:\n var_len_processor_inputs.append((processor, inputs[idx]))\n if len(encodes) != 0:\n encoded_self = torch.cat(encodes, dim=1)\n input_exist = True\n else:\n input_exist = False\n if len(var_len_processor_inputs) > 0 and self.rsa is not None:\n # Some inputs need to be processed with a variable length encoder\n masks = get_zero_entities_mask([p_i[1] for p_i in var_len_processor_inputs])\n embeddings: List[torch.Tensor] = []\n processed_self = (\n self.x_self_encoder(encoded_self)\n if input_exist and self.x_self_encoder is not None\n else None\n )\n for processor, var_len_input in var_len_processor_inputs:\n embeddings.append(processor(processed_self, var_len_input))\n qkv = torch.cat(embeddings, dim=1)\n attention_embedding = self.rsa(qkv, masks)\n if not input_exist:\n encoded_self = torch.cat([attention_embedding], dim=1)\n input_exist = True\n else:\n encoded_self = torch.cat([encoded_self, attention_embedding], dim=1)\n\n if not input_exist:\n raise UnityTrainerException(\n \"The trainer was unable to process any of the provided inputs. \"\n \"Make sure the trained agents has at least one sensor attached to them.\"\n )\n\n return encoded_self\n\n def get_goal_encoding(self, inputs: List[torch.Tensor]) -> torch.Tensor:\n \"\"\"\n Encode observations corresponding to goals using a list of processors.\n :param inputs: List of Tensors corresponding to a set of obs.\n \"\"\"\n encodes = []\n for idx in self._goal_processor_indices:\n processor = self.processors[idx]\n if not isinstance(processor, EntityEmbedding):\n # The input can be encoded without having to process other inputs\n obs_input = inputs[idx]\n processed_obs = processor(obs_input)\n encodes.append(processed_obs)\n else:\n raise UnityTrainerException(\n \"The one of the goals uses variable length observations. This use \"\n \"case is not supported.\"\n )\n if len(encodes) != 0:\n encoded = torch.cat(encodes, dim=1)\n else:\n raise UnityTrainerException(\n \"Trainer was unable to process any of the goals provided as input.\"\n )\n return encoded\n\n\nclass NetworkBody(nn.Module):\n def __init__(\n self,\n observation_specs: List[ObservationSpec],\n network_settings: NetworkSettings,\n encoded_act_size: int = 0,\n ):\n super().__init__()\n self.normalize = network_settings.normalize\n self.use_lstm = network_settings.memory is not None\n self.h_size = network_settings.hidden_units\n self.m_size = (\n network_settings.memory.memory_size\n if network_settings.memory is not None\n else 0\n )\n self.observation_encoder = ObservationEncoder(\n observation_specs,\n self.h_size,\n network_settings.vis_encode_type,\n self.normalize,\n )\n self.processors = self.observation_encoder.processors\n total_enc_size = self.observation_encoder.total_enc_size\n total_enc_size += encoded_act_size\n\n if (\n self.observation_encoder.total_goal_enc_size > 0\n and network_settings.goal_conditioning_type == ConditioningType.HYPER\n ):\n self._body_endoder = ConditionalEncoder(\n total_enc_size,\n self.observation_encoder.total_goal_enc_size,\n self.h_size,\n network_settings.num_layers,\n 1,\n )\n else:\n self._body_endoder = LinearEncoder(\n total_enc_size, network_settings.num_layers, self.h_size\n )\n\n if self.use_lstm:\n self.lstm = LSTM(self.h_size, self.m_size)\n else:\n self.lstm = None # type: ignore\n\n def update_normalization(self, buffer: AgentBuffer) -> None:\n self.observation_encoder.update_normalization(buffer)\n\n def copy_normalization(self, other_network: \"NetworkBody\") -> None:\n self.observation_encoder.copy_normalization(other_network.observation_encoder)\n\n @property\n def memory_size(self) -> int:\n return self.lstm.memory_size if self.use_lstm else 0\n\n def forward(\n self,\n inputs: List[torch.Tensor],\n actions: Optional[torch.Tensor] = None,\n memories: Optional[torch.Tensor] = None,\n sequence_length: int = 1,\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n encoded_self = self.observation_encoder(inputs)\n if actions is not None:\n encoded_self = torch.cat([encoded_self, actions], dim=1)\n if isinstance(self._body_endoder, ConditionalEncoder):\n goal = self.observation_encoder.get_goal_encoding(inputs)\n encoding = self._body_endoder(encoded_self, goal)\n else:\n encoding = self._body_endoder(encoded_self)\n\n if self.use_lstm:\n # Resize to (batch, sequence length, encoding size)\n encoding = encoding.reshape([-1, sequence_length, self.h_size])\n encoding, memories = self.lstm(encoding, memories)\n encoding = encoding.reshape([-1, self.m_size // 2])\n return encoding, memories\n\n\nclass MultiAgentNetworkBody(torch.nn.Module):\n \"\"\"\n A network body that uses a self attention layer to handle state\n and action input from a potentially variable number of agents that\n share the same observation and action space.\n \"\"\"\n\n def __init__(\n self,\n observation_specs: List[ObservationSpec],\n network_settings: NetworkSettings,\n action_spec: ActionSpec,\n ):\n super().__init__()\n self.normalize = network_settings.normalize\n self.use_lstm = network_settings.memory is not None\n self.h_size = network_settings.hidden_units\n self.m_size = (\n network_settings.memory.memory_size\n if network_settings.memory is not None\n else 0\n )\n self.action_spec = action_spec\n self.observation_encoder = ObservationEncoder(\n observation_specs,\n self.h_size,\n network_settings.vis_encode_type,\n self.normalize,\n )\n self.processors = self.observation_encoder.processors\n\n # Modules for multi-agent self-attention\n obs_only_ent_size = self.observation_encoder.total_enc_size\n q_ent_size = (\n obs_only_ent_size\n + sum(self.action_spec.discrete_branches)\n + self.action_spec.continuous_size\n )\n\n attention_embeding_size = self.h_size\n self.obs_encoder = EntityEmbedding(\n obs_only_ent_size, None, attention_embeding_size\n )\n self.obs_action_encoder = EntityEmbedding(\n q_ent_size, None, attention_embeding_size\n )\n\n self.self_attn = ResidualSelfAttention(attention_embeding_size)\n\n self.linear_encoder = LinearEncoder(\n attention_embeding_size,\n network_settings.num_layers,\n self.h_size,\n kernel_gain=(0.125 / self.h_size) ** 0.5,\n )\n\n if self.use_lstm:\n self.lstm = LSTM(self.h_size, self.m_size)\n else:\n self.lstm = None # type: ignore\n self._current_max_agents = torch.nn.Parameter(\n torch.as_tensor(1), requires_grad=False\n )\n\n @property\n def memory_size(self) -> int:\n return self.lstm.memory_size if self.use_lstm else 0\n\n def update_normalization(self, buffer: AgentBuffer) -> None:\n self.observation_encoder.update_normalization(buffer)\n\n def copy_normalization(self, other_network: \"MultiAgentNetworkBody\") -> None:\n self.observation_encoder.copy_normalization(other_network.observation_encoder)\n\n def _get_masks_from_nans(self, obs_tensors: List[torch.Tensor]) -> torch.Tensor:\n \"\"\"\n Get attention masks by grabbing an arbitrary obs across all the agents\n Since these are raw obs, the padded values are still NaN\n \"\"\"\n only_first_obs = [_all_obs[0] for _all_obs in obs_tensors]\n # Just get the first element in each obs regardless of its dimension. This will speed up\n # searching for NaNs.\n only_first_obs_flat = torch.stack(\n [_obs.flatten(start_dim=1)[:, 0] for _obs in only_first_obs], dim=1\n )\n # Get the mask from NaNs\n attn_mask = only_first_obs_flat.isnan().float()\n return attn_mask\n\n def _copy_and_remove_nans_from_obs(\n self, all_obs: List[List[torch.Tensor]], attention_mask: torch.Tensor\n ) -> List[List[torch.Tensor]]:\n \"\"\"\n Helper function to remove NaNs from observations using an attention mask.\n \"\"\"\n obs_with_no_nans = []\n for i_agent, single_agent_obs in enumerate(all_obs):\n no_nan_obs = []\n for obs in single_agent_obs:\n new_obs = obs.clone()\n new_obs[attention_mask.bool()[:, i_agent], ::] = 0.0 # Remove NaNs fast\n no_nan_obs.append(new_obs)\n obs_with_no_nans.append(no_nan_obs)\n return obs_with_no_nans\n\n def forward(\n self,\n obs_only: List[List[torch.Tensor]],\n obs: List[List[torch.Tensor]],\n actions: List[AgentAction],\n memories: Optional[torch.Tensor] = None,\n sequence_length: int = 1,\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Returns sampled actions.\n If memory is enabled, return the memories as well.\n :param obs_only: Observations to be processed that do not have corresponding actions.\n These are encoded with the obs_encoder.\n :param obs: Observations to be processed that do have corresponding actions.\n After concatenation with actions, these are processed with obs_action_encoder.\n :param actions: After concatenation with obs, these are processed with obs_action_encoder.\n :param memories: If using memory, a Tensor of initial memories.\n :param sequence_length: If using memory, the sequence length.\n \"\"\"\n self_attn_masks = []\n self_attn_inputs = []\n concat_f_inp = []\n if obs:\n obs_attn_mask = self._get_masks_from_nans(obs)\n obs = self._copy_and_remove_nans_from_obs(obs, obs_attn_mask)\n for inputs, action in zip(obs, actions):\n encoded = self.observation_encoder(inputs)\n cat_encodes = [\n encoded,\n action.to_flat(self.action_spec.discrete_branches),\n ]\n concat_f_inp.append(torch.cat(cat_encodes, dim=1))\n f_inp = torch.stack(concat_f_inp, dim=1)\n self_attn_masks.append(obs_attn_mask)\n self_attn_inputs.append(self.obs_action_encoder(None, f_inp))\n\n concat_encoded_obs = []\n if obs_only:\n obs_only_attn_mask = self._get_masks_from_nans(obs_only)\n obs_only = self._copy_and_remove_nans_from_obs(obs_only, obs_only_attn_mask)\n for inputs in obs_only:\n encoded = self.observation_encoder(inputs)\n concat_encoded_obs.append(encoded)\n g_inp = torch.stack(concat_encoded_obs, dim=1)\n self_attn_masks.append(obs_only_attn_mask)\n self_attn_inputs.append(self.obs_encoder(None, g_inp))\n\n encoded_entity = torch.cat(self_attn_inputs, dim=1)\n encoded_state = self.self_attn(encoded_entity, self_attn_masks)\n\n flipped_masks = 1 - torch.cat(self_attn_masks, dim=1)\n num_agents = torch.sum(flipped_masks, dim=1, keepdim=True)\n if torch.max(num_agents).item() > self._current_max_agents:\n self._current_max_agents = torch.nn.Parameter(\n torch.as_tensor(torch.max(num_agents).item()), requires_grad=False\n )\n\n # num_agents will be -1 for a single agent and +1 when the current maximum is reached\n num_agents = num_agents * 2.0 / self._current_max_agents - 1\n\n encoding = self.linear_encoder(encoded_state)\n if self.use_lstm:\n # Resize to (batch, sequence length, encoding size)\n encoding = encoding.reshape([-1, sequence_length, self.h_size])\n encoding, memories = self.lstm(encoding, memories)\n encoding = encoding.reshape([-1, self.m_size // 2])\n encoding = torch.cat([encoding, num_agents], dim=1)\n return encoding, memories\n\n\nclass Critic(abc.ABC):\n @abc.abstractmethod\n def update_normalization(self, buffer: AgentBuffer) -> None:\n \"\"\"\n Updates normalization of Actor based on the provided List of vector obs.\n :param vector_obs: A List of vector obs as tensors.\n \"\"\"\n pass\n\n def critic_pass(\n self,\n inputs: List[torch.Tensor],\n memories: Optional[torch.Tensor] = None,\n sequence_length: int = 1,\n ) -> Tuple[Dict[str, torch.Tensor], torch.Tensor]:\n \"\"\"\n Get value outputs for the given obs.\n :param inputs: List of inputs as tensors.\n :param memories: Tensor of memories, if using memory. Otherwise, None.\n :returns: Dict of reward stream to output tensor for values.\n \"\"\"\n pass\n\n\nclass ValueNetwork(nn.Module, Critic):\n def __init__(\n self,\n stream_names: List[str],\n observation_specs: List[ObservationSpec],\n network_settings: NetworkSettings,\n encoded_act_size: int = 0,\n outputs_per_stream: int = 1,\n ):\n\n # This is not a typo, we want to call __init__ of nn.Module\n nn.Module.__init__(self)\n self.network_body = NetworkBody(\n observation_specs, network_settings, encoded_act_size=encoded_act_size\n )\n if network_settings.memory is not None:\n encoding_size = network_settings.memory.memory_size // 2\n else:\n encoding_size = network_settings.hidden_units\n self.value_heads = ValueHeads(stream_names, encoding_size, outputs_per_stream)\n\n def update_normalization(self, buffer: AgentBuffer) -> None:\n self.network_body.update_normalization(buffer)\n\n @property\n def memory_size(self) -> int:\n return self.network_body.memory_size\n\n def critic_pass(\n self,\n inputs: List[torch.Tensor],\n memories: Optional[torch.Tensor] = None,\n sequence_length: int = 1,\n ) -> Tuple[Dict[str, torch.Tensor], torch.Tensor]:\n value_outputs, critic_mem_out = self.forward(\n inputs, memories=memories, sequence_length=sequence_length\n )\n return value_outputs, critic_mem_out\n\n def forward(\n self,\n inputs: List[torch.Tensor],\n actions: Optional[torch.Tensor] = None,\n memories: Optional[torch.Tensor] = None,\n sequence_length: int = 1,\n ) -> Tuple[Dict[str, torch.Tensor], torch.Tensor]:\n encoding, memories = self.network_body(\n inputs, actions, memories, sequence_length\n )\n output = self.value_heads(encoding)\n return output, memories\n\n\nclass Actor(abc.ABC):\n @abc.abstractmethod\n def update_normalization(self, buffer: AgentBuffer) -> None:\n \"\"\"\n Updates normalization of Actor based on the provided List of vector obs.\n :param vector_obs: A List of vector obs as tensors.\n \"\"\"\n pass\n\n def get_action_and_stats(\n self,\n inputs: List[torch.Tensor],\n masks: Optional[torch.Tensor] = None,\n memories: Optional[torch.Tensor] = None,\n sequence_length: int = 1,\n ) -> Tuple[AgentAction, Dict[str, Any], torch.Tensor]:\n \"\"\"\n Returns sampled actions.\n If memory is enabled, return the memories as well.\n :param inputs: A List of inputs as tensors.\n :param masks: If using discrete actions, a Tensor of action masks.\n :param memories: If using memory, a Tensor of initial memories.\n :param sequence_length: If using memory, the sequence length.\n :return: A Tuple of AgentAction, ActionLogProbs, entropies, and memories.\n Memories will be None if not using memory.\n \"\"\"\n pass\n\n def get_stats(\n self,\n inputs: List[torch.Tensor],\n actions: AgentAction,\n masks: Optional[torch.Tensor] = None,\n memories: Optional[torch.Tensor] = None,\n sequence_length: int = 1,\n ) -> Dict[str, Any]:\n \"\"\"\n Returns log_probs for actions and entropies.\n If memory is enabled, return the memories as well.\n :param inputs: A List of inputs as tensors.\n :param actions: AgentAction of actions.\n :param masks: If using discrete actions, a Tensor of action masks.\n :param memories: If using memory, a Tensor of initial memories.\n :param sequence_length: If using memory, the sequence length.\n :return: A Tuple of AgentAction, ActionLogProbs, entropies, and memories.\n Memories will be None if not using memory.\n \"\"\"\n\n pass\n\n @abc.abstractmethod\n def forward(\n self,\n inputs: List[torch.Tensor],\n masks: Optional[torch.Tensor] = None,\n memories: Optional[torch.Tensor] = None,\n ) -> Tuple[Union[int, torch.Tensor], ...]:\n \"\"\"\n Forward pass of the Actor for inference. This is required for export to ONNX, and\n the inputs and outputs of this method should not be changed without a respective change\n in the ONNX export code.\n \"\"\"\n pass\n\n\nclass SimpleActor(nn.Module, Actor):\n MODEL_EXPORT_VERSION = 3 # Corresponds to ModelApiVersion.MLAgents2_0\n\n def __init__(\n self,\n observation_specs: List[ObservationSpec],\n network_settings: NetworkSettings,\n action_spec: ActionSpec,\n conditional_sigma: bool = False,\n tanh_squash: bool = False,\n ):\n super().__init__()\n self.action_spec = action_spec\n self.version_number = torch.nn.Parameter(\n torch.Tensor([self.MODEL_EXPORT_VERSION]), requires_grad=False\n )\n self.is_continuous_int_deprecated = torch.nn.Parameter(\n torch.Tensor([int(self.action_spec.is_continuous())]), requires_grad=False\n )\n self.continuous_act_size_vector = torch.nn.Parameter(\n torch.Tensor([int(self.action_spec.continuous_size)]), requires_grad=False\n )\n self.discrete_act_size_vector = torch.nn.Parameter(\n torch.Tensor([self.action_spec.discrete_branches]), requires_grad=False\n )\n self.act_size_vector_deprecated = torch.nn.Parameter(\n torch.Tensor(\n [\n self.action_spec.continuous_size\n + sum(self.action_spec.discrete_branches)\n ]\n ),\n requires_grad=False,\n )\n self.network_body = NetworkBody(observation_specs, network_settings)\n if network_settings.memory is not None:\n self.encoding_size = network_settings.memory.memory_size // 2\n else:\n self.encoding_size = network_settings.hidden_units\n self.memory_size_vector = torch.nn.Parameter(\n torch.Tensor([int(self.network_body.memory_size)]), requires_grad=False\n )\n\n self.action_model = ActionModel(\n self.encoding_size,\n action_spec,\n conditional_sigma=conditional_sigma,\n tanh_squash=tanh_squash,\n deterministic=network_settings.deterministic,\n )\n\n @property\n def memory_size(self) -> int:\n return self.network_body.memory_size\n\n def update_normalization(self, buffer: AgentBuffer) -> None:\n self.network_body.update_normalization(buffer)\n\n def get_action_and_stats(\n self,\n inputs: List[torch.Tensor],\n masks: Optional[torch.Tensor] = None,\n memories: Optional[torch.Tensor] = None,\n sequence_length: int = 1,\n ) -> Tuple[AgentAction, Dict[str, Any], torch.Tensor]:\n\n encoding, memories = self.network_body(\n inputs, memories=memories, sequence_length=sequence_length\n )\n action, log_probs, entropies = self.action_model(encoding, masks)\n run_out = {}\n # This is the clipped action which is not saved to the buffer\n # but is exclusively sent to the environment.\n run_out[\"env_action\"] = action.to_action_tuple(\n clip=self.action_model.clip_action\n )\n run_out[\"log_probs\"] = log_probs\n run_out[\"entropy\"] = entropies\n\n return action, run_out, memories\n\n def get_stats(\n self,\n inputs: List[torch.Tensor],\n actions: AgentAction,\n masks: Optional[torch.Tensor] = None,\n memories: Optional[torch.Tensor] = None,\n sequence_length: int = 1,\n ) -> Dict[str, Any]:\n encoding, actor_mem_outs = self.network_body(\n inputs, memories=memories, sequence_length=sequence_length\n )\n\n log_probs, entropies = self.action_model.evaluate(encoding, masks, actions)\n run_out = {}\n run_out[\"log_probs\"] = log_probs\n run_out[\"entropy\"] = entropies\n return run_out\n\n def forward(\n self,\n inputs: List[torch.Tensor],\n masks: Optional[torch.Tensor] = None,\n memories: Optional[torch.Tensor] = None,\n ) -> Tuple[Union[int, torch.Tensor], ...]:\n \"\"\"\n Note: This forward() method is required for exporting to ONNX. Don't modify the inputs and outputs.\n\n At this moment, torch.onnx.export() doesn't accept None as tensor to be exported,\n so the size of return tuple varies with action spec.\n \"\"\"\n encoding, memories_out = self.network_body(\n inputs, memories=memories, sequence_length=1\n )\n\n (\n cont_action_out,\n disc_action_out,\n action_out_deprecated,\n deterministic_cont_action_out,\n deterministic_disc_action_out,\n ) = self.action_model.get_action_out(encoding, masks)\n export_out = [self.version_number, self.memory_size_vector]\n if self.action_spec.continuous_size > 0:\n export_out += [\n cont_action_out,\n self.continuous_act_size_vector,\n deterministic_cont_action_out,\n ]\n if self.action_spec.discrete_size > 0:\n export_out += [\n disc_action_out,\n self.discrete_act_size_vector,\n deterministic_disc_action_out,\n ]\n if self.network_body.memory_size > 0:\n export_out += [memories_out]\n return tuple(export_out)\n\n\nclass SharedActorCritic(SimpleActor, Critic):\n def __init__(\n self,\n observation_specs: List[ObservationSpec],\n network_settings: NetworkSettings,\n action_spec: ActionSpec,\n stream_names: List[str],\n conditional_sigma: bool = False,\n tanh_squash: bool = False,\n ):\n self.use_lstm = network_settings.memory is not None\n super().__init__(\n observation_specs,\n network_settings,\n action_spec,\n conditional_sigma,\n tanh_squash,\n )\n self.stream_names = stream_names\n self.value_heads = ValueHeads(stream_names, self.encoding_size)\n\n def critic_pass(\n self,\n inputs: List[torch.Tensor],\n memories: Optional[torch.Tensor] = None,\n sequence_length: int = 1,\n ) -> Tuple[Dict[str, torch.Tensor], torch.Tensor]:\n encoding, memories_out = self.network_body(\n inputs, memories=memories, sequence_length=sequence_length\n )\n return self.value_heads(encoding), memories_out\n\n\nclass GlobalSteps(nn.Module):\n def __init__(self):\n super().__init__()\n self.__global_step = nn.Parameter(\n torch.Tensor([0]).to(torch.int64), requires_grad=False\n )\n\n @property\n def current_step(self):\n return int(self.__global_step.item())\n\n @current_step.setter\n def current_step(self, value):\n self.__global_step[:] = value\n\n def increment(self, value):\n self.__global_step += value\n\n\nclass LearningRate(nn.Module):\n def __init__(self, lr):\n # Todo: add learning rate decay\n super().__init__()\n self.learning_rate = torch.Tensor([lr])\n", "repo_name": "Unity-Technologies/ml-agents", "sub_path": "ml-agents/mlagents/trainers/torch_entities/networks.py", "file_name": "networks.py", "file_ext": "py", "file_size_in_byte": 29280, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 15647, "dataset": "github-code", "pt": "48", "api": [{"api_name": "typing.Callable", "line_number": 25, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 25, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 25, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 26, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 27, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 27, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.nn.Module", "line_number": 33, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.nn", "line_number": 33, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 38, "usage_type": "name"}, {"api_name": "mlagents_envs.base_env.ObservationSpec", "line_number": 38, "usage_type": "name"}, {"api_name": "mlagents.trainers.settings.EncoderType", "line_number": 40, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.utils.ModelUtils.create_input_processors", "line_number": 48, "usage_type": "call"}, {"api_name": "mlagents.trainers.torch_entities.utils.ModelUtils", "line_number": 48, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.utils.ModelUtils.create_residual_self_attention", "line_number": 55, "usage_type": "call"}, {"api_name": "mlagents.trainers.torch_entities.utils.ModelUtils", "line_number": 55, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 66, "usage_type": "name"}, {"api_name": "mlagents_envs.base_env.ObservationType.GOAL_SIGNAL", "line_number": 68, "usage_type": "attribute"}, {"api_name": "mlagents_envs.base_env.ObservationType", "line_number": 68, "usage_type": "name"}, {"api_name": "mlagents.trainers.buffer.AgentBuffer", "line_number": 86, "usage_type": "name"}, {"api_name": "mlagents.trainers.trajectory.ObsUtil.from_buffer", "line_number": 87, "usage_type": "call"}, {"api_name": "mlagents.trainers.trajectory.ObsUtil", "line_number": 87, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.encoders.VectorInput", "line_number": 89, "usage_type": "argument"}, {"api_name": "mlagents.torch_utils.torch.as_tensor", "line_number": 90, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 90, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.encoders.VectorInput", "line_number": 95, "usage_type": "argument"}, {"api_name": "typing.List", "line_number": 98, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 98, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 98, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 104, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 104, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.nn.Module", "line_number": 104, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.nn", "line_number": 104, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 104, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 104, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.attention.EntityEmbedding", "line_number": 107, "usage_type": "argument"}, {"api_name": "mlagents.torch_utils.torch.cat", "line_number": 115, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 115, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.attention.get_zero_entities_mask", "line_number": 121, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 122, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 122, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 122, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.cat", "line_number": 130, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 130, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.cat", "line_number": 133, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 133, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.cat", "line_number": 136, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 136, "usage_type": "name"}, {"api_name": "mlagents.trainers.exception.UnityTrainerException", "line_number": 139, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 146, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 146, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 146, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.attention.EntityEmbedding", "line_number": 154, "usage_type": "argument"}, {"api_name": "mlagents.trainers.exception.UnityTrainerException", "line_number": 160, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch.cat", "line_number": 165, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 165, "usage_type": "name"}, {"api_name": "mlagents.trainers.exception.UnityTrainerException", "line_number": 167, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.nn.Module", "line_number": 173, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.nn", "line_number": 173, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 176, "usage_type": "name"}, {"api_name": "mlagents_envs.base_env.ObservationSpec", "line_number": 176, "usage_type": "name"}, {"api_name": "mlagents.trainers.settings.NetworkSettings", "line_number": 177, "usage_type": "name"}, {"api_name": "mlagents.trainers.settings.ConditioningType.HYPER", "line_number": 201, "usage_type": "attribute"}, {"api_name": "mlagents.trainers.settings.ConditioningType", "line_number": 201, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.conditioning.ConditionalEncoder", "line_number": 203, "usage_type": "call"}, {"api_name": "mlagents.trainers.torch_entities.layers.LinearEncoder", "line_number": 211, "usage_type": "call"}, {"api_name": "mlagents.trainers.torch_entities.layers.LSTM", "line_number": 216, "usage_type": "call"}, {"api_name": "mlagents.trainers.buffer.AgentBuffer", "line_number": 220, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 232, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 232, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 232, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 233, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 233, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 233, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 234, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 234, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 234, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.cat", "line_number": 239, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 239, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.conditioning.ConditionalEncoder", "line_number": 240, "usage_type": "argument"}, {"api_name": "typing.Tuple", "line_number": 236, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 236, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 236, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.nn", "line_number": 254, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 254, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 263, "usage_type": "name"}, {"api_name": "mlagents_envs.base_env.ObservationSpec", "line_number": 263, "usage_type": "name"}, {"api_name": "mlagents.trainers.settings.NetworkSettings", "line_number": 264, "usage_type": "name"}, {"api_name": "mlagents_envs.base_env.ActionSpec", "line_number": 265, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.attention.EntityEmbedding", "line_number": 294, "usage_type": "call"}, {"api_name": "mlagents.trainers.torch_entities.attention.EntityEmbedding", "line_number": 297, "usage_type": "call"}, {"api_name": "mlagents.trainers.torch_entities.attention.ResidualSelfAttention", "line_number": 301, "usage_type": "call"}, {"api_name": "mlagents.trainers.torch_entities.layers.LinearEncoder", "line_number": 303, "usage_type": "call"}, {"api_name": "mlagents.trainers.torch_entities.layers.LSTM", "line_number": 311, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch.nn.Parameter", "line_number": 314, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch.nn", "line_number": 314, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 314, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.as_tensor", "line_number": 315, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 315, "usage_type": "name"}, {"api_name": "mlagents.trainers.buffer.AgentBuffer", "line_number": 322, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 328, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 328, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 328, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.stack", "line_number": 336, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 336, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 344, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 344, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 344, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 345, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 345, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 345, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 361, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 361, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 361, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 362, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 362, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 362, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 363, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.agent_action.AgentAction", "line_number": 363, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 364, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 364, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 364, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.cat", "line_number": 390, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 390, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.stack", "line_number": 391, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 391, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.stack", "line_number": 402, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 402, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.cat", "line_number": 406, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 406, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.cat", "line_number": 409, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 409, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.sum", "line_number": 410, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 410, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.max", "line_number": 411, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 411, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.nn.Parameter", "line_number": 412, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch.nn", "line_number": 412, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 412, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.as_tensor", "line_number": 413, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 413, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.max", "line_number": 413, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch.cat", "line_number": 425, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 425, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 366, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 366, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 366, "usage_type": "name"}, {"api_name": "abc.ABC", "line_number": 429, "usage_type": "attribute"}, {"api_name": "mlagents.trainers.buffer.AgentBuffer", "line_number": 431, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 430, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 440, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 440, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 440, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 441, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 441, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 441, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 443, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 443, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 443, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 443, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.nn.Module", "line_number": 453, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.nn", "line_number": 453, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 456, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 457, "usage_type": "name"}, {"api_name": "mlagents_envs.base_env.ObservationSpec", "line_number": 457, "usage_type": "name"}, {"api_name": "mlagents.trainers.settings.NetworkSettings", "line_number": 458, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.nn.Module.__init__", "line_number": 464, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.nn.Module", "line_number": 464, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.nn", "line_number": 464, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.decoders.ValueHeads", "line_number": 472, "usage_type": "call"}, {"api_name": "mlagents.trainers.buffer.AgentBuffer", "line_number": 474, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 483, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 483, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 483, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 484, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 484, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 484, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 486, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 486, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 486, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 486, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 494, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 494, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 494, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 495, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 495, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 495, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 496, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 496, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 496, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 498, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 498, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 498, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 498, "usage_type": "name"}, {"api_name": "abc.ABC", "line_number": 506, "usage_type": "attribute"}, {"api_name": "mlagents.trainers.buffer.AgentBuffer", "line_number": 508, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 507, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 517, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 517, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 517, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 518, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 518, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 518, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 519, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 519, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 519, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 521, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.agent_action.AgentAction", "line_number": 521, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 521, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 521, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 521, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 521, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 536, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 536, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 536, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.agent_action.AgentAction", "line_number": 537, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 538, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 538, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 538, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 539, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 539, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 539, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 541, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 541, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 559, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 559, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 559, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 560, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 560, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 560, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 561, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 561, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 561, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 556, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 562, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 562, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 562, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 562, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.nn.Module", "line_number": 571, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.nn", "line_number": 571, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 576, "usage_type": "name"}, {"api_name": "mlagents_envs.base_env.ObservationSpec", "line_number": 576, "usage_type": "name"}, {"api_name": "mlagents.trainers.settings.NetworkSettings", "line_number": 577, "usage_type": "name"}, {"api_name": "mlagents_envs.base_env.ActionSpec", "line_number": 578, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.nn.Parameter", "line_number": 584, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch.nn", "line_number": 584, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 584, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 585, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 585, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.nn.Parameter", "line_number": 587, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch.nn", "line_number": 587, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 587, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 588, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 588, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.nn.Parameter", "line_number": 590, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch.nn", "line_number": 590, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 590, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 591, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 591, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.nn.Parameter", "line_number": 593, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch.nn", "line_number": 593, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 593, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 594, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 594, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.nn.Parameter", "line_number": 596, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch.nn", "line_number": 596, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 596, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 597, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 597, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.nn.Parameter", "line_number": 610, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch.nn", "line_number": 610, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 610, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 611, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 611, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.action_model.ActionModel", "line_number": 614, "usage_type": "call"}, {"api_name": "mlagents.trainers.buffer.AgentBuffer", "line_number": 626, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 631, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 631, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 631, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 632, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 632, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 632, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 633, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 633, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 633, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 635, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.agent_action.AgentAction", "line_number": 635, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 635, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 635, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 635, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 635, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 654, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 654, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 654, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.agent_action.AgentAction", "line_number": 655, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 656, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 656, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 656, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 657, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 657, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 657, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 659, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 659, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 672, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 672, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 672, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 673, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 673, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 673, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 674, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 674, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 674, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 675, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 675, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 675, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 675, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 714, "usage_type": "name"}, {"api_name": "mlagents_envs.base_env.ObservationSpec", "line_number": 714, "usage_type": "name"}, {"api_name": "mlagents.trainers.settings.NetworkSettings", "line_number": 715, "usage_type": "name"}, {"api_name": "mlagents_envs.base_env.ActionSpec", "line_number": 716, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 717, "usage_type": "name"}, {"api_name": "mlagents.trainers.torch_entities.decoders.ValueHeads", "line_number": 730, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 734, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 734, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 734, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 735, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 735, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 735, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 737, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 737, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 737, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 737, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.nn.Module", "line_number": 744, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.nn", "line_number": 744, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.nn.Parameter", "line_number": 747, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.nn", "line_number": 747, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 748, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 748, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.int64", "line_number": 748, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.nn.Module", "line_number": 763, "usage_type": "attribute"}, {"api_name": "mlagents.torch_utils.nn", "line_number": 763, "usage_type": "name"}, {"api_name": "mlagents.torch_utils.torch.Tensor", "line_number": 767, "usage_type": "call"}, {"api_name": "mlagents.torch_utils.torch", "line_number": 767, "usage_type": "name"}]} +{"seq_id": "31197720015", "text": "import networkx as nx\nimport matplotlib.pyplot as plt\n\nentity_dict = {}\nwith open(\"data/entity2id.txt\", \"r\") as f:\n f.readline()\n for line in f:\n entity_list = line.strip().split('\\t')\n entity_name, entity_id = entity_list[0], entity_list[1]\n entity_dict[int(entity_id)] = entity_name\n\nrelation_dict = {}\nwith open(\"data/relation2id.txt\", \"r\") as f:\n f.readline()\n for line in f:\n relation_list = line.strip().split('\\t')\n relation_name, relation_id = relation_list[0], relation_list[1]\n relation_dict[int(relation_id)] = relation_name\n\nedges = []\nwith open(\"data/train2id.txt\", \"r\") as f:\n f.readline()\n for line in f:\n edge_list = line.strip().split('\\t')\n head_id, relation_id, tail_id = edge_list[0], edge_list[1], edge_list[2]\n edges.append((int(head_id), int(tail_id), int(relation_id)))\n\n\n# 生成节点和边列表\nnodes = set()\nfor edge in edges:\n nodes.add(edge[0])\n nodes.add(edge[2])\nnodes = list(nodes)\nedges = [(entity_dict[edge[0]], entity_dict[edge[2]], relation_dict[edge[1]]) for edge in edges]\n\n# 使用networkx库绘制图形网络\n\nG = nx.DiGraph()\nG.add_nodes_from(nodes)\nfor edge in edges:\n source_node, target_node, relation = edge\n# G.add_edges_from(source_node,target_node)\n G.add_edges_from([(source_node, target_node, {'relation': relation}) for source_node, target_node, relation in edges])\n\n# nx.draw(G, with_labels=True)\npos = nx.spring_layout(G)\nnx.draw_networkx_nodes(G, pos)\nnx.draw_networkx_edges(G, pos)\nnx.draw_networkx_labels(G, pos)\nplt.show()\n", "repo_name": "ChenSuperstar/MRS-BasedOn-KG", "sub_path": "draw_association_rules.py", "file_name": "draw_association_rules.py", "file_ext": "py", "file_size_in_byte": 1580, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "networkx.DiGraph", "line_number": 39, "usage_type": "call"}, {"api_name": "networkx.spring_layout", "line_number": 47, "usage_type": "call"}, {"api_name": "networkx.draw_networkx_nodes", "line_number": 48, "usage_type": "call"}, {"api_name": "networkx.draw_networkx_edges", "line_number": 49, "usage_type": "call"}, {"api_name": "networkx.draw_networkx_labels", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}]} +{"seq_id": "914738358", "text": "import sys\nimport os\nimport os.path\nimport traceback\nimport time\nimport collections\nimport logging\n\nimport six\nimport yaml\nimport numpy as np\n\nfrom PySide2 import QtCore\n\nfrom quantiphyse.processes import Process\nfrom quantiphyse.processes.io import *\nfrom quantiphyse.processes.misc import *\nfrom quantiphyse.utils.logger import set_base_log_level\nfrom quantiphyse.data import ImageVolumeManagement, load, save\n\nfrom . import get_plugins, ifnone\nfrom .exceptions import QpException\n\n# Default basic processes - all others are imported from packages\nBASIC_PROCESSES = {\n \"RenameData\" : RenameProcess,\n \"RenameRoi\" : RenameProcess,\n \"Rename\" : RenameProcess,\n \"Delete\" : DeleteProcess,\n \"RoiCleanup\" : RoiCleanupProcess,\n \"Load\" : LoadProcess,\n \"Save\" : SaveProcess,\n \"SaveAllExcept\" : SaveAllExceptProcess,\n \"SaveAndDelete\" : SaveDeleteProcess,\n \"LoadData\" : LoadDataProcess,\n \"LoadRois\" : LoadRoisProcess,\n \"SaveArtifacts\" : SaveArtifactsProcess,\n \"SaveExtras\" : SaveArtifactsProcess\n}\n\ndef to_yaml(processes, indent=\"\"):\n \"\"\"\n Turn a process list into YAML\n\n The reason for using this function instead of the built-in PyYAML\n dump functions is to get the flow we want and also handle Numpy \n arrays. In particular, we want lists to be inline but dictionaries\n to be in block format.\n\n This only supports a small subset of YAML types:\n \n - The processes must either be a list of dictionaries, or a single dictionary.\n - Dictionary keys must be strings\n - Dictionary values must be strings, numbers, lists, Numpy arrays or dictionaries\n \n Anything else will throw a ValueError. While the list of supported types might\n increase in the future, part of the intention is to constrain the types that\n processes can use in for options, so it will not change much.\n\n This does not affect the parsing of YAML code which uses PyYAML and can use\n any supported YAML code.\n \"\"\"\n def _dict_to_yaml(stream, valdict, indent=\"\", prefix=\"\"):\n for key, value in valdict.items():\n if not isinstance(key, six.string_types):\n try:\n key = str(int(key))\n except ValueError:\n raise ValueError(\"Keys must be strings or ints\")\n\n if value is None:\n continue\n\n stream.write(\"%s%s: \" % (prefix, key))\n if isinstance(value, six.string_types):\n stream.write(\"%s\\n\" % value)\n elif isinstance(value, (int, float, list, np.floating, np.integer)):\n stream.write(\"%s\\n\" % str(value))\n elif isinstance(value, np.ndarray):\n stream.write(\"%s\\n\" % str(value.tolist()))\n elif isinstance(value, collections.abc.Sequence):\n stream.write(\"%s\\n\" % str(list(value)))\n elif isinstance(value, collections.abc.Mapping):\n stream.write(\"\\n\")\n _dict_to_yaml(stream, value, indent + \" \", prefix=indent + \" \")\n else:\n raise ValueError(\"Unsupported option value type: %s\" % type(value)) \n\n if isinstance(processes, dict):\n processes = [processes,]\n\n yaml_str = six.StringIO()\n for process in processes:\n _dict_to_yaml(yaml_str, process, indent=indent + \" \", prefix=\" - \")\n yaml_str.write(\"\\n\")\n return yaml_str.getvalue()\n\nclass Script(Process):\n \"\"\"\n A processing script. It consists of three types of information:\n\n - Generic options (e.g. debug mode)\n - A single pipeline of processing steps\n - Optional list of BatchCase objects to apply these steps to\n\n A batch script can be run on a specified IVM, or it can be\n run on its cases. In this case a new IVM is created for\n each case\n \"\"\"\n\n PROCESS_NAME = \"Script\"\n\n IGNORE = 1\n NEXT_CASE = 2\n FAIL = 3\n\n sig_start_case = QtCore.Signal(object)\n sig_done_case = QtCore.Signal(object)\n sig_start_process = QtCore.Signal(object, dict)\n sig_process_progress = QtCore.Signal(float)\n sig_done_process = QtCore.Signal(object, dict)\n\n def __init__(self, ivm=None, **kwargs):\n \"\"\"\n fname: File name containing YAML code to load from\n code: YAML code as a string\n yamlroot: Parsed YAML code as Python objects\n \"\"\"\n super(Script, self).__init__(ivm, **kwargs)\n \n self._current_ivm = None\n self._current_process = None\n self._current_params = None\n self._process_num = 0\n self._process_start = None\n self._current_case = None\n self._case_num = 0\n self._pipeline = []\n self._cases = []\n self._generic_params = {}\n self._error_action = kwargs.get(\"error_action\", Script.IGNORE)\n self._embed_log = kwargs.get(\"embed_log\", False)\n self._output_items = []\n self._logfile_names = []\n\n # Find all the process implementations\n self.known_processes = dict(BASIC_PROCESSES)\n plugin_processes = get_plugins(\"processes\")\n for process in plugin_processes:\n self.known_processes[process.PROCESS_NAME] = process\n\n def run(self, options):\n \"\"\"\n Run the script\n\n The pipeline is created first, either from supplied\n YAML code, a filename or a set of parsed objects\n\n If no ``Case`` are included, a single default ``Case``\n is created. The completed pipeline is then run on all\n cases.\n\n Runs are asynchronous - initially we start the first\n process of the first case, and connect to the 'process finished'\n signal. When the slot is called, we start the next process, \n or the next case as required. So the ``run()`` method returns\n as soon as the first process is started. \n \"\"\"\n if \"parsed-yaml\" in options:\n root = dict(options.pop(\"parsed-yaml\"))\n elif \"yaml\" in options:\n root = yaml.safe_load(options.pop(\"yaml\"))\n elif \"yaml-file\" in options:\n with open(options.pop(\"yaml-file\"), \"r\") as yaml_file:\n root = yaml.safe_load(yaml_file)\n else:\n raise RuntimeError(\"Neither filename nor YAML code provided\")\n\n if root is None: \n # Handle special case of empty content\n root = {}\n\n # Can set mode=check to just validate the YAML\n self._load_yaml(root)\n self.debug(self._pipeline)\n self._output_items = []\n self._logfile_names = []\n mode = options.pop(\"mode\", \"run\")\n if mode == \"run\":\n self.status = Process.RUNNING\n self._case_num = 0\n self._next_case()\n elif mode != \"check\":\n raise QpException(\"Unknown mode: %s\" % mode)\n\n def cancel(self):\n if self._current_process is not None:\n self._current_process.cancel()\n \n def _load_yaml(self, root=None):\n \"\"\"\n Load YAML content\n \"\"\"\n self._pipeline = []\n for process in root.pop(\"Processing\", []):\n name = list(process.keys())[0]\n proc = self.known_processes.get(name, None)\n params = process[name]\n if params is None: params = {}\n\n if proc is None:\n raise RuntimeError(\"Unknown process: %s\" % name)\n else:\n params[\"id\"] = params.get(\"id\", name)\n params[\"__impl\"] = proc\n self._pipeline.append(params)\n\n # Cases can be expressed as list or dict\n self._cases = []\n yaml_cases = root.pop(\"Cases\", [])\n if isinstance(yaml_cases, dict):\n for case_id in sorted(yaml_cases.keys()):\n self._cases.append(Case(str(case_id), yaml_cases[case_id]))\n else:\n for case in yaml_cases:\n case_id = list(case.keys())[0]\n self._cases.append(Case(str(case_id), case.get(case_id, {})))\n \n # Create default case if we have not been specified any\n if not self._cases:\n self._cases.append(Case(\"case\", {}))\n # After removing processes and cases, remainder is the generic options\n self._generic_params = root\n \n def _next_case(self):\n if self.status != self.RUNNING:\n return\n \n if self._case_num < len(self._cases):\n case = self._cases[self._case_num]\n self._case_num += 1\n self.sig_start_case.emit(case)\n self.debug(\"Starting case %s\", case.case_id)\n self._start_case(case)\n else:\n self.debug(\"All cases complete\")\n self.status = Process.SUCCEEDED\n self._complete()\n\n def _start_case(self, case):\n if self.ivm is not None:\n self._current_ivm = self.ivm\n else:\n self._current_ivm = ImageVolumeManagement()\n self._current_case = case\n self._process_num = 0\n self._next_process()\n\n def _next_process(self):\n if self.status != self.RUNNING:\n return\n \n if self._process_num < len(self._pipeline):\n process = self._pipeline[self._process_num]\n self._process_num += 1\n self._start_process(process)\n else:\n self.debug(\"All processes complete\")\n if len(self._cases) > 1:\n self.log(\"CASE COMPLETE\\n\")\n self.sig_done_case.emit(self._current_case)\n self._next_case()\n\n def _start_process(self, proc_params):\n # Make copy so process does not mess up shared config\n proc_params = dict(proc_params)\n generic_params = dict(self._generic_params)\n\n # Override values which are defined in the individual case\n if self._current_case is not None:\n case_params = dict(self._current_case.params)\n override = case_params.pop(proc_params[\"id\"], {})\n proc_params.update(override)\n generic_params.update(case_params)\n # OutputId defaults to the case ID if not specified\n if \"OutputId\" not in generic_params:\n generic_params[\"OutputId\"] = self._current_case.case_id\n\n # Set debug level for this individual process based on whether logging\n # was enabled generically, for this case, and for this process\n if \"--debug\" in sys.argv or proc_params.get(\"Debug\", generic_params.get(\"Debug\", False)):\n set_base_log_level(logging.DEBUG)\n else:\n set_base_log_level(logging.WARN)\n\n # Include the case ID as a subfolder of the input folder if\n # InputUseCaseId is set to True\n if generic_params.get(\"InputUseCaseId\", False) and \"InputId\" not in generic_params:\n generic_params[\"InputId\"] = self._current_case.case_id\n\n try:\n outdir = os.path.abspath(os.path.join(ifnone(generic_params.get(\"OutputFolder\", \"\"), \"\"), \n ifnone(generic_params.get(\"OutputId\", \"\"), \"\"),\n ifnone(generic_params.get(\"OutputSubFolder\", \"\"), \"\")))\n indir = os.path.abspath(os.path.join(ifnone(generic_params.get(\"InputFolder\", generic_params.get(\"Folder\", \"\")), \"\"), \n ifnone(generic_params.get(\"InputId\", \"\"), \"\"),\n ifnone(generic_params.get(\"InputSubFolder\", \"\"), \"\")))\n \n # Basic variable substitution, this is very crude but allows process arguments that are files to express\n # them relative to the input/output folders\n for subst_key, subst_value in {\"indir\" : indir, \"outdir\" : outdir}.items():\n subst_key = \"${%s}\" % subst_key.upper()\n for k, v in list(proc_params.items()):\n if isinstance(v, str) and subst_key in v:\n proc_params[k] = v.replace(subst_key, subst_value)\n\n proc_id = proc_params.pop(\"id\")\n process = proc_params.pop(\"__impl\")(self._current_ivm, indir=indir, outdir=outdir, proc_id=proc_id)\n \n self._current_process = process\n self._current_params = proc_params\n process.sig_finished.connect(self._process_finished)\n process.sig_progress.connect(self._process_progress)\n process.sig_log.connect(self._process_log)\n \n self._process_start = time.time()\n if len(self._pipeline) > 1:\n self.log(\"Running %s\\n\\n\" % process.proc_id)\n for key, value in proc_params.items():\n self.debug(\" %s=%s\" % (key, str(value)))\n\n self.sig_start_process.emit(process, dict(proc_params))\n process.execute(proc_params)\n \n except Exception as exc:\n # Could not create process - treat as process failure\n self._process_finished(Process.FAILED, \"Process failed to start: \" + str(exc), exc)\n finally:\n pass\n\n def _process_finished(self, status, log, exception):\n self.debug(\"Process finished: %s\", self._current_process.proc_id)\n self._current_process.sig_finished.disconnect(self._process_finished)\n self._current_process.sig_progress.disconnect(self._process_progress)\n self._current_process.sig_log.disconnect(self._process_log)\n if self.status != self.RUNNING:\n return\n\n end = time.time()\n self.sig_done_process.emit(self._current_process, dict(self._current_params))\n \n self._logfile_names.append(self._current_process.logfile_name())\n if status == Process.SUCCEEDED:\n if len(self._pipeline) > 1:\n self.log(\"\\nDONE (%.1fs)\\n\" % (end - self._process_start))\n self._output_items.extend(self._current_process.output_data_items())\n self._next_process()\n else:\n self.log(\"\".join(traceback.format_exception_only(type(exception), exception)))\n self.log(\"\\nFAILED: %i\\n\" % status)\n if self._error_action == Script.IGNORE:\n self.debug(\"Process failed - ignoring\")\n self._next_process()\n elif self._error_action == Script.FAIL:\n self.debug(\"Process failed - stopping script\")\n self.status = status\n self.exception = exception\n self._current_process = None\n self._current_params = None\n self._complete()\n elif self._error_action == Script.NEXT_CASE:\n self.debug(\"Process failed - going to next case\")\n self.log(\"CASE FAILED\\n\")\n self.sig_done_case.emit(self._current_case)\n self._next_case()\n\n def _process_progress(self, complete):\n self.sig_process_progress.emit(complete)\n script_complete = ((self._case_num-1)*len(self._pipeline) + \n (self._process_num - 1 + complete)) / (len(self._pipeline)*len(self._cases))\n self.sig_progress.emit(script_complete)\n\n def _process_log(self, msg):\n self.log(msg)\n \n def output_data_items(self):\n return self._output_items\n\n def logfile_name(self):\n if len(self._logfile_names) == 1:\n return self._logfile_names[0]\n else:\n return \"logfile\"\n\nclass Case(object):\n \"\"\"\n An individual case (e.g. patient scan) which a processing pipeline is applied to\n \"\"\"\n def __init__(self, case_id, params):\n self.case_id = case_id\n if params is None:\n params = {}\n self.params = params\n\nclass BatchScript(Script):\n \"\"\"\n A Script which sends human readable output to a log stream. It also\n saves the logs of the processes to a file in the output folder.\n\n This is used as the runner for batch scripts started from the console\n or from the ``BatchBuilder`` widget.\n \"\"\"\n def __init__(self, ivm=None, stdout=sys.stdout, **kwargs):\n Script.__init__(self, ivm, **kwargs)\n self.stdout = stdout\n self.start = None\n self._quit_on_exit = kwargs.get(\"quit_on_exit\", True)\n\n self.sig_start_case.connect(self._log_start_case)\n self.sig_done_case.connect(self._log_done_case)\n self.sig_start_process.connect(self._log_start_process)\n self.sig_process_progress.connect(self._log_process_progress)\n self.sig_done_process.connect(self._log_done_process)\n self.sig_progress.connect(self._log_progress)\n self.sig_finished.connect(self._log_done_script)\n\n def _log_start_case(self, case):\n self.stdout.write(\"Processing case: %s\\n\" % case.case_id)\n sys.stdout.flush()\n\n def _log_done_case(self, case):\n pass\n\n def _log_start_process(self, process, params):\n self.start = time.time()\n self.stdout.write(\" - Running %s... 0%%\" % process.proc_id)\n for key, value in params.items():\n self.debug(\" %s=%s\" % (key, str(value)))\n sys.stdout.flush()\n \n def _log_done_process(self, process, params):\n if process.status == Process.SUCCEEDED:\n end = time.time()\n self.stdout.write(\" DONE (%.1fs)\\n\" % (end - self.start))\n fname = os.path.join(process.outdir, \"%s.log\" % process.proc_id)\n self._save_text(process.get_log(), fname)\n if params:\n self.warn(\"Unused parameters\")\n for key, val in params.items():\n self.warn(\"%s=%s\", str(key), str(val))\n else:\n self.stdout.write(\" FAILED: %i\\n\" % process.status)\n self.warn(str(process.exception))\n self.debug(\"\".join(traceback.format_exception_only(type(process.exception), process.exception)))\n sys.stdout.flush()\n\n def _log_progress(self, complete):\n #self.stdout.write(\"%i%%\\n\" % int(100*complete))\n pass\n\n def _log_process_progress(self, complete):\n percent = int(100*complete)\n self.stdout.write(\"\\b\\b\\b\\b%3i%%\" % percent)\n self.stdout.flush()\n\n def _log_done_script(self):\n if self.status == Process.SUCCEEDED:\n self.stdout.write(\"Script finished\\n\")\n else:\n self.stdout.write(\" FAILED: %i\\n\" % self.status)\n self.warn(str(self.exception))\n self.debug(\"\".join(traceback.format_exception_only(type(self.exception), self.exception)))\n sys.stdout.flush()\n if self._quit_on_exit:\n QtCore.QCoreApplication.instance().quit()\n\n def _save_text(self, text, fname, ext=\"txt\"):\n if text:\n if \".\" not in fname: fname = \"%s.%s\" % (fname, ext)\n dirname = os.path.dirname(fname)\n if not os.path.exists(dirname): os.makedirs(dirname)\n with open(fname, \"w\") as text_file:\n text_file.write(text)\n", "repo_name": "physimals/quantiphyse", "sub_path": "quantiphyse/utils/batch.py", "file_name": "batch.py", "file_ext": "py", "file_size_in_byte": 18969, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 22, "dataset": "github-code", "pt": "48", "api": [{"api_name": "six.string_types", "line_number": 65, "usage_type": "attribute"}, {"api_name": "six.string_types", "line_number": 75, "usage_type": "attribute"}, {"api_name": "numpy.floating", "line_number": 77, "usage_type": "attribute"}, {"api_name": "numpy.integer", "line_number": 77, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 79, "usage_type": "attribute"}, {"api_name": "collections.abc", "line_number": 81, "usage_type": "attribute"}, {"api_name": "collections.abc", "line_number": 83, "usage_type": "attribute"}, {"api_name": "six.StringIO", "line_number": 92, "usage_type": "call"}, {"api_name": "quantiphyse.processes.Process", "line_number": 98, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Signal", "line_number": 117, "usage_type": "call"}, {"api_name": "PySide2.QtCore", "line_number": 117, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Signal", "line_number": 118, "usage_type": "call"}, {"api_name": "PySide2.QtCore", "line_number": 118, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Signal", "line_number": 119, "usage_type": "call"}, {"api_name": "PySide2.QtCore", "line_number": 119, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Signal", "line_number": 120, "usage_type": "call"}, {"api_name": "PySide2.QtCore", "line_number": 120, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Signal", "line_number": 121, "usage_type": "call"}, {"api_name": "PySide2.QtCore", "line_number": 121, "usage_type": "name"}, {"api_name": "yaml.safe_load", "line_number": 172, "usage_type": "call"}, {"api_name": "yaml.safe_load", "line_number": 175, "usage_type": "call"}, {"api_name": "quantiphyse.processes.Process.RUNNING", "line_number": 190, "usage_type": "attribute"}, {"api_name": "quantiphyse.processes.Process", "line_number": 190, "usage_type": "name"}, {"api_name": "exceptions.QpException", "line_number": 194, "usage_type": "call"}, {"api_name": "quantiphyse.processes.Process.SUCCEEDED", "line_number": 247, "usage_type": "attribute"}, {"api_name": "quantiphyse.processes.Process", "line_number": 247, "usage_type": "name"}, {"api_name": "quantiphyse.data.ImageVolumeManagement", "line_number": 254, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 291, "usage_type": "attribute"}, {"api_name": "quantiphyse.utils.logger.set_base_log_level", "line_number": 292, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 292, "usage_type": "attribute"}, {"api_name": "quantiphyse.utils.logger.set_base_log_level", "line_number": 294, "usage_type": "call"}, {"api_name": "logging.WARN", "line_number": 294, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 302, "usage_type": "call"}, {"api_name": "os.path", "line_number": 302, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 302, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 305, "usage_type": "call"}, {"api_name": "os.path", "line_number": 305, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 305, "usage_type": "call"}, {"api_name": "time.time", "line_number": 326, "usage_type": "call"}, {"api_name": "quantiphyse.processes.Process.FAILED", "line_number": 337, "usage_type": "attribute"}, {"api_name": "quantiphyse.processes.Process", "line_number": 337, "usage_type": "name"}, {"api_name": "time.time", "line_number": 349, "usage_type": "call"}, {"api_name": "quantiphyse.processes.Process.SUCCEEDED", "line_number": 353, "usage_type": "attribute"}, {"api_name": "quantiphyse.processes.Process", "line_number": 353, "usage_type": "name"}, {"api_name": "traceback.format_exception_only", "line_number": 359, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 413, "usage_type": "attribute"}, {"api_name": "sys.stdout.flush", "line_number": 429, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 429, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 435, "usage_type": "call"}, {"api_name": "sys.stdout.flush", "line_number": 439, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 439, "usage_type": "attribute"}, {"api_name": "quantiphyse.processes.Process.SUCCEEDED", "line_number": 442, "usage_type": "attribute"}, {"api_name": "quantiphyse.processes.Process", "line_number": 442, "usage_type": "name"}, {"api_name": "time.time", "line_number": 443, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 445, "usage_type": "call"}, {"api_name": "os.path", "line_number": 445, "usage_type": "attribute"}, {"api_name": "traceback.format_exception_only", "line_number": 454, "usage_type": "call"}, {"api_name": "sys.stdout.flush", "line_number": 455, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 455, "usage_type": "attribute"}, {"api_name": "quantiphyse.processes.Process.SUCCEEDED", "line_number": 467, "usage_type": "attribute"}, {"api_name": "quantiphyse.processes.Process", "line_number": 467, "usage_type": "name"}, {"api_name": "traceback.format_exception_only", "line_number": 472, "usage_type": "call"}, {"api_name": "sys.stdout.flush", "line_number": 473, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 473, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore.QCoreApplication.instance", "line_number": 475, "usage_type": "call"}, {"api_name": "PySide2.QtCore.QCoreApplication", "line_number": 475, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore", "line_number": 475, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 480, "usage_type": "call"}, {"api_name": "os.path", "line_number": 480, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 481, "usage_type": "call"}, {"api_name": "os.path", "line_number": 481, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 481, "usage_type": "call"}]} +{"seq_id": "4537094978", "text": "import matplotlib.colors as colors\nimport matplotlib.pyplot as plt\nimport csv\nimport math\nimport sys\n\nfrom common import *\n\ndef get_bandwidth(base_file, type, data):\n with open(f'{base_file}_{type}_fenced.csv') as csvfile:\n plots = csv.reader(csvfile, delimiter=',')\n for row in plots:\n threads = int(row[1])\n access_size = int(row[2])\n bandwidth = float(row[4]) / 1000\n\n if (access_size <= 65536):\n data[threads - 1][int(math.log2(access_size)) - 6] = bandwidth\n\n\ndef plot_bm(data_dir, plot_dir, types):\n fig, axes = plt.subplots(1, 2, figsize=(10, 3))\n\n cmap = colors.ListedColormap(['#000033', 'midnightblue', 'darkslateblue', 'fuchsia', 'orange', 'yellow'])\n\n xticks = [0, 2, 4, 6, 8, 10]\n xtick_labels = [\"64\", \"256\", \"1K\", \"4K\", \"16K\", \"64K\"]\n\n for i, (t, _) in enumerate(types):\n ax = axes[i]\n data = [[0 for x in range(11)] for y in range(36)]\n get_bandwidth(f'{data_dir}/sequential_write', t, data)\n im = ax.imshow(data, cmap=cmap, interpolation='bicubic', aspect='auto',\n vmin=0, vmax=13)\n ax.invert_yaxis()\n ax.set_xlabel('Access Size [Byte]', fontsize=18)\n ax.set_xticks(xticks)\n ax.set_xticklabels(xtick_labels)\n SET_LABEL_SIZE(ax)\n\n axes[0].set_ylabel('Threads [\\#]', fontsize=18)\n\n axes[0].set_title(f\"a) {types[0][1]}\", fontsize=18)\n axes[1].set_title(f\"b) {types[1][1]}\", fontsize=18)\n\n # start at x=0.25, y=1, length=0.5, height=0.05\n cb_ax = fig.add_axes([0.25, 1.1, 0.5, 0.05])\n cbar = fig.colorbar(im, cax=cb_ax, orientation='horizontal')\n cbar.ax.tick_params(labelsize=18)\n fig.text(0.5, 1.2, \"Bandwidth [GB/s]\", ha='center', fontsize=18)\n\n plot_path = f'{plot_dir}/write_heatmap'\n SAVE_PLOT(plot_path)\n\n\nif __name__ == '__main__':\n INIT_MATPLOT()\n\n if (len(sys.argv) != 3):\n raise RuntimeError(\"Need /path/to/data/dir /path/to/plot/dir\")\n\n data_dir = sys.argv[1]\n plot_dir = sys.argv[2]\n types = [(\"log\", \"Grouped Access\"), (\"disjoint\", \"Individual Access\")]\n plot_bm(data_dir, plot_dir, types)\n\n PRINT_PLOT_PATHS()\n", "repo_name": "hpides/pmem-olap", "sub_path": "plot_scripts/heatmap.py", "file_name": "heatmap.py", "file_ext": "py", "file_size_in_byte": 2173, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 19, "dataset": "github-code", "pt": "48", "api": [{"api_name": "csv.reader", "line_number": 11, "usage_type": "call"}, {"api_name": "math.log2", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 22, "usage_type": "name"}, {"api_name": "matplotlib.colors.ListedColormap", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.colors", "line_number": 24, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 59, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 62, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 63, "usage_type": "attribute"}]} +{"seq_id": "14524064361", "text": "from lib.types import IStdin, IStdout\nimport random\n\n\ndef main(stdin: IStdin, stdout: IStdout):\n\n stdout.write(\"This time you will have to sort an array\\n\")\n\n a = [random.randint(-200, 200) for _ in range(random.randint(10, 30))]\n\n stdout.write(f\"Array: {' '.join(map(str, a))}\\n\")\n stdout.write(\"Answer >> \")\n stdout.flush()\n\n answer = stdin.readline().strip()\n\n if answer != \" \".join(map(str, sorted(a))):\n stdout.write(\"Wrooong!\\n\")\n return\n\n stdout.write(\"Flag: donnuCTF{d1d_u_us3_th3_bubble_s0r7}\\n\")\n", "repo_name": "0awawa0/DonNU_CTF", "sub_path": "2020_2021/Training_9/sort_array/sort_array_easy.py", "file_name": "sort_array_easy.py", "file_ext": "py", "file_size_in_byte": 544, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "lib.types.IStdin", "line_number": 5, "usage_type": "name"}, {"api_name": "lib.types.IStdout", "line_number": 5, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 9, "usage_type": "call"}]} +{"seq_id": "45436653906", "text": "import scipy\nfrom scipy.stats import multivariate_normal\nimport numpy as np\nfrom numpy.random import default_rng\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import mplot3d\n\n\ndef classify(data, labels, hatred):\n decisions = []\n for dat in data:\n probabilities = [pdf2.pdf(dat) * l2 + pdf03.pdf(dat) * l3 * 0.5 * hatred + pdf13.pdf(dat) * l3 * 0.5 * hatred,\n pdf1.pdf(dat) * l1 + pdf03.pdf(dat) * l3 * 0.5 * hatred + pdf13.pdf(dat) * l3 * 0.5 * hatred,\n pdf1.pdf(dat) * l1 + pdf2.pdf(dat) * l2]\n decisions.append(np.argmin(probabilities) + 1)\n\n l1correct = []\n l2correct = []\n l3correct = []\n l1wrong = []\n l2wrong = []\n l3wrong = []\n\n # cmat[x][y] = # where true = x + 1 and guess = y + 1 (I guess this would make more sense in matlab ¯\\_(ツ)_/¯)\n cmat = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n errors = 0\n\n for i in range(len(decisions)):\n x = labels[i]\n y = decisions[i]\n val = data[i]\n cmat[int(x) - 1][int(y) - 1] = cmat[int(x) - 1][int(y) - 1] + 1\n if x == 1:\n if y == 1:\n l1correct.append(val)\n else:\n l1wrong.append(val)\n errors = errors + 1\n if x == 2:\n if y == 2:\n l2correct.append(val)\n else:\n l2wrong.append(val)\n errors = errors + 1\n if x == 3:\n if y == 3:\n l3correct.append(val)\n else:\n l3wrong.append(val)\n errors = errors + 1\n\n cmat[int(0)] = np.array(cmat[int(0)]) / (len(l1wrong) + len(l1correct))\n cmat[int(1)] = np.array(cmat[int(1)]) / (len(l2wrong) + len(l2correct))\n cmat[int(2)] = np.array(cmat[int(2)]) / (len(l3wrong) + len(l3correct))\n perror = errors / len(labels)\n print('Confusion matrix')\n print('\\t1\\t2\\t3')\n print('1\\t' + str(cmat[0]))\n print('2\\t' + str(cmat[1]))\n print('3\\t' + str(cmat[2]))\n print('pError: ' + str(perror))\n\n lamda = [[0,1,hatred], [1,0, hatred], [1,1,0]]\n probs = [[l1,l2,l3], [l1,l2, l3], [l1, l2, l3]]\n minerror = (np.array(lamda) * np.array(probs))\n minerror = (minerror * np.array(cmat))\n print('Expected risk: ' + str(np.sum(minerror)))\n\n fig = plt.figure()\n ax1 = fig.add_subplot(1, 2, 1, projection='3d')\n ax2 = fig.add_subplot(1, 2, 2, projection='3d')\n\n col = ax1.scatter3D(*zip(*data), c=labels, cmap='viridis')\n plt.colorbar(col, ax=ax1, location='left', shrink=0.5)\n ax1.set_title('True Dataset')\n\n ax2.scatter3D(*zip(*l1correct), c='green', marker='x', label='1 Correct')\n ax2.scatter3D(*zip(*l2correct), c='green', marker='.', label='2 Correct')\n ax2.scatter3D(*zip(*l3correct), c='green', marker='*', label='3 Correct')\n ax2.scatter3D(*zip(*l1wrong), c='red', marker='x', label='1 Wrong')\n ax2.scatter3D(*zip(*l2wrong), c='red', marker='.', label='2 Wrong')\n ax2.scatter3D(*zip(*l3wrong), c='red', marker='*', label='3 Wrong')\n ax2.legend()\n ax2.set_title(\"Classified Dataset\")\n\n plt.show()\n\n\n# generate set of 1000k\n# constants\nl3 = 0.4\nl2 = 0.3\nl1 = 0.3\nl3sub = 0.5\n\nDATASIZE = 10000\n# pdf constants\nm01 = [1, 1, 5]\nc01 = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\nm02 = [5, 5, 5]\nc02 = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\nm03 = [1, 5, 5]\nc03 = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\nm13 = [5, 1, 5]\nc13 = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\nclasses = 3\neps = 2 ** -52\n\nrng = default_rng()\npdf1 = multivariate_normal(mean=m01, cov=c01) # 1 label\npdf2 = multivariate_normal(mean=m02, cov=c02) # 2 label\npdf03 = multivariate_normal(mean=m03, cov=c03) # 3 label < 0.5\npdf13 = multivariate_normal(mean=m13, cov=c13) # 3 label > 0.5\n\n# define datasets for labels\nl1Dataset = []\nl2Dataset = []\nl3Dataset = []\n\n# generate dataset\nfor i in range(DATASIZE):\n test = rng.uniform()\n if test < l1:\n l1Dataset.append(rng.multivariate_normal(m01, c01))\n elif test < l1 + l2:\n l2Dataset.append(rng.multivariate_normal(m02, c02))\n else:\n if test < l1 + l2 + l3 / 2:\n l3Dataset.append(rng.multivariate_normal(m03, c03))\n else:\n l3Dataset.append(rng.multivariate_normal(m13, c13))\n\ndata = l1Dataset + l2Dataset + l3Dataset\nlabels = np.append(np.ones(len(l1Dataset)), np.full(len(l2Dataset), 2))\nlabels = np.append(labels, np.full(len(l3Dataset), 3))\n\n# classify our data\nclassify(data, labels, 1)\nclassify(data, labels, 10)\nclassify(data, labels, 100)", "repo_name": "santiago-pinzon/HW1", "sub_path": "src/hw2.py", "file_name": "hw2.py", "file_ext": "py", "file_size_in_byte": 4492, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "numpy.argmin", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 74, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 86, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 86, "usage_type": "name"}, {"api_name": "numpy.random.default_rng", "line_number": 109, "usage_type": "call"}, {"api_name": "scipy.stats.multivariate_normal", "line_number": 110, "usage_type": "call"}, {"api_name": "scipy.stats.multivariate_normal", "line_number": 111, "usage_type": "call"}, {"api_name": "scipy.stats.multivariate_normal", "line_number": 112, "usage_type": "call"}, {"api_name": "scipy.stats.multivariate_normal", "line_number": 113, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 134, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 134, "usage_type": "call"}, {"api_name": "numpy.full", "line_number": 134, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.full", "line_number": 135, "usage_type": "call"}]} +{"seq_id": "13122560847", "text": "import numpy as np\nimport argparse\nimport torch\n\nfrom data.Transforms import to_pointset_optimal_transport\n\nfrom utils.Config import ParseSampleConfig\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-c\", \"--config\", help=\"Config file\", required=True)\n parser.add_argument(\"-m\", \"--model\", help=\"Path to checkpoint file\", required=True)\n parser.add_argument(\"--cond\", nargs='+', type=float, help='Conditionning values', required=False, default=None)\n parser.add_argument(\"-s\", \"--shape\", nargs='+', type=int, help='Shape of points to generate', default=[16, 2, 8, 8])\n parser.add_argument(\"-o\", \"--output\", help=\"Output file\", default='out.npy')\n parser.add_argument(\"-t\", \"--timesteps\", help=\"Number of timesteps\", type=int, default=1000)\n parser.add_argument(\"--ot\", help=\"Applied inverse ot mapping transform to input\", type=bool, default=True)\n \n\n args = parser.parse_args()\n\n device = torch.device('cuda')\n model = ParseSampleConfig(args.config)\n \n model.load_state_dict(torch.load(args.model)[\"diffu\"])\n model.to(device)\n model.set_num_timesteps(args.timesteps)\n model.eval()\n\n cond = args.cond\n if cond is not None:\n cond = torch.from_numpy(np.asarray(cond).astype(np.float32)).to(device)\n cond = cond.repeat(args.shape[0], 1)\n\n print(args.shape)\n with torch.no_grad():\n samples_tmp = model.p_sample_loop(args.shape, img=None, cond=cond, with_tqdm=True, with_sampling=True)\n \n samples = []\n samples_tmp = samples_tmp.cpu().numpy()\n\n if args.ot:\n for sample in samples_tmp:\n sample = to_pointset_optimal_transport(sample)\n samples.append(sample.reshape(sample.shape[0], np.prod(sample.shape[1:])).T)\n \n np.save(args.output, samples)\n else:\n np.save(args.output, samples_tmp)", "repo_name": "BDoignies/ExampleBasedSamplingWithDiffusion", "sub_path": "sample.py", "file_name": "sample.py", "file_ext": "py", "file_size_in_byte": 1870, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.device", "line_number": 22, "usage_type": "call"}, {"api_name": "utils.Config.ParseSampleConfig", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 25, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 32, "usage_type": "attribute"}, {"api_name": "torch.no_grad", "line_number": 36, "usage_type": "call"}, {"api_name": "data.Transforms.to_pointset_optimal_transport", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.prod", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 49, "usage_type": "call"}]} +{"seq_id": "9387237674", "text": "from typing import List, Optional\n\n\ndef cost_per_step(pod):\n return {\"a\": 1, \"b\": 10, \"c\": 100, \"d\": 1000}[pod]\n\n\nclass Board:\n state: List[str]\n\n def __init__(self, rooms=None):\n state = [\".\" for _ in range(11 + 4 * 4)]\n\n if rooms:\n state[11] = rooms[0][0]\n state[12] = rooms[0][1]\n state[13] = rooms[0][2]\n state[14] = rooms[0][3]\n\n state[15] = rooms[1][0]\n state[16] = rooms[1][1]\n state[17] = rooms[1][2]\n state[18] = rooms[1][3]\n\n state[19] = rooms[2][0]\n state[20] = rooms[2][1]\n state[21] = rooms[2][2]\n state[22] = rooms[2][3]\n\n state[23] = rooms[3][0]\n state[24] = rooms[3][1]\n state[25] = rooms[3][2]\n state[26] = rooms[3][3]\n\n self.state = state\n\n def print(self):\n print(\"#\" * 13)\n print(\"#\" + \"\".join(self.at(\"h\", n) for n in range(11)) + \"#\")\n print(\"###\" + \"#\".join(self.at(r, 0) for r in [\"a\", \"b\", \"c\", \"d\"]) + \"###\")\n print(\" #\" + \"#\".join(self.at(r, 1) for r in [\"a\", \"b\", \"c\", \"d\"]) + \"#\")\n print(\" #\" + \"#\".join(self.at(r, 2) for r in [\"a\", \"b\", \"c\", \"d\"]) + \"#\")\n print(\" #\" + \"#\".join(self.at(r, 3) for r in [\"a\", \"b\", \"c\", \"d\"]) + \"#\")\n print(\" \" + \"#\" * 9)\n print()\n\n def copy(self):\n b = Board()\n b.state = [x for x in self.state]\n return b\n\n def move(self, start, end):\n c = self.copy()\n pod = c.at(start)\n c.set(pod, end)\n c.set(\".\", start)\n\n if not c.validate():\n print(\"Before: \")\n self.print()\n print(\"After: \")\n c.print()\n raise Exception(\"Unhandled case: empty spot inside room\")\n\n return c\n\n def is_done(self):\n return all(self.at(r, n) == r for r in [\"a\", \"b\", \"c\", \"d\"] for n in [0, 1])\n\n def to_index(self, r: str, n: Optional[int] = None):\n if n is None:\n r, n = r[0], int(r[1:])\n assert n >= 0 and n < 11\n if r == \"h\":\n return n\n assert n < 4\n if r == \"a\":\n return 11 + n\n if r == \"b\":\n return 15 + n\n if r == \"c\":\n return 19 + n\n if r == \"d\":\n return 23 + n\n raise Exception(f\"Invalid position: {r} {n}\")\n\n def set(self, pod: str, r: str, n: Optional[int] = None):\n idx = self.to_index(r, n)\n assert (\n self.state[idx] == \".\" or pod == \".\"\n ), f\"set({pod}, {r}, {n}): move {pod} to room with {self.state[idx]} (idx: {idx})\"\n self.state[idx] = pod\n\n def at(self, r: str, n: Optional[int] = None):\n return self.state[self.to_index(r, n)]\n\n def possible_moves_from_hallway(self):\n moves = []\n\n for x in range(11):\n pod = self.at(\"h\", x)\n if pod == \".\":\n continue\n\n # Test if the target room is occupied by other pod types\n if any(self.at(pod, n) not in (\".\", pod) for n in range(4)):\n continue\n\n entrance = {\"a\": 2, \"b\": 4, \"c\": 6, \"d\": 8}[pod]\n\n step = 1 if entrance > x else -1\n if all(self.at(\"h\", i) == \".\" for i in range(x + step, entrance, step)):\n for n in range(3, -1, -1):\n if self.at(pod, n) == \".\":\n moves.append(\n (\n f\"h{x}\",\n f\"{pod}{n}\",\n (n + 1 + abs(x - entrance)) * cost_per_step(pod),\n )\n )\n break\n\n return moves\n\n def validate(self):\n for room in [\"a\", \"b\", \"c\", \"d\"]:\n empty = True\n for n in range(4):\n if self.at(room, n) == \".\":\n if not empty:\n self.print()\n return False\n else:\n empty = False\n return True\n\n def room_contains_only_correct_pod(self, room):\n return all(self.at(room, i) == room for i in range(4))\n\n def possible_moves_from_room(self, room):\n moves = []\n\n # This room is empty. No moves start here.\n if all(self.at(room, i) == \".\" for i in range(4)):\n return []\n\n # Room is filled with correct pod. Done!\n if all(self.at(room, i) == room for i in range(4)):\n return []\n\n entrances = {\"a\": 2, \"b\": 4, \"c\": 6, \"d\": 8}\n\n def test_hallway(start_pos, pod, x, cost):\n nonlocal moves\n if x == entrances[pod]:\n start_x = entrances[start_pos[0]]\n horz_cost = cost_per_step(pod) * abs(start_x - x)\n if self.room_contains_only_correct_pod(pod):\n for i in range(3, -1, -1):\n if self.at(room, i) == \".\":\n moves.append(\n (\n start_pos,\n f\"{pod}{i}\",\n cost + horz_cost + cost_per_step(pod) * (i + 1),\n )\n )\n\n if x not in [2, 4, 6, 8]:\n start_x = entrances[start_pos[0]]\n moves.append(\n (start_pos, f\"h{x}\", cost + cost_per_step(pod) * abs(start_x - x))\n )\n\n # Test moves from the each cell in the current room\n for i in range(4):\n p = self.at(f\"{room}{i}\")\n if p != \".\":\n for x in range(entrances[room], -1, -1):\n if self.at(\"h\", x) != \".\":\n break\n test_hallway(f\"{room}{i}\", p, x, (i + 1) * cost_per_step(p))\n\n for x in range(entrances[room], 11):\n if self.at(\"h\", x) != \".\":\n break\n test_hallway(f\"{room}{i}\", p, x, (i + 1) * cost_per_step(p))\n break\n\n return moves\n\n def possible_moves(self):\n return (\n self.possible_moves_from_room(\"a\")\n + self.possible_moves_from_room(\"b\")\n + self.possible_moves_from_room(\"c\")\n + self.possible_moves_from_room(\"d\")\n + self.possible_moves_from_hallway()\n )\n\n\ndef part1(rooms, verbose=False):\n brd = Board(rooms)\n min_cost = None\n best_path = []\n visited_states = {}\n attempt = 0\n\n def print_verbose_state(brd):\n print(\"Board:\")\n brd.print()\n print(\"Moves from room A: \", brd.possible_moves_from_room(\"a\"))\n print(\"Moves from room B: \", brd.possible_moves_from_room(\"b\"))\n print(\"Moves from room C: \", brd.possible_moves_from_room(\"c\"))\n print(\"Moves from room D: \", brd.possible_moves_from_room(\"d\"))\n print(\"Moves from hallway: \", brd.possible_moves_from_hallway())\n\n def rec(brd: Board, cost: int, path: List):\n nonlocal verbose, attempt\n nonlocal min_cost, best_path\n\n attempt += 1\n if attempt % 100000 == 0:\n print(f\"Attempt {attempt}\")\n\n if min_cost is not None and min_cost < cost:\n return\n\n investigate = [(\"d0\", \"h10\"), (\"d1\", \"h0\")]\n state_tuple = tuple(brd.state)\n\n if len(path) > 0 and all(\n investigate[n][0] == path[n][0] and investigate[n][1] == path[n][1]\n for n in range(min(len(investigate), len(path)))\n ):\n print(\"WHUTT!!\")\n print(path)\n print_verbose_state(brd)\n print(f\"Already visited? {state_tuple in visited_states}\")\n # input()\n\n if state_tuple in visited_states:\n if visited_states[state_tuple] <= cost:\n return\n visited_states[state_tuple] = cost\n\n if verbose:\n print_verbose_state(brd)\n input()\n\n if brd.is_done():\n if min_cost is None or min_cost > cost:\n best_path = path\n min_cost = cost\n print(f\"New min cost: {min_cost}\")\n else:\n moves = brd.possible_moves()\n for move in moves:\n npath = [p for p in path] + [move]\n new_board = brd.move(move[0], move[1])\n\n # if all(\n # investigate[n][0] == npath[n][0]\n # and investigate[n][1] == npath[n][1]\n # for n in range(len(npath))\n # ):\n # # verbose = True\n # print(f\"Found! {npath}\")\n # print(f\"Cost: {cost + move[2]}\")\n # # new_board.print()\n # print_verbose_state(new_board)\n\n # if len(investigate) == len(npath):\n # if all(\n # investigate[n][0] == npath[n][0]\n # and investigate[n][1] == npath[n][1]\n # for n in range(len(investigate))\n # ):\n # verbose = True\n # print(f\"Found! {npath}\")\n\n rec(new_board, cost + move[2], npath)\n\n rec(brd, 0, [])\n\n if min_cost is None:\n print(\"No solution found\")\n else:\n print(\"Lowest cost: \", min_cost)\n print(\"Best moves: \", best_path)\n\n if verbose:\n c = brd.copy()\n c.print()\n cost = 0\n for move in best_path:\n c = c.move(move[0], move[1])\n print(f\"Move from {move[0]} to {move[1]}\")\n cost = cost + move[2]\n print(f\"Cost: {move[2]}. Total cost: {cost}\")\n c.print()\n input()\n\n return 1\n\n\nexample = [[\"b\", \"a\"], [\"c\", \"d\"], [\"b\", \"c\"], [\"d\", \"a\"]]\ninp = [[\"d\", \"d\"], [\"a\", \"c\"], [\"c\", \"b\"], [\"a\", \"b\"]]\nexample2 = [\n [\"b\", \"d\", \"d\", \"a\"],\n [\"c\", \"c\", \"b\", \"d\"],\n [\"b\", \"b\", \"a\", \"c\"],\n [\"d\", \"a\", \"c\", \"a\"],\n]\nexample3 = [\n [\"b\", \"a\", \"a\", \"a\"],\n [\"a\", \"b\", \"b\", \"b\"],\n [\"c\", \"c\", \"c\", \"c\"],\n [\"d\", \"d\", \"d\", \"d\"],\n]\ninp2 = [\n [\"d\", \"d\", \"d\", \"d\"],\n [\"a\", \"c\", \"b\", \"c\"],\n [\"c\", \"b\", \"a\", \"b\"],\n [\"a\", \"a\", \"c\", \"b\"],\n]\n\nimport sys\n\nsys.setrecursionlimit(10000)\nprint(f\"Part 1 with example data: {part1(inp2, verbose=False)}\")\n# print(f\"Part 1 with real input: {part1(lines)}\")\n# print(f\"Part 2 with example data: {part2(example, verbose=True)}\")\n# print(f\"Part 2 with real input: {part2(lines)}\")\n", "repo_name": "jomag/advent-of-code", "sub_path": "2021/day23/day23.py", "file_name": "day23.py", "file_ext": "py", "file_size_in_byte": 10600, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "typing.List", "line_number": 9, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 70, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 87, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 94, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 219, "usage_type": "name"}, {"api_name": "sys.setrecursionlimit", "line_number": 331, "usage_type": "call"}]} +{"seq_id": "23772289740", "text": "import time\nimport pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport allure\nfrom allure_commons.types import AttachmentType\n\ndriver = webdriver.Chrome()\nwait = WebDriverWait(driver, 15)\naction = ActionChains(driver)\n\n\n@pytest.fixture(autouse=True, scope='session')\ndef init_test():\n driver.maximize_window()\n driver.implicitly_wait(20)\n yield\n time.sleep(3)\n driver.quit()\n\n\ndef verifai_txt(expected, result):\n try:\n assert expected == result\n except AssertionError:\n screenshot(\"Expected: \" + expected + \" Result is: \" + result)\n assert False\n\n\ndef screenshot(name):\n allure.attach(driver.get_screenshot_as_png(), name=name, attachment_type=AttachmentType.PNG)\n", "repo_name": "Almog81/AutomationPlayground-Python", "sub_path": "base.py", "file_name": "base.py", "file_ext": "py", "file_size_in_byte": 825, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "selenium.webdriver.Chrome", "line_number": 9, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 9, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.wait.WebDriverWait", "line_number": 10, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.action_chains.ActionChains", "line_number": 11, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 19, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 14, "usage_type": "call"}, {"api_name": "allure.attach", "line_number": 32, "usage_type": "call"}, {"api_name": "allure_commons.types.AttachmentType.PNG", "line_number": 32, "usage_type": "attribute"}, {"api_name": "allure_commons.types.AttachmentType", "line_number": 32, "usage_type": "name"}]} +{"seq_id": "490888503", "text": "import numpy as np\nfrom collections import Counter\n\ndef load_mutation_status(genetic_file, mutation_type):\n \"\"\"Loads the mutation data from a genetic file\n\n Args:\n genetic_file (string): The path to the genetic file\n mutation_type (list): List of the genetic mutations to load\n\n Returns:\n dict: A dict containing 'patient_IDs', 'mutation_label' and\n 'mutation_type'\n \"\"\"\n\n mutation_names, patient_IDs, mutation_status = load_genetic_file(\n genetic_file)\n\n print(mutation_type)\n mutation_label = list()\n for i_mutation in mutation_type:\n if len(i_mutation) == 1:\n mutation_index = np.where(mutation_names == i_mutation[0])[0]\n print(i_mutation[0])\n if mutation_index.size == 0:\n raise ValueError('Could not find mutation: ' + i_mutation)\n else:\n mutation_label.append(mutation_status[:, mutation_index])\n else:\n # This is a combined mutation\n mutation_index = list()\n for i_combined_mutation in i_mutation:\n mutation_index.append(\n np.where(mutation_names == i_combined_mutation)[0])\n mutation_index = np.asarray(mutation_index)\n\n mutation_label.append(np.prod(mutation_status[:, mutation_index],\n axis=1))\n\n mutation_data = dict()\n mutation_data['patient_IDs'] = patient_IDs\n mutation_data['mutation_label'] = mutation_label\n mutation_data['mutation_name'] = mutation_type\n\n return mutation_data\n\n\ndef load_genetic_file(input_file):\n \"\"\"\n Load the patient IDs and genetic data from the genetic file\n\n Args:\n input_file (string): Path of the genetic file\n\n Returns:\n mutation_names (numpy array): Names of the different genetic mutations\n patient_ID (numpy array): IDs of patients for which genetic data is\n loaded\n mutation_status (numpy array): The status of the different mutations\n for each patient\n \"\"\"\n\n data = np.loadtxt(input_file, np.str)\n\n # Load and check the header\n header = data[0, :]\n if header[0] != 'Patient':\n raise AssertionError('First column should be patient ID!')\n else:\n # cut out the first header, only keep genetic header\n mutation_names = header[1::]\n\n # Patient IDs are stored in the first column\n patient_ID = data[1:, 0]\n\n # Mutation status is stored in all remaining columns\n mutation_status = data[1:, 1:]\n # mutation_status = mutation_status.astype(np.int)\n # Make sure no double patients\n unique_list = [item for item, count in Counter(patient_ID).iteritems() if count > 1]\n if len(unique_list) > 0:\n raise ValueError('Double patients are in list: ' + str(unique_list))\n\n return mutation_names, patient_ID, mutation_status\n", "repo_name": "Svdvoort/PREDICT", "sub_path": "Genetics/genetic_processing.py", "file_name": "genetic_processing.py", "file_ext": "py", "file_size_in_byte": 2878, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "numpy.where", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.prod", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.str", "line_number": 63, "usage_type": "attribute"}, {"api_name": "collections.Counter", "line_number": 80, "usage_type": "call"}]} +{"seq_id": "73168403347", "text": "import torch\nimport os\nimport sys\nimport pandas as pd\nimport numpy as np\n\nsys.path.append('../../')\nsys.path.append(os.path.dirname(__file__))\n\nfrom get_reconstruction_map import get_reconstruction_map\nfrom hyperparameter_tuning.validate_coarse_to_fine import ValidateCoarseToFine\nfrom torchmetrics.functional import peak_signal_noise_ratio as psnr\nfrom torchmetrics.functional import structural_similarity_index_measure as ssim\n\n\ndef validate(method, modality, device, job_name, **kwargs):\n\n mode = 'val'\n\n # data loader\n sys.path.append(f'../{modality}/')\n from data.data_loader import get_dataloader\n if modality == \"ct\":\n noise_level = kwargs.get('noise_level', 2.0)\n data_loader = get_dataloader(mode, noise_level=noise_level)\n elif modality == \"mri\":\n coil_type = kwargs.get('coil_type', 'single')\n acc = kwargs.get('acc', 4)\n cf = kwargs.get('cf', 0.08)\n noise_sd = kwargs.get('noise_sd', 0.0)\n data_type = kwargs.get('data_type', 'pd')\n data_loader = get_dataloader(mode, coil_type=coil_type, acc=acc, cf=cf, noise_sd=noise_sd, data_type=data_type)\n else:\n raise ValueError(f\"modality: {modality} not recognized\")\n\n \n # reconstruction map\n reconstruction_map = get_reconstruction_map(method, modality, device=device, **kwargs)\n\n # reconstruction map wrapper for batch\n n_hyperparameters = kwargs.get('n_hyperparameters', 2)\n reconstruction_map_wrapper = ReconstructionMap(reconstruction_map, data_loader, n_hyperparameters=n_hyperparameters, device=device, modality=modality)\n\n # get directory name of current file\n dir_name = os.path.dirname(__file__)\n dir_name = f'{os.path.dirname(__file__)}/../{modality}/validation_data'\n\n\n # if folder does not exist, create it\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n\n\n freeze_p2 = (reconstruction_map_wrapper.n_hyperparameters == 1)\n\n # extra parameters\n gamma_stop = kwargs.get('gamma_stop', 1.05)\n\n kwargs['gamma_stop'] = gamma_stop\n\n\n validator = ValidateCoarseToFine(reconstruction_map_wrapper.batch_score, dir_name=dir_name, exp_name=job_name, freeze_p2=freeze_p2, **kwargs)\n validator.run()\n \n\ndef test(method, modality, device, job_name, **kwargs):\n\n mode = 'test'\n\n # get directory name of current file\n dir_name = f'{os.path.dirname(__file__)}/../{modality}/test_data'\n dir_name_val = f'{os.path.dirname(__file__)}/../{modality}/validation_data'\n\n # if folder does not exist, create it\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n\n dir_name_recon = f'{os.path.dirname(__file__)}/../{modality}/test_data/recon/{job_name}'\n if not os.path.exists(dir_name_recon):\n os.makedirs(dir_name_recon)\n\n\n # val data to recover hyperparameters\n try:\n val_data = pd.read_csv(f\"{dir_name_val}/validation_scores_{job_name}.csv\").reset_index(drop=True)\n except:\n raise ValueError(f\"validation_file_name: validation_scores_{job_name}.csv not found\")\n \n # get hyperparameters\n p1 = val_data.loc[val_data[\"psnr\"].idxmax()][\"p1\"]\n p2 = val_data.loc[val_data[\"psnr\"].idxmax()][\"p2\"]\n\n print(f\"Optimal validation hyperparameters p1: {p1}, p2: {p2}\")\n\n # data loader\n sys.path.append(f'../{modality}/')\n from data.data_loader import get_dataloader\n if modality == \"ct\":\n noise_level = kwargs.get('noise_level', 2.0)\n data_loader = get_dataloader(mode, noise_level=noise_level)\n elif modality == \"mri\":\n coil_type = kwargs.get('coil_type', 'single')\n acc = kwargs.get('acc', 4)\n cf = kwargs.get('cf', 0.08)\n noise_sd = kwargs.get('noise_sd', 0.0)\n data_type = kwargs.get('data_type', 'mixed')\n data_loader = get_dataloader(mode, coil_type=coil_type, acc=acc, cf=cf, noise_sd=noise_sd, data_type=data_type)\n else:\n raise ValueError(f\"modality: {modality} not recognized\")\n\n # reconstruction map\n reconstruction_map = get_reconstruction_map(method, modality, device=device, **kwargs)\n\n \n\n # reconstruction map wrapper for batch\n n_hyperparameters = kwargs.get('n_hyperparameters', 2)\n\n reconstruction_map_wrapper = ReconstructionMap(reconstruction_map, data_loader, n_hyperparameters=n_hyperparameters, device=device, modality=modality, export=True, num_exports=10, export_name=f'{dir_name_recon}/{job_name}', mode = 'test')\n\n\n psnr_, ssim_, n_iter_ = reconstruction_map_wrapper.batch_score(p1, p2)\n\n cols = [\"p1\", \"p2\", \"job_name\", \"psnr\", \"ssim\", \"niter\"]\n\n data = [[p1, p2, job_name, psnr_, ssim_, n_iter_]]\n df = pd.DataFrame(data, columns=cols)\n\n df.to_csv(f\"{dir_name}/{job_name}.csv\")\n\n\n \n\n\nclass ReconstructionMap():\n def __init__(self, sample_reconstruction_map, data_loader, n_hyperparameters=2, modality=\"ct\", device='cuda:0', **kwargs):\n\n self.sample_reconstruction_map = sample_reconstruction_map\n self.data_loader = data_loader\n self.n_hyperparameters = n_hyperparameters\n self.device = device\n self.modality = modality\n\n self.mode = kwargs.get(\"mode\", \"val\")\n self.export = kwargs.get(\"export\", False)\n self.num_exports = kwargs.get(\"num_exports\", 10)\n self.export_name = kwargs.get(\"export_name\", \"test\")\n\n if n_hyperparameters > 2 or n_hyperparameters < 1:\n raise ValueError(\"n_hyperparameters must be 1 or 2\")\n \n def batch_score(self, p1, p2=None):\n\n data_loader = self.data_loader\n psnr_val = torch.zeros(len(data_loader))\n ssim_val = torch.zeros(len(data_loader))\n n_iter_val = torch.zeros(len(data_loader))\n\n for idx, batch in enumerate(data_loader):\n if self.modality == \"ct\":\n phantom = batch[\"phantom\"].to(self.device)\n sinogram = batch[\"sinogram\"].to(self.device)\n fbp = batch[\"fbp\"].to(self.device)\n \n if self.n_hyperparameters == 1:\n x, psnr_, ssim_, n_iter_ = self.sample_reconstruction_map(sinogram, p1, x_gt=phantom, x_init=fbp)\n else:\n x, psnr_, ssim_, n_iter_ = self.sample_reconstruction_map(sinogram, p1, p2, x_gt=phantom, x_init=fbp)\n\n if self.export:\n if idx % (len(data_loader)//self.num_exports) == 0:\n x_np = x.squeeze().detach().cpu().numpy()\n np.save(f\"{self.export_name}_x_{idx}.npy\", x_np)\n\n elif self.modality == \"mri\":\n x = batch[\"x\"].to(self.device)\n y = batch[\"y\"].to(self.device)\n mask = batch[\"mask\"].to(self.device)\n if \"smaps\" in batch:\n smaps = batch[\"smaps\"].to(self.device)\n else:\n smaps = None\n \n if self.n_hyperparameters == 1:\n x, psnr_, ssim_, n_iter_ = self.sample_reconstruction_map(y, mask, smaps, p1, x_gt=x)\n else:\n x, psnr_, ssim_, n_iter_ = self.sample_reconstruction_map(y, mask, smaps, p1, p2, x_gt=x)\n\n if self.export:\n if idx % (len(data_loader)//self.num_exports) == 0:\n x_np = x.squeeze().detach().cpu().numpy()\n np.save(f\"{self.export_name}_x_{idx}.npy\", x_np)\n\n\n psnr_val[idx] = psnr_\n n_iter_val[idx] = n_iter_\n ssim_val[idx] = ssim_\n if self.mode == \"test\":\n print(f\" {idx+1}/{len(data_loader)} ==> average: psnr {psnr_val[:idx+1].mean().item():.2f}, ssim {ssim_val[:idx+1].mean().item():.3f})\")\n return(psnr_val.mean().item(), ssim_val.mean().item(), n_iter_val.mean().item())\n\n \n\n", "repo_name": "axgoujon/convex_ridge_regularizers", "sub_path": "inverse_problems/utils_inverse_problems/batch_wrapper.py", "file_name": "batch_wrapper.py", "file_ext": "py", "file_size_in_byte": 7753, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "48", "api": [{"api_name": "sys.path.append", "line_number": 7, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "sys.path.append", "line_number": 8, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "sys.path.append", "line_number": 21, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "data.data_loader.get_dataloader", "line_number": 25, "usage_type": "call"}, {"api_name": "data.data_loader.get_dataloader", "line_number": 32, "usage_type": "call"}, {"api_name": "get_reconstruction_map.get_reconstruction_map", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path", "line_number": 46, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 51, "usage_type": "call"}, {"api_name": "hyperparameter_tuning.validate_coarse_to_fine.ValidateCoarseToFine", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 71, "usage_type": "call"}, {"api_name": "os.path", "line_number": 71, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path", "line_number": 72, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 75, "usage_type": "call"}, {"api_name": "os.path", "line_number": 75, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path", "line_number": 78, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 79, "usage_type": "call"}, {"api_name": "os.path", "line_number": 79, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 80, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 85, "usage_type": "call"}, {"api_name": "sys.path.append", "line_number": 96, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 96, "usage_type": "attribute"}, {"api_name": "data.data_loader.get_dataloader", "line_number": 100, "usage_type": "call"}, {"api_name": "data.data_loader.get_dataloader", "line_number": 107, "usage_type": "call"}, {"api_name": "get_reconstruction_map.get_reconstruction_map", "line_number": 112, "usage_type": "call"}, {"api_name": "data.data_loader", "line_number": 126, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 127, "usage_type": "call"}, {"api_name": "data.data_loader", "line_number": 127, "usage_type": "argument"}, {"api_name": "torch.zeros", "line_number": 155, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 156, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 173, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 192, "usage_type": "call"}]} +{"seq_id": "10233022028", "text": "import unittest\nimport torch\n\nfrom pytorch3d.structures import utils as struct_utils\n\nfrom common_testing import TestCaseMixin\n\n\nclass TestStructUtils(TestCaseMixin, unittest.TestCase):\n def test_list_to_padded(self):\n device = torch.device(\"cuda:0\")\n N = 5\n K = 20\n ndim = 2\n x = []\n for _ in range(N):\n dims = torch.randint(K, size=(ndim,)).tolist()\n x.append(torch.rand(dims, device=device))\n pad_size = [K] * ndim\n x_padded = struct_utils.list_to_padded(\n x, pad_size=pad_size, pad_value=0.0, equisized=False\n )\n\n self.assertEqual(x_padded.shape[1], K)\n self.assertEqual(x_padded.shape[2], K)\n for i in range(N):\n self.assertClose(\n x_padded[i, : x[i].shape[0], : x[i].shape[1]], x[i]\n )\n\n # check for no pad size (defaults to max dimension)\n x_padded = struct_utils.list_to_padded(\n x, pad_value=0.0, equisized=False\n )\n max_size0 = max(y.shape[0] for y in x)\n max_size1 = max(y.shape[1] for y in x)\n self.assertEqual(x_padded.shape[1], max_size0)\n self.assertEqual(x_padded.shape[2], max_size1)\n for i in range(N):\n self.assertClose(\n x_padded[i, : x[i].shape[0], : x[i].shape[1]], x[i]\n )\n\n # check for equisized\n x = [torch.rand((K, 10), device=device) for _ in range(N)]\n x_padded = struct_utils.list_to_padded(x, equisized=True)\n self.assertClose(x_padded, torch.stack(x, 0))\n\n # catch ValueError for invalid dimensions\n with self.assertRaisesRegex(ValueError, \"Pad size must\"):\n pad_size = [K] * 4\n struct_utils.list_to_padded(\n x, pad_size=pad_size, pad_value=0.0, equisized=False\n )\n\n # invalid input tensor dimensions\n x = []\n ndim = 3\n for _ in range(N):\n dims = torch.randint(K, size=(ndim,)).tolist()\n x.append(torch.rand(dims, device=device))\n pad_size = [K] * 2\n with self.assertRaisesRegex(ValueError, \"Supports only\"):\n x_padded = struct_utils.list_to_padded(\n x, pad_size=pad_size, pad_value=0.0, equisized=False\n )\n\n def test_padded_to_list(self):\n device = torch.device(\"cuda:0\")\n N = 5\n K = 20\n ndim = 2\n dims = [K] * ndim\n x = torch.rand([N] + dims, device=device)\n\n x_list = struct_utils.padded_to_list(x)\n for i in range(N):\n self.assertClose(x_list[i], x[i])\n\n split_size = torch.randint(1, K, size=(N,)).tolist()\n x_list = struct_utils.padded_to_list(x, split_size)\n for i in range(N):\n self.assertClose(x_list[i], x[i, : split_size[i]])\n\n split_size = torch.randint(1, K, size=(2 * N,)).view(N, 2).unbind(0)\n x_list = struct_utils.padded_to_list(x, split_size)\n for i in range(N):\n self.assertClose(\n x_list[i], x[i, : split_size[i][0], : split_size[i][1]]\n )\n\n with self.assertRaisesRegex(ValueError, \"Supports only\"):\n x = torch.rand((N, K, K, K, K), device=device)\n split_size = torch.randint(1, K, size=(N,)).tolist()\n struct_utils.padded_to_list(x, split_size)\n\n def test_list_to_packed(self):\n device = torch.device(\"cuda:0\")\n N = 5\n K = 20\n x, x_dims = [], []\n dim2 = torch.randint(K, size=(1,)).item()\n for _ in range(N):\n dim1 = torch.randint(K, size=(1,)).item()\n x_dims.append(dim1)\n x.append(torch.rand([dim1, dim2], device=device))\n\n out = struct_utils.list_to_packed(x)\n x_packed = out[0]\n num_items = out[1]\n item_packed_first_idx = out[2]\n item_packed_to_list_idx = out[3]\n\n cur = 0\n for i in range(N):\n self.assertTrue(num_items[i] == x_dims[i])\n self.assertTrue(item_packed_first_idx[i] == cur)\n self.assertTrue(\n item_packed_to_list_idx[cur : cur + x_dims[i]].eq(i).all()\n )\n self.assertClose(x_packed[cur : cur + x_dims[i]], x[i])\n cur += x_dims[i]\n# Helpful comments below.# Helpful comments below.# Helpful comments below.# Helpful comments below.# Helpful comments below.", "repo_name": "Lynn-Vang42/demo-data", "sub_path": "test_struct_utils.py", "file_name": "test_struct_utils.py", "file_ext": "py", "file_size_in_byte": 4385, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "48", "api": [{"api_name": "common_testing.TestCaseMixin", "line_number": 9, "usage_type": "name"}, {"api_name": "unittest.TestCase", "line_number": 9, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 11, "usage_type": "call"}, {"api_name": "torch.randint", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.rand", "line_number": 18, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils.list_to_padded", "line_number": 20, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils", "line_number": 20, "usage_type": "name"}, {"api_name": "pytorch3d.structures.utils.list_to_padded", "line_number": 32, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils", "line_number": 32, "usage_type": "name"}, {"api_name": "torch.rand", "line_number": 45, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils.list_to_padded", "line_number": 46, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils", "line_number": 46, "usage_type": "name"}, {"api_name": "torch.stack", "line_number": 47, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils.list_to_padded", "line_number": 52, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils", "line_number": 52, "usage_type": "name"}, {"api_name": "torch.randint", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.rand", "line_number": 61, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils.list_to_padded", "line_number": 64, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils", "line_number": 64, "usage_type": "name"}, {"api_name": "torch.device", "line_number": 69, "usage_type": "call"}, {"api_name": "torch.rand", "line_number": 74, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils.padded_to_list", "line_number": 76, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils", "line_number": 76, "usage_type": "name"}, {"api_name": "torch.randint", "line_number": 80, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils.padded_to_list", "line_number": 81, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils", "line_number": 81, "usage_type": "name"}, {"api_name": "torch.randint", "line_number": 85, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils.padded_to_list", "line_number": 86, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils", "line_number": 86, "usage_type": "name"}, {"api_name": "torch.rand", "line_number": 93, "usage_type": "call"}, {"api_name": "torch.randint", "line_number": 94, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils.padded_to_list", "line_number": 95, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils", "line_number": 95, "usage_type": "name"}, {"api_name": "torch.device", "line_number": 98, "usage_type": "call"}, {"api_name": "torch.randint", "line_number": 102, "usage_type": "call"}, {"api_name": "torch.randint", "line_number": 104, "usage_type": "call"}, {"api_name": "torch.rand", "line_number": 106, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils.list_to_packed", "line_number": 108, "usage_type": "call"}, {"api_name": "pytorch3d.structures.utils", "line_number": 108, "usage_type": "name"}]} +{"seq_id": "26673088899", "text": "# -*- coding: utf-8 -*-\n# @Time : 2018/5/2 20:57\n# @Author : play4fun\n# @File : 午夜生成新log1.py\n# @Software: PyCharm\n\n\"\"\"\n午夜生成新log1.py:\n\"\"\"\nfrom time import sleep\nimport logging\nfrom logging.handlers import TimedRotatingFileHandler\n\nlogHandler = TimedRotatingFileHandler(filename=\"logs/logfile\", when=\"midnight\")\nlogFormatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')\nlogHandler.setFormatter(logFormatter)\n\nlogger = logging.getLogger('MyLogger')\nlogger.addHandler(logHandler)\nlogger.setLevel(logging.INFO)\n\nwhile True:\n for k in range(5):\n logger.info(\"Line %d\" % k)\n sleep(3)", "repo_name": "19760909/Python_Master_Courses", "sub_path": "Python3.6/logging1/午夜生成新log1.py", "file_name": "午夜生成新log1.py", "file_ext": "py", "file_size_in_byte": 650, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "48", "api": [{"api_name": "logging.handlers.TimedRotatingFileHandler", "line_number": 14, "usage_type": "call"}, {"api_name": "logging.Formatter", "line_number": 15, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 18, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 20, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "74097380304", "text": "import sys\nimport numpy as np\nimport PIL as pl\nimport matplotlib.pyplot as plt\nimport skimage as sk\nfrom skimage import filters, feature, io, measure\n\ndef flipImage():\n testIm = pl.Image.open(\"../test20.png\")\n im_flipped = testIm.transpose(method=pl.Image.FLIP_LEFT_RIGHT)\n im_flipped.show()\n\n #im = pl.Image.open(\"../os-shot_182_450/090249.png\")\n'''\npath = str(sys.argv[1])\nNAME = path\npath = \"../os-shot_182_450/\" + path\nim = io.imread(path)\n'''\nim = io.imread(\"../os-shot_182_450/090249.png\")\n#im = io.imread(\"../test21.png\")\n\nim = sk.color.rgb2gray(im)\nim = filters.gaussian(im)\nim2 = np.copy(im)\n\n\n\n#im = feature.canny(im, sigma=4.5, low_threshold=0.15, high_threshold=0.15)\n#im = filters.sobel(im)\ndef threshold(image):\n otsu = filters.threshold_otsu(image)\n return image < otsu\n\ndef conrecs():\n #im = feature.corner_shi_tomasi(im).corner_harris(im)\n keypoints1 = feature.corner_peaks(\n feature.corner_shi_tomasi(im), min_distance=1)\n print(keypoints1)\n \n extractor = feature.BRIEF()\n \n extractor.extract(im, keypoints1)\n keys = keypoints1[extractor.mask]\n \n fig, ax = plt.subplots(figsize=(18,13))\n ax.imshow(im, cmap=plt.cm.gray)\n \n for pair in keys : \n plt.scatter(pair[0], pair[1])\n\n\n'''\nfig, ax = plt.subplots(figsize=(18,13))\nax.imshow(im, cmap=plt.cm.gray)\n'''\n\ndef findContours(skiit_image):\n contours = measure.find_contours(skiit_image, 0.975,\n fully_connected=\"high\")\n return contours\n \ndef plotContours(contours):\n \n fig, ax = plt.subplots(figsize=(18,13))\n ax.imshow(im, cmap=plt.cm.gray)\n \n for n, contour in enumerate(contours):\n ax.plot(contour[:, 1], contour[:, 0], linewidth=2)\n \ndef plotContour(contour): \n fig, ax = plt.subplots(figsize=(18,13))\n ax.imshow(im, cmap=plt.cm.gray)\n \n ax.plot(contour[:, 1], contour[:, 0], linewidth=2)\n \nconturs = findContours(im)\n\n\ndef maxContour(contours) -> int :\n maxLen = 0\n maxPos = 0\n for n , contur in enumerate(conturs):\n if len(contur) > maxLen:\n maxLen = len(contur)\n maxPos = n\n \n return maxPos\n\nmyContour = conturs[maxContour(conturs)]\n\ndef writeToFile(): \n with open(\"../test.txt\",'w') as f:\n for elem in conturs[maxContour(conturs)] :\n f.write(str(elem))\n f.write(\"\\n\")\n\n\ndef plot_contour(contours): \n myContur = contours[maxContour(contours)] \n fig, ax = plt.subplots(figsize=(18,13))\n #for elem in myContur:\n plt.gca().invert_yaxis()\n plt.plot(myContur[:,1], myContur[:,0])\n\n\ndef find_dots(contour):\n for i in (250, 500, 1400, 1800, 3300, 3550, 4650, 4900):\n plt.plot(contour[i,1], contour[i,0], 'rx')\n\n\ndef first_dot(contour):\n plt.plot(contour[0,1], contour[0,0], 'rx')\n return contour[0]\n\n\ndef pixel_average(pixels):\n pixels = np.asarray(pixels)\n \n x_avg = np.average(pixels[:,0])\n y_avg = np.average(pixels[:,1])\n \n return np.asarray([x_avg, y_avg])\n\n \ndef sort_horizontal_contour(contour, _min=1275, _max=1290):\n #_min = 35 max = 41\n #lower_contour = (pixel for pixel in contour)\n lower_contour = (x for x in contour if x[0] > _min \n and x[0] < _max)\n\n lower_contour = sorted(\n list(lower_contour), key=lambda x: x[1])\n #dtype = [('x', np.float64, (1,)), ('y', np.float64, (1,))]\n #lower_contour = np.fromiter(lower_contour, dtype=np.float64)\n #lower_contour = np.sort(lower_contour, order='x')\n\n return np.array(lower_contour)\n\n\ndef sort_vertical_contour(contour, _min=50, _max=55):\n #_min = 1757 max = 1763\n vert_contour = (x for x in contour if x[1] > _min \n and x[1] < _max)\n\n vert_contour = sorted(\n list(vert_contour), key=lambda x: x[0])\n \n return np.array(vert_contour)\n\n\n#----------test----\n#np.dtype(myContour) \n#lowerC = sort_lower_contour(myContour) \n#plotContour(lowerC) \n'''\nar = [[1227, 221],\n [1220, 215],\n [1230, 229]]\n'''\n#print(np.average(ar))\n#print((pixel_average(ar)))\nC = sort_horizontal_contour(myContour) \nplotContour(C) \nfirst_dot(C)\n\n#plt.savefig('test/' + NAME)\n \n \n \n \n", "repo_name": "glbter/linuxStudies", "sub_path": "border_estimation.py", "file_name": "border_estimation.py", "file_ext": "py", "file_size_in_byte": 4269, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "PIL.Image.open", "line_number": 9, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 9, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 10, "usage_type": "attribute"}, {"api_name": "skimage.io.imread", "line_number": 20, "usage_type": "call"}, {"api_name": "skimage.io", "line_number": 20, "usage_type": "name"}, {"api_name": "skimage.color.rgb2gray", "line_number": 23, "usage_type": "call"}, {"api_name": "skimage.color", "line_number": 23, "usage_type": "attribute"}, {"api_name": "skimage.filters.gaussian", "line_number": 24, "usage_type": "call"}, {"api_name": "skimage.filters", "line_number": 24, "usage_type": "name"}, {"api_name": "numpy.copy", "line_number": 25, "usage_type": "call"}, {"api_name": "skimage.filters.threshold_otsu", "line_number": 32, "usage_type": "call"}, {"api_name": "skimage.filters", "line_number": 32, "usage_type": "name"}, {"api_name": "skimage.feature.corner_peaks", "line_number": 37, "usage_type": "call"}, {"api_name": "skimage.feature", "line_number": 37, "usage_type": "name"}, {"api_name": "skimage.feature.corner_shi_tomasi", "line_number": 38, "usage_type": "call"}, {"api_name": "skimage.feature", "line_number": 38, "usage_type": "name"}, {"api_name": "skimage.feature.BRIEF", "line_number": 41, "usage_type": "call"}, {"api_name": "skimage.feature", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.cm", "line_number": 47, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}, {"api_name": "skimage.measure.find_contours", "line_number": 59, "usage_type": "call"}, {"api_name": "skimage.measure", "line_number": 59, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.cm", "line_number": 66, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 72, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.cm", "line_number": 73, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 101, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 101, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 103, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 103, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 104, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 109, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 113, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.average", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.average", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 149, "usage_type": "call"}]} +{"seq_id": "30632228292", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Author: Mario S. Könz \n# pylint: disable=missing-docstring\n\nimport sys\nimport subprocess\n\nimport click\n__all__ = ['cppcheck_hook']\n\n\n@click.command()\n@click.argument('src', nargs=-1)\n@click.option('--enable', default='all')\n@click.option('--std', default='c++14')\ndef cppcheck_hook(enable, std, src):\n if not src:\n return\n\n cmd = (\n 'cppcheck',\n '--template=[{file}:{line}:{column}]: ({id}) {message}\\n{code}',\n '--quiet',\n '--enable={}'.format(enable),\n '--std={}'.format(std),\n ) + src\n\n res = subprocess.run(\n cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8'\n )\n err = res.stderr.strip().split('\\n')\n\n actual_err = []\n i = 0\n while i < len(err):\n line = err[i]\n errid = line.split('(', 1)[1].split(')', 1)[0]\n if line.startswith('[nofile'):\n code = None\n i += 1\n continue\n else:\n code = err[i + 1]\n highlight = err[i + 2]\n i += 3\n\n if 'cppcheck-disable={}'.format(errid) in code:\n continue\n\n if line == '':\n continue\n if 'The function' in line and 'is never used.' in line:\n continue\n if 'struct member' in line and 'is never used.' in line:\n continue\n actual_err.append(line)\n if code is not None:\n actual_err.append(code)\n actual_err.append(highlight)\n\n # print(actual_err)\n\n if actual_err:\n print('\\n'.join(actual_err))\n sys.exit(1)\n if res.returncode:\n print(res.stdout.strip())\n sys.exit(res.returncode)\n", "repo_name": "mskoenz/pre-commit-cppcheck", "sub_path": "cppcheck_hook/_cppcheck_hook.py", "file_name": "_cppcheck_hook.py", "file_ext": "py", "file_size_in_byte": 1723, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "subprocess.run", "line_number": 29, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 30, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 66, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 69, "usage_type": "call"}, {"api_name": "click.command", "line_number": 13, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 14, "usage_type": "call"}, {"api_name": "click.option", "line_number": 15, "usage_type": "call"}, {"api_name": "click.option", "line_number": 16, "usage_type": "call"}]} +{"seq_id": "32161329125", "text": "# Question: https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/537/week-4-may-22nd-may-28th/3342/\n\n\"\"\"\nGiven a set of N people (numbered 1, 2, ..., N), we would like to split everyone into two groups of any size.\nEach person may dislike some other people, and they should not go into the same group. \nFormally, if dislikes[i] = [a, b], it means it is not allowed to put the people numbered a and b into the same group.\nReturn true if and only if it is possible to split everyone into two groups in this way.\n\nExample 1:\n Input: N = 4, dislikes = [[1,2],[1,3],[2,4]]\n Output: true\n Explanation: group1 [1,4], group2 [2,3]\n\nExample 2:\n Input: N = 3, dislikes = [[1,2],[1,3],[2,3]]\n Output: false\n\nExample 3:\n Input: N = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]\n Output: false\n\nNote:\n (1) 1 <= N <= 2000\n (2) 0 <= dislikes.length <= 10000\n (3) 1 <= dislikes[i][j] <= N\n (4) dislikes[i][0] < dislikes[i][1]\n (5) There does not exist i != j for which dislikes[i] == dislikes[j].\n\"\"\"\n\nfrom collections import defaultdict\n\nclass Solution:\n def possibleBipartition(self, N, dislikes): # possibleBipartition(self, N: int, dislikes: List[List[int]]) -> bool\n neighbours = defaultdict(list)\n\n # Creating a list of disliked neighbours, for each person in the group\n for a,b in dislikes:\n neighbours[a-1].append(b-1)\n neighbours[b-1].append(a-1)\n\n # If an element (node) has not been visited, then colors[element] = 0\n # Later its value becomes 1 or -1, depending upon the group it belongs to\n colors = [0]*N\n\n def no_neighbour_color_conflict(person, color):\n # Change the color of node, as it no longer remains unvisited\n colors[person] = color\n\n for neighbour in neighbours[person]:\n # If a node has already been visited, then compare its color \n # with the color of its parent node\n if colors[neighbour] == color:\n return False\n \n # If a node has not been visited, then visit it, and check for color conflict\n # If given node doesn't have the color of any group, \n # then assign it the color of opposite group of that of its parent\n if colors[neighbour] == 0 and not no_neighbour_color_conflict(neighbour, -color):\n return False\n return True\n\n for i in range(N):\n # Check whether given element has been visited or not\n # If not visited, then visit it and then check for color conflict for each of its neighbours\n # If there is any conflict in color of any of its neighbour, return \"True\"\n if colors[i] == 0 and not no_neighbour_color_conflict(i,1):\n return False\n\n # No conflicts were found, hence it can be resolved into 2 groups\n return True\n\ninputs1 = [1,2,4,3,5]\n\ninputs2 = [\n [],\n [],\n [[1,2],[1,3],[2,4]],\n [[1,2],[1,3],[2,3]],\n [[1,2],[2,3],[3,4],[4,5],[1,5]]\n]\n\noutputs = [True, True, True, False, False]\n\nS = Solution()\nfor i in range(len(inputs1)):\n print(S.possibleBipartition(inputs1[i], inputs2[i]))", "repo_name": "patel-himanshu/leetcode-problems", "sub_path": "2020 - May LeetCoding Challenge/886-possible-bipartion.py", "file_name": "886-possible-bipartion.py", "file_ext": "py", "file_size_in_byte": 3235, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "48", "api": [{"api_name": "collections.defaultdict", "line_number": 34, "usage_type": "call"}]} +{"seq_id": "21899982424", "text": "from __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nDOCUMENTATION = '''\n---\nmodule: netscaler_gslb_service\nshort_description: Manage gslb service entities in Netscaler.\ndescription:\n - Manage gslb service entities in Netscaler.\n\n\nauthor: George Nikolopoulos (@giorgos-nikolopoulos)\n\noptions:\n\n servicename:\n description:\n - >-\n Name for the GSLB service. Must begin with an ASCII alphanumeric or underscore C(_) character, and\n must contain only ASCII alphanumeric, underscore C(_), hash C(#), period C(.), space, colon C(:), at C(@),\n equals C(=), and hyphen C(-) characters. Can be changed after the GSLB service is created.\n - >-\n - \"Minimum length = 1\"\n\n cnameentry:\n description:\n - \"Canonical name of the GSLB service. Used in CNAME-based GSLB.\"\n - \"Minimum length = 1\"\n\n\n servername:\n description:\n - \"Name of the server hosting the GSLB service.\"\n - \"Minimum length = 1\"\n\n servicetype:\n choices:\n - 'HTTP'\n - 'FTP'\n - 'TCP'\n - 'UDP'\n - 'SSL'\n - 'SSL_BRIDGE'\n - 'SSL_TCP'\n - 'NNTP'\n - 'ANY'\n - 'SIP_UDP'\n - 'SIP_TCP'\n - 'SIP_SSL'\n - 'RADIUS'\n - 'RDP'\n - 'RTSP'\n - 'MYSQL'\n - 'MSSQL'\n - 'ORACLE'\n description:\n - \"Type of service to create.\"\n\n port:\n description:\n - \"Port on which the load balancing entity represented by this GSLB service listens.\"\n - \"Minimum value = 1\"\n - \"Range 1 - 65535\"\n - \"* in CLI is represented as 65535 in NITRO API\"\n\n publicip:\n description:\n - >-\n The public IP address that a NAT device translates to the GSLB service's private IP address.\n Optional.\n\n publicport:\n description:\n - >-\n The public port associated with the GSLB service's public IP address. The port is mapped to the\n service's private port number. Applicable to the local GSLB service. Optional.\n\n maxclient:\n description:\n - >-\n The maximum number of open connections that the service can support at any given time. A GSLB service\n whose connection count reaches the maximum is not considered when a GSLB decision is made, until the\n connection count drops below the maximum.\n - \"Minimum value = C(0)\"\n - \"Maximum value = C(4294967294)\"\n\n healthmonitor:\n description:\n - \"Monitor the health of the GSLB service.\"\n type: bool\n\n sitename:\n description:\n - \"Name of the GSLB site to which the service belongs.\"\n - \"Minimum length = 1\"\n\n cip:\n choices:\n - 'enabled'\n - 'disabled'\n description:\n - >-\n In the request that is forwarded to the GSLB service, insert a header that stores the client's IP\n address. Client IP header insertion is used in connection-proxy based site persistence.\n\n cipheader:\n description:\n - >-\n Name for the HTTP header that stores the client's IP address. Used with the Client IP option. If\n client IP header insertion is enabled on the service and a name is not specified for the header, the\n NetScaler appliance uses the name specified by the cipHeader parameter in the set ns param command\n or, in the GUI, the Client IP Header parameter in the Configure HTTP Parameters dialog box.\n - \"Minimum length = 1\"\n\n sitepersistence:\n choices:\n - 'ConnectionProxy'\n - 'HTTPRedirect'\n - 'NONE'\n description:\n - \"Use cookie-based site persistence. Applicable only to C(HTTP) and C(SSL) GSLB services.\"\n\n siteprefix:\n description:\n - >-\n The site's prefix string. When the service is bound to a GSLB virtual server, a GSLB site domain is\n generated internally for each bound service-domain pair by concatenating the site prefix of the\n service and the name of the domain. If the special string NONE is specified, the site-prefix string\n is unset. When implementing HTTP redirect site persistence, the NetScaler appliance redirects GSLB\n requests to GSLB services by using their site domains.\n\n clttimeout:\n description:\n - >-\n Idle time, in seconds, after which a client connection is terminated. Applicable if connection proxy\n based site persistence is used.\n - \"Minimum value = 0\"\n - \"Maximum value = 31536000\"\n\n maxbandwidth:\n description:\n - >-\n Integer specifying the maximum bandwidth allowed for the service. A GSLB service whose bandwidth\n reaches the maximum is not considered when a GSLB decision is made, until its bandwidth consumption\n drops below the maximum.\n\n downstateflush:\n choices:\n - 'enabled'\n - 'disabled'\n description:\n - >-\n Flush all active transactions associated with the GSLB service when its state transitions from UP to\n DOWN. Do not enable this option for services that must complete their transactions. Applicable if\n connection proxy based site persistence is used.\n\n maxaaausers:\n description:\n - >-\n Maximum number of SSL VPN users that can be logged on concurrently to the VPN virtual server that is\n represented by this GSLB service. A GSLB service whose user count reaches the maximum is not\n considered when a GSLB decision is made, until the count drops below the maximum.\n - \"Minimum value = C(0)\"\n - \"Maximum value = C(65535)\"\n\n monthreshold:\n description:\n - >-\n Monitoring threshold value for the GSLB service. If the sum of the weights of the monitors that are\n bound to this GSLB service and are in the UP state is not equal to or greater than this threshold\n value, the service is marked as DOWN.\n - \"Minimum value = C(0)\"\n - \"Maximum value = C(65535)\"\n\n hashid:\n description:\n - \"Unique hash identifier for the GSLB service, used by hash based load balancing methods.\"\n - \"Minimum value = C(1)\"\n\n comment:\n description:\n - \"Any comments that you might want to associate with the GSLB service.\"\n\n appflowlog:\n choices:\n - 'enabled'\n - 'disabled'\n description:\n - \"Enable logging appflow flow information.\"\n\n ipaddress:\n description:\n - >-\n IP address for the GSLB service. Should represent a load balancing, content switching, or VPN virtual\n server on the NetScaler appliance, or the IP address of another load balancing device.\n\n monitor_bindings:\n description:\n - Bind monitors to this gslb service\n suboptions:\n\n weight:\n description:\n - Weight to assign to the monitor-service binding.\n - A larger number specifies a greater weight.\n - Contributes to the monitoring threshold, which determines the state of the service.\n - Minimum value = C(1)\n - Maximum value = C(100)\n\n monitor_name:\n description:\n - Monitor name.\n\nextends_documentation_fragment:\n- community.network.netscaler\n\nrequirements:\n - nitro python sdk\n'''\n\nEXAMPLES = '''\n- name: Setup gslb service 2\n\n delegate_to: localhost\n register: result\n check_mode: \"{{ check_mode }}\"\n\n community.network.netscaler_gslb_service:\n operation: present\n\n servicename: gslb-service-2\n cnameentry: example.com\n sitename: gslb-site-1\n'''\n\nRETURN = '''\nloglines:\n description: list of logged messages by the module\n returned: always\n type: list\n sample: \"['message 1', 'message 2']\"\n\nmsg:\n description: Message detailing the failure reason\n returned: failure\n type: str\n sample: \"Action does not exist\"\n\ndiff:\n description: List of differences between the actual configured object and the configuration specified in the module\n returned: failure\n type: dict\n sample: \"{ 'targetlbvserver': 'difference. ours: (str) server1 other: (str) server2' }\"\n'''\n\nimport copy\n\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler import (\n ConfigProxy,\n get_nitro_client,\n netscaler_common_arguments,\n log,\n loglines,\n ensure_feature_is_enabled,\n monkey_patch_nitro_api,\n get_immutables_intersection,\n)\n\ntry:\n monkey_patch_nitro_api()\n from nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice import gslbservice\n from nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice_lbmonitor_binding import gslbservice_lbmonitor_binding\n from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception\n PYTHON_SDK_IMPORTED = True\nexcept ImportError as e:\n PYTHON_SDK_IMPORTED = False\n\n\ndef gslb_service_exists(client, module):\n if gslbservice.count_filtered(client, 'servicename:%s' % module.params['servicename']) > 0:\n return True\n else:\n return False\n\n\ndef gslb_service_identical(client, module, gslb_service_proxy):\n gslb_service_list = gslbservice.get_filtered(client, 'servicename:%s' % module.params['servicename'])\n diff_dict = gslb_service_proxy.diff_object(gslb_service_list[0])\n # Ignore ip attribute missing\n if 'ip' in diff_dict:\n del diff_dict['ip']\n if len(diff_dict) == 0:\n return True\n else:\n return False\n\n\ndef get_actual_monitor_bindings(client, module):\n log('get_actual_monitor_bindings')\n # Get actual monitor bindings and index them by monitor_name\n actual_monitor_bindings = {}\n if gslbservice_lbmonitor_binding.count(client, servicename=module.params['servicename']) != 0:\n # Get all monitor bindings associated with the named gslb vserver\n fetched_bindings = gslbservice_lbmonitor_binding.get(client, servicename=module.params['servicename'])\n # index by monitor name\n for binding in fetched_bindings:\n # complete_missing_attributes(binding, gslbservice_lbmonitor_binding_rw_attrs, fill_value=None)\n actual_monitor_bindings[binding.monitor_name] = binding\n return actual_monitor_bindings\n\n\ndef get_configured_monitor_bindings(client, module):\n log('get_configured_monitor_bindings')\n configured_monitor_proxys = {}\n gslbservice_lbmonitor_binding_rw_attrs = [\n 'weight',\n 'servicename',\n 'monitor_name',\n ]\n # Get configured monitor bindings and index them by monitor_name\n if module.params['monitor_bindings'] is not None:\n for configured_monitor_bindings in module.params['monitor_bindings']:\n binding_values = copy.deepcopy(configured_monitor_bindings)\n binding_values['servicename'] = module.params['servicename']\n proxy = ConfigProxy(\n actual=gslbservice_lbmonitor_binding(),\n client=client,\n attribute_values_dict=binding_values,\n readwrite_attrs=gslbservice_lbmonitor_binding_rw_attrs,\n readonly_attrs=[],\n )\n configured_monitor_proxys[configured_monitor_bindings['monitor_name']] = proxy\n return configured_monitor_proxys\n\n\ndef monitor_bindings_identical(client, module):\n log('monitor_bindings_identical')\n actual_bindings = get_actual_monitor_bindings(client, module)\n configured_proxys = get_configured_monitor_bindings(client, module)\n\n actual_keyset = set(actual_bindings.keys())\n configured_keyset = set(configured_proxys.keys())\n\n symmetric_difference = actual_keyset ^ configured_keyset\n if len(symmetric_difference) != 0:\n log('Symmetric difference %s' % symmetric_difference)\n return False\n\n # Item for item equality test\n for key, proxy in configured_proxys.items():\n if not proxy.has_equal_attributes(actual_bindings[key]):\n log('monitor binding difference %s' % proxy.diff_object(actual_bindings[key]))\n return False\n\n # Fallthrough to True result\n return True\n\n\ndef sync_monitor_bindings(client, module):\n log('sync_monitor_bindings')\n\n actual_monitor_bindings = get_actual_monitor_bindings(client, module)\n configured_monitor_proxys = get_configured_monitor_bindings(client, module)\n\n # Delete actual bindings not in configured bindings\n for monitor_name, actual_binding in actual_monitor_bindings.items():\n if monitor_name not in configured_monitor_proxys.keys():\n log('Deleting absent binding for monitor %s' % monitor_name)\n log('dir is %s' % dir(actual_binding))\n gslbservice_lbmonitor_binding.delete(client, actual_binding)\n\n # Delete and re-add actual bindings that differ from configured\n for proxy_key, binding_proxy in configured_monitor_proxys.items():\n if proxy_key in actual_monitor_bindings:\n actual_binding = actual_monitor_bindings[proxy_key]\n if not binding_proxy.has_equal_attributes(actual_binding):\n log('Deleting differing binding for monitor %s' % actual_binding.monitor_name)\n log('dir %s' % dir(actual_binding))\n log('attribute monitor_name %s' % getattr(actual_binding, 'monitor_name'))\n log('attribute monitorname %s' % getattr(actual_binding, 'monitorname', None))\n gslbservice_lbmonitor_binding.delete(client, actual_binding)\n log('Adding anew binding for monitor %s' % binding_proxy.monitor_name)\n binding_proxy.add()\n\n # Add configured monitors that are missing from actual\n for proxy_key, binding_proxy in configured_monitor_proxys.items():\n if proxy_key not in actual_monitor_bindings.keys():\n log('Adding monitor binding for monitor %s' % binding_proxy.monitor_name)\n binding_proxy.add()\n\n\ndef diff_list(client, module, gslb_service_proxy):\n gslb_service_list = gslbservice.get_filtered(client, 'servicename:%s' % module.params['servicename'])\n diff_list = gslb_service_proxy.diff_object(gslb_service_list[0])\n if 'ip' in diff_list:\n del diff_list['ip']\n return diff_list\n\n\ndef all_identical(client, module, gslb_service_proxy):\n return gslb_service_identical(client, module, gslb_service_proxy) and monitor_bindings_identical(client, module)\n\n\ndef main():\n\n module_specific_arguments = dict(\n servicename=dict(type='str'),\n cnameentry=dict(type='str'),\n servername=dict(type='str'),\n servicetype=dict(\n type='str',\n choices=[\n 'HTTP',\n 'FTP',\n 'TCP',\n 'UDP',\n 'SSL',\n 'SSL_BRIDGE',\n 'SSL_TCP',\n 'NNTP',\n 'ANY',\n 'SIP_UDP',\n 'SIP_TCP',\n 'SIP_SSL',\n 'RADIUS',\n 'RDP',\n 'RTSP',\n 'MYSQL',\n 'MSSQL',\n 'ORACLE',\n ]\n ),\n port=dict(type='int'),\n publicip=dict(type='str'),\n publicport=dict(type='int'),\n maxclient=dict(type='float'),\n healthmonitor=dict(type='bool'),\n sitename=dict(type='str'),\n cip=dict(\n type='str',\n choices=[\n 'enabled',\n 'disabled',\n ]\n ),\n cipheader=dict(type='str'),\n sitepersistence=dict(\n type='str',\n choices=[\n 'ConnectionProxy',\n 'HTTPRedirect',\n 'NONE',\n ]\n ),\n siteprefix=dict(type='str'),\n clttimeout=dict(type='float'),\n maxbandwidth=dict(type='float'),\n downstateflush=dict(\n type='str',\n choices=[\n 'enabled',\n 'disabled',\n ]\n ),\n maxaaausers=dict(type='float'),\n monthreshold=dict(type='float'),\n hashid=dict(type='float'),\n comment=dict(type='str'),\n appflowlog=dict(\n type='str',\n choices=[\n 'enabled',\n 'disabled',\n ]\n ),\n ipaddress=dict(type='str'),\n )\n\n hand_inserted_arguments = dict(\n monitor_bindings=dict(type='list'),\n )\n\n argument_spec = dict()\n\n argument_spec.update(netscaler_common_arguments)\n argument_spec.update(module_specific_arguments)\n argument_spec.update(hand_inserted_arguments)\n\n module = AnsibleModule(\n argument_spec=argument_spec,\n supports_check_mode=True,\n )\n module_result = dict(\n changed=False,\n failed=False,\n loglines=loglines,\n )\n\n # Fail the module if imports failed\n if not PYTHON_SDK_IMPORTED:\n module.fail_json(msg='Could not load nitro python sdk')\n\n # Fallthrough to rest of execution\n client = get_nitro_client(module)\n\n try:\n client.login()\n except nitro_exception as e:\n msg = \"nitro exception during login. errorcode=%s, message=%s\" % (str(e.errorcode), e.message)\n module.fail_json(msg=msg)\n except Exception as e:\n if str(type(e)) == \"\":\n module.fail_json(msg='Connection error %s' % str(e))\n elif str(type(e)) == \"\":\n module.fail_json(msg='SSL Error %s' % str(e))\n else:\n module.fail_json(msg='Unexpected error during login %s' % str(e))\n\n readwrite_attrs = [\n 'servicename',\n 'cnameentry',\n 'ip',\n 'servername',\n 'servicetype',\n 'port',\n 'publicip',\n 'publicport',\n 'maxclient',\n 'healthmonitor',\n 'sitename',\n 'cip',\n 'cipheader',\n 'sitepersistence',\n 'siteprefix',\n 'clttimeout',\n 'maxbandwidth',\n 'downstateflush',\n 'maxaaausers',\n 'monthreshold',\n 'hashid',\n 'comment',\n 'appflowlog',\n 'ipaddress',\n ]\n\n readonly_attrs = [\n 'gslb',\n 'svrstate',\n 'svreffgslbstate',\n 'gslbthreshold',\n 'gslbsvcstats',\n 'monstate',\n 'preferredlocation',\n 'monitor_state',\n 'statechangetimesec',\n 'tickssincelaststatechange',\n 'threshold',\n 'clmonowner',\n 'clmonview',\n '__count',\n ]\n\n immutable_attrs = [\n 'servicename',\n 'cnameentry',\n 'ip',\n 'servername',\n 'servicetype',\n 'port',\n 'sitename',\n 'state',\n 'cipheader',\n 'cookietimeout',\n 'clttimeout',\n 'svrtimeout',\n 'viewip',\n 'monitor_name_svc',\n 'newname',\n ]\n\n transforms = {\n 'healthmonitor': ['bool_yes_no'],\n 'cip': [lambda v: v.upper()],\n 'downstateflush': [lambda v: v.upper()],\n 'appflowlog': [lambda v: v.upper()],\n }\n\n # params = copy.deepcopy(module.params)\n module.params['ip'] = module.params['ipaddress']\n\n # Instantiate config proxy\n gslb_service_proxy = ConfigProxy(\n actual=gslbservice(),\n client=client,\n attribute_values_dict=module.params,\n transforms=transforms,\n readwrite_attrs=readwrite_attrs,\n readonly_attrs=readonly_attrs,\n immutable_attrs=immutable_attrs,\n )\n\n try:\n ensure_feature_is_enabled(client, 'GSLB')\n # Apply appropriate state\n if module.params['state'] == 'present':\n if not gslb_service_exists(client, module):\n if not module.check_mode:\n gslb_service_proxy.add()\n sync_monitor_bindings(client, module)\n if module.params['save_config']:\n client.save_config()\n module_result['changed'] = True\n elif not all_identical(client, module, gslb_service_proxy):\n\n # Check if we try to change value of immutable attributes\n immutables_changed = get_immutables_intersection(gslb_service_proxy, diff_list(client, module, gslb_service_proxy).keys())\n if immutables_changed != []:\n module.fail_json(\n msg='Cannot update immutable attributes %s' % (immutables_changed,),\n diff=diff_list(client, module, gslb_service_proxy),\n **module_result\n )\n\n # Update main configuration object\n if not gslb_service_identical(client, module, gslb_service_proxy):\n if not module.check_mode:\n gslb_service_proxy.update()\n\n # Update monitor bindigns\n if not monitor_bindings_identical(client, module):\n if not module.check_mode:\n sync_monitor_bindings(client, module)\n\n # Fallthrough to save and change status update\n module_result['changed'] = True\n if module.params['save_config']:\n client.save_config()\n else:\n module_result['changed'] = False\n\n # Sanity check for state\n if not module.check_mode:\n if not gslb_service_exists(client, module):\n module.fail_json(msg='GSLB service does not exist', **module_result)\n if not gslb_service_identical(client, module, gslb_service_proxy):\n module.fail_json(\n msg='GSLB service differs from configured',\n diff=diff_list(client, module, gslb_service_proxy),\n **module_result\n )\n if not monitor_bindings_identical(client, module):\n module.fail_json(\n msg='Monitor bindings differ from configured',\n diff=diff_list(client, module, gslb_service_proxy),\n **module_result\n )\n\n elif module.params['state'] == 'absent':\n if gslb_service_exists(client, module):\n if not module.check_mode:\n gslb_service_proxy.delete()\n if module.params['save_config']:\n client.save_config()\n module_result['changed'] = True\n else:\n module_result['changed'] = False\n\n # Sanity check for state\n if not module.check_mode:\n if gslb_service_exists(client, module):\n module.fail_json(msg='GSLB service still exists', **module_result)\n\n except nitro_exception as e:\n msg = \"nitro exception errorcode=%s, message=%s\" % (str(e.errorcode), e.message)\n module.fail_json(msg=msg, **module_result)\n\n client.logout()\n module.exit_json(**module_result)\n\n\nif __name__ == \"__main__\":\n main()\n", "repo_name": "ansible-collections/community.network", "sub_path": "plugins/modules/netscaler_gslb_service.py", "file_name": "netscaler_gslb_service.py", "file_ext": "py", "file_size_in_byte": 23752, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 108, "dataset": "github-code", "pt": "48", "api": [{"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.monkey_patch_nitro_api", "line_number": 273, "usage_type": "call"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice.gslbservice.count_filtered", "line_number": 283, "usage_type": "call"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice.gslbservice", "line_number": 283, "usage_type": "name"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice.gslbservice.get_filtered", "line_number": 290, "usage_type": "call"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice.gslbservice", "line_number": 290, "usage_type": "name"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.log", "line_number": 302, "usage_type": "call"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice_lbmonitor_binding.gslbservice_lbmonitor_binding.count", "line_number": 305, "usage_type": "call"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice_lbmonitor_binding.gslbservice_lbmonitor_binding", "line_number": 305, "usage_type": "name"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice_lbmonitor_binding.gslbservice_lbmonitor_binding.get", "line_number": 307, "usage_type": "call"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice_lbmonitor_binding.gslbservice_lbmonitor_binding", "line_number": 307, "usage_type": "name"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.log", "line_number": 316, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 326, "usage_type": "call"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.ConfigProxy", "line_number": 328, "usage_type": "call"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice_lbmonitor_binding.gslbservice_lbmonitor_binding", "line_number": 329, "usage_type": "call"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.log", "line_number": 340, "usage_type": "call"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.log", "line_number": 349, "usage_type": "call"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.log", "line_number": 355, "usage_type": "call"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.log", "line_number": 363, "usage_type": "call"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.log", "line_number": 371, "usage_type": "call"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.log", "line_number": 372, "usage_type": "call"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice_lbmonitor_binding.gslbservice_lbmonitor_binding.delete", "line_number": 373, "usage_type": "call"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice_lbmonitor_binding.gslbservice_lbmonitor_binding", "line_number": 373, "usage_type": "name"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.log", "line_number": 380, "usage_type": "call"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.log", "line_number": 381, "usage_type": "call"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.log", "line_number": 382, "usage_type": "call"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.log", "line_number": 383, "usage_type": "call"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice_lbmonitor_binding.gslbservice_lbmonitor_binding.delete", "line_number": 384, "usage_type": "call"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice_lbmonitor_binding.gslbservice_lbmonitor_binding", "line_number": 384, "usage_type": "name"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.log", "line_number": 385, "usage_type": "call"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.log", "line_number": 391, "usage_type": "call"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice.gslbservice.get_filtered", "line_number": 396, "usage_type": "call"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice.gslbservice", "line_number": 396, "usage_type": "name"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.netscaler_common_arguments", "line_number": 488, "usage_type": "argument"}, {"api_name": "ansible.module_utils.basic.AnsibleModule", "line_number": 492, "usage_type": "call"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.loglines", "line_number": 499, "usage_type": "name"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.get_nitro_client", "line_number": 507, "usage_type": "call"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.exception.nitro_exception.nitro_exception", "line_number": 511, "usage_type": "name"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.ConfigProxy", "line_number": 595, "usage_type": "call"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice.gslbservice", "line_number": 596, "usage_type": "call"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.ensure_feature_is_enabled", "line_number": 606, "usage_type": "call"}, {"api_name": "ansible_collections.community.network.plugins.module_utils.network.netscaler.netscaler.get_immutables_intersection", "line_number": 619, "usage_type": "call"}, {"api_name": "nssrc.com.citrix.netscaler.nitro.exception.nitro_exception.nitro_exception", "line_number": 676, "usage_type": "name"}]} +{"seq_id": "25483210382", "text": "import os\nfrom setuptools import setup\n\n\n__version__ = '21.12'\n\n\nwith open('README.md') as f:\n long_description = f.read()\n\n\ndef get_data_files():\n \"\"\"\n Get the data files for the package.\n \"\"\"\n return [\n ('share/jupyter/nbextensions/genepattern', [\n 'genepattern/static/index.js',\n ]),\n ('share/jupyter/nbextensions/genepattern/resources',\n ['genepattern/static/resources/' + f for f in os.listdir('genepattern/static/resources')]\n ),\n ('etc/jupyter/nbconfig/notebook.d', ['genepattern.json']),\n # ('share/jupyter/lab/extensions', [\n # 'genepattern/static/index.js',\n # 'genepattern/static/resources',\n # ])\n ]\n\n\nsetup(name='genepattern-notebook',\n packages=['genepattern'],\n version=__version__,\n description='GenePattern Notebook extension for Jupyter',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n license='BSD',\n author='Thorin Tabor',\n author_email='tmtabor@cloud.ucsd.edu',\n url='https://github.com/genepattern/genepattern-notebook',\n download_url='https://github.com/genepattern/genepattern-notebook/archive/' + __version__ + '.tar.gz',\n keywords=['genepattern', 'genomics', 'bioinformatics', 'ipython', 'jupyter'],\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Science/Research',\n 'Intended Audience :: Developers',\n 'Topic :: Scientific/Engineering :: Bio-Informatics',\n 'License :: OSI Approved :: BSD License',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Framework :: Jupyter',\n ],\n install_requires=[\n 'genepattern-python>=1.4.2',\n 'nbtools>=19',\n 'notebook>=5.0.0',\n 'ipywidgets>=7.0.0',\n ],\n package_data={'genepattern': ['static/index.js', 'static/resources/*']},\n data_files=get_data_files(),\n normalize_version=False,\n )\n", "repo_name": "springtan/genepattern-notebook", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 2073, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "48", "api": [{"api_name": "os.listdir", "line_number": 21, "usage_type": "call"}, {"api_name": "setuptools.setup", "line_number": 31, "usage_type": "call"}]} +{"seq_id": "36333435816", "text": "from tkinter import *\r\n#used for making the GUI\r\nfrom PIL import Image, ImageTk\r\n#from datetime import *\r\nfrom datetime import datetime\r\nfrom pytz import timezone\r\nimport time\r\nroot = Tk()\r\n\r\n\r\nlogo = Image.open(\"eagles_logo.jpg\")\r\nphoto = ImageTk.PhotoImage(logo)\r\nlogoLabel = Label(root, image = photo)\r\nlogoLabel.pack()\r\n\r\ndef main():\r\n #layout of GUI\r\n root.title(\"TheBaldEagle4133\")\r\n root.geometry(\"600x600\")\r\n root.configure(bg = '#135252')\r\n #display of words\r\n dayLabels = Label(root, text = 'Days \\t|\\t Hours \\t|\\t Minutes |\\t Seconds', \r\n width = '100', font = 'Arial 12 bold', bg = '#135252')\r\n dayLabels.pack()\r\n \r\ndef printtext():\r\n tz = timezone('US/Eastern')\r\n startDate = datetime.now(tz)\r\n \r\n newDate = userInput.get() \r\n month = int(newDate[0:2])\r\n day = int(newDate[2:4])\r\n year = int(newDate[4:8])\r\n timeHour = int(newDate[8:10])\r\n #if minutes are/n't entered\r\n if (len(newDate) > 10):\r\n timeMinutes = int(newDate[10:12])\r\n else:\r\n timeMinutes = 0\r\n timeSeconds = 0\r\n \r\n endDate = datetime(year, month, day, timeHour, timeMinutes, timeSeconds)\r\n \r\n startDay = int(startDate.strftime(\"%d\"))\r\n endDay = int(endDate.strftime(\"%d\"))\r\n newDay = endDay - startDay\r\n currentMonth = int(startDate.strftime(\"%m\"))\r\n currentYear = int(startDate.strftime(\"%Y\"))\r\n \r\n if (currentYear < year):\r\n yearDifference = year - currentYear\r\n newYear = yearDifference * 365\r\n if (currentMonth < month):\r\n monthDifference = month - currentMonth\r\n newMonth = monthDifference * 30\r\n newDay += newMonth + newYear\r\n else:\r\n newDay += newYear\r\n else:\r\n if (currentMonth < month):\r\n monthDifference = month - currentMonth\r\n newMonth = monthDifference * 30\r\n newDay += newMonth\r\n \r\n \r\n startHour = int(startDate.strftime(\"%H\"))\r\n endHour = int(endDate.strftime(\"%H\"))\r\n newHour = endHour - startHour\r\n if (newHour < 0):\r\n newHour += 24\r\n \r\n startMinute = int(startDate.strftime(\"%M\"))\r\n endMinute = int(endDate.strftime(\"%M\"))\r\n newMinute = endMinute - startMinute\r\n if(newMinute < 0):\r\n newMinute += 60\r\n \r\n startSecond = int(startDate.strftime(\"%S\"))\r\n endSecond = int(endDate.strftime(\"%S\"))\r\n newSecond = endSecond - startSecond\r\n if (newSecond < 0):\r\n newSecond += 60\r\n \r\n setButton.destroy()\r\n userInput.destroy() \r\n countdown(newDay, newHour, newMinute, newSecond)\r\n \r\n \r\n#Set button\r\nuserInput = Entry(root)\r\nuserInput.pack()\r\nuserInput.focus_set()\r\n \r\nsetButton = Button(root, text = 'Set', width = '10', command = printtext)\r\nsetButton.pack(side = 'bottom')\r\n\r\nplaceHolder = Label(root, text = '', width = '600', font = 'Arial 80 bold',\r\n fg = 'black')\r\nplaceHolder.pack()\r\n\r\n\r\ndef countdown(newDay,newHour,newMinute,newSecond):\r\n #display of numbers\r\n numbersLabel = placeHolder\r\n \r\n root.update()\r\n days = newDay\r\n hours = newHour\r\n minutes = newMinute \r\n seconds = newSecond\r\n while(days>=0 and hours>=0 and minutes>=0 and seconds>=0):\r\n \r\n #track the length of numbers\r\n s = str(seconds)\r\n m = str(minutes)\r\n h = str(hours)\r\n \r\n #hours(2) , minutes(2) , seconds(1)\r\n if (len(h)!=1 and len(m)!=1 and len(s)==1):\r\n numbersLabel.configure(text=\"%d:%d:%d:%d%d\"%(days,hours,minutes,0,seconds))\r\n \r\n #hours(1) , minutes(2) , seconds(1)\r\n elif (len(h)==1 and len(m)!=1 and len(s)==1):\r\n numbersLabel.configure(text=\"%d:%d%d:%d:%d%d\"%(days,0,hours,minutes,0,seconds))\r\n \r\n #hours(2) , minutes(1) , seconds(2) \r\n elif (len(h)!=1 and len(m)==1 and len(s)!=1):\r\n numbersLabel.configure(text=\"%d:%d:%d%d:%d\"%(days,hours,0,minutes,seconds))\r\n \r\n #hours(2) , minutes(1) , seconds(1) \r\n elif (len(h)!=1 and len(m)==1 and len(s)==1):\r\n numbersLabel.configure(text=\"%d:%d:%d%d:%d%d\"%(days,hours,0,minutes,0,seconds))\r\n \r\n #hours(1) , minutes(1) , seconds(2) \r\n elif (len(h)==1 and len(m)==1 and len(s)!=1):\r\n numbersLabel.configure(text=\"%d:%d%d:%d%d:%d\"%(days,0,hours,0,minutes,seconds))\r\n \r\n #hours(1) , minutes(1) , seconds(1) \r\n elif (len(h)==1 and len(m)==1 and len(s)==1):\r\n numbersLabel.configure(text=\"%d:%d%d:%d%d:%d%d\"%(days,0,hours,0,minutes,0,seconds))\r\n \r\n #hours(1) , minutes(2) , seconds(2) \r\n elif (len(h)==1 and len(m)!=1 and len(s)!=1):\r\n numbersLabel.configure(text=\"%d:%d%d:%d:%d\"%(days,0,hours,minutes,seconds))\r\n \r\n #hours(2) , minutes(2) , seconds(2)\r\n else:\r\n numbersLabel.configure(text=\"%d:%d:%d:%d\"%(days,hours,minutes,seconds))\r\n \r\n root.update()\r\n \r\n #minutes(01) , seconds(00)\r\n if (minutes!=0 and seconds==0):\r\n seconds = 60\r\n minutes -= 1\r\n #hours(01) , minutes(00) , seconds(00)\r\n if (hours!=0 and minutes==0 and seconds==0):\r\n seconds = 60\r\n minutes = 59\r\n hours -= 1\r\n #days(01) , hours(00) , minutes(00) , seconds(00)\r\n if (days!=0 and hours==0 and minutes==0 and seconds==0):\r\n seconds = 60\r\n minutes = 59\r\n hours = 23\r\n days -= 1\r\n seconds -= 1\r\n time.sleep(1)\r\n numbersLabel.configure(text=\"Game Time\")\r\nmain()\r\nroot.mainloop()", "repo_name": "Keila-Cressman/Countdown", "sub_path": "Countdown.py", "file_name": "Countdown.py", "file_ext": "py", "file_size_in_byte": 5647, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "PIL.Image.open", "line_number": 11, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 11, "usage_type": "name"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 12, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 12, "usage_type": "name"}, {"api_name": "pytz.timezone", "line_number": 27, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 28, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 28, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 42, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 168, "usage_type": "call"}]} +{"seq_id": "4944140460", "text": "import datetime\nfrom floodsystem.stationdata import build_station_list, update_water_levels\nfrom floodsystem.flood import stations_highest_rel_level\nfrom floodsystem.datafetcher import fetch_measure_levels\nfrom floodsystem.plot import plot_water_levels\n\ndef run():\n \"\"\"Requirements for Task 2E\"\"\"\n\n #build and update list of station objects\n stations = build_station_list()\n update_water_levels(stations)\n\n dt = 10\n \n # Get the list of station object tuples\n high_stations = stations_highest_rel_level(stations, 5)\n \n # Make list of these 5 stations' measure_ids\n high_station_id = []\n \n for i in range(5):\n high_station_tuple = (high_stations[i][0]).measure_id\n high_station_id.append(high_station_tuple)\n \n # Make list of the station names\n high_objects = []\n for i in range(5):\n high_objects.append(high_stations[i][0])\n\n for i in range(5):\n dates, levels = fetch_measure_levels(high_objects[i].measure_id, dt=datetime.timedelta(days=dt))\n plot_water_levels(high_objects[i], dates, levels)\n\nif __name__ == \"__main__\":\n print(\"*** Task 2E: CUED Part IA Flood Warning System ***\")\n run()\n", "repo_name": "jgm48/ia-flood-risk-project", "sub_path": "Task2E.py", "file_name": "Task2E.py", "file_ext": "py", "file_size_in_byte": 1184, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "floodsystem.stationdata.build_station_list", "line_number": 11, "usage_type": "call"}, {"api_name": "floodsystem.stationdata.update_water_levels", "line_number": 12, "usage_type": "call"}, {"api_name": "floodsystem.flood.stations_highest_rel_level", "line_number": 17, "usage_type": "call"}, {"api_name": "floodsystem.datafetcher.fetch_measure_levels", "line_number": 32, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 32, "usage_type": "call"}, {"api_name": "floodsystem.plot.plot_water_levels", "line_number": 33, "usage_type": "call"}]} +{"seq_id": "2524523203", "text": "from fastapi import FastAPI\nfrom routers.users import users\nfrom starlette.middleware.sessions import SessionMiddleware\nfrom firebase_admin import firestore, storage, auth\nimport uvicorn\nfrom fastapi.middleware.cors import CORSMiddleware\n\n\napp = FastAPI()\napp.add_middleware(SessionMiddleware ,secret_key='maihoonjiyan')\n\n\nimport firebase_admin\nfrom firebase_admin import credentials\n\n\n\n\nif not firebase_admin._apps:\n cred = credentials.Certificate(\"serviceAccountKey.json\")\n firebase_admin.initialize_app(cred)\n\n\nallow_all = ['*']\napp.add_middleware(\n CORSMiddleware,\n allow_origins=allow_all,\n allow_credentials=True,\n allow_methods=allow_all,\n allow_headers=allow_all\n)\norigins = [\n \"http://localhost:3000\",\n ]\napp.include_router(users)\n\n\n@app.get(\"/\")\ndef read_root():\n db = firestore.client()\n doc_ref = db.collection('user').document()\n doc_ref.set({\n 'first': 'Barrack',\n 'last': 'Obama',\n 'born': 1815123132132\n })\n return {\"message\": \"welcome to FastAPI!\"}\n\nif __name__ == \"__main__\":\n uvicorn.run(\"main:app\")\n\n#sudo /opt/lampp/lampp start\n\n\n#source venv/bin/activate\n# run => uvicorn index:app --reload\n#dockefile => uvicorn index:app --reload\n", "repo_name": "micies/ort", "sub_path": "server/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1215, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "fastapi.FastAPI", "line_number": 9, "usage_type": "call"}, {"api_name": "starlette.middleware.sessions.SessionMiddleware", "line_number": 10, "usage_type": "argument"}, {"api_name": "firebase_admin._apps", "line_number": 19, "usage_type": "attribute"}, {"api_name": "firebase_admin.credentials.Certificate", "line_number": 20, "usage_type": "call"}, {"api_name": "firebase_admin.credentials", "line_number": 20, "usage_type": "name"}, {"api_name": "firebase_admin.initialize_app", "line_number": 21, "usage_type": "call"}, {"api_name": "fastapi.middleware.cors.CORSMiddleware", "line_number": 26, "usage_type": "argument"}, {"api_name": "routers.users.users", "line_number": 35, "usage_type": "argument"}, {"api_name": "firebase_admin.firestore.client", "line_number": 40, "usage_type": "call"}, {"api_name": "firebase_admin.firestore", "line_number": 40, "usage_type": "name"}, {"api_name": "uvicorn.run", "line_number": 50, "usage_type": "call"}]} +{"seq_id": "42695748352", "text": "from flask import render_template, request, redirect, send_file, session, flash\nfrom config import URL_HOME\nimport os\nfrom app import app\nfrom app import utils\nfrom app import models\n# from sqlalchemy import or_\nimport jwt\nfrom functools import wraps\n\n\n# Authentication\ndef requires_auth(f):\n @wraps(f)\n def decorated_function(*args):\n print(session['rol'], \"AUTH\")\n if session['rol'] == 'None' or session['rol'] is None or session['rol'] == '':\n url = f'{URL_HOME}logout/You dont have permissions'\n return redirect(url)\n else:\n pass\n return f(*args)\n return decorated_function\n\n\n# ROUTE FLASK\n@app.route(\"/\")\ndef inici():\n \"\"\"\n Redirecciona a la pagina principal.\n\n :returns: Retorna el html de la pagina principal.\n :rtype: render_template\n \"\"\"\n\n equips = models.session.query(models.Fitxes).filter(models.Fitxes.codi_aux.like('EIM%')).all()\n return render_template(\"main.html\", equips=equips)\n\n\n# Ruta per seleccionar les files de les mostres\n@app.route(\"/fitxa_tecnica\", methods=[\"POST\"])\ndef fitxa_tecnica():\n \"\"\"\n Redirecciona l'html principal per afegir l'arxiu d'input.\n\n :returns: Retorna l'html corresponent.\n :rtype: render_template\n \"\"\"\n\n try:\n equip = request.form['codi_aux']\n dades = models.session.query(models.Fitxes).filter(models.Fitxes.codi_aux == equip).first()\n return render_template(\"fitxa_tecnica.html\", dades=dades)\n\n except Exception:\n flash(\"L'equip seleccionat no existeix!\", \"warning\")\n return redirect(\"/\")\n\n\n# Generar pdf\n@app.route(\"/generar_pdf\", methods=[\"POST\"])\ndef generar_pdf():\n data = {}\n\n for key, value in request.form.items():\n data[key] = value\n # print(key, value)\n\n uploaded_files = request.form.getlist(\"imagenes[]\")\n for i, file in enumerate(uploaded_files):\n data[\"desc_img_\" + str(i)] = file\n\n # print(data)\n # return \"ok\"\n\n if data[\"img_1\"] == '':\n data[\"img_1\"] = \"no_foto.png\"\n if data[\"img_2\"] == '':\n data[\"img_2\"] = \"no_foto.png\"\n if data[\"img_3\"] == '':\n data[\"img_3\"] = \"no_foto.png\"\n\n try:\n\n equip = models.session.query(models.Fitxes).filter(models.Fitxes.codi_aux == data[\"codi_aux\"]).first()\n data[\"data_modificacio\"] = equip.data_modificacio\n data[\"versio_doc\"] = equip.versio_doc\n equip.descripcio = data[\"descripcio\"]\n equip.fabricant = data[\"fabricant\"]\n equip.ref_fabricant = data[\"ref_fabricant\"]\n equip.serial_number = data[\"serial_number\"]\n equip.model = data[\"model\"]\n equip.emp_subministradora = data[\"emp_subministradora\"]\n # Servei Tecnic = data[\"servei_tecnic\"]\n # Telefon = data[\"telefon\"]\n equip.data_alta = data[\"data_alta\"]\n equip.condicions_equip = data[\"condicions_equip\"]\n equip.data_baixa = data[\"data_baixa\"]\n equip.situacio_contractual = data[\"situacio_contractual\"]\n equip.preu = data[\"preu\"]\n equip.tipus = data[\"tipus\"]\n equip.amplada = data[\"amplada\"]\n equip.alçada = data[\"alçada\"]\n equip.profunditat = data[\"profunditat\"]\n equip.pes = data[\"pes\"]\n equip.volum = data[\"volum\"]\n equip.condicions_ambientals = data[\"condicions_ambientals\"]\n equip.humitat = data[\"humitat\"]\n equip.presa_aigua = data[\"presa_aigua\"]\n equip.marca_pantalla = data[\"marca_pantalla\"]\n equip.model_pantalla = data[\"model_pantalla\"]\n equip.num_serie_pantalla = data[\"num_serie_pantalla\"]\n equip.codi_pantalla = data[\"codi_pantalla\"]\n equip.marca_sai = data[\"marca_sai\"]\n equip.model_sai = data[\"model_sai\"]\n equip.num_serie_sai = data[\"num_serie_sai\"]\n equip.codi_sai = data[\"codi_sai\"]\n # Cont Comercial = data[?]\n # Cont Tecnic = data[?]\n # Observacions = data[?]\n equip.marca_lector = data[\"marca_lector\"]\n equip.model_lector = data[\"model_lector\"]\n equip.num_serie_lector = data[\"num_serie_lector\"]\n equip.codi_lector = data[\"codi_lector\"]\n equip.marca_impresora = data[\"marca_impresora\"]\n equip.model_impresora = data[\"model_impresora\"]\n equip.num_serie_impresora = data[\"num_serie_impresora\"]\n equip.codi_impresora = data[\"codi_impresora\"]\n equip.marca_tensio = data[\"marca_tensio\"]\n equip.model_tensio = data[\"model_tensio\"]\n equip.num_serie_tensio = data[\"num_serie_tensio\"]\n equip.codi_tensio = data[\"codi_tensio\"]\n equip.soft_1 = data[\"soft_1\"]\n equip.versio_1 = data[\"versio_1\"]\n equip.soft_2 = data[\"soft_2\"]\n equip.versio_2 = data[\"versio_2\"]\n equip.soft_3 = data[\"soft_3\"]\n equip.versio_3 = data[\"versio_3\"]\n equip.soft_4 = data[\"soft_4\"]\n equip.versio_4 = data[\"versio_4\"]\n equip.soft_5 = data[\"soft_5\"]\n equip.versio_5 = data[\"versio_5\"]\n equip.personal_tecnic_udmmp = data[\"personal_tecnic_udmmp\"]\n equip.facultatius_udmmp = data[\"facultatius_udmmp\"]\n equip.personal_tecnic_udmmp_2 = data[\"personal_tecnic_udmmp_2\"]\n equip.facultatius_udmmp_2 = data[\"facultatius_udmmp_2\"]\n equip.personal_tecnic_udmmp_3 = data[\"personal_tecnic_udmmp_3\"]\n equip.facultatius_udmmp_3 = data[\"facultatius_udmmp_3\"]\n equip.personal_tecnic_udmmp_4 = data[\"personal_tecnic_udmmp_4\"]\n equip.facultatius_udmmp_4 = data[\"facultatius_udmmp_4\"]\n equip.personal_tecnic_udmmp_5 = data[\"personal_tecnic_udmmp_5\"]\n equip.facultatius_udmmp_5 = data[\"facultatius_udmmp_5\"]\n equip.ref_fung1 = data[\"ref_fung1\"]\n equip.desc_fung1 = data[\"desc_fung1\"]\n equip.ref_fung2 = data[\"ref_fung2\"]\n equip.desc_fung2 = data[\"desc_fung2\"]\n equip.ref_fung3 = data[\"ref_fung3\"]\n equip.desc_fung3 = data[\"desc_fung3\"]\n equip.ref_fung4 = data[\"ref_fung4\"]\n equip.desc_fung4 = data[\"desc_fung4\"]\n equip.ref_fung5 = data[\"ref_fung5\"]\n equip.desc_fung5 = data[\"desc_fung5\"]\n equip.doc1 = data[\"doc1\"]\n equip.doc2 = data[\"doc2\"]\n equip.cont_manteniment = data[\"cont_manteniment\"]\n equip.manteniment_ext = data[\"manteniment_ext\"]\n equip.manteniment_int = data[\"manteniment_int\"]\n equip.verificacio_int = data[\"verificacio_int\"]\n equip.verificacio_ext = data[\"verificacio_ext\"]\n equip.cal_ext = data[\"cal_ext\"]\n equip.cal_int = data[\"cal_int\"]\n equip.nom_contracte = data[\"nom_contracte\"]\n equip.emp_respon1 = data[\"emp_respon1\"]\n equip.periode_cober1 = data[\"periode_cober1\"]\n equip.dades_cont1 = data[\"dades_cont1\"]\n equip.emp_respon2 = data[\"emp_respon2\"]\n equip.periode_cober2 = data[\"periode_cober2\"]\n equip.dades_cont2 = data[\"dades_cont2\"]\n equip.emp_respon_prev_ext = data[\"emp_respon_prev_ext\"]\n equip.periodicitat_prev_ext = data[\"periodicitat_prev_ext\"]\n equip.cont_prev_ext = data[\"cont_prev_ext\"]\n equip.mant_prev_ext = data[\"mant_prev_ext\"]\n equip.verif_prev_ext = data[\"verif_prev_ext\"]\n equip.calib_prev_ext = data[\"calib_prev_ext\"]\n equip.marges_accept_prev_ext = data[\"marges_accept_prev_ext\"]\n equip.desc_prev_int = data[\"desc_prev_int\"]\n equip.periodicitat_prev_int = data[\"periodicitat_prev_int\"]\n equip.marges_accept_prev_int = data[\"marges_accept_prev_int\"]\n equip.desc_verif_int = data[\"desc_verif_int\"]\n equip.periodicitat_verif_int = data[\"periodicitat_verif_int\"]\n equip.marges_accept_verif_int = data[\"marges_accept_verif_int\"]\n equip.calib_desc_int = data[\"calib_desc_int\"]\n equip.calib_periodicitat_int = data[\"calib_periodicitat_int\"]\n equip.calib_marges_accept_int = data[\"calib_marges_accept_int\"]\n equip.motiu_modificacio = data[\"motiu_modificacio\"]\n models.session.commit()\n\n # Generar DOCX i PDF\n path_docx, report_name = utils.create_docx(data)\n utils.create_pdf(path_docx, report_name)\n path_pdf = \"/app/volums_fitxes_tecniques/pdfs/\" + report_name + \".pdf\"\n # path_zip = utils.zip_files(path_docx, path_pdf, report_name)\n\n return send_file(path_pdf, as_attachment=True)\n\n except Exception:\n flash(\"No s'ha creat el pdf, error intern!\", \"warning\")\n return redirect(\"/\")\n\n\n# Afegir equip\n@app.route(\"/form_afegir_equip\")\ndef form_afegir_equip():\n \"\"\"\n Redirecciona a la pagina principal.\n\n :returns: Retorna el html de la pagina principal.\n :rtype: render_template\n \"\"\"\n # Redirecciona al html\n return render_template(\"afegir_equip.html\")\n\n\n# Afegir equip\n@app.route(\"/afegir_equip\", methods=[\"POST\"])\ndef afegir_equip():\n \"\"\"\n Redirecciona a la pagina principal.\n\n :returns: Retorna el html de la pagina principal.\n :rtype: render_template\n \"\"\"\n\n info = {}\n dades = request.form.items()\n for key, value in dades:\n info[key] = value\n\n if info[\"codi_aux\"] == \"\":\n flash(\"Error, el codi_aux es obligatori!\", \"warning\")\n return redirect(\"/form_afegir_equip\")\n\n equip = models.session.query(models.Fitxes).filter(models.Fitxes.codi_aux == info[\"codi_aux\"]).first()\n if equip is not None:\n flash(\"Error, el codi_aux no pot esta repetit!\", \"warning\")\n return redirect(\"/form_afegir_equip\")\n\n try:\n insert = models.Fitxes(\n codi_aux=info[\"codi_aux\"],\n codi_cgc=info[\"codi_cgc\"],\n descripcio=info[\"descripcio\"],\n fabricant=info[\"fabricant\"],\n ref_fabricant=info[\"ref_fabricant\"],\n serial_number=info[\"serial_number\"],\n model=info[\"model\"],\n emp_subministradora=info[\"emp_subministradora\"],\n data_alta=info[\"data_alta\"],\n condicions_equip=info[\"condicions_equip\"],\n data_baixa=info[\"data_baixa\"],\n situacio_contractual=info[\"situacio_contractual\"],\n preu=info[\"preu\"],\n tipus=info[\"tipus\"],\n amplada=info[\"amplada\"],\n alçada=info[\"alçada\"],\n profunditat=info[\"profunditat\"],\n pes=info[\"pes\"],\n condicions_ambientals=info[\"condicions_ambientals\"],\n humitat=info[\"humitat\"],\n presa_aigua=info[\"presa_aigua\"],\n marca_sai=info[\"sai\"],\n cont_comercial=info[\"contacte_comercial\"],\n cont_tecnic=info[\"contacte_tecnic\"],\n observacions=info[\"observacions\"]\n )\n models.session.add(insert)\n models.session.commit()\n flash(\"Afegit correctament\", \"success\")\n return redirect(\"/\")\n except Exception:\n flash(\"Error al afegir\", \"warning\")\n return redirect(\"/form_afegir_equip\")\n\n\n# Historic\n@app.route(\"/historic\")\ndef historic():\n equips = models.session.query(models.Fitxes).filter(models.Fitxes.codi_aux.like('EIM%'),\n models.Fitxes.motiu_modificacio.isnot(None),\n models.Fitxes.motiu_modificacio != '').all()\n\n return render_template(\"historic.html\", equips=equips)\n\n\n# Historic PDF\n@app.route(\"/historic_pdf\", methods=[\"POST\"])\ndef historic_pdf():\n codi_equip = request.form['codi']\n path_pdf = \"/app/volums_fitxes_tecniques/pdfs/\" + codi_equip + \".pdf\"\n return send_file(path_pdf, as_attachment=True)\n\n\n@app.route('/guardar_imagen', methods=['POST'])\ndef guardar_imagen():\n if 'img_' not in request.files:\n pass\n # return jsonify({'success': False, 'message': 'No se proporcionó ninguna imagen'}), 400\n\n imagen = request.files['imagen']\n\n if imagen.filename == '':\n pass\n # return jsonify({'success': False, 'message': 'No se seleccionó ningún archivo'}), 400\n\n if imagen:\n filename = os.path.join(\"/app/volums_fitxes_tecniques/static\", imagen.filename)\n imagen.save(filename)\n # return jsonify({'success': True, 'message': 'Imagen guardada exitosamente', 'imageUrl': filename}), 200\n\n return \"ok\"\n # return jsonify({'success': False, 'message': 'Error al guardar la imagen'}), 500\n\n\n@app.route('/guardar_imagenes_desc', methods=['POST'])\ndef guardar_imagenes_desc():\n imagenes = request.files.getlist('imagenes[]')\n for imagen in imagenes:\n if imagen:\n filename = os.path.join(\"/app/volums_fitxes_tecniques/static\", imagen.filename)\n imagen.save(filename)\n\n return \"ok\"\n\n\n# Route to go Home\n@app.route(\"/home\", methods=[\"POST\", \"GET\"])\ndef home():\n \"\"\"\n Redirects the home page.\n\n :returns: Returns the corresponding html.\n :rtype: redirect\n \"\"\"\n return redirect(\"/\")\n\n\n# Route for logout\n@app.route(\"/logout\")\ndef logout():\n \"\"\"\n Redirects to logout page.\n\n :returns: Returns the corresponding html.\n :rtype: redirect\n \"\"\"\n url = URL_HOME + 'logout'\n return redirect(url)\n\n\n@app.route('/receive_token', methods=[\"POST\", \"GET\"])\ndef receive_token():\n received_token = request.args.get('token')\n secret_key = '12345' # Debe ser la misma clave utilizada para generar el token\n\n try:\n decoded_token = jwt.decode(received_token, secret_key, algorithms=['HS256'])\n session['user'] = decoded_token.get('user_tok', 'Usuario no encontrado')\n session['rols'] = decoded_token.get('rols_tok', 'Usuario no encontrado')\n session['email'] = decoded_token.get('email_tok', 'Usuario no encontrado')\n session['idClient'] = decoded_token.get('id_client_tok', 'Usuario no encontrado')\n session['rol'] = decoded_token.get('rol_tok', 'Usuario no encontrado')\n session['acronim'] = decoded_token.get('rol_tok', 'Usuario no encontrado')\n print(session['user'])\n print(session['rols'])\n print(session['email'])\n print(session['idClient'])\n print(session['rol'])\n print(session['acronim'])\n return redirect('/')\n except Exception:\n return redirect('/logout')\n\n\n@app.route('/apps', methods=[\"POST\", \"GET\"])\ndef apps():\n tocken_cookies = {'user_tok': session['user'], 'rols_tok': session['rols'], 'email_tok': session['email'],\n 'id_client_tok': session['idClient'], 'rol_tok': 'None', 'acronim_tok': session['acronim']}\n secret_key = '12345'\n token = jwt.encode(tocken_cookies, secret_key, algorithm='HS256')\n url = f'{URL_HOME}apps/token?token={token}'\n\n return redirect(url)\n", "repo_name": "GENCARDIO/fitxes_tecniques", "sub_path": "app/routes.py", "file_name": "routes.py", "file_ext": "py", "file_size_in_byte": 14511, "program_lang": "python", "lang": "ca", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "flask.session", "line_number": 16, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 17, "usage_type": "name"}, {"api_name": "config.URL_HOME", "line_number": 18, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 19, "usage_type": "call"}, {"api_name": "functools.wraps", "line_number": 14, "usage_type": "call"}, {"api_name": "app.models.session.query", "line_number": 36, "usage_type": "call"}, {"api_name": "app.models.session", "line_number": 36, "usage_type": "attribute"}, {"api_name": "app.models", "line_number": 36, "usage_type": "name"}, {"api_name": "app.models.Fitxes", "line_number": 36, "usage_type": "attribute"}, {"api_name": "app.models.Fitxes.codi_aux.like", "line_number": 36, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 37, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 27, "usage_type": "call"}, {"api_name": "app.app", "line_number": 27, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 51, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 51, "usage_type": "name"}, {"api_name": "app.models.session.query", "line_number": 52, "usage_type": "call"}, {"api_name": "app.models.session", "line_number": 52, "usage_type": "attribute"}, {"api_name": "app.models", "line_number": 52, "usage_type": "name"}, {"api_name": "app.models.Fitxes", "line_number": 52, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 53, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 56, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 57, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 41, "usage_type": "call"}, {"api_name": "app.app", "line_number": 41, "usage_type": "name"}, {"api_name": "flask.request.form.items", "line_number": 65, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 65, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 65, "usage_type": "name"}, {"api_name": "flask.request.form.getlist", "line_number": 69, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 69, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 69, "usage_type": "name"}, {"api_name": "app.models.session.query", "line_number": 85, "usage_type": "call"}, {"api_name": "app.models.session", "line_number": 85, "usage_type": "attribute"}, {"api_name": "app.models", "line_number": 85, "usage_type": "name"}, {"api_name": "app.models.Fitxes", "line_number": 85, "usage_type": "attribute"}, {"api_name": "app.models.session.commit", "line_number": 196, "usage_type": "call"}, {"api_name": "app.models.session", "line_number": 196, "usage_type": "attribute"}, {"api_name": "app.models", "line_number": 196, "usage_type": "name"}, {"api_name": "app.utils.create_docx", "line_number": 199, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 199, "usage_type": "name"}, {"api_name": "app.utils.create_pdf", "line_number": 200, "usage_type": "call"}, {"api_name": "app.utils", "line_number": 200, "usage_type": "name"}, {"api_name": "flask.send_file", "line_number": 204, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 207, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 208, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 61, "usage_type": "call"}, {"api_name": "app.app", "line_number": 61, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 221, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 212, "usage_type": "call"}, {"api_name": "app.app", "line_number": 212, "usage_type": "name"}, {"api_name": "flask.request.form.items", "line_number": 235, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 235, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 235, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 240, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 241, "usage_type": "call"}, {"api_name": "app.models.session.query", "line_number": 243, "usage_type": "call"}, {"api_name": "app.models.session", "line_number": 243, "usage_type": "attribute"}, {"api_name": "app.models", "line_number": 243, "usage_type": "name"}, {"api_name": "app.models.Fitxes", "line_number": 243, "usage_type": "attribute"}, {"api_name": "flask.flash", "line_number": 245, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 246, "usage_type": "call"}, {"api_name": "app.models.Fitxes", "line_number": 249, "usage_type": "call"}, {"api_name": "app.models", "line_number": 249, "usage_type": "name"}, {"api_name": "app.models.session.add", "line_number": 276, "usage_type": "call"}, {"api_name": "app.models.session", "line_number": 276, "usage_type": "attribute"}, {"api_name": "app.models", "line_number": 276, "usage_type": "name"}, {"api_name": "app.models.session.commit", "line_number": 277, "usage_type": "call"}, {"api_name": "app.models.session", "line_number": 277, "usage_type": "attribute"}, {"api_name": "app.models", "line_number": 277, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 278, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 279, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 281, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 282, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 225, "usage_type": "call"}, {"api_name": "app.app", "line_number": 225, "usage_type": "name"}, {"api_name": "app.models.session.query", "line_number": 288, "usage_type": "call"}, {"api_name": "app.models.session", "line_number": 288, "usage_type": "attribute"}, {"api_name": "app.models", "line_number": 288, "usage_type": "name"}, {"api_name": "app.models.Fitxes", "line_number": 288, "usage_type": "attribute"}, {"api_name": "app.models.Fitxes.codi_aux.like", "line_number": 288, "usage_type": "call"}, {"api_name": "app.models.Fitxes.motiu_modificacio.isnot", "line_number": 289, "usage_type": "call"}, {"api_name": "app.models.Fitxes", "line_number": 289, "usage_type": "attribute"}, {"api_name": "app.models", "line_number": 289, "usage_type": "name"}, {"api_name": "app.models.Fitxes", "line_number": 290, "usage_type": "attribute"}, {"api_name": "app.models", "line_number": 290, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 292, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 286, "usage_type": "call"}, {"api_name": "app.app", "line_number": 286, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 298, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 298, "usage_type": "name"}, {"api_name": "flask.send_file", "line_number": 300, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 296, "usage_type": "call"}, {"api_name": "app.app", "line_number": 296, "usage_type": "name"}, {"api_name": "flask.request.files", "line_number": 305, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 305, "usage_type": "name"}, {"api_name": "flask.request.files", "line_number": 309, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 309, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 316, "usage_type": "call"}, {"api_name": "os.path", "line_number": 316, "usage_type": "attribute"}, {"api_name": "app.app.route", "line_number": 303, "usage_type": "call"}, {"api_name": "app.app", "line_number": 303, "usage_type": "name"}, {"api_name": "flask.request.files.getlist", "line_number": 326, "usage_type": "call"}, {"api_name": "flask.request.files", "line_number": 326, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 326, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 329, "usage_type": "call"}, {"api_name": "os.path", "line_number": 329, "usage_type": "attribute"}, {"api_name": "app.app.route", "line_number": 324, "usage_type": "call"}, {"api_name": "app.app", "line_number": 324, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 344, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 336, "usage_type": "call"}, {"api_name": "app.app", "line_number": 336, "usage_type": "name"}, {"api_name": "config.URL_HOME", "line_number": 356, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 357, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 348, "usage_type": "call"}, {"api_name": "app.app", "line_number": 348, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 362, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 362, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 362, "usage_type": "name"}, {"api_name": "jwt.decode", "line_number": 366, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 367, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 368, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 369, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 370, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 371, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 372, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 373, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 374, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 375, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 376, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 377, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 378, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 379, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 381, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 360, "usage_type": "call"}, {"api_name": "app.app", "line_number": 360, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 386, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 387, "usage_type": "name"}, {"api_name": "jwt.encode", "line_number": 389, "usage_type": "call"}, {"api_name": "config.URL_HOME", "line_number": 390, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 392, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 384, "usage_type": "call"}, {"api_name": "app.app", "line_number": 384, "usage_type": "name"}]} +{"seq_id": "32076871275", "text": "\"\"\"\n200. Number of Islands\nMedium\n\nGiven a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.\n\nExample 1:\n\nInput:\n11110\n11010\n11000\n00000\n\nOutput: 1\n\nExample 2:\n\nInput:\n11000\n11000\n00100\n00011\n\nOutput: 3\n\nmy approach: use BFS to collapse each found island\n11000\n10001\n00000\n00000\n\n00000\n00001 1\n00000\n00000\n\n00000\n00000 2\n00000\n00000\n\"\"\"\n\nfrom typing import List\n\n\nclass Solution:\n def numOfIslands(self, grid: List[List[str]]) -> int:\n if not grid:\n return 0\n\n count = 0\n row = len(grid)\n col = len(grid[0])\n visited = [[False for j in range(col)] for i in range(row)]\n\n def dfs(i: int, j: int):\n if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or visited[i][j] == True or grid[i][j] == '0':\n return # if any of the above are true, we exit the dfs function\n visited[i][j] = True\n dfs(i-1, j)\n dfs(i+1, j)\n dfs(i, j-1)\n dfs(i, j+1)\n\n for i in range(row):\n for j in range(col):\n if grid[i][j] == '1' and not visited[i][j]:\n dfs(i, j)\n count += 1\n\n return count\n\n\ngrid = [[\"1\", \"1\", \"1\", \"1\", \"0\"],\n [\"1\", \"1\", \"0\", \"1\", \"0\"],\n [\"1\", \"1\", \"0\", \"0\", \"0\"],\n [\"0\", \"0\", \"0\", \"0\", \"1\"]]\nsol = Solution()\nprint(sol.numOfIslands(grid))\n\n\n\"\"\"\nclass Solution(object):\n def numIslands(self, grid):\n# \n# : type grid: List[List[str]]\n# : rtype: int\n# \n if not grid: return 0\n r, c = len(grid), len(grid[0])\n visited = [[False for _ in range(c)] for _ in range(r)]\n\n def dfs(i, j):\n if i < 0 or i >= r or j < 0 or j >= c or grid[i][j] == '0' or visited[i][j]:\n return\n visited[i][j] = True\n dfs(i + 1, j)\n dfs(i - 1, j)\n dfs(i, j + 1)\n dfs(i, j - 1)\n\n count = 0\n for i in range(r):\n for j in range(c):\n if not visited[i][j] and grid[i][j] == '1':\n dfs(i, j)\n count += 1\n return count\n\"\"\"\n", "repo_name": "lestgabo/data-structures-and-algorithms", "sub_path": "200 Number of Islands.py", "file_name": "200 Number of Islands.py", "file_ext": "py", "file_size_in_byte": 2320, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "typing.List", "line_number": 48, "usage_type": "name"}]} +{"seq_id": "37601641548", "text": "import wikipedia\nimport pydash as _\n\n\ndef obtain(search_term, category):\n \n try:\n wpage = wikipedia.WikipediaPage(title=search_term)\n except BaseException:\n return None\n \n wimages = wpage.images\n wimages_length = len(wimages)\n if wimages_length <= 6:\n wimages = []\n wimages = _.drop_right(\n wimages,\n wimages_length - 6\n )\n \n return {\n \"metadata\": {\n \"type\": \"wikipedia-information\",\n \"term\": search_term,\n \"category\": category\n },\n \"data\": {\n \"name\": search_term,\n \"description\": wpage.summary,\n \"images\": wimages\n }\n }\n ", "repo_name": "OracleChrome/nlp", "sub_path": "api_wikipedia.py", "file_name": "api_wikipedia.py", "file_ext": "py", "file_size_in_byte": 592, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "48", "api": [{"api_name": "wikipedia.WikipediaPage", "line_number": 8, "usage_type": "call"}, {"api_name": "pydash.drop_right", "line_number": 16, "usage_type": "call"}]} +{"seq_id": "41859075103", "text": "import json\nfrom flask import Flask, request, redirect, render_template, url_for\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef hello(nombre = \"invitado\"):\n try:\n data = json.loads(request.cookies.get('data'))\n except TypeError:\n data = {}\n else:\n nombre = data.get('nombre')\n contexto = {'name':nombre}\n return render_template(\"template2.html\", **contexto)\n\n\n@app.route(\"/suma//\")\n@app.route(\"/suma//\")\n@app.route(\"/suma//\")\n@app.route(\"/suma//\")\ndef suma(num1=0,num2=0):\n contexto = {'num1':num1, 'num2':num2}\n return render_template(\"template1.html\", **contexto)\n\n@app.route(\"/contacto\")\ndef contacto():\n return render_template(\"template_contacto.html\")\n\n@app.route(\"/enviar\", methods=['POST'])\ndef enviar():\n response = redirect(url_for('hello'))\n response.set_cookie(json.dumps(dict(request.form.items())))\n response.set_cookie('data',json.dumps(dict(request.form.items())))\n response.set_cookie('session','session_undefined_value')\n ##return \"Exito\"\n return response\n\nif __name__ == \"__main__\":\n app.run(debug=True)", "repo_name": "josepaul1986/aprendiendo-python", "sub_path": "Flask/app_contacto.py", "file_name": "app_contacto.py", "file_ext": "py", "file_size_in_byte": 1173, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "48", "api": [{"api_name": "flask.Flask", "line_number": 4, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 10, "usage_type": "call"}, {"api_name": "flask.request.cookies.get", "line_number": 10, "usage_type": "call"}, {"api_name": "flask.request.cookies", "line_number": 10, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 10, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 16, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 25, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 29, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 33, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 33, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 34, "usage_type": "call"}, {"api_name": "flask.request.form.items", "line_number": 34, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 34, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 34, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 35, "usage_type": "call"}, {"api_name": "flask.request.form.items", "line_number": 35, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 35, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 35, "usage_type": "name"}]} +{"seq_id": "70304738706", "text": "#!/usr/bin/env python\n# coding: utf-8\nfrom __future__ import print_function\nimport sys\nimport platform\nimport os\nimport subprocess\nimport json\nfrom config_path import ConfigPath # type: ignore\n\nVERSION = '1.0.4'\n\ndefault_config_json = u'''{\n \"folders_to_prune\": [\".svn\", \".git\", \".hg\"],\n \"files_to_prune\": [\"*~\"]\n}\n'''\n\nclass SmartFindError(Exception):\n pass\n\nclass SmartFind:\n '''\n Find goals\n * Simple find is short to type\n * Find . -name => smart-find \n * Find dir1 dir2 => smart-find dir1 dir2 \n * Find new files —since