diff --git "a/1269.jsonl" "b/1269.jsonl" new file mode 100644--- /dev/null +++ "b/1269.jsonl" @@ -0,0 +1,290 @@ +{"seq_id": "32409365405", "text": "#!/usr/bin/env python3\n\nfrom big_query_manager import *\nfrom sql_table_manager import SqlManager\nfrom google.cloud import bigquery\nfrom google.oauth2 import service_account\nimport json\n\nif __name__ == \"__main__\":\n\n with open(\"./bigquery_config.json\") as json_file:\n config = json.load(json_file)\n\n key_path = os.path.abspath(\"./google_api_credentials.json\") \n credentials = service_account.Credentials.from_service_account_file(key_path,\n scopes=[\"https://www.googleapis.com/auth/cloud-platform\"])\n client = bigquery.Client(credentials=credentials,\n project=credentials.project_id)\n\n #Since original table's repository_created_at columns is not of type timestampt it is not queryable\n #So it needs to be cast into timestamp type\n cast_to_timestamp(client= client,\n project_id= config[\"project_id\"],\n dataset_id= config[\"dataset_id\"],\n table_id= config[\"table_id\"],\n target_project_id=config[\"target_project_id\"],\n target_dataset_id=config[\"target_dataset_id\"],\n target_table_id= config[\"target_table_id\"],\n column= config[\"column\"],\n target_column= config[\"target_column\"])\n\n #Sends query qith given date interval and downloads all files from cloud storage\n get_date_range(client= client,\n key_path= key_path,\n project_id= config[\"target_project_id\"],\n dataset_id= config[\"target_dataset_id\"],\n table_id= config[\"target_table_id\"],\n bucket_name= config[\"bucket_name\"],\n from_date= config[\"from_date\"],\n to_date= config[\"to_date\"])\n\n #If you want to quickly check this function u can comment above two functions and run script again\n create_table_str = create_sql_from_table(client= client,\n dataset_id= config[\"target_dataset_id\"],\n table_id= config[\"table_id\"],\n dest_file= config[\"sql_create_script\"])\n\n sqlManager = SqlManager(config_path='./sql_config.json')\n sqlManager.create_database(db_name=config[\"target_table_id\"])\n sqlManager.create_table(create_query=create_table_str)\n #To-do\n # sqlManager.insert_csv_rows(data_dir=\"./github_timeline_test_2009_01_01_2010_12_30\", \n # column_data_path=\"./column_data.json\",\n # table_id=\"github_timeline\")\n ", "repo_name": "alpkarakush/BigQueryToSQL", "sub_path": "export_bigquery_to_googlestorage.py", "file_name": "export_bigquery_to_googlestorage.py", "file_ext": "py", "file_size_in_byte": 2815, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "27", "api": [{"api_name": "json.load", "line_number": 12, "usage_type": "call"}, {"api_name": "google.oauth2.service_account.Credentials.from_service_account_file", "line_number": 15, "usage_type": "call"}, {"api_name": "google.oauth2.service_account.Credentials", "line_number": 15, "usage_type": "attribute"}, {"api_name": "google.oauth2.service_account", "line_number": 15, "usage_type": "name"}, {"api_name": "google.cloud.bigquery.Client", "line_number": 17, "usage_type": "call"}, {"api_name": "google.cloud.bigquery", "line_number": 17, "usage_type": "name"}, {"api_name": "sql_table_manager.SqlManager", "line_number": 48, "usage_type": "call"}]} +{"seq_id": "13397526705", "text": "import os\nimport pandas as pd\nfrom django.http import FileResponse\nimport psycopg2\n\n\ndef index(request):\n DATABASE_URL = os.environ['DATABASE_URL']\n conn = psycopg2.connect(DATABASE_URL)\n cur = conn.cursor()\n cur.execute(\"select date,flightdate,departure,arrival,price from prices;\")\n allEntries = cur.fetchall()\n df = pd.DataFrame(allEntries)\n df.to_excel(\n 'file.xlsx',\n index=False,\n header=['Date', 'Flight Date', 'Departure', 'Arrival', 'Price (BRL)']\n )\n return FileResponse(\n open('file.xlsx', 'rb'),\n as_attachment=True,\n filename='prices.xlsx'\n )\n", "repo_name": "vcalasans/air-ticket-crawler", "sub_path": "views/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 628, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "27", "api": [{"api_name": "os.environ", "line_number": 8, "usage_type": "attribute"}, {"api_name": "psycopg2.connect", "line_number": 9, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 13, "usage_type": "call"}, {"api_name": "django.http.FileResponse", "line_number": 19, "usage_type": "call"}]} +{"seq_id": "21206373620", "text": "import numpy as np\n\ndef freq_to_prob(freq):\n if (freq < 0):\n return round((-freq) / (1 - freq), 5)\n else:\n return round(1 / (1 + freq), 5)\n\n\nimport scipy.stats\ndef mean_confidence_interval(data, confidence=0.95):\n a = 1.0 * np.array(data)\n n = len(a)\n m, se = np.mean(a), scipy.stats.sem(a)\n h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)\n return m, m-h, m+h\n\n\ndef reject_outliers(data, m = 2.):\n d = np.abs(data - np.median(data))\n mdev = np.median(d)\n s = d/mdev if mdev else 0.\n return data[s \"InvoiceFilters\":\n filters = InvoiceFilters(options)\n\n for key in filters.options[\"search\"]:\n seach_term = req.args.get(\"search.\" + key, default=None)\n if seach_term is not None:\n filters.add_search(key, seach_term)\n\n for key in filters.options[\"select\"]:\n selected = req.args.get(\"select.\" + key, default=None)\n if selected is not None and selected in filters.options[\"select\"][key][\"options\"]:\n encoded = filters.options[\"select\"][key][\"options\"][selected]\n filters.add_select(key, encoded)\n\n for key in filters.options[\"date\"]:\n date = req.args.get(\"date.\" + key, default=None)\n if date is not None:\n frm, to, *_ = date.split(\",\")\n filters.add_date(key, frm, to)\n\n for key in filters.options[\"number\"]:\n num = req.args.get(\"number.\" + key, default=None)\n if num is not None:\n frm, to, *_ = num.split(\",\")\n filters.add_number(key, frm, to)\n \n return filters\n \n def to_dict(self):\n if \"paid\" not in self.__data:\n self.add_paid(\"overdue\")\n \n return self.__data\n\n def add_paid(self, paid: str):\n self.__add(\"paid\", paid)\n \n def add_date(self, name, frm, to):\n if frm != \"\":\n self.__add(name + \"-from\", frm)\n if to != \"\":\n self.__add(name + \"-to\", to)\n \n def add_select(self, name, selected):\n self.__add(name, selected)\n\n def add_search(self, name, s):\n self.__add(name, s)\n\n def add_number(self, name, frm, to):\n self.__add(name + \"-toNum\", format_number(to))\n self.__add(name + \"-fromNum\", format_number(frm))\n\n def __add(self, key, value):\n # all filter values are wrapped in an array\n self.__data[key] = [value]\n\n\ndef format_date(date):\n if date is None:\n return \"\"\n\n return date.strftime(\"%d %B %Y\")\n\n\ndef format_number(num):\n if num is None:\n return \"\"\n \n return str(num)\n", "repo_name": "christianscott/formitize-api", "sub_path": "formitize/invoice.py", "file_name": "invoice.py", "file_ext": "py", "file_size_in_byte": 4264, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "enum.Enum", "line_number": 68, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 81, "usage_type": "attribute"}]} +{"seq_id": "20630436545", "text": "# 112. Path Sum\n\nclass TreeNode:\n\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nfrom typing import Optional\nimport collections\n\nclass Solution:\n\n # recursion\n def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n if not root:\n return False\n return self.backtrack(root, targetSum)\n \n\n def backtrack(self, root, target):\n if not root.left and not root.right:\n if root.val == target:\n return True\n return False\n \n if root.left:\n if (self.backtrack(root.left, target - root.val)):\n return True\n \n if root.right:\n if (self.backtrack(root.right, target - root.val)):\n return True\n \n return False\n\n\n '''\n time complexity:\n o(n)\n \n space complexity:\n o(n)\n '''\n\n # iteration\n def hasPathSum_iteration(self, root: Optional[TreeNode], targetSum: int) -> bool:\n if not root:\n return False\n \n queue = collections.deque()\n pathsum = collections.deque()\n \n queue.append(root)\n pathsum.append(root.val)\n\n while queue:\n cur = queue.popleft()\n cursum = pathsum.popleft()\n if not cur.left and not cur.right and cursum == targetSum:\n return True\n if cur.left:\n queue.append(cur.left)\n pathsum.append(cursum + cur.left.val)\n if cur.right:\n queue.append(cur.right)\n pathsum.append(cursum + cur.right.val)\n \n return False\n \n '''\n time complexity:\n o(n)\n \n space complexity:\n o(n)\n '''\n", "repo_name": "Jiashu2000/LeetCode", "sub_path": "Oct27/PathSum.py", "file_name": "PathSum.py", "file_ext": "py", "file_size_in_byte": 1820, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "typing.Optional", "line_number": 16, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 48, "usage_type": "name"}, {"api_name": "collections.deque", "line_number": 52, "usage_type": "call"}, {"api_name": "collections.deque", "line_number": 53, "usage_type": "call"}]} +{"seq_id": "34923721774", "text": "#-*- coding:utf-8 -*-\nfrom selenium import webdriver\n\ndriver = webdriver.Chrome()\n\n\n# 有些弹出对话框窗,我们可以通过判断是否为当前窗口的方式进行操作。\n\n#获得当前窗口\nnowhandle=driver.current_window_handle\n\n#打开弹窗\ndriver.find_element_by_name(\"xxx\").click()\n\n#获得所有窗口\nallhandles=driver.window_handles\nfor handle in allhandles:\n if handle!=nowhandle: #比较当前窗口是不是原先的窗口\n driver.switch_to_window(handle) #获得当前窗口的句柄\n driver.find_element_by_class_name(\"xxxx\").click() #在当前窗口操作\n\n#回到原先的窗口\ndriver.switch_to_window(nowhandle)\n\n\n# 这里只是操作窗口的代码片段, 提供一个思路, 能否完成我们想要的结果, 还需要我们\n# 通过实例去验证。", "repo_name": "Yangle16/Spider", "sub_path": "selenium/17dilog.py", "file_name": "17dilog.py", "file_ext": "py", "file_size_in_byte": 808, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "selenium.webdriver.Chrome", "line_number": 4, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 4, "usage_type": "name"}]} +{"seq_id": "12447800685", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\n\nfrom requests import RequestException, TooManyRedirects\nfrom six.moves.urllib import parse\n\nfrom school_api.check_code import CHECK_CODE\nfrom school_api.client.api.base import BaseSchoolApi\nfrom school_api.client.api.utils import get_alert_tip, get_view_state_from_html\nfrom school_api.exceptions import IdentityException, CheckCodeException, LoginException, \\\n OtherException\nfrom school_api.utils import to_binary, to_text\n\n\nclass Login(BaseSchoolApi):\n ''' 登录模块 '''\n\n def get_login(self, school, **kwargs):\n ''' 登录入口 与 异常处理 '''\n args = (school.login_url, school.exist_verify)\n try:\n res = self._get_api(*args, **kwargs)\n except OtherException as reqe:\n raise LoginException(self.school_code, to_text(str(reqe)))\n\n except RequestException:\n if school.proxies and not self.user.proxy_state:\n # 使用内网代理\n proxy_session = self._switch_proxy()\n if proxy_session:\n # 存在内网代理会话\n return True\n try:\n res = self._get_api(*args, **kwargs)\n except RequestException:\n raise LoginException(self.school_code, '教务系统异常,切用代理登录失败')\n else:\n\n if self.user.proxy_state:\n raise LoginException(self.school_code, '教务系统异常,使用代理登录失败')\n else:\n raise LoginException(self.school_code, '教务系统外网异常')\n\n # 处理登录结果\n try:\n self._handle_login_result(res)\n except CheckCodeException:\n try:\n # 验证码错误时,再次登录\n res = self._get_api(*args, **kwargs)\n except RequestException:\n raise LoginException(self.school_code, '教务系统请求异常')\n else:\n self._handle_login_result(res)\n\n return True\n\n def _handle_login_result(self, res):\n ''' 处理页面弹框信息 '''\n if res is True:\n # 登录成功\n return\n tip = get_alert_tip(res.text)\n if tip:\n if tip == '验证码不正确!!':\n raise CheckCodeException(self.school_code, tip)\n raise IdentityException(self.school_code, tip)\n raise LoginException(self.school_code, '教务系统请求异常')\n\n def _get_login_payload(self, login_url, **kwargs):\n ''' 获取登录页面的 请求参数'''\n try:\n kwargs['timeout'] = 3\n res = self._get(login_url, **kwargs)\n except TooManyRedirects as reqe:\n res = self._get(reqe.response.headers[\"Location\"], **kwargs)\n\n except RequestException:\n # 首次请求可能出现 Connection aborted\n res = self._get(login_url, **kwargs)\n\n url_info = res.url.split(login_url)[0].split('/(')\n if len(url_info) == 2:\n self._update_url_token('/(' + url_info[1])\n\n view_state = get_view_state_from_html(res.text)\n return {'__VIEWSTATE': view_state}\n\n def _get_api(self, login_url, exist_verify, **kwargs):\n # 登录请求\n code = ''\n login_types = ['学生', '教师', '部门']\n login_payload = self._get_login_payload(login_url, **kwargs)\n if exist_verify:\n res = self._get('/CheckCode.aspx')\n if res.content[:7] != to_binary('GIF89aH'):\n raise CheckCodeException(self.school_code, \"验证码获取失败\")\n code = CHECK_CODE.verify(res.content)\n\n account = self.user.account.encode('gb2312')\n payload = {\n 'txtUserName': account,\n 'TextBox1': account,\n 'TextBox2': self.user.password,\n 'TextBox3': code,\n 'txtSecretCode': code,\n 'RadioButtonList1': login_types[self.user.user_type].encode('gb2312'),\n 'Button1': ' 登 录 '.encode('gb2312')\n }\n payload.update(login_payload)\n try:\n res = self._post(login_url, data=payload, **kwargs)\n except TooManyRedirects:\n # 302跳转 代表登录成功\n return True\n return res\n\n def check_session(self):\n \"\"\" 检查登陆会话是否有效 \"\"\"\n account = parse.quote(self.user.account.encode('gb2312'))\n try:\n self._head(self.school_url['HOME_URL'] + account)\n except RequestException:\n return False\n\n return True\n", "repo_name": "dairoot/school-api", "sub_path": "school_api/client/api/login.py", "file_name": "login.py", "file_ext": "py", "file_size_in_byte": 4705, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 199, "dataset": "github-code", "pt": "27", "api": [{"api_name": "school_api.client.api.base.BaseSchoolApi", "line_number": 15, "usage_type": "name"}, {"api_name": "school_api.exceptions.OtherException", "line_number": 23, "usage_type": "name"}, {"api_name": "school_api.exceptions.LoginException", "line_number": 24, "usage_type": "call"}, {"api_name": "school_api.utils.to_text", "line_number": 24, "usage_type": "call"}, {"api_name": "requests.RequestException", "line_number": 26, "usage_type": "name"}, {"api_name": "requests.RequestException", "line_number": 35, "usage_type": "name"}, {"api_name": "school_api.exceptions.LoginException", "line_number": 36, "usage_type": "call"}, {"api_name": "school_api.exceptions.LoginException", "line_number": 40, "usage_type": "call"}, {"api_name": "school_api.exceptions.LoginException", "line_number": 42, "usage_type": "call"}, {"api_name": "school_api.exceptions.CheckCodeException", "line_number": 47, "usage_type": "name"}, {"api_name": "requests.RequestException", "line_number": 51, "usage_type": "name"}, {"api_name": "school_api.exceptions.LoginException", "line_number": 52, "usage_type": "call"}, {"api_name": "school_api.client.api.utils.get_alert_tip", "line_number": 63, "usage_type": "call"}, {"api_name": "school_api.exceptions.CheckCodeException", "line_number": 66, "usage_type": "call"}, {"api_name": "school_api.exceptions.IdentityException", "line_number": 67, "usage_type": "call"}, {"api_name": "school_api.exceptions.LoginException", "line_number": 68, "usage_type": "call"}, {"api_name": "requests.TooManyRedirects", "line_number": 75, "usage_type": "name"}, {"api_name": "requests.RequestException", "line_number": 78, "usage_type": "name"}, {"api_name": "school_api.client.api.utils.get_view_state_from_html", "line_number": 86, "usage_type": "call"}, {"api_name": "school_api.utils.to_binary", "line_number": 96, "usage_type": "call"}, {"api_name": "school_api.exceptions.CheckCodeException", "line_number": 97, "usage_type": "call"}, {"api_name": "school_api.check_code.CHECK_CODE.verify", "line_number": 98, "usage_type": "call"}, {"api_name": "school_api.check_code.CHECK_CODE", "line_number": 98, "usage_type": "name"}, {"api_name": "requests.TooManyRedirects", "line_number": 113, "usage_type": "name"}, {"api_name": "six.moves.urllib.parse.quote", "line_number": 120, "usage_type": "call"}, {"api_name": "six.moves.urllib.parse", "line_number": 120, "usage_type": "name"}, {"api_name": "requests.RequestException", "line_number": 123, "usage_type": "name"}]} +{"seq_id": "4218415490", "text": "import argparse\nimport os\nfrom autoencoder import Autoencoder, soft_relu, matrix_root, normalize\nfrom data_processing import load_data_memory, DATA_PATHS\nfrom bitarray import bitarray\nimport pickle as pkl\nimport numpy as np\nimport json\n\ndef decode_random(ae_path:str,\n random_data_path:str,\n meta_path:str,\n decoded_save_path:str\n ):\n b = Autoencoder(from_saved=True,path=ae_path)\n\n with open(random_data_path,\"rb\") as f:\n data = pkl.load(f)\n\n with open(meta_path,\"rb\") as f:\n mean_b,cov_b = pkl.load(f)\n\n data = normalize(data,(mean_b, cov_b),inverse=True)\n\n decoded = b.decoder.predict(data)\n decoded = np.array(list(map(lambda x: 0 if x <.5 else 1, decoded.flatten()))).reshape(decoded.shape)\n decoded_ba = [bitarray(list(x)) for x in decoded]\n with open(decoded_save_path,\"wb\") as f:\n pkl.dump(decoded_ba,f)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-cf\", type=str, default=\"config.json\", help=\"configuration file path\")\n args = parser.parse_args()\n\n config = json.load(open(args.cf))\n os.chdir(args.cf.rstrip(\".json\"))\n decode_random(config[\"autoencoder\"][\"save_path_b\"],\n config[\"linking\"][\"random_data_path\"],\n config[\"encoder\"][\"path_meta_b\"],\n config[\"linking\"][\"decoded_data_path\"])\n", "repo_name": "vicolinho/pprl_autoencoder", "sub_path": "src/encode_scripts/b_encoding_mapper.py", "file_name": "b_encoding_mapper.py", "file_ext": "py", "file_size_in_byte": 1420, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "27", "api": [{"api_name": "autoencoder.Autoencoder", "line_number": 15, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 18, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 21, "usage_type": "call"}, {"api_name": "autoencoder.normalize", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 26, "usage_type": "call"}, {"api_name": "bitarray.bitarray", "line_number": 27, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 29, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 33, "usage_type": "call"}, {"api_name": "json.load", "line_number": 37, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 38, "usage_type": "call"}]} +{"seq_id": "17655603207", "text": "from collections import defaultdict\n\n\nclass Solution(object):\n def subarraySum(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n\n sumCounter = defaultdict(int)\n sumCounter[0] = 1\n count = 0\n\n sum = 0\n for num in nums:\n\n sum += num\n if sum - k in sumCounter:\n count += (sumCounter[sum - k])\n sumCounter[sum] += 1\n\n return count\n", "repo_name": "aliahsan07/daily-leetcode", "sub_path": "560. Subarray sums equal K/solution.py", "file_name": "solution.py", "file_ext": "py", "file_size_in_byte": 482, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "27", "api": [{"api_name": "collections.defaultdict", "line_number": 12, "usage_type": "call"}]} +{"seq_id": "14621848002", "text": "import os\nfrom glob import glob\nfrom setuptools import setup\n\npackage_name = 'AutoFollowCar'\n\nsetup(\n name=package_name,\n version='0.0.0',\n packages=[package_name],\n data_files=[\n ('share/ament_index/resource_index/packages',\n ['resource/' + package_name]),\n\n ('share/' + package_name, ['package.xml']),\n\n (os.path.join('share', package_name),\n glob('launch/*launch.[pxy][yma]*'))\n ],\n install_requires=['setuptools'],\n zip_safe=True,\n maintainer='be105',\n maintainer_email='bensonw830@gmail.com',\n description='Beginner client libraries tutorials practice package',\n license='Apache License 2.0',\n tests_require=['pytest'],\n entry_points={\n 'console_scripts': [\n 'drive = AutoFollowCar.drive:main',\n 'get_jetson_info = AutoFollowCar.get_jetson_info:main',\n 'operation = AutoFollowCar.operation:main',\n 'test = AutoFollowCar.test:main',\n 'talker = AutoFollowCar.publisher_member_function:main',\n 'listener = AutoFollowCar.subscriber_member_function:main',\n ],\n },\n)\n", "repo_name": "bnb70/AutoFollowCar", "sub_path": "rpi4/rpi4_ros2_ws/src/AutoFollowCar/setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 1128, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "setuptools.setup", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 18, "usage_type": "call"}]} +{"seq_id": "28775070594", "text": "from ooo.oenv.env_const import UNO_NONE\nfrom .drop_target_drag_event import DropTargetDragEvent as DropTargetDragEvent_d60612e7\nfrom ...uno.x_interface import XInterface as XInterface_8f010a43\nfrom .x_drop_target_drag_context import XDropTargetDragContext as XDropTargetDragContext_10221422\nimport typing\nfrom ..data_flavor import DataFlavor as DataFlavor_ffd30deb\n\n\nclass DropTargetDragEnterEvent(DropTargetDragEvent_d60612e7):\n \"\"\"\n Struct Class\n\n The DropTargetDragEnterEvent is delivered from the drop target to the currently registered drop target listeners whenever the logical cursor associated with a Drag and Drop operation enters the visible geometry of a window associated with a drop target.\n \n It contains the com.sun.star.datatransfer.DataFlavor types supported by the transferable object of the current Drag and Drop operation.\n\n See Also:\n `API DropTargetDragEnterEvent `_\n \"\"\"\n __ooo_ns__: str = 'com.sun.star.datatransfer.dnd'\n __ooo_full_ns__: str = 'com.sun.star.datatransfer.dnd.DropTargetDragEnterEvent'\n __ooo_type_name__: str = 'struct'\n typeName: str = 'com.sun.star.datatransfer.dnd.DropTargetDragEnterEvent'\n \"\"\"Literal Constant ``com.sun.star.datatransfer.dnd.DropTargetDragEnterEvent``\"\"\"\n\n def __init__(self, Source: typing.Optional[XInterface_8f010a43] = None, Dummy: typing.Optional[int] = 0, Context: typing.Optional[XDropTargetDragContext_10221422] = None, DropAction: typing.Optional[int] = 0, LocationX: typing.Optional[int] = 0, LocationY: typing.Optional[int] = 0, SourceActions: typing.Optional[int] = 0, SupportedDataFlavors: typing.Optional[typing.Tuple[DataFlavor_ffd30deb, ...]] = ()) -> None:\n \"\"\"\n Constructor\n\n Arguments:\n Source (XInterface, optional): Source value.\n Dummy (int, optional): Dummy value.\n Context (XDropTargetDragContext, optional): Context value.\n DropAction (int, optional): DropAction value.\n LocationX (int, optional): LocationX value.\n LocationY (int, optional): LocationY value.\n SourceActions (int, optional): SourceActions value.\n SupportedDataFlavors (typing.Tuple[DataFlavor, ...], optional): SupportedDataFlavors value.\n \"\"\"\n\n if isinstance(Source, DropTargetDragEnterEvent):\n oth: DropTargetDragEnterEvent = Source\n self.Source = oth.Source\n self.Dummy = oth.Dummy\n self.Context = oth.Context\n self.DropAction = oth.DropAction\n self.LocationX = oth.LocationX\n self.LocationY = oth.LocationY\n self.SourceActions = oth.SourceActions\n self.SupportedDataFlavors = oth.SupportedDataFlavors\n return\n\n kargs = {\n \"Source\": Source,\n \"Dummy\": Dummy,\n \"Context\": Context,\n \"DropAction\": DropAction,\n \"LocationX\": LocationX,\n \"LocationY\": LocationY,\n \"SourceActions\": SourceActions,\n \"SupportedDataFlavors\": SupportedDataFlavors,\n }\n self._init(**kargs)\n\n def _init(self, **kwargs) -> None:\n self._supported_data_flavors = kwargs[\"SupportedDataFlavors\"]\n inst_keys = ('SupportedDataFlavors',)\n kargs = kwargs.copy()\n for key in inst_keys:\n del kargs[key]\n super()._init(**kargs)\n\n\n @property\n def SupportedDataFlavors(self) -> typing.Tuple[DataFlavor_ffd30deb, ...]:\n \"\"\"\n A sequence of supported com.sun.star.datatransfer.DataFlavor types.\n \"\"\"\n return self._supported_data_flavors\n\n @SupportedDataFlavors.setter\n def SupportedDataFlavors(self, value: typing.Tuple[DataFlavor_ffd30deb, ...]) -> None:\n self._supported_data_flavors = value\n\n\n__all__ = ['DropTargetDragEnterEvent']\n", "repo_name": "Amourspirit/python-ooouno", "sub_path": "ooo/lo/datatransfer/dnd/drop_target_drag_enter_event.py", "file_name": "drop_target_drag_enter_event.py", "file_ext": "py", "file_size_in_byte": 3952, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "27", "api": [{"api_name": "drop_target_drag_event.DropTargetDragEvent", "line_number": 9, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 26, "usage_type": "attribute"}, {"api_name": "uno.x_interface.XInterface", "line_number": 26, "usage_type": "name"}, {"api_name": "x_drop_target_drag_context.XDropTargetDragContext", "line_number": 26, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 26, "usage_type": "attribute"}, {"api_name": "data_flavor.DataFlavor", "line_number": 26, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 75, "usage_type": "attribute"}, {"api_name": "data_flavor.DataFlavor", "line_number": 75, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 82, "usage_type": "attribute"}, {"api_name": "data_flavor.DataFlavor", "line_number": 82, "usage_type": "name"}]} +{"seq_id": "16343192453", "text": "\"\"\"\n@Author: Kasugano Sora\n@Github: https://github.com/jiangyuxiaoxiao\n@Date: 2023/09/27-10:34\n@Desc: BertVits2封装\n@Ver : 1.0.0\n\"\"\"\nimport aiohttp\nimport asyncio\nimport aiofiles\nfrom Hiyori.Utils.API.BertVits.config import bertVitsConfig\nfrom Hiyori.Utils.API.Baidu.OpenTranslate import Translate\n\n\ndef getBV_Map() -> dict:\n \"\"\"获取角色名——(model_id,chr_id)映射\"\"\"\n chrDict: dict[str, dict[str, int]] = dict()\n for index, model in enumerate(bertVitsConfig.models):\n for name, cid in model[\"spk2id\"].items():\n chrDict[name] = {\n \"mid\": index,\n \"cid\": cid\n }\n return chrDict\n\n\ndef getModelsConfig() -> list:\n return bertVitsConfig.models\n\n\nasync def getVoice(text: str, model: int | str, character: int | str, sdp_ratio: float = 0.2,\n noise: float = 0.2, noisew: float = 0.9,\n length: float = 1.0, url=None) -> bytes | None:\n \"\"\"\n 获取bertVits语音(TTS)\n\n :param text: 待转换文本\n :param model: 当为int时为模型索引id,当为str时为模型名\n :param character: 当为int时为角色索引id,当为str时为角色名\n :param sdp_ratio:\n :param noise:\n :param noisew:\n :param length:\n :param url: 临时的url\n :return: 音频字节\n \"\"\"\n if url is None:\n url = f\"{bertVitsConfig.host}:{bertVitsConfig.port}/voice\"\n bv_model = None\n model_id = 0\n if isinstance(model, int):\n model_id = model\n if model_id >= len(bertVitsConfig.models):\n # 无效模型\n return None\n bv_model = bertVitsConfig.models[model_id]\n elif isinstance(model, str):\n for index, m in enumerate(bertVitsConfig.models):\n if model in m[\"names\"]:\n bv_model = m\n model_id = index\n break\n if bv_model is None:\n return None\n else:\n raise TypeError(\"model should be a str or int value\")\n\n if isinstance(character, int):\n chr_id = character\n elif isinstance(character, str):\n if character not in bv_model[\"spk2id\"].keys():\n return None\n chr_id = bv_model[\"spk2id\"][character]\n else:\n raise TypeError(\"character should be a str or int value\")\n\n # 检查是否需要翻译\n if \"trans\" in bv_model:\n trans = bv_model[\"trans\"]\n texts = text.split(\"\\n\")\n outs = []\n for t in texts:\n if t != \"\":\n out = await Translate(Sentence=t, to_Language=trans)\n outs.append(out)\n else:\n outs.append(t)\n text = \"\\n\".join(outs)\n\n params = {\n \"model_id\": model_id,\n \"chr_id\": chr_id,\n \"text\": text,\n \"sdp_ratio\": sdp_ratio,\n \"noise\": noise,\n \"noisew\": noisew,\n \"length\": length\n }\n async with aiohttp.ClientSession() as session:\n async with session.get(url, params=params) as response:\n if response.status == 200:\n response = await response.read()\n return response\n return None\n\n\nasync def saveVoice(savePath: str, text: str, model: int | str, chr: int | str, sdp_ratio: float = 0.2,\n noise: float = 0.2, noisew: float = 0.9,\n length: float = 1.0) -> bool:\n \"\"\"保存音频文件至本地\"\"\"\n audio = await getVoice(text, model, chr, sdp_ratio, noise, noisew, length)\n if audio is None:\n return False\n async with aiofiles.open(savePath, 'wb') as f:\n await f.write(audio)\n return True\n\n\nif __name__ == '__main__':\n asyncio.run(saveVoice(\"Data/Test/1.wav\", \"\",\n 1, \"顾真真\"))\n", "repo_name": "jiangyuxiaoxiao/Hiyori", "sub_path": "Hiyori/Utils/API/BertVits/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 3714, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 23, "dataset": "github-code", "pt": "27", "api": [{"api_name": "Hiyori.Utils.API.BertVits.config.bertVitsConfig.models", "line_number": 18, "usage_type": "attribute"}, {"api_name": "Hiyori.Utils.API.BertVits.config.bertVitsConfig", "line_number": 18, "usage_type": "name"}, {"api_name": "Hiyori.Utils.API.BertVits.config.bertVitsConfig.models", "line_number": 28, "usage_type": "attribute"}, {"api_name": "Hiyori.Utils.API.BertVits.config.bertVitsConfig", "line_number": 28, "usage_type": "name"}, {"api_name": "Hiyori.Utils.API.BertVits.config.bertVitsConfig.host", "line_number": 48, "usage_type": "attribute"}, {"api_name": "Hiyori.Utils.API.BertVits.config.bertVitsConfig", "line_number": 48, "usage_type": "name"}, {"api_name": "Hiyori.Utils.API.BertVits.config.bertVitsConfig.port", "line_number": 48, "usage_type": "attribute"}, {"api_name": "Hiyori.Utils.API.BertVits.config.bertVitsConfig.models", "line_number": 53, "usage_type": "attribute"}, {"api_name": "Hiyori.Utils.API.BertVits.config.bertVitsConfig", "line_number": 53, "usage_type": "name"}, {"api_name": "Hiyori.Utils.API.BertVits.config.bertVitsConfig.models", "line_number": 56, "usage_type": "attribute"}, {"api_name": "Hiyori.Utils.API.BertVits.config.bertVitsConfig", "line_number": 56, "usage_type": "name"}, {"api_name": "Hiyori.Utils.API.BertVits.config.bertVitsConfig.models", "line_number": 58, "usage_type": "attribute"}, {"api_name": "Hiyori.Utils.API.BertVits.config.bertVitsConfig", "line_number": 58, "usage_type": "name"}, {"api_name": "Hiyori.Utils.API.Baidu.OpenTranslate.Translate", "line_number": 84, "usage_type": "call"}, {"api_name": "aiohttp.ClientSession", "line_number": 99, "usage_type": "call"}, {"api_name": "aiofiles.open", "line_number": 114, "usage_type": "call"}, {"api_name": "asyncio.run", "line_number": 120, "usage_type": "call"}]} +{"seq_id": "26842560967", "text": "import sys\nimport os\nfrom datetime import timedelta, datetime\n\nfrom kivy.core.audio import Sound\nfrom kivy.core.window import window_sdl2 # noqa\nimport pytest\n\n\ndef start(animation, widget):\n animation.dispatch('on_start', widget)\n\n for proprety_name, value in animation.animated_properties.items():\n setattr(widget, proprety_name, value)\n animation.dispatch('on_complete', widget)\n\n\n@staticmethod\ndef load(name):\n return Sound()\n\n\n@pytest.fixture(autouse=True)\ndef patch_env(request, monkeypatch):\n test_name = request._pyfuncitem.name\n try:\n import settings\n\n reload(settings)\n from configure import configure\n settings.KIVY_GRAPHICS_WIDTH = 1\n settings.KIVY_GRAPHICS_HEIGHT = 1\n configure()\n settings.DATABASE_NAME = \"test-%s-db.sqlite3\" % test_name\n settings.DATABASE_PATH = os.path.join(settings.PROJECT_DIR, settings.DATABASE_NAME)\n\n # try to import module overriding\n module_overrides = getattr(request.module, \"SETTINGS_OVERRIDE\", {})\n for option_name, option_value in module_overrides.items():\n setattr(settings, option_name, option_value)\n\n from kivy.config import ConfigParser\n ConfigParser._named_configs = {}\n\n # apply overriding from the function itself\n if hasattr(request.function, 'settings'):\n function_overrides = request.function.settings\n for option_name, option_value in function_overrides.items():\n setattr(settings, option_name, option_value)\n sys.modules[\"settings\"] = settings\n\n monkeypatch.setattr('kivy.animation.Animation.start', start)\n monkeypatch.setattr('kivy.clock.Clock.create_trigger', lambda c, t=None: c)\n monkeypatch.setattr('kivy.core.audio.SoundLoader.load', load)\n\n def fin():\n from managers.database import database_manager\n\n if database_manager._connection:\n database_manager._connection.close()\n database_manager._connection = None\n if os.path.exists(\"test-%s-db.sqlite3\" % test_name):\n os.remove(\"test-%s-db.sqlite3\" % test_name)\n\n if os.path.exists(\"kognitivo-test-%s.ini\" % test_name):\n os.remove(\"kognitivo-test-%s.ini\" % test_name)\n\n request.addfinalizer(fin)\n except:\n if os.path.exists(\"test-%s-db.sqlite3\" % test_name):\n os.remove(\"test-%s-db.sqlite3\" % test_name)\n\n if os.path.exists(\"kognitivo-test-%s.ini\" % test_name):\n os.remove(\"kognitivo-test-%s.ini\" % test_name)\n raise\n\n\n@pytest.fixture(params=[\n \"en\", \"es\", \"ru\", \"de\", \"ua\"\n], ids=[\n \"en_lang\", \"es_lang\", \"ru_lang\", \"de_lang\", \"ua_lang\"\n])\ndef app(request):\n from main import KognitivoApp\n\n test_name = request._pyfuncitem.name\n application = KognitivoApp(name=\"kognitivo-test-%s\" % test_name)\n application.lang = request.param\n from utils import _\n _.switch_lang(application.lang)\n\n def fin():\n if os.path.exists(application.storage.filename):\n os.remove(application.storage.filename)\n\n request.addfinalizer(fin)\n return application\n\n\n@pytest.fixture\ndef running_app(monkeypatch, app):\n @staticmethod\n def get_running_app(**kwargs):\n if not app.manager:\n from root_manager import RootManager\n\n app.manager = RootManager()\n from kivy.base import EventLoop\n\n window = EventLoop.window\n app._app_window = window\n window.children = []\n\n if not app.config:\n app.load_config()\n return app\n\n monkeypatch.setattr('kivy.base.runTouchApp', lambda: None)\n\n monkeypatch.setattr('kivy.app.App.get_running_app', get_running_app)\n from kivy.app import App\n\n return App.get_running_app()\n\n\n@pytest.fixture\ndef root_manager(running_app):\n return running_app.manager\n\n\n@pytest.fixture\ndef navigation(running_app):\n return running_app.root\n\n\n@pytest.fixture\ndef empty_data(monkeypatch):\n monkeypatch.setattr('managers.database.database_manager.day_percents', lambda *args, **kwargs: {})\n monkeypatch.setattr('managers.database.database_manager.hour_percents', lambda *args, **kwargs: {})\n monkeypatch.setattr('managers.database.database_manager.recent_percents', lambda *args, **kwargs: {})\n\n\n@pytest.fixture\ndef not_empty_data(monkeypatch):\n monkeypatch.setattr('managers.database.database_manager.hour_percents',\n lambda *args, **kwargs: {key: 1.0 for key in range(24)})\n monkeypatch.setattr('managers.database.database_manager.day_percents',\n lambda *args, **kwargs: {key: 1.0 for key in range(7)})\n monkeypatch.setattr('managers.database.database_manager.recent_percents',\n lambda *args, **kwargs: {(datetime.now() - timedelta(days=key)).date(): 1.0 for key in\n range(7)})\n\n\n@pytest.fixture\ndef webbrowser(mocker):\n mock_webbrowser_open = mocker.patch('webbrowser.open')\n return mock_webbrowser_open\n\n\n@pytest.fixture\ndef tracker(mocker, running_app):\n mocker.spy(running_app.tracker, 'send_event')\n return running_app.tracker\n\n\n@pytest.fixture\ndef google_client(mocker, running_app):\n mocker.spy(running_app.google_client, 'increment_achievement')\n mocker.spy(running_app.google_client, 'unlock_achievement')\n mocker.spy(running_app.google_client, 'submit_score')\n return running_app.google_client\n\n\n@pytest.fixture\ndef vibrator(mocker):\n from managers.vibration import vibration_manager\n mocker.spy(vibration_manager, 'vibrate')\n return vibration_manager\n\n\n@pytest.fixture\ndef storage(running_app):\n return running_app.storage\n\n\n@pytest.fixture\ndef billing(running_app, mocker):\n running_app.initialize_billing()\n mocker.spy(running_app.billing, 'buy')\n return running_app.billing\n\n\n@pytest.fixture\ndef billing_no_connection(running_app, monkeypatch):\n running_app.initialize_billing()\n monkeypatch.setattr('billing.BillingService.get_available_items', lambda *args, **kwargs: [])\n return running_app.billing\n", "repo_name": "thorin-schiffer/kognitivo", "sub_path": "tests/conftest.py", "file_name": "conftest.py", "file_ext": "py", "file_size_in_byte": 6149, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 77, "dataset": "github-code", "pt": "27", "api": [{"api_name": "kivy.core.audio.Sound", "line_number": 20, "usage_type": "call"}, {"api_name": "settings.KIVY_GRAPHICS_WIDTH", "line_number": 31, "usage_type": "attribute"}, {"api_name": "settings.KIVY_GRAPHICS_HEIGHT", "line_number": 32, "usage_type": "attribute"}, {"api_name": "configure.configure", "line_number": 33, "usage_type": "call"}, {"api_name": "settings.DATABASE_NAME", "line_number": 34, "usage_type": "attribute"}, {"api_name": "settings.DATABASE_PATH", "line_number": 35, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "settings.PROJECT_DIR", "line_number": 35, "usage_type": "attribute"}, {"api_name": "settings.DATABASE_NAME", "line_number": 35, "usage_type": "attribute"}, {"api_name": "kivy.config.ConfigParser._named_configs", "line_number": 43, "usage_type": "attribute"}, {"api_name": "kivy.config.ConfigParser", "line_number": 43, "usage_type": "name"}, {"api_name": "sys.modules", "line_number": 50, "usage_type": "attribute"}, {"api_name": "managers.database.database_manager._connection", "line_number": 59, "usage_type": "attribute"}, {"api_name": "managers.database.database_manager", "line_number": 59, "usage_type": "name"}, {"api_name": "managers.database.database_manager._connection.close", "line_number": 60, "usage_type": "call"}, {"api_name": "managers.database.database_manager._connection", "line_number": 60, "usage_type": "attribute"}, {"api_name": "managers.database.database_manager", "line_number": 60, "usage_type": "name"}, {"api_name": "managers.database.database_manager._connection", "line_number": 61, "usage_type": "attribute"}, {"api_name": "managers.database.database_manager", "line_number": 61, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path", "line_number": 62, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 63, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 70, "usage_type": "call"}, {"api_name": "os.path", "line_number": 70, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 71, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path", "line_number": 73, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 74, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 23, "usage_type": "call"}, {"api_name": "main.KognitivoApp", "line_number": 87, "usage_type": "call"}, {"api_name": "utils._.switch_lang", "line_number": 90, "usage_type": "call"}, {"api_name": "utils._", "line_number": 90, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 93, "usage_type": "call"}, {"api_name": "os.path", "line_number": 93, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 94, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 78, "usage_type": "call"}, {"api_name": "root_manager.RootManager", "line_number": 107, "usage_type": "call"}, {"api_name": "kivy.base.EventLoop.window", "line_number": 110, "usage_type": "attribute"}, {"api_name": "kivy.base.EventLoop", "line_number": 110, "usage_type": "name"}, {"api_name": "kivy.app.App.get_running_app", "line_number": 123, "usage_type": "call"}, {"api_name": "kivy.app.App", "line_number": 123, "usage_type": "name"}, {"api_name": "pytest.fixture", "line_number": 100, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 126, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 131, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 136, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 150, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 150, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 150, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 143, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 154, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 160, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 166, "usage_type": "attribute"}, {"api_name": "managers.vibration.vibration_manager", "line_number": 177, "usage_type": "argument"}, {"api_name": "managers.vibration.vibration_manager", "line_number": 178, "usage_type": "name"}, {"api_name": "pytest.fixture", "line_number": 174, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 181, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 186, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 193, "usage_type": "attribute"}]} +{"seq_id": "71329012552", "text": "import matplotlib.pyplot as plt\nimport random\n\nfrom modu.template import ChangedTemperaturesOnMyBirthday\nfrom modu.template.basic_hist import highest_temperature\n\ndef sorted_random_arr()-> []:\n arr = []\n [arr.append(random.randint(1, 1000)) for i in range(13)]\n return arr\n\ndef show_boxplot(arr:[]):\n plt.boxplot(arr)\n plt.show()\n\ndef show_boxplot_month(month:str):\n plt.boxplot(highest_temperature(month))\n plt.show()\ndef show_boxplot_all_month():\n birth = ChangedTemperaturesOnMyBirthday()\n birth.read_data()\n data = birth.data\n\n #monthls =[]\n #month1 = []\n month = [[],[],[],[],[],[],[],[],[],[],[],[]]\n #for row in data:\n # if row[-1] !='':\n # month[int(row[0].split('-')[1])-1].append(float(row[-1]))\n #print(len(month))\n #print(month)\n #[[month1[int(row[0].split('-')[1]) - 1].append(float(row[-1])) for row in data if row[-1] != ''] for i in range(12)]\n #month = []\n [[month[int(row[0].split('-')[1])-1].append(float(row[-1])) for row in data if row[-1] !=''] for i in range(12)]\n #print(month[4])\n #print(len(month))\n return month\n\ndef show_boxplot_per_date(month : str):\n birth = ChangedTemperaturesOnMyBirthday()\n birth.read_data()\n data = birth.data\n day =[]\n [day.append([]) for i in range(31)]\n [day[int(i[0].split('-')[2])-1].append(float(i[-1])) for i in data if i[-1] !='' if i[0].split('-')[1]==month]\n plt.style.use('ggplot')\n plt.figure(figsize=(10,5),dpi=300)\n plt.boxplot(day, showfliers=False)\n plt.show()\n\nif __name__ == '__main__':\n #highest_temperature_boxplot(arr=highest_temperature(month='08'))\n #show_boxplot_all_month()\n #show_boxplot(show_boxplot_all_month())\n show_boxplot_per_date('08')", "repo_name": "YoonHyunSung/Bitcamp_Python", "sub_path": "modu/template/basic_boxplot.py", "file_name": "basic_boxplot.py", "file_ext": "py", "file_size_in_byte": 1743, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "random.randint", "line_number": 9, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.boxplot", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 13, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 14, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 14, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.boxplot", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 17, "usage_type": "name"}, {"api_name": "modu.template.basic_hist.highest_temperature", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "modu.template.ChangedTemperaturesOnMyBirthday", "line_number": 20, "usage_type": "call"}, {"api_name": "modu.template.ChangedTemperaturesOnMyBirthday", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style.use", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 46, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.boxplot", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 48, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}]} +{"seq_id": "71843048393", "text": "from __future__ import division\n\nimport torch\nimport numpy as np\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\n\nfrom dataset import ResDataset\nfrom smodule import SmallNet\nfrom utils import *\n\nimport argparse\n\nimport pdb\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--epochs\", type=int, default=200, help=\"number of epochs\")\n parser.add_argument(\"--lr\", type=float, default=0.00001, help=\"learning rate is a optimizer's paramenter\")\n parser.add_argument(\"--momentum\", type=float, default=0.9, help=\"momentum factor is a optimizer's paramenter\")\n parser.add_argument(\"--weight_decay\", type=float, default=1e-3, help=\"over fitting decay paramenter\")\n parser.add_argument(\"--batch_size\", type=int, default=4, help=\"number of a echo train's pictures\")\n parser.add_argument(\"--n_cpu\", type=int, default=4, help=\"number of cup\")\n parser.add_argument(\"--checkpoint_interval\", type=int, default=1, help=\"interval between saving model weights\")\n parser.add_argument(\"--gpu_id\", type=int, default=0, help=\"The id of gup\")\n opt = parser.parse_args()\n print(opt)\n\n torch.cuda.set_device(opt.gpu_id)\n fp = open(\"./print_loss.txt\", \"w\")\n\n \n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n net = SmallNet()\n net.float().to(device)\n net.apply(weights_init_normal)\n \n dataset = ResDataset()\n dataLoader = DataLoader(dataset,\n opt.batch_size,\n shuffle=True,\n num_workers=opt.n_cpu,\n pin_memory=True,\n )\n\n optimizer = optim.Adam(net.parameters(),lr=opt.lr)\n \n '''\n optimizer = optim.SGD(net.parameters(),\n lr=opt.lr,\n momentum=opt.momentum,\n weight_decay=opt.weight_decay,\n )\n '''\n\n criterion = nn.CrossEntropyLoss()\n\n for epoch in range(opt.epochs):\n net.train()\n for i, (img, label, oth) in enumerate(dataLoader):\n img, label = Variable(img).to(device), Variable(label).to(device)\n oth = Variable(oth).to(device)\n\n output = net(img, oth)\n loss = criterion(output, label.long())\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n fp.write('[ Epoch {:005d} -> {:005d}] loss : {:15}\\n'.format(\n epoch+1,\n (i+1) * opt.batch_size,\n loss.cpu().data.numpy()))\n fp.flush()\n\n if epoch % opt.checkpoint_interval == 0:\n torch.save(net.state_dict(), f\"checkpoints/smallNet_ckpt_%d.pth\" % epoch)\n \n", "repo_name": "mkln0/MCM", "sub_path": "train.py", "file_name": "train.py", "file_ext": "py", "file_size_in_byte": 2820, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.cuda.set_device", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 31, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 35, "usage_type": "attribute"}, {"api_name": "smodule.SmallNet", "line_number": 37, "usage_type": "call"}, {"api_name": "dataset.ResDataset", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 49, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 49, "usage_type": "name"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 59, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 59, "usage_type": "name"}, {"api_name": "torch.autograd.Variable", "line_number": 64, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 80, "usage_type": "call"}]} +{"seq_id": "9882269756", "text": "from collections import deque\r\n\r\n\r\nclass BinaryTree:\r\n\r\n\tdef __init__(self, rootObj):\r\n\t\tself.key = rootObj\r\n\t\tself.leftChild = None\r\n\t\tself.rightChild = None\r\n\r\n\tdef insertLeft(self, newNode):\r\n\t\tif self.leftChild == None:\r\n\t\t\tself.leftChild = BinaryTree(newNode)\r\n\t\telse:\r\n\t\t\tt = BinaryTree(newNode)\r\n\t\t\tt.leftChild = self.leftChild\r\n\t\t\tself.leftChild = t\r\n\r\n\tdef insertRight(self, newNode):\r\n\t\tif self.rightChild == None:\r\n\t\t\tself.rightChild = BinaryTree(newNode)\r\n\t\telse:\r\n\t\t\tt = BinaryTree(newNode)\r\n\t\t\tt.rightChild = self.rightChild\r\n\t\t\tself.rightChild = t\r\n\r\n\tdef get_leaves(self):\r\n\t\tif self.leftChild == None and self.rightChild == None:\r\n\t\t\treturn [self.key]\r\n\t\tif self.leftChild == None:\r\n\t\t\treturn self.rightChild.get_leaves()\r\n\t\tif self.rightChild == None:\r\n\t\t\treturn self.leftChild.get_leaves()\r\n\t\treturn self.leftChild.get_leaves() + self.rightChild.get_leaves()\r\n\r\n\tdef preorder(self):\r\n\t\t'''\r\n\t\tRoot -> Left -> Right\r\n\t\t'''\r\n\t\tif self.leftChild == None and self.rightChild == None:\r\n\t\t\treturn [self.key]\r\n\t\tif self.leftChild == None:\r\n\t\t\treturn [self.key] + self.rightChild.preorder()\r\n\t\tif self.rightChild == None:\r\n\t\t\treturn [self.key] + self.leftChild.preorder()\r\n\t\treturn [self.key] + self.leftChild.preorder() + self.rightChild.preorder()\r\n\r\n\tdef inorder(self):\r\n\t\t'''\r\n\t\tLeft -> Root -> Right\r\n\t\t'''\r\n\t\tif self.leftChild == None and self.rightChild == None:\r\n\t\t\treturn [self.key]\r\n\t\tif self.leftChild == None:\r\n\t\t\treturn [self.key] + self.rightChild.inorder()\r\n\t\tif self.rightChild == None:\r\n\t\t\treturn self.leftChild.inorder() + [self.key]\r\n\t\treturn self.leftChild.inorder() + [self.key] + self.rightChild.inorder()\r\n\r\n\tdef postorder(self):\r\n\t\t'''\r\n\t\tLeft -> Right -> Root\r\n\t\t'''\r\n\t\tif self.leftChild == None and self.rightChild == None:\r\n\t\t\treturn [self.key]\r\n\t\tif self.leftChild == None:\r\n\t\t\treturn self.rightChild.postorder() + [self.key]\r\n\t\tif self.rightChild == None:\r\n\t\t\treturn self.leftChild.postorder() + [self.key]\r\n\t\treturn self.leftChild.postorder() + self.rightChild.postorder() + [self.key]\r\n\r\n\r\n\tdef level_order(self):\r\n\t\t'''\r\n\t\tBreadth first search traversal\r\n\t\t'''\r\n\t\tq = deque()\r\n\t\tq.appendleft(self)\r\n\t\twhile len(q) != 0:\r\n\t\t\ttmp = q.pop()\r\n\t\t\tif tmp.leftChild != None:\r\n\t\t\t\tq.appendleft(tmp.leftChild)\r\n\t\t\tif tmp.rightChild != None:\r\n\t\t\t\tq.appendleft(tmp.rightChild)\r\n\t\t\tprint(tmp.key)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\timport argparse\r\n\tCLI=argparse.ArgumentParser()\r\n\tCLI.add_argument(\r\n\t\t\"--list\",\r\n\t\tnargs=\"*\",\r\n\t\ttype=int,\r\n\t\tdefault=[3,2,1]\r\n\t)\r\n\targs = CLI.parse_args()\r\n\r\n\tt = BinaryTree(1)\r\n\tt.insertRight(3)\r\n\tt.insertLeft(4)\r\n\tt.insertLeft(2)\r\n\tt.leftChild.insertRight(5)\r\n\tprint(t.get_leaves())\r\n\tprint(t.inorder())\r\n\tprint(t.postorder())\r\n\tprint(t.preorder())\r\n\tprint(t.level_order())\r\n\r\n", "repo_name": "Alshadex/AlgorithmNotes", "sub_path": "DataStructures/Trees/BinaryTree.py", "file_name": "BinaryTree.py", "file_ext": "py", "file_size_in_byte": 2743, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "collections.deque", "line_number": 77, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 90, "usage_type": "call"}]} +{"seq_id": "14350004779", "text": "import pandas as pd\nfrom transformers import (\n MT5ForConditionalGeneration,\n T5Tokenizer,\n Text2TextGenerationPipeline,\n)\n\nDATA = \"data/chinese/preprocessed/all.csv\"\n\npath = \"K024/mt5-zh-ja-en-trimmed\"\npipe = Text2TextGenerationPipeline(\n model=MT5ForConditionalGeneration.from_pretrained(path, cache_dir=\"./cache\"),\n tokenizer=T5Tokenizer.from_pretrained(path, cache_dir=\"./cache\"),\n device=\"cuda:7\",\n)\n\ndf = pd.read_csv(DATA).dropna()\ndf[\"text\"] = \"zh2ja: \" + df[\"text\"]\ndf[\"text\"] = list(\n map(\n lambda x: x[\"generated_text\"],\n pipe(df[\"text\"].tolist(), max_length=300, num_beams=4),\n )\n)\ndf.to_csv(\"all_ja.csv\", index=False)\n", "repo_name": "Yusuke196/socio_com_presentation", "sub_path": "utils/translation/t5.py", "file_name": "t5.py", "file_ext": "py", "file_size_in_byte": 668, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "transformers.Text2TextGenerationPipeline", "line_number": 11, "usage_type": "call"}, {"api_name": "transformers.MT5ForConditionalGeneration.from_pretrained", "line_number": 12, "usage_type": "call"}, {"api_name": "transformers.MT5ForConditionalGeneration", "line_number": 12, "usage_type": "name"}, {"api_name": "transformers.T5Tokenizer.from_pretrained", "line_number": 13, "usage_type": "call"}, {"api_name": "transformers.T5Tokenizer", "line_number": 13, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 17, "usage_type": "call"}]} +{"seq_id": "44689963224", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[7]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import PassiveAggressiveRegressor\n\ndata = pd.read_csv('C:/Users/A5327/Desktop/New folder/Python/Python/project/Instagram data.csv', encoding = 'latin1')\nprint(data.head())\n\n\n# In[9]:\n\n\ndata.isnull().sum() #contains no nul values\ndata=data.dropna() #drop null values if any\n\n\n# In[10]:\n\n\ndata.info()\n\n\n# In[17]:\n\n\nplt.figure(figsize=(10,8))\nplt.style.use('fivethirtyeight')\nplt.title('Distribution of Impression from home')\nsns.distplot(data['From Home'])\nplt.show\n\n\n# In[19]:\n\n\nplt.figure(figsize=(10,8))\nplt.style.use('fivethirtyeight')\nplt.title('Distribution of Impression from Hastags')\nsns.distplot(data['From Hashtags'])\nplt.show\n\n\n# In[21]:\n\n\nplt.figure(figsize=(10,8))\n#plt.style.use('fivethirtyeight')\nplt.title('Distribution of Impression from Explore')\nsns.distplot(data['From Explore'])\nplt.show\n\n\n# In[30]:\n\n\nhome=data[\"From Home\"].sum()\nhashtags=data[\"From Hashtags\"].sum()\nexplore=data[\"From Explore\"].sum()\nother=data[\"From Other\"].sum()\n\nlabels=['From Home','From Hashtags','From Explore','Other']\nvalues= [home, hashtags, explore, other]\n\nfig=px.pie(data, values=values, names=labels, title='pie chart')\nfig.show()\n\n\n# In[34]:\n\n\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\n\n\n# In[45]:\n\n\ntext=\" \".join(i for i in data.Caption)\nstopwords=set(STOPWORDS)\nwordcloud= WordCloud(stopwords = stopwords ,background_color=\"white\").generate(text)\nplt.style.use('classic')\nplt.figure(figsize=(10,8))\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.axis('off')\nplt.show()\n\n\n# In[46]:\n\n\ntext=\" \".join(i for i in data.Hashtags)\nstopwords=set(STOPWORDS)\nwordcloud= WordCloud(stopwords = stopwords ,background_color=\"white\").generate(text)\nplt.style.use('classic')\nplt.figure(figsize=(10,8))\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.axis('off')\nplt.show()\n\n", "repo_name": "akshitaKESHARWANI/Instagram-Reach-Analysis-using-Python", "sub_path": "Instagram Reach Analysis using Python.py", "file_name": "Instagram Reach Analysis using Python.py", "file_ext": "py", "file_size_in_byte": 2046, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "pandas.read_csv", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.style.use", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 36, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "seaborn.distplot", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 39, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.style.use", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 46, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "seaborn.distplot", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 49, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 57, "usage_type": "name"}, {"api_name": "seaborn.distplot", "line_number": 58, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 59, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}, {"api_name": "plotly.express.pie", "line_number": 73, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 73, "usage_type": "name"}, {"api_name": "wordcloud.STOPWORDS", "line_number": 87, "usage_type": "argument"}, {"api_name": "wordcloud.WordCloud", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style.use", "line_number": 89, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 89, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 89, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 90, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 90, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 91, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 91, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 92, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 92, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 93, "usage_type": "name"}, {"api_name": "wordcloud.STOPWORDS", "line_number": 100, "usage_type": "argument"}, {"api_name": "wordcloud.WordCloud", "line_number": 101, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style.use", "line_number": 102, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 102, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 102, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 103, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 103, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 104, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 105, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 105, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 106, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 106, "usage_type": "name"}]} +{"seq_id": "19412789115", "text": "from functools import wraps\nimport pycompss.util.context as context\nfrom pycompss.api.commons.error_msgs import not_in_pycompss\nfrom pycompss.util.arguments import check_arguments\nfrom pycompss.api.commons.decorator import PyCOMPSsDecorator\nfrom pycompss.api.commons.decorator import keep_arguments\nfrom pycompss.api.commons.decorator import CORE_ELEMENT_KEY\nfrom pycompss.runtime.task.core_element import CE\n\nif __debug__:\n import logging\n logger = logging.getLogger(__name__)\n\nMANDATORY_ARGUMENTS = {'source_class',\n 'method'}\nSUPPORTED_ARGUMENTS = {'source_class',\n 'method'}\nDEPRECATED_ARGUMENTS = {'sourceClass'}\n\n\nclass Implement(PyCOMPSsDecorator):\n \"\"\"\n This decorator also preserves the argspec, but includes the __init__ and\n __call__ methods, useful on mpi task creation.\n \"\"\"\n\n __slots__ = ['first_register']\n\n def __init__(self, *args, **kwargs):\n \"\"\" Store arguments passed to the decorator.\n\n self = itself.\n args = not used.\n kwargs = dictionary with the given implement parameters.\n\n :param args: Arguments.\n :param kwargs: Keyword arguments.\n \"\"\"\n self.first_register = False\n decorator_name = \"\".join(('@', self.__class__.__name__.lower()))\n super(self.__class__, self).__init__(decorator_name, *args, **kwargs)\n if self.scope:\n # Check the arguments\n check_arguments(MANDATORY_ARGUMENTS,\n DEPRECATED_ARGUMENTS,\n SUPPORTED_ARGUMENTS | DEPRECATED_ARGUMENTS,\n list(kwargs.keys()),\n decorator_name)\n\n def __call__(self, func):\n \"\"\" Parse and set the implement parameters within the task core element.\n\n :param func: Function to decorate.\n :return: Decorated function.\n \"\"\"\n @wraps(func)\n def implement_f(*args, **kwargs):\n # This is executed only when called.\n if not self.scope:\n raise Exception(not_in_pycompss(\"implement\"))\n\n if __debug__:\n logger.debug(\"Executing implement_f wrapper.\")\n\n if context.in_master():\n # master code\n if not self.core_element_configured:\n self.__configure_core_element__(kwargs)\n else:\n # worker code\n pass\n\n with keep_arguments(args, kwargs, prepend_strings=True):\n # Call the method\n ret = func(*args, **kwargs)\n\n return ret\n\n implement_f.__doc__ = func.__doc__\n\n if context.in_master() and not self.first_register:\n import pycompss.api.task as t\n self.first_register = True\n t.REGISTER_ONLY = True\n self.__call__(func)(self)\n t.REGISTER_ONLY = False\n\n return implement_f\n\n def __configure_core_element__(self, kwargs):\n # type: (dict) -> None\n \"\"\" Include the registering info related to @implement.\n\n IMPORTANT! Updates self.kwargs[CORE_ELEMENT_KEY].\n\n :param kwargs: Keyword arguments received from call.\n :return: None\n \"\"\"\n if __debug__:\n logger.debug(\"Configuring @implement core element.\")\n\n # Resolve @implement specific parameters\n if 'sourceClass' in self.kwargs:\n another_class = self.kwargs['sourceClass']\n self.kwargs['source_class'] = self.kwargs.pop('sourceClass')\n else:\n another_class = self.kwargs['source_class']\n another_method = self.kwargs['method']\n ce_signature = '.'.join((another_class, another_method))\n impl_type = \"METHOD\"\n # impl_args = [another_class, another_method] # set by @task\n\n if CORE_ELEMENT_KEY in kwargs:\n # Core element has already been created in a higher level decorator\n # (e.g. @constraint)\n kwargs[CORE_ELEMENT_KEY].set_ce_signature(ce_signature)\n kwargs[CORE_ELEMENT_KEY].set_impl_type(impl_type)\n # @task sets the implementation type arguments\n # kwargs[CORE_ELEMENT_KEY].set_impl_type_args(impl_args)\n else:\n # @implement is in the top of the decorators stack.\n # Instantiate a new core element object, update it and include\n # it into kwarg\n core_element = CE()\n core_element.set_ce_signature(ce_signature)\n core_element.set_impl_type(impl_type)\n # @task sets the implementation type arguments\n # core_element.set_impl_type_args(impl_args)\n kwargs[CORE_ELEMENT_KEY] = core_element\n\n # Set as configured\n self.core_element_configured = True\n\n\n# ########################################################################### #\n# ################## IMPLEMENT DECORATOR ALTERNATIVE NAME ################### #\n# ########################################################################### #\n\nimplement = Implement\nIMPLEMENT = Implement\n", "repo_name": "curiousTauseef/compss", "sub_path": "compss/programming_model/bindings/python/src/pycompss/api/implement.py", "file_name": "implement.py", "file_ext": "py", "file_size_in_byte": 5080, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "27", "api": [{"api_name": "logging.getLogger", "line_number": 12, "usage_type": "call"}, {"api_name": "pycompss.api.commons.decorator.PyCOMPSsDecorator", "line_number": 21, "usage_type": "name"}, {"api_name": "pycompss.util.arguments.check_arguments", "line_number": 44, "usage_type": "call"}, {"api_name": "pycompss.api.commons.error_msgs.not_in_pycompss", "line_number": 60, "usage_type": "call"}, {"api_name": "pycompss.util.context.in_master", "line_number": 65, "usage_type": "call"}, {"api_name": "pycompss.util.context", "line_number": 65, "usage_type": "name"}, {"api_name": "pycompss.api.commons.decorator.keep_arguments", "line_number": 73, "usage_type": "call"}, {"api_name": "functools.wraps", "line_number": 56, "usage_type": "call"}, {"api_name": "pycompss.util.context.in_master", "line_number": 81, "usage_type": "call"}, {"api_name": "pycompss.util.context", "line_number": 81, "usage_type": "name"}, {"api_name": "pycompss.api.task.REGISTER_ONLY", "line_number": 84, "usage_type": "attribute"}, {"api_name": "pycompss.api.task", "line_number": 84, "usage_type": "name"}, {"api_name": "pycompss.api.task.REGISTER_ONLY", "line_number": 86, "usage_type": "attribute"}, {"api_name": "pycompss.api.task", "line_number": 86, "usage_type": "name"}, {"api_name": "pycompss.api.commons.decorator.CORE_ELEMENT_KEY", "line_number": 113, "usage_type": "name"}, {"api_name": "pycompss.api.commons.decorator.CORE_ELEMENT_KEY", "line_number": 116, "usage_type": "name"}, {"api_name": "pycompss.api.commons.decorator.CORE_ELEMENT_KEY", "line_number": 117, "usage_type": "name"}, {"api_name": "pycompss.runtime.task.core_element.CE", "line_number": 124, "usage_type": "call"}, {"api_name": "pycompss.api.commons.decorator.CORE_ELEMENT_KEY", "line_number": 129, "usage_type": "name"}]} +{"seq_id": "35879266267", "text": "import datetime\n\nfrom Functions import *\n\n\ndef add_interval(intervals, interval, five):\n '''\n This functions links a five to an interval adding it to the intervals list\n - intervals: intervals of playing fives (dictionary of {tuple: set})\n - interval: interval of the game without substitutions (tuple: (string, string))\n - five: set of players (set)\n '''\n intervals[interval] = five\n\n\ndef check_oncourt(team, player, Q, oncourt, tempOncourtIntervals, oncourtIntervals):\n '''\n This function is launched to check whether the presence of the player was already detected. In\n case it was not, it adds it to the players on court and to the previous fives if needed\n - team: team of the player, either 1 or 2 (string)\n - player: name of the player (string)\n - Q: current quarter (string)\n - oncourt: players on court (list of dictionaries {player: string})\n - tempOncourtIntervals: players on court for each interval without substitutions waiting to be completed (dictionary of {tuple: set of strings})\n - oncourtIntervals: players on court for each interval without substitutions (dictionary of {tuple: set of strings})\n '''\n if player != \"-\":\n # we check the player is in the current playing list:\n if player not in oncourt[team-1]:\n clock = quarter_start_time(Q)\n oncourt[team-1][player] = string_from_time(clock)\n # we add the player to previous incomplete fives:\n if len(tempOncourtIntervals[team-1]) > 0:\n toDelete = []\n for interval in tempOncourtIntervals[team-1]:\n tempOncourtIntervals[team-1][interval].add(player)\n # if any five is now complete we add it to the definitive dictionary and delete them from the temporal one:\n if len(tempOncourtIntervals[team-1][interval]) == 5:\n add_interval(oncourtIntervals[team-1], interval, tempOncourtIntervals[team-1][interval])\n toDelete.append(interval)\n for interval in toDelete:\n del tempOncourtIntervals[team-1][interval]\n\n\ndef quarter_end(Q, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub):\n '''\n This function is launched every time a quarter end is detected.\n It treats the quarter end as a substitution, as the five players can be completely new at the next quarter\n - Q: quarter that has just ended (string)\n - oncourt: players on court at the time of the action (list of dictionaries {player: string})\n - playersIntervals: playing intervals for every team member (dictionary of {string: list of tuples})\n - oncourtIntervals: players on court for each interval without substitutions (dictionary of {tuple: set of strings})\n - lastSub: time of the last substitution (string)\n '''\n # we add the minutes of the players that end the quarter (as it is usually done when they are substituted):\n clock = quarter_end_time(Q)\n clock = string_from_time(clock)\n for team in range(1,3):\n for interval in tempOncourtIntervals[team-1]:\n add_interval(oncourtIntervals[team-1], interval, tempOncourtIntervals[team-1][interval])\n \n for player in oncourt[team-1]:\n if player not in playerIntervals[team-1].keys():\n playerIntervals[team-1][player] = []\n playerIntervals[team-1][player].append((oncourt[team-1][player], clock))\n add_interval(oncourtIntervals[team-1], (lastSub[team-1], clock), set(oncourt[team-1]))\n \n # we delete current variables as the five players can be completely new at the next quarter:\n oncourt[team-1].clear()\n tempOncourtIntervals[team-1].clear()\n lastSub[team-1] = string_from_time(quarter_start_time(next_quarter(Q)))\n\n\ndef quarter_check(action, prevQ, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub):\n '''\n This function is launched to detect a change of quarter. If it is the case, quarter_end is launched\n - action: play that we are going to study (list)\n - prevQ: quarter of the previous action (string)\n - oncourt: players on court at the time of the action (list of dictionaries {player: string})\n - playersIntervals: playing intervals for every team member (dictionary of {string: list of tuples})\n - tempOncourtIntervals: players on court for each interval without substitutions waiting to be completed (dictionary of {tuple: set of strings})\n - oncourtIntervals: players on court for each interval without substitutions (dictionary of {tuple: set of strings})\n - lastSub: time of the last substitution (string)\n Output: quarter of the action (string)\n '''\n clock = action[0]\n Q = quarter_from_time(clock)\n if prevQ != Q:\n quarter_end(prevQ, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub)\n return Q\n\n\ndef substitution(action, Q, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub):\n '''\n Treatment of an action that was detected as a substitution. It will have the following structure:\n clock team player playerOut playerIn\n The substitution will mean the end of a five and the start of another one\n - action: studied play (list)\n - Q: quarter of the action (string)\n - oncourt: players on court at the time of the action (list of dictionaries {player: string})\n - playersIntervals: playing intervals for every team member (dictionary of {string: list of tuples})\n - tempOncourtIntervals: players on court for each interval without substitutions waiting to be completed (dictionary of {tuple: set of strings})\n - oncourtIntervals: players on court for each interval without substitutions (dictionary of {tuple: set of strings})\n - lastSub: time of the last substitution (string)\n '''\n clock, team, playerOut, playerIn = action[0], int(action[1]), action[2], action[4]\n check_oncourt(team, playerOut, Q, oncourt, tempOncourtIntervals, oncourtIntervals)\n Q, minutes, seconds = clock.split(\":\")\n clock = Q + \":\" + datetime.time(0, int(minutes), int(seconds)).strftime(\"%M:%S\")\n\n # playerIntervals treatment: player played from oncourt[team-1][playerOut] until clock\n if playerOut not in playerIntervals[team-1].keys():\n playerIntervals[team-1][playerOut] = []\n playerIntervals[team-1][playerOut].append((oncourt[team-1][playerOut], clock))\n\n if clock != lastSub[team-1]: # to avoid adding fives in the middle of consecutive substitutions\n if len(oncourt[team-1]) == 5: # if the five is complete, we send it to the definitive list\n add_interval(oncourtIntervals[team-1], (lastSub[team-1], clock), set(oncourt[team-1]))\n else: # if the five is incomplete, we send it to the temporal list\n add_interval(tempOncourtIntervals[team-1], (lastSub[team-1], clock), set(oncourt[team-1]))\n del oncourt[team-1][playerOut]\n oncourt[team-1][playerIn] = clock\n lastSub[team-1] = clock\n\n\ndef treat_line(line, prevQ, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub):\n '''\n This function is launched to detect the type of play an action is and treat it in case it is a shot\n - line: action that we are going to study (string)\n - prevQ: quarter of the previous action (string)\n - oncourt: players on court at the time of the action (list of dictionaries {player: string})\n - playersIntervals: playing intervals for every team member (dictionary of {string: list of tuples})\n - tempOncourtIntervals: players on court for each interval without substitutions waiting to be completed (dictionary of {tuple: set of strings})\n - oncourtIntervals: players on court for each interval without substitutions (dictionary of {tuple: set of strings})\n - lastSub: time of the last substitution (string)\n Output: quarter of the action (string)\n '''\n action = line.split(\", \")\n\n Q = quarter_check(action, prevQ, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub)\n if len(action) > 3 and action[3] == \"S\": # there can be either one or two players\n team, player = int(action[1]), action[2]\n check_oncourt(team, player, Q, oncourt, tempOncourtIntervals, oncourtIntervals)\n distGiven = action[5] != \"I\" and action[5] != \"O\" # true if it is not I or O, so in this position we have the distance\n if len(action) == 8+distGiven and action[6+distGiven] == \"A\": # there is an assist\n assistant = action[7+distGiven]\n check_oncourt(team, assistant, Q, oncourt, tempOncourtIntervals, oncourtIntervals)\n elif len(action) > 3 and (action[3] == \"R\" or action[3] == \"T\"): # there is only one player\n team, player = int(action[1]), action[2]\n check_oncourt(team, player, Q, oncourt, tempOncourtIntervals, oncourtIntervals)\n elif len(action) > 3 and (action[3] == \"St\" or action[3] == \"B\"): # there are two players\n team, player, receiver = int(action[1]), action[2], action[4]\n check_oncourt(team, player, Q, oncourt, tempOncourtIntervals, oncourtIntervals)\n opTeam = other_team(team)\n check_oncourt(opTeam, receiver, Q, oncourt, tempOncourtIntervals, oncourtIntervals)\n elif len(action) > 3 and action[3] == \"F\": # there can be either one or two players\n team, player, kind = int(action[1]), action[2], action[4]\n if kind != \"T\":\n check_oncourt(team, player, Q, oncourt, tempOncourtIntervals, oncourtIntervals)\n if len(action) == 6: # there is a player from the opposite team that receives the foul\n receiver = action[5]\n opTeam = other_team(team)\n check_oncourt(opTeam, receiver, Q, oncourt, tempOncourtIntervals, oncourtIntervals)\n elif len(action) > 3 and action[3] == \"Su\":\n substitution(action, Q, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub)\n return Q\n\n\ndef main(file):\n '''\n This function returns the playing intervals for every player and the 5 on court for each interval\n - file: play-by-play input file (string)\n Output:\n - playersIntervals: playing intervals for every team member (dictionary of {string: list of tuples})\n - oncourtIntervals: players on court for each interval without substitutions (dictionary of {tuple: set of strings})\n '''\n playerIntervals = [{}, {}]\n oncourt = [{}, {}]\n tempOncourtIntervals = [{}, {}]\n oncourtIntervals = [{}, {}]\n lastSub = [\"1Q:12:00\", \"1Q:12:00\"]\n Q = \"1Q\"\n\n with open(file, encoding=\"utf-8\") as f:\n lines = f.readlines()\n for line in lines:\n line = line.strip()\n Q = treat_line(line, Q, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub)\n quarter_end(Q, oncourt, playerIntervals, tempOncourtIntervals, oncourtIntervals, lastSub)\n\n return playerIntervals, oncourtIntervals", "repo_name": "XavierRubiesCullell/Basketball-information-extraction-from-play-by-play-data", "sub_path": "Code/PlayingIntervals.py", "file_name": "PlayingIntervals.py", "file_ext": "py", "file_size_in_byte": 10904, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "27", "api": [{"api_name": "datetime.time", "line_number": 109, "usage_type": "call"}]} +{"seq_id": "2044793358", "text": "# Python\nfrom typing import Optional, Dict, List\nfrom enum import Enum\nfrom uuid import UUID\nfrom datetime import date, datetime\n\n\n# Pydantic\nfrom pydantic import BaseModel\nfrom pydantic import SecretStr\nfrom pydantic import EmailStr\nfrom pydantic import Field\n\n\n# FastAPI\nfrom fastapi import FastAPI, status\nfrom fastapi import Body, Path\nfrom fastapi import HTTPException\n\napp = FastAPI()\napp.title = \"Library\"\napp.version = \" 0.0.1\"\n\n\n# Modes\nclass ReadingAge(Enum):\n yearsDefault = \"No defined\"\n years1_3 = \"1 - 3 years\"\n years4_7 = \"4 - 7 years\"\n years8_10 = \"8 - 10 years\"\n years11_14 = \"11 - 14 years\"\n years15_17 = \"15 - 17 years\"\n years18 = \"older than 18\"\n\n\nclass Language(Enum):\n default = \"No defined\"\n english = \"english\"\n spanish = \"spanish\"\n french = \"french \"\n german = \"german \"\n\n\nclass BookBase(BaseModel):\n '''\n Class base of books\n '''\n title: str = Field(\n ...,\n min_length=1,\n max_length=100,\n example=\"A Monster Calls\"\n )\n author: str = Field(\n ...,\n min_length=1,\n max_length=50,\n example=\"Patrick Ness\"\n )\n reading_age: Optional[ReadingAge] = Field(\n default=ReadingAge.yearsDefault,\n example=ReadingAge.years18\n )\n pages: Optional[int] = Field(\n default=None,\n ge=1,\n le=10000,\n example=128\n )\n language: Optional[Language] = Field(\n default=Language.default,\n example=Language.english\n )\n publisher: Optional[str] = Field(\n default=None,\n min_length=1,\n max_length=50,\n example=\"Candlewick\"\n )\n date_add: datetime = Field(default=datetime.now())\n date_update: Optional[datetime] = Field(default=None)\n\n\nclass Book(BookBase):\n isbn_10: str = Field(\n ...,\n min_length=10,\n max_length=12,\n example=\"0763692158\"\n )\n id_book: UUID = Field(...)\n\n\nclass BookOut(BookBase):\n '''\n Books as response\n '''\n pass\n\n\nclass AuthorBase(BaseModel):\n full_name: str = Field(\n ...,\n min_length=1,\n max_length=50,\n example=\"Patrick Ness\"\n )\n birthdate: Optional[date] = Field(\n default=None,\n example='1998-06-23'\n )\n nationality: Optional[str] = Field(\n default=None,\n min_length=1,\n max_length=120,\n example='American-British'\n )\n genre: Optional[str] = Field(\n default=None,\n min_length=1,\n max_length=120,\n example='Young adult'\n )\n\n\nclass Author(AuthorBase):\n id_author: UUID = Field(...)\n\n\nclass AuthorOut(AuthorBase):\n pass\n\n\nclass LoginBase(BaseModel):\n username: str = Field(\n ...,\n max_length=20,\n example=\"lita2021\"\n )\n email: EmailStr = Field(\n ...,\n )\n message: str = Field(\n default=\"Login Succesfully!\"\n )\n\n\nclass Login(LoginBase):\n password: SecretStr = Field(\n ...,\n min_length=8,\n max_length=64\n )\n\n\nclass LoginOut(LoginBase):\n pass\n\n\n# Home\n@app.get(\n path=\"/\",\n status_code=status.HTTP_200_OK,\n tags=[\"Home\"]\n )\ndef home() -> Dict:\n return {\"Hello\": \"World\"}\n\n\n# User\n# Register a user\n@app.post(\n path=\"/signup\",\n response_model=LoginOut,\n status_code=status.HTTP_201_CREATED,\n summary=\"Register a User\",\n tags=[\"Login\"]\n)\ndef signup():\n pass\n\n\n# Login a user\n@app.post(\n path=\"/login\",\n response_model=LoginOut,\n status_code=status.HTTP_200_OK,\n summary=\"Login a User\",\n tags=[\"Login\"]\n)\ndef login():\n pass\n\n\n# Books\n# Create a book\n@app.post(\n path=\"/book/new\",\n response_model=BookOut,\n status_code=status.HTTP_201_CREATED,\n tags=[\"Book\"],\n summary=\"Create a new book and return it\"\n )\ndef create_book(book: Book = Body(...)):\n \"\"\"\n \"Create a new book\"\n\n - Args:\n book (Book): Book = Body(...)\n\n - Returns:\n The book object that was passed in.\n \"\"\"\n return book\n\n\nbooks_id = [1, 2, 3, 4, 5, 6, 7, 8, 9] # books ID\n\n\n# Show a book\n@app.get(\n path=\"/book/{id_book}\",\n status_code=status.HTTP_200_OK,\n response_model=BookOut,\n tags=[\"Book\"],\n summary=\"Show a book\"\n )\ndef show_book_path(\n id_book: int = Path(\n ...,\n title=\"Code book\",\n gt=0,\n example=7\n )\n):\n \"\"\"\n \"Check a book in library\"\n It returns a dictionary with the id_book as the\n key and a string as the value. The id_book is an\n integer that is greater than 0 and the example value is 112233.\n If the id_book is not in the id_book list, then it raises\n an HTTPException with a status code of 404 and a detail message.\n\n - Args:\n id_book (int): int = Path(\n\n - Returns:\n A dictionary with the id_book as the key and a string as the value.\n \"\"\"\n if id_book not in books_id:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND,\n detail=\"¡This book is not in our library\"\n )\n return {id_book: \"It exists!\"}\n\n\n# Show all books\n@app.get(\n path=\"/books\",\n response_model=List[BookOut],\n status_code=status.HTTP_200_OK,\n summary=\"Show all books\",\n tags=[\"Book\"]\n)\ndef show_all_books():\n pass\n\n\n# Delete a book\n@app.delete(\n path=\"/book/{id_book}/delete\",\n response_model=BookOut,\n status_code=status.HTTP_200_OK,\n summary=\"Delete a book\",\n tags=[\"Book\"]\n)\ndef delete_a_book():\n pass\n\n\n# Update a book\n@app.put(\n path=\"/book/update_book/{id_book}/{isbn_10}\",\n status_code=status.HTTP_200_OK,\n tags=[\"Book\"],\n summary=\"Updates a book\"\n )\ndef update_book(\n id_book: int = Path(\n ...,\n title=\"Code book\",\n gt=0,\n example=7\n ),\n isbn_10: str = Path(\n ...,\n title=\"book ID (ISBN-10)\",\n description=\"Code ISBN-10\",\n min_length=10,\n max_length=12,\n example=\"0111112229\"\n ),\n book: Book = Body(...)\n):\n \"\"\"\n \"Updates a book and returns it\"\n\n - Args:\n code_book (int): The ID of the book to be updated.\n book (Book): A `Book` object with the updated information.\n\n - Returns:\n dict: A dictionary with the updated book information.\n \"\"\"\n results = book.dict()\n results.update({'isbn_10': isbn_10})\n return results\n\n\n# Author\n# Create an author\n@app.post(\n path=\"/author/new\",\n response_model=AuthorOut,\n status_code=status.HTTP_201_CREATED,\n tags=[\"Author\"],\n summary=\"Create a new author\"\n )\ndef create_author(author: Author = Body(...)):\n \"\"\"\n \"Create a new author\"\n\n - Args:\n author (Author): Author = Body(...)\n\n - Returns:\n The author object\n \"\"\"\n return author\n\n\n# Show an author\n@app.get(\n path=\"/author/{id_author}\",\n response_model=AuthorOut,\n status_code=status.HTTP_200_OK,\n summary=\"Show an author\",\n tags=[\"Author\"]\n)\ndef show_an_author():\n pass\n\n\n# Show all authors\n@app.get(\n path=\"/authors\",\n response_model=List[AuthorOut],\n status_code=status.HTTP_200_OK,\n summary=\"Show all authors\",\n tags=[\"Author\"]\n)\ndef show_all_authors():\n pass\n\n\n# Delete an author\n@app.delete(\n path=\"/author/{id_author}/delete\",\n response_model=AuthorOut,\n status_code=status.HTTP_200_OK,\n summary=\"Delete an author\",\n tags=[\"Author\"]\n)\ndef delete_an_author():\n pass\n\n\n# Update an author\n@app.put(\n path=\"/author/{id_author}/update\",\n response_model=AuthorOut,\n status_code=status.HTTP_200_OK,\n summary=\"Update an author\",\n tags=[\"Author\"]\n)\ndef update_an_author():\n pass\n", "repo_name": "luisqpra/FastApiBooks", "sub_path": "pass_main.py", "file_name": "pass_main.py", "file_ext": "py", "file_size_in_byte": 7584, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "fastapi.FastAPI", "line_number": 20, "usage_type": "call"}, {"api_name": "enum.Enum", "line_number": 26, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 36, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 44, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 48, "usage_type": "call"}, {"api_name": "pydantic.Field", "line_number": 54, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 60, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 60, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 64, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 64, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 70, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 70, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 74, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 74, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 80, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 80, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 80, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 81, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 81, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 81, "usage_type": "call"}, {"api_name": "pydantic.Field", "line_number": 85, "usage_type": "call"}, {"api_name": "uuid.UUID", "line_number": 91, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 91, "usage_type": "call"}, {"api_name": "pydantic.BaseModel", "line_number": 101, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 102, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 108, "usage_type": "name"}, {"api_name": "datetime.date", "line_number": 108, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 108, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 112, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 112, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 118, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 118, "usage_type": "call"}, {"api_name": "uuid.UUID", "line_number": 127, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 127, "usage_type": "call"}, {"api_name": "pydantic.BaseModel", "line_number": 134, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 135, "usage_type": "call"}, {"api_name": "pydantic.EmailStr", "line_number": 140, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 140, "usage_type": "call"}, {"api_name": "pydantic.Field", "line_number": 143, "usage_type": "call"}, {"api_name": "pydantic.SecretStr", "line_number": 149, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 149, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 163, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 163, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 166, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_201_CREATED", "line_number": 175, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 175, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 187, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 187, "usage_type": "name"}, {"api_name": "fastapi.Body", "line_number": 204, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_201_CREATED", "line_number": 200, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 200, "usage_type": "name"}, {"api_name": "fastapi.Path", "line_number": 229, "usage_type": "call"}, {"api_name": "fastapi.HTTPException", "line_number": 251, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_404_NOT_FOUND", "line_number": 252, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 252, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 223, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 223, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 261, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 262, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 262, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 274, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 274, "usage_type": "name"}, {"api_name": "fastapi.Path", "line_number": 290, "usage_type": "call"}, {"api_name": "fastapi.Path", "line_number": 296, "usage_type": "call"}, {"api_name": "fastapi.Body", "line_number": 304, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 285, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 285, "usage_type": "name"}, {"api_name": "fastapi.Body", "line_number": 330, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_201_CREATED", "line_number": 326, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 326, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 347, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 347, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 358, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 359, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 359, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 371, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 371, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 383, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 383, "usage_type": "name"}]} +{"seq_id": "32117349865", "text": "from django import forms\nfrom django.contrib.flatpages.models import FlatPage\nfrom django.contrib.sites.models import Site\nfrom django.core.cache import cache\nfrom django.urls import reverse\n\nimport posts.settings as posts_settings\nfrom posts.models import Follow, Group, Post\nfrom posts.tests.test_settings import AllSettings\n\n\nclass Addition(AllSettings):\n def setUp(self):\n super().setUp()\n site = Site.objects.get(pk=1)\n self.flat_about = FlatPage.objects.create(\n url='/about-author/',\n title='about',\n content='content'\n )\n self.flat_spec = FlatPage.objects.create(\n url='/about-spec/',\n title='about spec',\n content='content'\n )\n self.flat_about.sites.add(site)\n self.flat_spec.sites.add(site)\n\n def check_context_form(self, response):\n \"\"\"\n The function checks the context of the form\n\n The entrance accepts:\n ~ response - received request response\n \"\"\"\n list_field = {\n 'text': forms.CharField,\n 'group': forms.ChoiceField\n }\n for value, expected in list_field.items():\n with self.subTest(value=value):\n form_field = response.context.get('form').fields.get(value)\n self.assertIsInstance(form_field, expected)\n\n def check_context_page(self, response, check_with, expected_count):\n \"\"\"\n The function checks context ['page']\n\n The entrance accepts:\n ~ response - the result of the request\n ~ check_with - what to compare the first post from page to\n ~ expected_count - how many posts should be on one page\n \"\"\"\n page = response.context['page']\n first_item = page[0]\n page_len = len(page)\n\n self.assertEqual(first_item, check_with)\n self.assertEqual(page_len, expected_count)\n\n\nclass ViewsTest(Addition):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n for i in range(15):\n Post.objects.create(\n author=cls.user,\n text=f'Текст поста {i}',\n group=cls.group,\n )\n\n for i in range(15):\n Group.objects.create(\n title='Тестовый title',\n slug=f'groups-{i}',\n description='Тестовый description'\n )\n\n for i in range(15):\n Post.objects.create(\n author=cls.user_2,\n text=f'Текст поста автора {i}',\n group=cls.group,\n )\n\n def test_show_correct_context_index(self):\n response = self.authorized_client.get(reverse('posts:index'))\n\n count_posts_all = response.context['paginator'].count\n\n self.check_context_page(response, self.post,\n posts_settings.NUMBER_ITEM_PAGINATOR_POST)\n self.assertEqual(count_posts_all, Post.objects.count())\n\n def test_show_correct_follow_index(self):\n self.follow_1 = Follow.objects.create(\n user=self.user,\n author=self.user_2\n )\n response = self.authorized_client.get(reverse('posts:follow_index'))\n\n count_posts_all = response.context['paginator'].count\n\n self.check_context_page(response, self.posts_follow,\n posts_settings.NUMBER_ITEM_PAGINATOR_POST)\n self.assertEqual(count_posts_all, self.user_2.posts.count())\n\n def test_show_correct_follow_index_not_following(self):\n self.follow_1 = Follow.objects.create(\n user=self.user,\n author=self.user_2\n )\n response = self.authorized_client_3.get(reverse('posts:follow_index'))\n\n count_posts_all = response.context['paginator'].count\n\n self.assertEqual(count_posts_all, 0)\n\n def test_show_correct_context_group(self):\n response = self.authorized_client.get(\n reverse('posts:group_posts', args=[self.group.slug])\n )\n\n group = response.context['group']\n\n self.check_context_page(response, self.post,\n posts_settings.NUMBER_ITEM_PAGINATOR_POST)\n self.assertEqual(group, self.group)\n\n def test_show_correct_context_groups(self):\n response = self.authorized_client.get(reverse('posts:groups'))\n\n self.check_context_page(\n response,\n self.group,\n posts_settings.NUMBER_ITEM_PAGINATOR_ALL_GROUPS\n )\n\n def test_show_correct_context_new_post(self):\n response = self.authorized_client.get(reverse('posts:new_post'))\n\n self.check_context_form(response)\n\n def test_show_correct_context_group_without_post(self):\n response = self.authorized_client.get(\n reverse('posts:group_posts', args=[self.group_without_post.slug])\n )\n\n paginator_len = response.context['paginator'].count\n\n self.assertEqual(paginator_len, 0)\n\n def test_show_correct_context_edit(self):\n response = self.authorized_client.get(\n reverse('posts:post_edit', args=[self.user, self.post.id]))\n\n post = response.context['post']\n\n self.assertEqual(post, self.post)\n self.check_context_form(response)\n\n def test_show_correct_context_profile(self):\n response = self.authorized_client.get(\n reverse('posts:profile', args=[self.user])\n )\n\n author = response.context['author']\n\n self.check_context_page(response, self.post,\n posts_settings.NUMBER_ITEM_PAGINATOR_POST)\n self.assertEqual(author, self.user)\n\n def test_show_correct_context_post(self):\n response = self.authorized_client.get(\n reverse('posts:post', args=[self.user, self.post.id])\n )\n\n post = response.context['post']\n\n self.assertEqual(post, self.post)\n\n def test_show_correct_context_flatpages(self):\n list_content_flatpage = {\n 'about': self.flat_about.content,\n 'terms': self.flat_spec.content\n }\n\n for reverse_name, contents in list_content_flatpage.items():\n with self.subTest():\n response = self.authorized_client.get(reverse(reverse_name))\n self.assertEqual(\n response.context['flatpage'].content,\n contents\n )\n\n def test_cash(self):\n response = self.authorized_client.get(reverse('posts:index'))\n should_be_content = response.content\n Post.objects.create(\n text='Просто текст',\n author=self.user\n )\n\n response = self.authorized_client.get(reverse('posts:index'))\n content_without_new_post = response.content\n\n cache.clear()\n response = self.authorized_client.get(reverse('posts:index'))\n content_with_new_post = response.content\n\n self.assertEqual(content_without_new_post, should_be_content)\n self.assertNotEqual(content_with_new_post, should_be_content)\n\n\nclass FollowTest(Addition):\n def test_follow(self):\n follow_count = Follow.objects.count()\n response = self.authorized_client_2.get(\n reverse('posts:profile_follow', args=[self.user])\n )\n\n self.assertRedirects(\n response,\n reverse('posts:profile', args=[self.user])\n )\n\n self.assertEqual(Follow.objects.count(), follow_count + 1)\n follow = Follow.objects.last()\n self.assertEqual(follow.user, self.user_2)\n self.assertEqual(follow.author, self.user)\n\n def test_unfollow(self):\n Follow.objects.create(\n user=self.user,\n author=self.user_2\n )\n response = self.authorized_client.get(\n reverse('posts:profile_unfollow', args=[self.user_2])\n )\n\n self.assertRedirects(\n response,\n reverse('posts:profile', args=[self.user_2])\n )\n self.assertEqual(Follow.objects.count(), 0)\n\n# class LikeTest(Addition):\n# def test_like(self):\n# like_count = Like.objects.count()\n#\n# response = self.authorized_client_2.get(\n# reverse('posts:like_or_unlike', args=[self.user, self.post.id])+'?next='+reverse('posts:profile', args=[self.user.username])\n# )\n#\n# self.assertRedirects(\n# response,\n# reverse(response.request['QUERY_STRING'].split('=')[1])\n# )\n# #\n# # self.assertEqual(Follow.objects.count(), follow_count + 1)\n# # like = Like.objects.last()\n# # self.assertEqual(follow.user, self.user_2)\n# # self.assertEqual(follow.author, self.user)\n", "repo_name": "FlowHack/yatube", "sub_path": "posts/tests/test_views.py", "file_name": "test_views.py", "file_ext": "py", "file_size_in_byte": 8779, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "posts.tests.test_settings.AllSettings", "line_number": 12, "usage_type": "name"}, {"api_name": "django.contrib.sites.models.Site.objects.get", "line_number": 15, "usage_type": "call"}, {"api_name": "django.contrib.sites.models.Site.objects", "line_number": 15, "usage_type": "attribute"}, {"api_name": "django.contrib.sites.models.Site", "line_number": 15, "usage_type": "name"}, {"api_name": "django.contrib.flatpages.models.FlatPage.objects.create", "line_number": 16, "usage_type": "call"}, {"api_name": "django.contrib.flatpages.models.FlatPage.objects", "line_number": 16, "usage_type": "attribute"}, {"api_name": "django.contrib.flatpages.models.FlatPage", "line_number": 16, "usage_type": "name"}, {"api_name": "django.contrib.flatpages.models.FlatPage.objects.create", "line_number": 21, "usage_type": "call"}, {"api_name": "django.contrib.flatpages.models.FlatPage.objects", "line_number": 21, "usage_type": "attribute"}, {"api_name": "django.contrib.flatpages.models.FlatPage", "line_number": 21, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 37, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 37, "usage_type": "name"}, {"api_name": "django.forms.ChoiceField", "line_number": 38, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 38, "usage_type": "name"}, {"api_name": "posts.models.Post.objects.create", "line_number": 67, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 67, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 67, "usage_type": "name"}, {"api_name": "posts.models.Group.objects.create", "line_number": 74, "usage_type": "call"}, {"api_name": "posts.models.Group.objects", "line_number": 74, "usage_type": "attribute"}, {"api_name": "posts.models.Group", "line_number": 74, "usage_type": "name"}, {"api_name": "posts.models.Post.objects.create", "line_number": 81, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 81, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 81, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 88, "usage_type": "call"}, {"api_name": "posts.settings.NUMBER_ITEM_PAGINATOR_POST", "line_number": 93, "usage_type": "attribute"}, {"api_name": "posts.settings", "line_number": 93, "usage_type": "name"}, {"api_name": "posts.models.Post.objects.count", "line_number": 94, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 94, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 94, "usage_type": "name"}, {"api_name": "posts.models.Follow.objects.create", "line_number": 97, "usage_type": "call"}, {"api_name": "posts.models.Follow.objects", "line_number": 97, "usage_type": "attribute"}, {"api_name": "posts.models.Follow", "line_number": 97, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 101, "usage_type": "call"}, {"api_name": "posts.settings.NUMBER_ITEM_PAGINATOR_POST", "line_number": 106, "usage_type": "attribute"}, {"api_name": "posts.settings", "line_number": 106, "usage_type": "name"}, {"api_name": "posts.models.Follow.objects.create", "line_number": 110, "usage_type": "call"}, {"api_name": "posts.models.Follow.objects", "line_number": 110, "usage_type": "attribute"}, {"api_name": "posts.models.Follow", "line_number": 110, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 114, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 122, "usage_type": "call"}, {"api_name": "posts.settings.NUMBER_ITEM_PAGINATOR_POST", "line_number": 128, "usage_type": "attribute"}, {"api_name": "posts.settings", "line_number": 128, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 132, "usage_type": "call"}, {"api_name": "posts.settings.NUMBER_ITEM_PAGINATOR_ALL_GROUPS", "line_number": 137, "usage_type": "attribute"}, {"api_name": "posts.settings", "line_number": 137, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 141, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 147, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 156, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 165, "usage_type": "call"}, {"api_name": "posts.settings.NUMBER_ITEM_PAGINATOR_POST", "line_number": 171, "usage_type": "attribute"}, {"api_name": "posts.settings", "line_number": 171, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 176, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 191, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 198, "usage_type": "call"}, {"api_name": "posts.models.Post.objects.create", "line_number": 200, "usage_type": "call"}, {"api_name": "posts.models.Post.objects", "line_number": 200, "usage_type": "attribute"}, {"api_name": "posts.models.Post", "line_number": 200, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 205, "usage_type": "call"}, {"api_name": "django.core.cache.cache.clear", "line_number": 208, "usage_type": "call"}, {"api_name": "django.core.cache.cache", "line_number": 208, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 209, "usage_type": "call"}, {"api_name": "posts.models.Follow.objects.count", "line_number": 218, "usage_type": "call"}, {"api_name": "posts.models.Follow.objects", "line_number": 218, "usage_type": "attribute"}, {"api_name": "posts.models.Follow", "line_number": 218, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 220, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 225, "usage_type": "call"}, {"api_name": "posts.models.Follow.objects.count", "line_number": 228, "usage_type": "call"}, {"api_name": "posts.models.Follow.objects", "line_number": 228, "usage_type": "attribute"}, {"api_name": "posts.models.Follow", "line_number": 228, "usage_type": "name"}, {"api_name": "posts.models.Follow.objects.last", "line_number": 229, "usage_type": "call"}, {"api_name": "posts.models.Follow.objects", "line_number": 229, "usage_type": "attribute"}, {"api_name": "posts.models.Follow", "line_number": 229, "usage_type": "name"}, {"api_name": "posts.models.Follow.objects.create", "line_number": 234, "usage_type": "call"}, {"api_name": "posts.models.Follow.objects", "line_number": 234, "usage_type": "attribute"}, {"api_name": "posts.models.Follow", "line_number": 234, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 239, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 244, "usage_type": "call"}, {"api_name": "posts.models.Follow.objects.count", "line_number": 246, "usage_type": "call"}, {"api_name": "posts.models.Follow.objects", "line_number": 246, "usage_type": "attribute"}, {"api_name": "posts.models.Follow", "line_number": 246, "usage_type": "name"}]} +{"seq_id": "26798719523", "text": "\"\"\"Computes what the failure modes were, and then stores this data in the\ngraphs.\"\"\"\nfrom typing import Dict, List, Tuple\n\nimport networkx as nx\nfrom snnalgorithms.sparse.MDSA.alg_params import get_algorithm_setting_name\nfrom typeguard import typechecked\n\nfrom snncompare.exp_config import Exp_config\nfrom snncompare.graph_generation.stage_1_create_graphs import (\n load_input_graph_from_file_with_init_props,\n)\nfrom snncompare.helper import get_snn_graph_name\nfrom snncompare.import_results.load_stage_1_and_2 import load_simsnn_graphs\nfrom snncompare.process_results.helper import graph_of_run_config_passed\nfrom snncompare.run_config.Run_config import Run_config\n\n# from dash.dependencies import Input, Output\n\n\n# pylint: disable=R0902\nclass Failure_mode_entry:\n \"\"\"Contains a list of neuron names.\"\"\"\n\n # pylint: disable=R0913\n # pylint: disable=R0903\n @typechecked\n def __init__(\n self,\n adaptation_name: str,\n incorrectly_spikes: bool,\n incorrectly_silent: bool,\n incorrect_u_increase: bool,\n incorrect_u_decrease: bool,\n neuron_names: List[str],\n run_config: Run_config,\n timestep: int,\n ) -> None:\n \"\"\"Stores a failure mode entry.\n\n Args:\n adaptation_name (str): The name of the adaptation.\n incorrectly_spikes (bool): Indicates if the neurons spiked\n incorrectly.\n neuron_names (List[str]): List of neuron names.\n run_config (Run_config): The run configuration.\n timestep (int): The timestep at which the failure mode occurred.\n \"\"\"\n self.adaptation_name: str = adaptation_name\n self.incorrectly_spikes: bool = incorrectly_spikes\n self.incorrectly_silent: bool = incorrectly_silent\n self.incorrect_u_increase: bool = incorrect_u_increase\n self.incorrect_u_decrease: bool = incorrect_u_decrease\n self.neuron_names: List = neuron_names\n self.run_config: Run_config = run_config\n self.timestep: int = timestep\n\n\n# pylint: disable=R0903\n# pylint: disable=R0902\nclass Table_settings:\n \"\"\"Creates the object with the settings for the Dash table.\"\"\"\n\n @typechecked\n def __init__(\n self,\n exp_config: Exp_config,\n run_configs: List[Run_config],\n ) -> None:\n \"\"\"Stores the Dash failure-mode plot settings.\n\n Args:\n exp_config (Exp_config): The experiment configuration.\n run_configs (List[Run_config]): List of run configurations.\n \"\"\"\n\n self.exp_config: Exp_config = exp_config\n self.run_configs: List[Run_config] = run_configs\n # Dropdown options.\n self.seeds = exp_config.seeds\n\n self.graph_sizes = list(\n map(\n lambda size_and_max_graphs: size_and_max_graphs[0],\n exp_config.size_and_max_graphs,\n )\n )\n\n self.algorithm_setts = []\n\n for algorithm_name, algo_specs in exp_config.algorithms.items():\n for algo_config in algo_specs:\n self.algorithm_setts.append(\n get_algorithm_setting_name(\n algorithm_setting={algorithm_name: algo_config}\n )\n )\n\n self.adaptation_names = []\n for adaptation in exp_config.adaptations:\n self.adaptation_names.append(\n f\"{adaptation.adaptation_type}_{adaptation.redundancy}\"\n )\n\n self.run_config_and_snns: List[\n Tuple[Run_config, Dict]\n ] = self.create_failure_mode_tables()\n\n @typechecked\n def create_failure_mode_tables(\n self,\n ) -> List[Tuple[Run_config, Dict]]:\n \"\"\"Returns the failure mode data for the selected settings.\n\n Returns:\n A list of tuples containing the run configuration and the failure\n mode data.\n \"\"\"\n run_config_and_snns: List[Tuple[Run_config, Dict]] = []\n print(\"Creating failure mode table.\")\n for i, run_config in enumerate(self.run_configs):\n snn_graphs: Dict = {}\n input_graph: nx.Graph = load_input_graph_from_file_with_init_props(\n run_config=run_config\n )\n print(\n f\"{i}/{len(self.run_configs)},{run_config.adaptation.__dict__}\"\n )\n\n for with_adaptation in [False, True]:\n for with_radiation in [False, True]:\n graph_name: str = get_snn_graph_name(\n with_adaptation=with_adaptation,\n with_radiation=with_radiation,\n )\n snn_graphs[graph_name] = load_simsnn_graphs(\n run_config=run_config,\n input_graph=input_graph,\n with_adaptation=with_adaptation,\n with_radiation=with_radiation,\n stage_index=7,\n )\n run_config_and_snns.append((run_config, snn_graphs))\n return run_config_and_snns\n\n # pylint: disable=R0912\n # pylint: disable=R0913\n # pylint: disable=R0914\n @typechecked\n def get_failure_mode_entries(\n self,\n first_timestep_only: bool,\n seed: int,\n graph_size: int,\n algorithm_setting: str,\n show_spike_failures: bool,\n ) -> List[Failure_mode_entry]:\n \"\"\"Returns the failure mode data for the selected settings.\n\n Args:\n seed: The seed value.\n graph_size: The size of the graph.\n algorithm_setting: The algorithm setting.\n\n Returns:\n A list of failure mode entries.\n\n Raises:\n ValueError: If the run configurations are not equal.\n \"\"\"\n failure_mode_entries: List[Failure_mode_entry] = []\n\n # Loop over the combination of run_config and accompanying snn graphs.\n for run_config, snn_graphs in self.run_config_and_snns:\n # Read the failure modes from the graph object.\n failure_run_config, failure_mode = (\n run_config,\n snn_graphs[\"rad_adapted_snn_graph\"].network.graph.graph[\n \"failure_modes\"\n ],\n )\n if run_config != failure_run_config:\n raise ValueError(\"Error, run configs not equal.\")\n\n # Check if the run config settings are desired.\n run_config_algorithm_name: str = get_algorithm_setting_name(\n algorithm_setting=run_config.algorithm\n )\n adaptation_name: str = (\n f\"{run_config.adaptation.adaptation_type}_\"\n + f\"{run_config.adaptation.redundancy}\"\n )\n\n if (\n run_config.seed == seed\n and run_config.graph_size == graph_size\n and run_config_algorithm_name == algorithm_setting\n and not graph_of_run_config_passed(\n graph_name=\"rad_adapted_snn_graph\",\n run_config=run_config,\n )\n ):\n get_failure_mode_obj(\n adaptation_name=adaptation_name,\n failure_mode=failure_mode,\n failure_mode_entries=failure_mode_entries,\n first_timestep_only=first_timestep_only,\n run_config=run_config,\n show_spike_failures=show_spike_failures,\n )\n\n return failure_mode_entries\n\n\n@typechecked\ndef get_failure_mode_obj(\n *,\n adaptation_name: str,\n failure_mode: Dict,\n failure_mode_entries: List[Failure_mode_entry],\n first_timestep_only: bool,\n run_config: Run_config,\n show_spike_failures: bool,\n) -> None:\n \"\"\"Parses input data to return a Failure mode object, containing the\n difference between the radiated and unradiated SNN.\"\"\"\n\n @typechecked\n def create_failure_mode_entry(\n incorrectly_spikes: bool,\n incorrectly_silent: bool,\n incorrect_u_increase: bool,\n incorrect_u_decrease: bool,\n neuron_list: List[str],\n ) -> Failure_mode_entry:\n \"\"\"Returns a Failure mode object, containing the difference between the\n radiated and unradiated SNN.\"\"\"\n return Failure_mode_entry(\n adaptation_name=adaptation_name,\n incorrectly_spikes=incorrectly_spikes,\n incorrectly_silent=incorrectly_silent,\n incorrect_u_increase=incorrect_u_increase,\n incorrect_u_decrease=incorrect_u_decrease,\n neuron_names=neuron_list,\n run_config=run_config,\n timestep=int(timestep),\n )\n\n @typechecked\n def append_failure_mode_entry(\n failure_mode_entry: Failure_mode_entry,\n ) -> None:\n if first_timestep_only:\n failure_mode_entries.append(failure_mode_entry)\n else:\n # Optionally handle first timestep only logic here\n print(\"passing\")\n\n if show_spike_failures:\n if \"incorrectly_silent\" in failure_mode:\n for timestep, neuron_list in failure_mode[\n \"incorrectly_silent\"\n ].items():\n failure_mode_entry = create_failure_mode_entry(\n False, True, False, False, neuron_list\n )\n append_failure_mode_entry(failure_mode_entry)\n\n if \"incorrectly_spikes\" in failure_mode:\n for timestep, neuron_list in failure_mode[\n \"incorrectly_spikes\"\n ].items():\n failure_mode_entry = create_failure_mode_entry(\n True, False, False, False, neuron_list\n )\n append_failure_mode_entry(failure_mode_entry)\n else:\n if \"inhibitory_delta_u\" in failure_mode:\n for timestep, neuron_list in failure_mode[\n \"inhibitory_delta_u\"\n ].items():\n failure_mode_entry = create_failure_mode_entry(\n False, False, False, True, neuron_list\n )\n append_failure_mode_entry(failure_mode_entry)\n\n if \"excitatory_delta_u\" in failure_mode:\n for timestep, neuron_list in failure_mode[\n \"excitatory_delta_u\"\n ].items():\n failure_mode_entry = create_failure_mode_entry(\n False, False, True, False, neuron_list\n )\n", "repo_name": "a-t-0/snncompare", "sub_path": "src/snncompare/process_results/Table_settings.py", "file_name": "Table_settings.py", "file_ext": "py", "file_size_in_byte": 10469, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "27", "api": [{"api_name": "typing.List", "line_number": 35, "usage_type": "name"}, {"api_name": "snncompare.run_config.Run_config.Run_config", "line_number": 36, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 54, "usage_type": "name"}, {"api_name": "snncompare.run_config.Run_config.Run_config", "line_number": 55, "usage_type": "name"}, {"api_name": "typeguard.typechecked", "line_number": 27, "usage_type": "name"}, {"api_name": "snncompare.exp_config.Exp_config", "line_number": 67, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 68, "usage_type": "name"}, {"api_name": "snncompare.run_config.Run_config.Run_config", "line_number": 68, "usage_type": "name"}, {"api_name": "snncompare.exp_config.Exp_config", "line_number": 77, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 78, "usage_type": "name"}, {"api_name": "snncompare.run_config.Run_config.Run_config", "line_number": 78, "usage_type": "name"}, {"api_name": "snnalgorithms.sparse.MDSA.alg_params.get_algorithm_setting_name", "line_number": 94, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 105, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 106, "usage_type": "name"}, {"api_name": "snncompare.run_config.Run_config.Run_config", "line_number": 106, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 106, "usage_type": "name"}, {"api_name": "typeguard.typechecked", "line_number": 64, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 119, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 119, "usage_type": "name"}, {"api_name": "snncompare.run_config.Run_config.Run_config", "line_number": 119, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 119, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 122, "usage_type": "name"}, {"api_name": "networkx.Graph", "line_number": 123, "usage_type": "attribute"}, {"api_name": "snncompare.graph_generation.stage_1_create_graphs.load_input_graph_from_file_with_init_props", "line_number": 123, "usage_type": "call"}, {"api_name": "snncompare.helper.get_snn_graph_name", "line_number": 132, "usage_type": "call"}, {"api_name": "snncompare.import_results.load_stage_1_and_2.load_simsnn_graphs", "line_number": 136, "usage_type": "call"}, {"api_name": "typeguard.typechecked", "line_number": 109, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 112, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 112, "usage_type": "name"}, {"api_name": "snncompare.run_config.Run_config.Run_config", "line_number": 112, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 112, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 171, "usage_type": "name"}, {"api_name": "snnalgorithms.sparse.MDSA.alg_params.get_algorithm_setting_name", "line_number": 186, "usage_type": "call"}, {"api_name": "snncompare.process_results.helper.graph_of_run_config_passed", "line_number": 198, "usage_type": "call"}, {"api_name": "typeguard.typechecked", "line_number": 149, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 157, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 219, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 220, "usage_type": "name"}, {"api_name": "snncompare.run_config.Run_config.Run_config", "line_number": 222, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 234, "usage_type": "name"}, {"api_name": "typeguard.typechecked", "line_number": 228, "usage_type": "name"}, {"api_name": "typeguard.typechecked", "line_number": 249, "usage_type": "name"}, {"api_name": "typeguard.typechecked", "line_number": 215, "usage_type": "name"}]} +{"seq_id": "9655852129", "text": "import collections\n\ndef bfs(graph,root):\n visited = []\n queue = collections.deque([root])\n print(queue)\n # visited.add(root)\n while queue:\n vertex = queue.popleft()\n if vertex not in visited:\n visited.append(vertex)\n print(vertex)\n for i in graph[vertex]:\n if i not in visited:\n queue.append(i)\n print(graph[vertex],'series : ',i)\n # visited_set = set(visited)\n print(visited)\n\n# graph = {\n# 0:[1,2,3],\n# 1:[0,2],\n# 2:[0,1,4],\n# 3:[0],\n# 4:[2]\n# }\n\ngraph = {\n 'a':['b','c'],\n 'b':['a','d','e'],\n 'c':['a','f','g'],\n 'd':[],\n 'e':[],\n 'f':[],\n 'g':[]\n}\n\nprint(graph)\nprint('BFS of above graph is : ')\n# bfs(graph,0)\nbfs(graph,'a')\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "repo_name": "Elevenv/DS-Stuff", "sub_path": "bfs.py", "file_name": "bfs.py", "file_ext": "py", "file_size_in_byte": 785, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "2", "api": [{"api_name": "collections.deque", "line_number": 5, "usage_type": "call"}]} +{"seq_id": "41105790845", "text": "from django.db import migrations, models\nimport django.db.models.deletion\n\n\ndef create_swimlane_userstory_statuses_for_existing_swimlanes(apps, schema_editor):\n Project = apps.get_model(\"projects\", \"Project\")\n SwimlaneUserStoryStatus = apps.get_model(\"projects\", \"SwimlaneUserStoryStatus\")\n\n projects = Project.objects.annotate(count=models.Count('swimlanes')).filter(count__gt=0)\n objects = []\n for project in projects:\n copy_from_main_status = project.swimlanes.all().count() == 1\n for swimlane in project.swimlanes.all():\n objects += [\n SwimlaneUserStoryStatus(\n swimlane=swimlane,\n status=status,\n wip_limit=status.wip_limit if copy_from_main_status else 0\n )\n for status in project.us_statuses.all()]\n\n SwimlaneUserStoryStatus.objects.bulk_create(objects)\n\n\ndef empty_reverse(apps, schema_editor):\n pass\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('projects', '0064_swimlane'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='SwimlaneUserStoryStatus',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('wip_limit', models.IntegerField(blank=True, default=None, null=True, verbose_name='work in progress limit')),\n ('status', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='swimlane_statuses', to='projects.UserStoryStatus', verbose_name='user story status')),\n ('swimlane', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='statuses', to='projects.Swimlane', verbose_name='status')),\n ],\n options={\n 'verbose_name': 'swimlane user story status',\n 'verbose_name_plural': 'swimlane user story statuses',\n 'ordering': ['swimlane', 'status', 'id'],\n 'unique_together': {('swimlane', 'status')},\n },\n ),\n migrations.RunPython(create_swimlane_userstory_statuses_for_existing_swimlanes, empty_reverse),\n ]\n", "repo_name": "kaleidos-ventures/taiga-back", "sub_path": "taiga/projects/migrations/0065_swimlaneuserstorystatus.py", "file_name": "0065_swimlaneuserstorystatus.py", "file_ext": "py", "file_size_in_byte": 2204, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 455, "dataset": "github-code", "pt": "2", "api": [{"api_name": "django.db.models.Count", "line_number": 9, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 9, "usage_type": "name"}, {"api_name": "django.db.migrations.Migration", "line_number": 29, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 29, "usage_type": "name"}, {"api_name": "django.db.migrations.CreateModel", "line_number": 36, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 36, "usage_type": "name"}, {"api_name": "django.db.models.AutoField", "line_number": 39, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 39, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 40, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 40, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 41, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 41, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 41, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 41, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 42, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 42, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 42, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 42, "usage_type": "name"}, {"api_name": "django.db.migrations.RunPython", "line_number": 51, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 51, "usage_type": "name"}]} +{"seq_id": "74656201325", "text": "import asyncio\nimport time\n\n# async defines a coroutine function.\nasync def task1():\n print(f\"{time.strftime('%H:%M:%S')} task start...\")\n time.sleep(2)\n print(f\"{time.strftime('%H:%M:%S')} task end.\")\n\n# call a coroutine function will not execute it, will return a coroutine object.\ncoroutine = task1()\nprint(f\"{time.strftime('%H:%M:%S')} generate coroutine object {coroutine}. The function is not called\")\nloop = asyncio.get_event_loop()\nstart = time.time()\n# use loop.run_until_complete() to execute coroutine.\nloop.run_until_complete(coroutine)\nend = time.time()\nprint(f\"{time.strftime('%H:%M:%S')} coroutine task finished, duration: {end - start}seconds\")\n", "repo_name": "xwphs/python", "sub_path": "Coroutine/create_coroutine.py", "file_name": "create_coroutine.py", "file_ext": "py", "file_size_in_byte": 670, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "time.strftime", "line_number": 6, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 7, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 8, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 12, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 13, "usage_type": "call"}, {"api_name": "time.time", "line_number": 14, "usage_type": "call"}, {"api_name": "time.time", "line_number": 17, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 18, "usage_type": "call"}]} +{"seq_id": "7530607045", "text": "#coding:utf-8\n\nfrom sklearn import svm\n\nfrom Model import Model\nfrom Prediction import Prediction\nfrom BinaryPredictionCollection import BinaryPredictionCollection\n\n\nclass SvmModel(Model):\n def __init__(self):\n self.__classifier = svm.SVC()\n \n \n def __get_classifier(self):\n return self.__classifier\n \n \n def learn(self, train_dataset, valid_dataset):\n for chunk in train_dataset.get_record_chunks_generator():\n input_matrix = train_dataset.get_input_matrix(chunk)\n labels = train_dataset.get_labels(chunk)\n self.__get_classifier().fit(input_matrix, labels)\n \n \n def predict(self, dataset):\n predictions = []\n for chunk in dataset.get_record_chunks_generator():\n ids = dataset.get_ids(chunk)\n input_matrix = dataset.get_input_matrix(chunk)\n actual_labels = dataset.get_labels(chunk)\n predicted_labels = self.__get_classifier().predict(input_matrix)\n \n for i,(id,a,p) in enumerate(zip(ids,actual_labels,predicted_labels)):\n prediction = Prediction(id=id,actual_label=a,predicted_label=p)\n predictions.append(prediction)\n \n prediction_collection = BinaryPredictionCollection(predictions)\n return prediction_collection\n \n \n def valid(self, dataset):\n raise NotImplementedError()\n", "repo_name": "Arudori5001/Bosch", "sub_path": "SvmModel.py", "file_name": "SvmModel.py", "file_ext": "py", "file_size_in_byte": 1419, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "Model.Model", "line_number": 10, "usage_type": "name"}, {"api_name": "sklearn.svm.SVC", "line_number": 12, "usage_type": "call"}, {"api_name": "sklearn.svm", "line_number": 12, "usage_type": "name"}, {"api_name": "Prediction.Prediction", "line_number": 35, "usage_type": "call"}, {"api_name": "BinaryPredictionCollection.BinaryPredictionCollection", "line_number": 38, "usage_type": "call"}]} +{"seq_id": "27318976187", "text": "from bs4 import BeautifulSoup\nimport requests\nimport os, shutil\n\n\ndef find_borders(groups):\n \"\"\"Get all + 1 tag is start\n last is end\"\"\"\n indices = [i for i, x in enumerate(groups) if x['value'] == 'All']\n return indices[1] + 1, indices[2]\n\ndef find_border_exam(groups):\n \"\"\"Get all + 1 tag is start\n next all